@joe-broadhead/opencode-mem 0.8.0 → 0.8.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 +1340 -0
- package/README.md +56 -26
- package/SECURITY.md +1 -1
- package/package.json +11 -7
- package/skills/{mem-usage → mem.usage}/SKILL.md +4 -1
- package/src/backend/v3.js +20 -5
- package/src/call-shapes.js +1 -0
- package/src/commands.js +8 -5
- package/src/credentials.js +413 -78
- package/src/errors.js +89 -0
- package/src/events.js +63 -20
- package/src/hooks.js +29 -17
- package/src/index.js +15 -3
- package/src/permissions.js +67 -0
- package/src/runtime.js +66 -7
- package/src/skills.js +1 -1
- package/src/spaces.js +41 -19
- package/src/spool.js +91 -4
- package/src/tools/commitments.js +2 -1
- package/src/tools/index.js +10 -5
- package/src/tools/memory.js +35 -4
- package/src/tools/shared.js +3 -1
- package/views/memory.html +2 -2
package/src/errors.js
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The words of a failed request, in the form Jelly's plugin authors' standard
|
|
3
|
+
* gives every tool error (item 8): `CODE: what happened. Next step: what to do.`
|
|
4
|
+
*
|
|
5
|
+
* `BackendError` (`src/backend/v3.js`), `ControlError` (`src/spaces.js`) and
|
|
6
|
+
* `CredentialError` (`src/credentials.js`) build their message here, so a tool
|
|
7
|
+
* that answers with one (`fail` in `src/tools/shared.js`) starts with the code
|
|
8
|
+
* and ends with the next step. A request whose credential could not be had
|
|
9
|
+
* keeps the credential's code and next step: those say what to fix.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** Where a next step sends the person: the setting names Jelly shows. */
|
|
13
|
+
const SETTINGS = "Memory's settings"
|
|
14
|
+
const KEY_STEP = `paste a key from Memory's /account page into the Memory key setting (${SETTINGS})`
|
|
15
|
+
|
|
16
|
+
/** `CODE: what happened. Next step: what to do.`, with one full stop each. */
|
|
17
|
+
export function codedMessage(code, what, next) {
|
|
18
|
+
return `${code}: ${stop(what)} Next step: ${stop(next, true)}`
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** True when a message is already in the coded form. */
|
|
22
|
+
export function isCoded(message) {
|
|
23
|
+
return /^[A-Z][A-Z0-9_]*: .* Next step: .+$/su.test(String(message ?? ""))
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* A coded message with a note added to what happened, before the next step:
|
|
28
|
+
* "MEMORY_X: …; nothing was saved. Next step: …". Any other message gets the
|
|
29
|
+
* note after it.
|
|
30
|
+
*/
|
|
31
|
+
export function withNote(message, note) {
|
|
32
|
+
const text = String(message ?? "")
|
|
33
|
+
const at = text.lastIndexOf(" Next step: ")
|
|
34
|
+
if (!isCoded(text) || at < 1) return `${text}; ${note}`
|
|
35
|
+
return `${text.slice(0, at).replace(/\.$/u, "")}; ${stop(note)}${text.slice(at)}`
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The code and next step for an HTTP status (0 when the service could not be
|
|
40
|
+
* reached). `prefix` names the service: MEMORY for the memory cell and
|
|
41
|
+
* gateway, SPACES for the spaces control plane.
|
|
42
|
+
*
|
|
43
|
+
* @param {number} status
|
|
44
|
+
* @param {"MEMORY" | "SPACES"} prefix
|
|
45
|
+
* @returns {{ code: string, next: string }}
|
|
46
|
+
*/
|
|
47
|
+
export function failureFor(status, prefix) {
|
|
48
|
+
if (status === 401) return { code: `${prefix}_UNAUTHORIZED`, next: `check the Memory key in ${SETTINGS}, or sign in to Jelly again` }
|
|
49
|
+
if (status === 403) return { code: `${prefix}_FORBIDDEN`, next: "use a space you may use (mem_spaces lists them), or ask the space's owner for access" }
|
|
50
|
+
if (status === 404) return { code: `${prefix}_NOT_FOUND`, next: "check the id or name; mem_recall and mem_wiki list what exists" }
|
|
51
|
+
if (status === 408) return { code: `${prefix}_TIMEOUT`, next: "try again in a moment" }
|
|
52
|
+
if (status === 429) return { code: `${prefix}_RATE_LIMITED`, next: "wait a minute, then try again" }
|
|
53
|
+
if (status === 0) return { code: `${prefix}_UNREACHABLE`, next: "try again in a moment; mem_status says whether memory is reachable" }
|
|
54
|
+
if (status >= 500) return { code: `${prefix}_SERVER_ERROR`, next: "try again in a moment; if it keeps failing, tell the Memory server's operator" }
|
|
55
|
+
return { code: `${prefix}_REJECTED`, next: "check the call against the tool's description, then try again" }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The code and next step for a credential that could not be had, by Jelly's refusal code. */
|
|
59
|
+
export function credentialFailure(code) {
|
|
60
|
+
switch (code) {
|
|
61
|
+
case "unavailable":
|
|
62
|
+
return { code: "MEMORY_SIGN_IN_UNAVAILABLE", next: `try again in a moment; if it keeps failing, ${KEY_STEP}` }
|
|
63
|
+
case "not_enrolled":
|
|
64
|
+
return { code: "MEMORY_NOT_ENROLLED", next: `sign this Jelly host in to your Jelly account, or ${KEY_STEP}` }
|
|
65
|
+
case "access_denied":
|
|
66
|
+
return { code: "MEMORY_ACCESS_DENIED", next: "ask the Jelly account's owner to restore the account" }
|
|
67
|
+
case "invalid_target":
|
|
68
|
+
return { code: "MEMORY_NOT_OFFERED", next: `ask the Jelly account's owner to offer Memory to this agent, or ${KEY_STEP}` }
|
|
69
|
+
case "not_signed_in":
|
|
70
|
+
// A saved key is the person's who pasted it, never the speaker's: no key step.
|
|
71
|
+
return { code: "MEMORY_NOT_LINKED", next: "link your Jelly account on this host in Jelly, then try again" }
|
|
72
|
+
default:
|
|
73
|
+
return { code: "MEMORY_SIGN_IN_FAILED", next: KEY_STEP }
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The coded parts an error already carries, or null. */
|
|
78
|
+
export function codedParts(error) {
|
|
79
|
+
if (!error || typeof error !== "object") return null
|
|
80
|
+
const { errorCode, what, next } = error
|
|
81
|
+
return typeof errorCode === "string" && typeof what === "string" && typeof next === "string" ? { code: errorCode, what, next } : null
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** One sentence's end: a full stop unless it has one; `capital` starts it with a capital too. */
|
|
85
|
+
function stop(text, capital = false) {
|
|
86
|
+
const trimmed = String(text ?? "").trim()
|
|
87
|
+
const first = capital ? trimmed.charAt(0).toUpperCase() + trimmed.slice(1) : trimmed
|
|
88
|
+
return /[.!?]$/u.test(first) ? first : `${first}.`
|
|
89
|
+
}
|
package/src/events.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { buildSessionPayload, extractCompactionSummary, newTurn } from "./capture.js"
|
|
2
|
+
import { UNLINKED_SENTENCE, asSession } from "./credentials.js"
|
|
2
3
|
import { CAPTURE_MESSAGE_CHARS, MAX_MESSAGES, splitContent } from "./limits.js"
|
|
3
4
|
import { parentIDOf, readSession } from "./sessions.js"
|
|
4
5
|
import { errorMessage, redactSecrets, rememberBounded, shortHash } from "./util.js"
|
|
@@ -43,13 +44,21 @@ export function summaryMessages(text) {
|
|
|
43
44
|
* releases: the shipped 2.0.x stream uses `session.inbox.*` and
|
|
44
45
|
* `session.execution.*`, while the documented V2 API uses `session.next.*`.
|
|
45
46
|
*
|
|
47
|
+
* Each turn is captured as its own session (`asSession`): inside Jelly it is
|
|
48
|
+
* sent with that session's token, which names the person who spoke there. A
|
|
49
|
+
* session whose speaker has no Jelly account linked on the host is skipped:
|
|
50
|
+
* nothing is sent or spooled for it.
|
|
51
|
+
*
|
|
52
|
+
* With `capture: false` the stream is still read, for `session.deleted` only:
|
|
53
|
+
* what is kept for a deleted session (its token among them) is dropped.
|
|
54
|
+
*
|
|
46
55
|
* @param {any} ctx
|
|
47
56
|
* @param {ReturnType<import("./runtime.js").createRuntime>} runtime
|
|
48
57
|
*/
|
|
49
58
|
export function attachCapture(ctx, runtime) {
|
|
50
|
-
|
|
59
|
+
const capturing = Boolean(runtime.config.capture)
|
|
51
60
|
if (!ctx?.event || typeof ctx.event.subscribe !== "function") {
|
|
52
|
-
runtime.log.warn("host has no event.subscribe; capture disabled")
|
|
61
|
+
if (capturing) runtime.log.warn("host has no event.subscribe; capture disabled")
|
|
53
62
|
return () => {}
|
|
54
63
|
}
|
|
55
64
|
|
|
@@ -60,14 +69,25 @@ export function attachCapture(ctx, runtime) {
|
|
|
60
69
|
const seenEvents = new Set()
|
|
61
70
|
const compacted = new Set()
|
|
62
71
|
let unavailableLogged = false
|
|
72
|
+
/** Sessions already logged as having an unlinked speaker; bounded like the other maps. */
|
|
73
|
+
const unlinkedLogged = new Set()
|
|
63
74
|
|
|
64
75
|
/**
|
|
65
|
-
* Memory is unavailable (a gateway or Jelly install with no credential)
|
|
66
|
-
*
|
|
76
|
+
* Memory is unavailable (a gateway or Jelly install with no credential), or
|
|
77
|
+
* the person speaking in this session has no Jelly account linked on the
|
|
78
|
+
* host: nothing is captured, and nothing is spooled for later. Logged once,
|
|
79
|
+
* and once per such session. Runs inside the session's `asSession`.
|
|
67
80
|
*/
|
|
68
|
-
function skipUnavailable(what) {
|
|
69
|
-
const reason = runtime.unavailable?.() ?? ""
|
|
81
|
+
async function skipUnavailable(what, sessionID) {
|
|
82
|
+
const reason = runtime.availability ? await runtime.availability() : (runtime.unavailable?.() ?? "")
|
|
70
83
|
if (!reason) return false
|
|
84
|
+
if (reason === UNLINKED_SENTENCE) {
|
|
85
|
+
if (!unlinkedLogged.has(sessionID)) {
|
|
86
|
+
rememberBounded(unlinkedLogged, sessionID, undefined, MODELS_MAX)
|
|
87
|
+
runtime.log.info(`${what} not captured: the person speaking hasn't linked a Jelly account on this host`, { sessionID })
|
|
88
|
+
}
|
|
89
|
+
return true
|
|
90
|
+
}
|
|
71
91
|
if (!unavailableLogged) {
|
|
72
92
|
unavailableLogged = true
|
|
73
93
|
runtime.log.info(`${what} not captured: memory is unavailable`, { reason })
|
|
@@ -111,11 +131,20 @@ export function attachCapture(ctx, runtime) {
|
|
|
111
131
|
}
|
|
112
132
|
}
|
|
113
133
|
|
|
114
|
-
|
|
134
|
+
/**
|
|
135
|
+
* Capture one session's open turn, as that session and that turn: a newer
|
|
136
|
+
* user message may have arrived (a superseded turn), and this turn's words
|
|
137
|
+
* go with this turn's token, never the newer speaker's.
|
|
138
|
+
*/
|
|
139
|
+
function flush(sessionID, reason = "idle") {
|
|
140
|
+
return asSession(sessionID, () => flushTurn(sessionID, reason), turns.get(sessionID)?.messageID)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function flushTurn(sessionID, reason) {
|
|
115
144
|
const turn = turns.get(sessionID)
|
|
116
145
|
if (!turn) return
|
|
117
146
|
turns.delete(sessionID)
|
|
118
|
-
if (skipUnavailable("turn")) return
|
|
147
|
+
if (await skipUnavailable("turn", sessionID)) return
|
|
119
148
|
if (skipSubagent(sessionID, "turn")) return
|
|
120
149
|
if (turn.model === "unknown" && models.has(sessionID)) turn.model = models.get(sessionID)
|
|
121
150
|
const facts = await sessionFacts(sessionID, turn)
|
|
@@ -169,16 +198,22 @@ export function attachCapture(ctx, runtime) {
|
|
|
169
198
|
runtime.drainSpool?.()
|
|
170
199
|
} catch (error) {
|
|
171
200
|
// A gateway or control failure leaves the turn in the spool with its
|
|
172
|
-
// visibility; the replay asks the gateway to place it again.
|
|
201
|
+
// visibility; the replay asks the gateway to place it again. A speaker
|
|
202
|
+
// Jelly says has no linked account (learnt during this send) is not
|
|
203
|
+
// kept: the spool deletes the entry.
|
|
173
204
|
const outcome = runtime.releaseSpool?.(staged, error)
|
|
174
205
|
runtime.log.warn("turn capture failed", { outcome: outcome ?? "kept", error: errorMessage(error) })
|
|
175
206
|
}
|
|
176
207
|
}
|
|
177
208
|
|
|
178
|
-
|
|
209
|
+
function captureCompaction(sessionID) {
|
|
210
|
+
return asSession(sessionID, () => captureCompactionSummary(sessionID))
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
async function captureCompactionSummary(sessionID) {
|
|
179
214
|
if (!runtime.config.captureScenarios) return
|
|
180
215
|
try {
|
|
181
|
-
if (skipUnavailable("compaction summary")) return
|
|
216
|
+
if (await skipUnavailable("compaction summary", sessionID)) return
|
|
182
217
|
if (skipSubagent(sessionID, "compaction")) return
|
|
183
218
|
const facts = await sessionFacts(sessionID, {})
|
|
184
219
|
if (skipSubagent(sessionID, "compaction")) return
|
|
@@ -263,6 +298,22 @@ export function attachCapture(ctx, runtime) {
|
|
|
263
298
|
}
|
|
264
299
|
|
|
265
300
|
const data = payloadOf(event)
|
|
301
|
+
if (event.type === "session.deleted") {
|
|
302
|
+
const sessionID = data.sessionID ?? data.info?.id
|
|
303
|
+
if (sessionID) {
|
|
304
|
+
turns.delete(sessionID)
|
|
305
|
+
models.delete(sessionID)
|
|
306
|
+
unlinkedLogged.delete(sessionID)
|
|
307
|
+
if (runtime.forgetSession) runtime.forgetSession(sessionID)
|
|
308
|
+
else runtime.invalidate?.(sessionID)
|
|
309
|
+
}
|
|
310
|
+
return
|
|
311
|
+
}
|
|
312
|
+
// A new user message: the person speaking may have changed, so the
|
|
313
|
+
// session's Jelly token is asked for again; also with capture off.
|
|
314
|
+
if (event.type === "session.inbox.enqueued" && data.item?.type === "user") runtime.userTurn?.(data.sessionID, data.inboxID)
|
|
315
|
+
if (event.type === "session.next.prompt.admitted") runtime.userTurn?.(data.sessionID, data.messageID)
|
|
316
|
+
if (!capturing) return
|
|
266
317
|
if (!seenTypes.has(event.type)) {
|
|
267
318
|
seenTypes.add(event.type)
|
|
268
319
|
runtime.log.debug("event type observed", event.type)
|
|
@@ -354,15 +405,7 @@ export function attachCapture(ctx, runtime) {
|
|
|
354
405
|
return
|
|
355
406
|
}
|
|
356
407
|
|
|
357
|
-
//
|
|
358
|
-
case "session.deleted": {
|
|
359
|
-
if (data.sessionID) {
|
|
360
|
-
turns.delete(data.sessionID)
|
|
361
|
-
models.delete(data.sessionID)
|
|
362
|
-
runtime.invalidate?.(data.sessionID)
|
|
363
|
-
}
|
|
364
|
-
return
|
|
365
|
-
}
|
|
408
|
+
// `session.deleted` is handled before the switch, also with capture off.
|
|
366
409
|
default:
|
|
367
410
|
return
|
|
368
411
|
}
|
package/src/hooks.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { buildCompactionInstruction } from "./compaction.js"
|
|
2
|
+
import { asSession } from "./credentials.js"
|
|
2
3
|
import { hasProtocol, protocolBlock } from "./protocol.js"
|
|
3
4
|
import { isChildSession } from "./sessions.js"
|
|
4
5
|
import { errorMessage } from "./util.js"
|
|
@@ -25,6 +26,10 @@ function positive(value, fallback) {
|
|
|
25
26
|
* Every hook is best effort. A memory, control-plane, or backend failure must
|
|
26
27
|
* never block a model call or a compaction.
|
|
27
28
|
*
|
|
29
|
+
* Each hook runs as its event's session (`asSession`): inside Jelly the pinned
|
|
30
|
+
* block and the checkpoint use that session's token, which names the person
|
|
31
|
+
* speaking there.
|
|
32
|
+
*
|
|
28
33
|
* @param {any} ctx
|
|
29
34
|
* @param {any} runtime
|
|
30
35
|
* @param {{ deadlineMs?: number, compactionTimeoutMs?: number }} [options]
|
|
@@ -67,23 +72,26 @@ export async function attachMemoryHooks(ctx, runtime, options = {}) {
|
|
|
67
72
|
}
|
|
68
73
|
}
|
|
69
74
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
75
|
+
// `prompt` runs once per user message, before the turn's model calls, tool
|
|
76
|
+
// calls and capture: the person speaking may have changed, so the session's
|
|
77
|
+
// Jelly token is asked for again (`runtime.userTurn`, src/credentials.js).
|
|
78
|
+
const promptRegistration = await ctx.session.hook("prompt", (event) => asSession(event?.sessionID, () => {
|
|
79
|
+
try {
|
|
80
|
+
runtime.userTurn?.(event?.sessionID, event?.messageID)
|
|
81
|
+
runtime.noteAgent?.(event?.sessionID, event?.agent)
|
|
82
|
+
if (!config.bootstrap) return
|
|
83
|
+
if (runtime.unavailable?.()) return
|
|
84
|
+
if (runtime.skipsSubagent?.(event.sessionID)) return
|
|
85
|
+
runtime.prefetchBootstrap?.(event.sessionID, event.agent)
|
|
86
|
+
} catch (error) {
|
|
87
|
+
log.warn("bootstrap prefetch failed", errorMessage(error))
|
|
88
|
+
}
|
|
89
|
+
}))
|
|
90
|
+
disposers.push(promptRegistration)
|
|
83
91
|
|
|
84
92
|
// The protocol is independent of the bootstrap setting: an agent with no
|
|
85
93
|
// global instruction file still needs the memory rules.
|
|
86
|
-
const contextRegistration = await ctx.session.hook("context", async (
|
|
94
|
+
const contextRegistration = await ctx.session.hook("context", (event) => asSession(event?.sessionID, async () => {
|
|
87
95
|
try {
|
|
88
96
|
// The agent of every model call, for turn capture (see runtime.noteAgent).
|
|
89
97
|
runtime.noteAgent?.(event?.sessionID, event?.agent)
|
|
@@ -113,6 +121,10 @@ export async function attachMemoryHooks(ctx, runtime, options = {}) {
|
|
|
113
121
|
}
|
|
114
122
|
}
|
|
115
123
|
|
|
124
|
+
// The bootstrap may have learnt that the person speaking has no Jelly
|
|
125
|
+
// account linked on this host: then no protocol either.
|
|
126
|
+
if (runtime.unavailable?.()) return
|
|
127
|
+
|
|
116
128
|
if (!alreadyTaught) {
|
|
117
129
|
const block = protocolBlock()
|
|
118
130
|
event.system.push({ type: "text", text: block })
|
|
@@ -121,10 +133,10 @@ export async function attachMemoryHooks(ctx, runtime, options = {}) {
|
|
|
121
133
|
} catch (error) {
|
|
122
134
|
log.warn("context hook failed", errorMessage(error))
|
|
123
135
|
}
|
|
124
|
-
})
|
|
136
|
+
}))
|
|
125
137
|
disposers.push(contextRegistration)
|
|
126
138
|
|
|
127
|
-
const compactionRegistration = await ctx.session.hook("compaction", async (
|
|
139
|
+
const compactionRegistration = await ctx.session.hook("compaction", (event) => asSession(event?.sessionID, async () => {
|
|
128
140
|
try {
|
|
129
141
|
const alreadyInstructed = event?.system?.some?.((part) => String(part?.text ?? "").includes("<mem_compaction"))
|
|
130
142
|
if (Array.isArray(event?.system) && !alreadyInstructed && !runtime.unavailable?.()) {
|
|
@@ -165,7 +177,7 @@ export async function attachMemoryHooks(ctx, runtime, options = {}) {
|
|
|
165
177
|
log.warn("bootstrap invalidation failed", errorMessage(error))
|
|
166
178
|
}
|
|
167
179
|
}
|
|
168
|
-
})
|
|
180
|
+
}))
|
|
169
181
|
disposers.push(compactionRegistration)
|
|
170
182
|
|
|
171
183
|
return {
|
package/src/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { configWarnings, resolveConfig } from "./config.js"
|
|
2
|
-
import { createCredentials, followOrigin } from "./credentials.js"
|
|
2
|
+
import { asSession, createCredentials, followOrigin } from "./credentials.js"
|
|
3
3
|
import { createLogger } from "./log.js"
|
|
4
4
|
import { createBackend } from "./backend/v3.js"
|
|
5
5
|
import { createRuntime } from "./runtime.js"
|
|
@@ -9,6 +9,7 @@ import { registerCommands } from "./commands.js"
|
|
|
9
9
|
import { attachMemoryHooks } from "./hooks.js"
|
|
10
10
|
import { attachCapture } from "./events.js"
|
|
11
11
|
import { registerViewRpc } from "./views/rpc.js"
|
|
12
|
+
import { registerDefaultRules } from "./permissions.js"
|
|
12
13
|
import { errorMessage, versionAtLeast } from "./util.js"
|
|
13
14
|
|
|
14
15
|
/**
|
|
@@ -84,7 +85,10 @@ export default {
|
|
|
84
85
|
skillRefreshQueued = options
|
|
85
86
|
return skillRefreshPromise
|
|
86
87
|
}
|
|
87
|
-
|
|
88
|
+
// The mirror serves every session of the engine: work with no session,
|
|
89
|
+
// never one speaker's (src/credentials.js), also when a session's
|
|
90
|
+
// /mem-sync or bind asked for it.
|
|
91
|
+
skillRefreshPromise = asSession("", async () => {
|
|
88
92
|
try {
|
|
89
93
|
// Nothing to mirror from while memory is unavailable.
|
|
90
94
|
if (runtime.unavailable()) return skillState
|
|
@@ -117,7 +121,7 @@ export default {
|
|
|
117
121
|
skillRefreshQueued = null
|
|
118
122
|
if (queued) void runtime.refreshSkills(queued)
|
|
119
123
|
}
|
|
120
|
-
})
|
|
124
|
+
})
|
|
121
125
|
return skillRefreshPromise
|
|
122
126
|
}
|
|
123
127
|
|
|
@@ -130,6 +134,14 @@ export default {
|
|
|
130
134
|
log.error("tool registration failed", error)
|
|
131
135
|
}
|
|
132
136
|
|
|
137
|
+
// mem_forget asks before it runs, on every agent with a base allow (D17).
|
|
138
|
+
try {
|
|
139
|
+
const rules = await registerDefaultRules(ctx, log)
|
|
140
|
+
if (typeof rules?.dispose === "function") disposers.push(() => rules.dispose())
|
|
141
|
+
} catch (error) {
|
|
142
|
+
log.error("default permission rules failed", error)
|
|
143
|
+
}
|
|
144
|
+
|
|
133
145
|
// Memory's views in Jelly call this RPC. It registers even while memory is
|
|
134
146
|
// unavailable, so the views can say why and what to do.
|
|
135
147
|
try {
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The plugin's own default permission rules: `mem_forget` asks before it runs
|
|
3
|
+
* (D17, "Forget asks"). Forgetting deletes, and a delete cannot be undone, so it
|
|
4
|
+
* asks in every space; the other tools run as the agent's rules let them.
|
|
5
|
+
*
|
|
6
|
+
* The engine consults a rule on a plugin tool's id only when the tool asserts
|
|
7
|
+
* it, so `mem_forget` asserts `mem_forget` before it deletes
|
|
8
|
+
* (`src/tools/memory.js`); this rule and Jelly's declared `ask` decide what
|
|
9
|
+
* that assertion does. A preview (`match` without `confirm`) asserts nothing.
|
|
10
|
+
*
|
|
11
|
+
* OpenCode evaluates an agent's rules last match first. The rule goes right
|
|
12
|
+
* after the agent's base "allow everything" rule, so everything later still
|
|
13
|
+
* wins: the agent's own stricter rules, the person's `permission` config, and
|
|
14
|
+
* an "always" answer. An agent with no base allow (each of Jelly's agents) is
|
|
15
|
+
* left alone: Jelly writes the declared `effect: "ask"` in `package.json` as
|
|
16
|
+
* the tool's default instead, and `test/jelly.test.js` holds the two equal.
|
|
17
|
+
*
|
|
18
|
+
* A team-visible forget still asserts `memory.forget` with its row ids
|
|
19
|
+
* (`src/tools/memory.js`), so the person sees which shared rows go; that is
|
|
20
|
+
* the risk that depends on the space, and `jelly.asks` names it.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/** @typedef {{ action: string, resource: string, effect: "allow" | "ask" | "deny" }} Rule */
|
|
24
|
+
|
|
25
|
+
/** @type {readonly Rule[]} */
|
|
26
|
+
export const DEFAULT_RULES = Object.freeze([Object.freeze({ action: "mem_forget", resource: "*", effect: "ask" })])
|
|
27
|
+
|
|
28
|
+
const BASE_ALLOW = { action: "*", resource: "*", effect: "allow" }
|
|
29
|
+
const same = (a, b) => a?.action === b.action && a?.resource === b.resource && a?.effect === b.effect
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Insert `rules` right after the agent's base allow, once. Returns whether it
|
|
33
|
+
* inserted: an agent with no base allow, or that already carries the rules
|
|
34
|
+
* after it, is left as it is.
|
|
35
|
+
*
|
|
36
|
+
* @param {Rule[]} permissions
|
|
37
|
+
* @param {readonly Rule[]} [rules]
|
|
38
|
+
*/
|
|
39
|
+
export function insertRules(permissions, rules = DEFAULT_RULES) {
|
|
40
|
+
if (!Array.isArray(permissions)) return false
|
|
41
|
+
const base = permissions.findIndex((rule) => same(rule, BASE_ALLOW))
|
|
42
|
+
if (base === -1) return false
|
|
43
|
+
if (rules.every((wanted) => permissions.some((rule, index) => index > base && same(rule, wanted)))) return false
|
|
44
|
+
permissions.splice(base + 1, 0, ...rules.map((rule) => ({ ...rule })))
|
|
45
|
+
return true
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Register the rules for every agent the host builds. A host without
|
|
50
|
+
* `agent.transform` (before OpenCode 2.2) gets none, and the log says so:
|
|
51
|
+
* there `mem_forget` runs as the agent's rules let it.
|
|
52
|
+
*
|
|
53
|
+
* @returns {Promise<{ dispose?: () => unknown } | undefined>}
|
|
54
|
+
*/
|
|
55
|
+
export async function registerDefaultRules(ctx, log) {
|
|
56
|
+
if (typeof ctx?.agent?.transform !== "function") {
|
|
57
|
+
log?.warn?.("this host cannot add default permission rules, so mem_forget runs without asking unless a permission rule says otherwise")
|
|
58
|
+
return undefined
|
|
59
|
+
}
|
|
60
|
+
return ctx.agent.transform((editor) => {
|
|
61
|
+
try {
|
|
62
|
+
for (const { id } of editor.list()) editor.update(id, (agent) => void insertRules(agent.permissions))
|
|
63
|
+
} catch (error) {
|
|
64
|
+
log?.warn?.("default permission rules could not be added, so mem_forget may run without asking", error)
|
|
65
|
+
}
|
|
66
|
+
})
|
|
67
|
+
}
|
package/src/runtime.js
CHANGED
|
@@ -4,7 +4,7 @@ import { createClock } from "./config.js"
|
|
|
4
4
|
import { dayIn, dueSection } from "./records.js"
|
|
5
5
|
import { createRecordsStore } from "./records-store.js"
|
|
6
6
|
import { buildCheckpoint, checkpointFingerprint } from "./compaction.js"
|
|
7
|
-
import { credentialLine, unavailableReason } from "./credentials.js"
|
|
7
|
+
import { UNLINKED_SENTENCE, asSession, credentialLine, unavailableReason } from "./credentials.js"
|
|
8
8
|
import { createControlClient } from "./spaces.js"
|
|
9
9
|
import { createSkillContexts } from "./skill-contexts.js"
|
|
10
10
|
import { createSpool } from "./spool.js"
|
|
@@ -100,14 +100,34 @@ export function createRuntime(input) {
|
|
|
100
100
|
* One sentence saying why memory is unavailable, or "" when it is. Only a
|
|
101
101
|
* gateway deployment needs a credential and an address; local direct mode
|
|
102
102
|
* never reports itself unavailable here.
|
|
103
|
+
*
|
|
104
|
+
* It answers for the session the current work runs in (`asSession`): a
|
|
105
|
+
* session whose speaker Jelly said has no Jelly account linked on this host
|
|
106
|
+
* gets `UNLINKED_SENTENCE` while the refusal is held. Synchronous, so it
|
|
107
|
+
* knows only what Jelly already answered; `availability` asks first.
|
|
103
108
|
*/
|
|
104
109
|
function unavailable() {
|
|
105
110
|
if (!control || !credentials) return ""
|
|
106
|
-
|
|
111
|
+
const reason = unavailableReason({
|
|
107
112
|
source: credentials.source(),
|
|
108
113
|
controlURL: config.controlURL,
|
|
109
114
|
inJelly: credentials.inJelly(),
|
|
110
115
|
})
|
|
116
|
+
if (reason) return reason
|
|
117
|
+
return credentials.unlinked?.() ? UNLINKED_SENTENCE : ""
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* `unavailable()` for the current session after asking Jelly for its token
|
|
122
|
+
* when nothing is cached or held for it: the tools, the commands and the
|
|
123
|
+
* capture call this before they act, so an unlinked speaker's session is
|
|
124
|
+
* known before anything is sent or spooled.
|
|
125
|
+
*/
|
|
126
|
+
async function availability() {
|
|
127
|
+
const reason = unavailable()
|
|
128
|
+
if (reason || !control || !credentials?.check) return reason
|
|
129
|
+
await credentials.check()
|
|
130
|
+
return unavailable()
|
|
111
131
|
}
|
|
112
132
|
|
|
113
133
|
/**
|
|
@@ -478,7 +498,9 @@ export function createRuntime(input) {
|
|
|
478
498
|
if (attempted && attempted.signature === signature && Date.now() - attempted.at < SKILL_BIND_RETRY_MS) return
|
|
479
499
|
if (skillMirror.inflight) return
|
|
480
500
|
skillMirror.attempts.set(spaceID, { signature, at: Date.now() })
|
|
481
|
-
|
|
501
|
+
// The mirror serves every session of the engine: it is work with no
|
|
502
|
+
// session, never one speaker's (src/credentials.js).
|
|
503
|
+
queueMicrotask(() => asSession("", () => {
|
|
482
504
|
if (skillMirror.inflight) return
|
|
483
505
|
skillMirror.inflight = Promise.resolve()
|
|
484
506
|
.then(() => api.refreshSkills({ reason: "session-bind", context, timeoutMs: SKILL_BIND_TIMEOUT_MS }))
|
|
@@ -486,7 +508,7 @@ export function createRuntime(input) {
|
|
|
486
508
|
.finally(() => {
|
|
487
509
|
skillMirror.inflight = null
|
|
488
510
|
})
|
|
489
|
-
})
|
|
511
|
+
}))
|
|
490
512
|
}
|
|
491
513
|
|
|
492
514
|
/**
|
|
@@ -689,13 +711,21 @@ export function createRuntime(input) {
|
|
|
689
711
|
* `reason` says why nothing was written: no-session, disabled, unavailable, subagent,
|
|
690
712
|
* context-unresolved, no-context, empty, duplicate, or write-failed.
|
|
691
713
|
*/
|
|
692
|
-
|
|
714
|
+
function writeCompactionCheckpoint(input = {}) {
|
|
715
|
+
// As the session compacting: its token, or nothing when its speaker has
|
|
716
|
+
// no Jelly account linked on this host.
|
|
717
|
+
return asSession(input?.sessionID, () => writeCheckpoint(input))
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
async function writeCheckpoint(input) {
|
|
693
721
|
if (!input || typeof input !== "object") input = {}
|
|
694
722
|
const sessionID = input.sessionID ? String(input.sessionID) : ""
|
|
695
723
|
const skipped = (reason) => ({ ok: false, chars: 0, sessionID, reason })
|
|
696
724
|
if (!sessionID) return skipped("no-session")
|
|
697
725
|
if (config.compactionCheckpoint === false) return skipped("disabled")
|
|
698
|
-
|
|
726
|
+
// As the session compacting: its token, or nothing when its speaker has
|
|
727
|
+
// no Jelly account linked on this host.
|
|
728
|
+
if (await availability()) return skipped("unavailable")
|
|
699
729
|
if (skipsSubagent(sessionID)) return skipped("subagent")
|
|
700
730
|
|
|
701
731
|
const timeoutMs =
|
|
@@ -789,7 +819,33 @@ export function createRuntime(input) {
|
|
|
789
819
|
}
|
|
790
820
|
}
|
|
791
821
|
|
|
792
|
-
const spool = createSpool({
|
|
822
|
+
const spool = createSpool({
|
|
823
|
+
config,
|
|
824
|
+
log,
|
|
825
|
+
backend,
|
|
826
|
+
captureTurn: gatewayCapture ? captureTurn : null,
|
|
827
|
+
now,
|
|
828
|
+
// The account the current session's token names, recorded with an entry,
|
|
829
|
+
// and checked again before its replay (src/spool.js).
|
|
830
|
+
subject: () => credentials?.subject?.() ?? "",
|
|
831
|
+
speaker: async () => {
|
|
832
|
+
if (!credentials?.check) return ""
|
|
833
|
+
await credentials.check()
|
|
834
|
+
return credentials.subject()
|
|
835
|
+
},
|
|
836
|
+
})
|
|
837
|
+
|
|
838
|
+
/** A new user message in a session: its Jelly token is asked for again (src/credentials.js `userTurn`). */
|
|
839
|
+
function userTurn(sessionID, messageID) {
|
|
840
|
+
credentials?.userTurn?.(sessionID, messageID)
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
/** Drop what is kept for a session OpenCode deleted: its credential, pinned block and context. */
|
|
844
|
+
function forgetSession(sessionID) {
|
|
845
|
+
if (!sessionID) return
|
|
846
|
+
credentials?.forget?.(sessionID)
|
|
847
|
+
invalidate(sessionID)
|
|
848
|
+
}
|
|
793
849
|
let lastDrain = 0
|
|
794
850
|
|
|
795
851
|
/**
|
|
@@ -860,6 +916,9 @@ export function createRuntime(input) {
|
|
|
860
916
|
today,
|
|
861
917
|
credentials,
|
|
862
918
|
unavailable,
|
|
919
|
+
availability,
|
|
920
|
+
userTurn,
|
|
921
|
+
forgetSession,
|
|
863
922
|
scope,
|
|
864
923
|
scopeFor,
|
|
865
924
|
sharedScope,
|
package/src/skills.js
CHANGED
|
@@ -3,7 +3,7 @@ import path from "node:path"
|
|
|
3
3
|
import { fileURLToPath } from "node:url"
|
|
4
4
|
import { slug, oneLine, shortHash } from "./util.js"
|
|
5
5
|
|
|
6
|
-
const BUILTIN_SKILL_PATH = fileURLToPath(new URL("../skills/mem
|
|
6
|
+
const BUILTIN_SKILL_PATH = fileURLToPath(new URL("../skills/mem.usage/SKILL.md", import.meta.url))
|
|
7
7
|
const MAX_SKILLS = 24
|
|
8
8
|
|
|
9
9
|
/**
|