ever-opencode 0.0.0-stage → 0.2.0
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/LICENSE +203 -0
- package/README.md +240 -2
- package/dist/everos.d.ts +72 -0
- package/dist/everos.js +118 -0
- package/dist/extract.d.ts +37 -0
- package/dist/extract.js +48 -0
- package/dist/identity.d.ts +28 -0
- package/dist/identity.js +56 -0
- package/dist/index.d.ts +36 -0
- package/dist/index.js +259 -0
- package/dist/inject.d.ts +18 -0
- package/dist/inject.js +49 -0
- package/dist/log.d.ts +11 -0
- package/dist/log.js +34 -0
- package/dist/tools.d.ts +63 -0
- package/dist/tools.js +155 -0
- package/dist/types.d.ts +83 -0
- package/dist/types.js +6 -0
- package/package.json +41 -4
package/dist/extract.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transcript extraction: OpenCode session messages → EverOS messages.
|
|
3
|
+
*
|
|
4
|
+
* The transcript from `ctx.session.context({sessionID})` is a list of
|
|
5
|
+
* OpenCode `SessionMessageInfo` discriminated by `type`. We keep:
|
|
6
|
+
* - type "user": has a flat `text` field
|
|
7
|
+
* - type "assistant": `content` is a tagged-union list; keep `type:"text"`
|
|
8
|
+
* parts (skip reasoning/tool parts), joined with "\n"
|
|
9
|
+
* and skip everything else (system, synthetic, compaction, shell, skill, …).
|
|
10
|
+
*
|
|
11
|
+
* Offset tracking: the caller passes in the number of transcript entries
|
|
12
|
+
* already consumed (cursor), we return only NEW messages plus the updated
|
|
13
|
+
* cursor. The transcript is append-ordered by creation time, so the index
|
|
14
|
+
* cursor is stable. The cursor is passed in/out and never stored here.
|
|
15
|
+
*/
|
|
16
|
+
function joinedText(msg) {
|
|
17
|
+
if (msg.type === "user") {
|
|
18
|
+
return typeof msg.text === "string" ? msg.text : "";
|
|
19
|
+
}
|
|
20
|
+
// assistant: join text parts only
|
|
21
|
+
const parts = Array.isArray(msg.content) ? msg.content : [];
|
|
22
|
+
return parts
|
|
23
|
+
.filter((p) => p.type === "text" && typeof p.text === "string")
|
|
24
|
+
.map((p) => p.text)
|
|
25
|
+
.join("\n");
|
|
26
|
+
}
|
|
27
|
+
export function extractTranscript(transcript, offset, opts = {}) {
|
|
28
|
+
// Defensive: sort by creation time (append order is normally already stable).
|
|
29
|
+
const sorted = [...transcript].sort((a, b) => (a.time?.created ?? 0) - (b.time?.created ?? 0));
|
|
30
|
+
const start = Math.max(0, Math.floor(offset));
|
|
31
|
+
const fresh = start >= sorted.length ? [] : sorted.slice(start);
|
|
32
|
+
const messages = [];
|
|
33
|
+
for (const msg of fresh) {
|
|
34
|
+
if (msg.type !== "user" && msg.type !== "assistant")
|
|
35
|
+
continue;
|
|
36
|
+
const content = joinedText(msg).trim();
|
|
37
|
+
if (content.length === 0)
|
|
38
|
+
continue;
|
|
39
|
+
messages.push({
|
|
40
|
+
sender_id: msg.type === "user" ? (opts.senderId ?? "user") : "assistant",
|
|
41
|
+
role: msg.type === "user" ? "user" : "assistant",
|
|
42
|
+
// OpenCode stores message times as epoch milliseconds.
|
|
43
|
+
timestamp: msg.time?.created ?? Date.now(),
|
|
44
|
+
content,
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
return { messages, offset: sorted.length };
|
|
48
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Identity / scoping resolution.
|
|
3
|
+
*
|
|
4
|
+
* - app_id: EVEROS_APP_ID env, else "opencode"
|
|
5
|
+
* - project_id: slug(basename of ctx.location.project.directory). The V2 SDK
|
|
6
|
+
* exposes no git remote URL (VcsInfo is only {provider, branch}),
|
|
7
|
+
* so the "owner-repo" idea from the plan collapses to the
|
|
8
|
+
* directory basename.
|
|
9
|
+
* - user_id: EVEROS_USER_ID env → process.env.USER → os.userInfo().username
|
|
10
|
+
* - session_id: the OpenCode sessionID (≤128 chars, matches EverOS charset)
|
|
11
|
+
*/
|
|
12
|
+
import type { PluginContext } from "./types.js";
|
|
13
|
+
export interface Identity {
|
|
14
|
+
appId: string;
|
|
15
|
+
projectId: string;
|
|
16
|
+
userId: string;
|
|
17
|
+
sessionId: string;
|
|
18
|
+
}
|
|
19
|
+
/** EverOS ScopeIds charset: ^[a-zA-Z0-9_.-]+$ */
|
|
20
|
+
export declare function slugify(input: string): string;
|
|
21
|
+
export declare function resolveIdentity(ctx: PluginContext): Identity;
|
|
22
|
+
export declare function withSession(identity: Omit<Identity, "sessionId">, sessionID: string): Identity;
|
|
23
|
+
export declare function resolveScope(ctx: PluginContext, sessionID: string): Promise<{
|
|
24
|
+
appId: string;
|
|
25
|
+
projectId: string;
|
|
26
|
+
userId: string;
|
|
27
|
+
sessionId: string;
|
|
28
|
+
}>;
|
package/dist/identity.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Identity / scoping resolution.
|
|
3
|
+
*
|
|
4
|
+
* - app_id: EVEROS_APP_ID env, else "opencode"
|
|
5
|
+
* - project_id: slug(basename of ctx.location.project.directory). The V2 SDK
|
|
6
|
+
* exposes no git remote URL (VcsInfo is only {provider, branch}),
|
|
7
|
+
* so the "owner-repo" idea from the plan collapses to the
|
|
8
|
+
* directory basename.
|
|
9
|
+
* - user_id: EVEROS_USER_ID env → process.env.USER → os.userInfo().username
|
|
10
|
+
* - session_id: the OpenCode sessionID (≤128 chars, matches EverOS charset)
|
|
11
|
+
*/
|
|
12
|
+
import * as nodeOs from "node:os";
|
|
13
|
+
import * as nodePath from "node:path";
|
|
14
|
+
/** EverOS ScopeIds charset: ^[a-zA-Z0-9_.-]+$ */
|
|
15
|
+
export function slugify(input) {
|
|
16
|
+
const slug = input
|
|
17
|
+
.trim()
|
|
18
|
+
.toLowerCase()
|
|
19
|
+
.replace(/[^a-z0-9_.-]+/g, "-")
|
|
20
|
+
.replace(/^[-.]+|[-.]+$/g, "")
|
|
21
|
+
.slice(0, 64);
|
|
22
|
+
return slug.length > 0 ? slug : "project";
|
|
23
|
+
}
|
|
24
|
+
function resolveUserId() {
|
|
25
|
+
const env = process.env.EVEROS_USER_ID;
|
|
26
|
+
if (env && env.trim().length > 0)
|
|
27
|
+
return env.trim();
|
|
28
|
+
const fromEnvUser = process.env.USER;
|
|
29
|
+
if (fromEnvUser && fromEnvUser.trim().length > 0)
|
|
30
|
+
return fromEnvUser.trim();
|
|
31
|
+
try {
|
|
32
|
+
return nodeOs.userInfo().username;
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return "unknown";
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
export function resolveIdentity(ctx) {
|
|
39
|
+
const appId = process.env.EVEROS_APP_ID?.trim() || "opencode";
|
|
40
|
+
const directory = ctx.location?.project?.directory ?? "";
|
|
41
|
+
const base = nodePath.basename(directory);
|
|
42
|
+
const projectId = slugify(base);
|
|
43
|
+
return {
|
|
44
|
+
appId,
|
|
45
|
+
projectId,
|
|
46
|
+
userId: resolveUserId(),
|
|
47
|
+
sessionId: "",
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
export function withSession(identity, sessionID) {
|
|
51
|
+
return { ...identity, sessionId: sessionID.slice(0, 128) };
|
|
52
|
+
}
|
|
53
|
+
export async function resolveScope(ctx, sessionID) {
|
|
54
|
+
const id = resolveIdentity(ctx);
|
|
55
|
+
return withSession(id, sessionID);
|
|
56
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* everos-opencode — persistent memory plugin for OpenCode V2.
|
|
3
|
+
*
|
|
4
|
+
* Zero agent discipline: capture each turn (fire-and-forget, deferred
|
|
5
|
+
* extraction), flush on the Nth capture and before compaction, and inject
|
|
6
|
+
* recall into future turns via the `context` hook. The plugin is LLM-free:
|
|
7
|
+
* it only talks HTTP to a local EverOS server; extraction runs server-side.
|
|
8
|
+
*
|
|
9
|
+
* Capture trigger (verified against @opencode/plugin 2.2.5 + @opencode/client
|
|
10
|
+
* generated event types): the V2 event stream has NO "message.*" events. The
|
|
11
|
+
* assistant-completion event is `session.text.ended`
|
|
12
|
+
* (data: {sessionID, assistantMessageID, ordinal, text}); we subscribe to it
|
|
13
|
+
* and re-read the full session transcript each time, letting the offset
|
|
14
|
+
* cursor emit only NEW messages. `session.step.ended` / `session.idle` also
|
|
15
|
+
* exist but fire less precisely per completed text.
|
|
16
|
+
*/
|
|
17
|
+
import type { PluginContext } from "./types.js";
|
|
18
|
+
export declare const storageKeys: {
|
|
19
|
+
offset: (sessionID: string) => string;
|
|
20
|
+
captures: (sessionID: string) => string;
|
|
21
|
+
degraded: (sessionID: string) => string;
|
|
22
|
+
recall: (sessionID: string, userMessageID: string) => string;
|
|
23
|
+
};
|
|
24
|
+
export declare function setupPlugin(rawCtx: PluginContext): Promise<() => void>;
|
|
25
|
+
export type { EverosOptions, PluginContext } from "./types.js";
|
|
26
|
+
export type { EverosEpisode, EverosMessage, EverosError } from "./everos.js";
|
|
27
|
+
export { EverosClient } from "./everos.js";
|
|
28
|
+
export { extractTranscript } from "./extract.js";
|
|
29
|
+
export { formatRecall, formatEpisodeLines } from "./inject.js";
|
|
30
|
+
export { buildTools, everosToolNames, registerTools } from "./tools.js";
|
|
31
|
+
export { slugify, resolveIdentity } from "./identity.js";
|
|
32
|
+
declare const _default: {
|
|
33
|
+
id: string;
|
|
34
|
+
setup: (ctx: unknown) => Promise<() => void>;
|
|
35
|
+
};
|
|
36
|
+
export default _default;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* everos-opencode — persistent memory plugin for OpenCode V2.
|
|
3
|
+
*
|
|
4
|
+
* Zero agent discipline: capture each turn (fire-and-forget, deferred
|
|
5
|
+
* extraction), flush on the Nth capture and before compaction, and inject
|
|
6
|
+
* recall into future turns via the `context` hook. The plugin is LLM-free:
|
|
7
|
+
* it only talks HTTP to a local EverOS server; extraction runs server-side.
|
|
8
|
+
*
|
|
9
|
+
* Capture trigger (verified against @opencode/plugin 2.2.5 + @opencode/client
|
|
10
|
+
* generated event types): the V2 event stream has NO "message.*" events. The
|
|
11
|
+
* assistant-completion event is `session.text.ended`
|
|
12
|
+
* (data: {sessionID, assistantMessageID, ordinal, text}); we subscribe to it
|
|
13
|
+
* and re-read the full session transcript each time, letting the offset
|
|
14
|
+
* cursor emit only NEW messages. `session.step.ended` / `session.idle` also
|
|
15
|
+
* exist but fire less precisely per completed text.
|
|
16
|
+
*/
|
|
17
|
+
import { EverosClient, EverosError } from "./everos.js";
|
|
18
|
+
import { extractTranscript } from "./extract.js";
|
|
19
|
+
import { formatRecall } from "./inject.js";
|
|
20
|
+
import { resolveScope } from "./identity.js";
|
|
21
|
+
import { Logger } from "./log.js";
|
|
22
|
+
import { registerTools } from "./tools.js";
|
|
23
|
+
const DEFAULTS = {
|
|
24
|
+
everosUrl: "http://127.0.0.1:8000",
|
|
25
|
+
flushEvery: 3,
|
|
26
|
+
topK: 5,
|
|
27
|
+
recallMethod: "keyword",
|
|
28
|
+
enabled: true,
|
|
29
|
+
logLevel: "info",
|
|
30
|
+
};
|
|
31
|
+
function resolveConfig(options) {
|
|
32
|
+
// Precedence: explicit option > env > default.
|
|
33
|
+
const url = options.everosUrl ?? process.env.EVEROS_URL ?? DEFAULTS.everosUrl;
|
|
34
|
+
return {
|
|
35
|
+
everosUrl: url,
|
|
36
|
+
flushEvery: clampInt(options.flushEvery, DEFAULTS.flushEvery, 1),
|
|
37
|
+
topK: clampInt(options.topK, DEFAULTS.topK, 1),
|
|
38
|
+
recallMethod: options.recallMethod ?? DEFAULTS.recallMethod,
|
|
39
|
+
enabled: options.enabled ?? DEFAULTS.enabled,
|
|
40
|
+
logLevel: (options.logLevel ?? DEFAULTS.logLevel),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
function clampInt(raw, fallback, min) {
|
|
44
|
+
const n = typeof raw === "number" ? raw : Number.NaN;
|
|
45
|
+
return Number.isFinite(n) && n >= min ? Math.floor(n) : fallback;
|
|
46
|
+
}
|
|
47
|
+
export const storageKeys = {
|
|
48
|
+
offset: (sessionID) => `everos:offset:${sessionID}`,
|
|
49
|
+
captures: (sessionID) => `everos:captures:${sessionID}`,
|
|
50
|
+
degraded: (sessionID) => `everos:degraded:${sessionID}`,
|
|
51
|
+
recall: (sessionID, userMessageID) => `everos:recall:${sessionID}:${userMessageID}`,
|
|
52
|
+
};
|
|
53
|
+
export async function setupPlugin(rawCtx) {
|
|
54
|
+
const config = resolveConfig(rawCtx.options);
|
|
55
|
+
const log = new Logger(config.logLevel);
|
|
56
|
+
// Core plugin state. `null` when disabled — hooks become no-ops.
|
|
57
|
+
let core = null;
|
|
58
|
+
if (config.enabled) {
|
|
59
|
+
const client = new EverosClient(config.everosUrl);
|
|
60
|
+
const scopeBase = await resolveScope(rawCtx, "");
|
|
61
|
+
core = { ctx: rawCtx, client, scopeBase };
|
|
62
|
+
}
|
|
63
|
+
/** Mark a session degraded (connection refused / timeout), log once. */
|
|
64
|
+
const markDegraded = async (sessionID, err) => {
|
|
65
|
+
const key = storageKeys.degraded(sessionID);
|
|
66
|
+
const already = await rawCtx.storage.get(key);
|
|
67
|
+
if (!already) {
|
|
68
|
+
await rawCtx.storage.set(key, true);
|
|
69
|
+
const detail = err instanceof EverosError ? `${err.code}: ${err.message}` : String(err);
|
|
70
|
+
log.error(`degraded:${sessionID}`, `server unreachable, session degraded (will retry): ${detail}`);
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
const withTimeoutGuard = async (fn, sessionID) => {
|
|
74
|
+
try {
|
|
75
|
+
await fn();
|
|
76
|
+
}
|
|
77
|
+
catch (err) {
|
|
78
|
+
await markDegraded(sessionID, err);
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
// ---- Recall injection -------------------------------------------------
|
|
82
|
+
const recallRegistration = await rawCtx.session.hook("context", async (input) => {
|
|
83
|
+
try {
|
|
84
|
+
if (!core || !config.enabled)
|
|
85
|
+
return;
|
|
86
|
+
const sessionID = input.sessionID;
|
|
87
|
+
// Dedupe per user message: the context hook fires on every model call,
|
|
88
|
+
// so the same user turn would otherwise trigger a search per call.
|
|
89
|
+
// The context hook delivers daemon messages ({id, role, content}),
|
|
90
|
+
// while ctx.session.context delivers {id, type, text}. Read both.
|
|
91
|
+
const messages = Array.isArray(input.messages) ? input.messages : [];
|
|
92
|
+
const roleOf = (m) => (typeof m?.role === "string" ? m.role : m?.type);
|
|
93
|
+
const textOf = (m) => {
|
|
94
|
+
if (typeof m?.text === "string")
|
|
95
|
+
return m.text;
|
|
96
|
+
if (typeof m?.content === "string")
|
|
97
|
+
return m.content;
|
|
98
|
+
if (Array.isArray(m?.content)) {
|
|
99
|
+
return m.content
|
|
100
|
+
.filter((p) => p?.type === "text" && typeof p.text === "string")
|
|
101
|
+
.map((p) => p.text)
|
|
102
|
+
.join("\n");
|
|
103
|
+
}
|
|
104
|
+
return "";
|
|
105
|
+
};
|
|
106
|
+
const isUser = (m) => roleOf(m) === "user";
|
|
107
|
+
const lastUser = [...messages].reverse().find(isUser);
|
|
108
|
+
const userKey = typeof lastUser?.id === "string" ? lastUser.id : `noid:${messages.length}`;
|
|
109
|
+
const dedupeKey = storageKeys.recall(sessionID, userKey);
|
|
110
|
+
if (await rawCtx.storage.get(dedupeKey))
|
|
111
|
+
return;
|
|
112
|
+
await rawCtx.storage.set(dedupeKey, true);
|
|
113
|
+
const query = messages
|
|
114
|
+
.filter(isUser)
|
|
115
|
+
.map(textOf)
|
|
116
|
+
.filter((t) => t.trim().length > 0)
|
|
117
|
+
.slice(-3)
|
|
118
|
+
.join(" ")
|
|
119
|
+
.slice(0, 2000);
|
|
120
|
+
if (query.trim().length === 0)
|
|
121
|
+
return;
|
|
122
|
+
const degraded = await rawCtx.storage.get(storageKeys.degraded(sessionID));
|
|
123
|
+
if (degraded)
|
|
124
|
+
return;
|
|
125
|
+
let episodes;
|
|
126
|
+
try {
|
|
127
|
+
episodes = await core.client.searchMemories(core.scopeBase.userId, query, {
|
|
128
|
+
method: config.recallMethod,
|
|
129
|
+
topK: config.topK,
|
|
130
|
+
scope: { appId: core.scopeBase.appId, projectId: core.scopeBase.projectId },
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
catch (err) {
|
|
134
|
+
await markDegraded(sessionID, err);
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
const block = formatRecall(episodes, { topK: config.topK });
|
|
138
|
+
if (block.length === 0)
|
|
139
|
+
return;
|
|
140
|
+
const system = Array.isArray(input.system) ? input.system : [];
|
|
141
|
+
system.push({ type: "text", text: block });
|
|
142
|
+
}
|
|
143
|
+
catch (err) {
|
|
144
|
+
// Never let recall break the turn.
|
|
145
|
+
log.debug(`recall error: ${err instanceof Error ? err.message : String(err)}`);
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
// ---- Capture ----------------------------------------------------------
|
|
149
|
+
const captureOnce = async (sessionID) => {
|
|
150
|
+
if (!core)
|
|
151
|
+
return;
|
|
152
|
+
await withTimeoutGuard(async () => {
|
|
153
|
+
const transcript = (await core.ctx.session.context({ sessionID }));
|
|
154
|
+
const offsetRaw = await rawCtx.storage.get(storageKeys.offset(sessionID));
|
|
155
|
+
const offset = typeof offsetRaw === "number" ? offsetRaw : 0;
|
|
156
|
+
const { messages, offset: nextOffset } = extractTranscript(transcript, offset, {
|
|
157
|
+
senderId: core.scopeBase.userId,
|
|
158
|
+
});
|
|
159
|
+
await rawCtx.storage.set(storageKeys.offset(sessionID), nextOffset);
|
|
160
|
+
if (messages.length === 0)
|
|
161
|
+
return;
|
|
162
|
+
const scope = {
|
|
163
|
+
session_id: sessionID.slice(0, 128),
|
|
164
|
+
app_id: core.scopeBase.appId,
|
|
165
|
+
project_id: core.scopeBase.projectId,
|
|
166
|
+
};
|
|
167
|
+
// Deferred extraction: buffered server-side, no LLM at capture time.
|
|
168
|
+
await core.client.addMemory(scope, messages, { deferExtraction: true });
|
|
169
|
+
const capturesRaw = await rawCtx.storage.get(storageKeys.captures(sessionID));
|
|
170
|
+
const captures = (typeof capturesRaw === "number" ? capturesRaw : 0) + 1;
|
|
171
|
+
await rawCtx.storage.set(storageKeys.captures(sessionID), captures);
|
|
172
|
+
if (captures % config.flushEvery === 0) {
|
|
173
|
+
await core.client.flushMemory(scope);
|
|
174
|
+
log.debug(`flushed after ${captures} captures (${sessionID})`);
|
|
175
|
+
}
|
|
176
|
+
}, sessionID);
|
|
177
|
+
};
|
|
178
|
+
// Serialize captures per session: events can arrive while a previous
|
|
179
|
+
// capture is still in flight, and concurrent reads of the offset cursor
|
|
180
|
+
// would double-capture the same messages.
|
|
181
|
+
const captureQueues = new Map();
|
|
182
|
+
// Fire-and-forget: the event subscription handler must never block turn end.
|
|
183
|
+
const enqueueCapture = (sessionID) => {
|
|
184
|
+
const prev = captureQueues.get(sessionID) ?? Promise.resolve();
|
|
185
|
+
const next = prev
|
|
186
|
+
.then(() => captureOnce(sessionID))
|
|
187
|
+
.catch(() => {
|
|
188
|
+
/* degraded latch handles reporting */
|
|
189
|
+
});
|
|
190
|
+
captureQueues.set(sessionID, next);
|
|
191
|
+
};
|
|
192
|
+
const controller = new AbortController();
|
|
193
|
+
const consumeEvents = async () => {
|
|
194
|
+
try {
|
|
195
|
+
const stream = rawCtx.event.subscribe({
|
|
196
|
+
types: ["session.text.ended"],
|
|
197
|
+
signal: controller.signal,
|
|
198
|
+
});
|
|
199
|
+
for await (const ev of stream) {
|
|
200
|
+
if (controller.signal.aborted)
|
|
201
|
+
break;
|
|
202
|
+
const sessionID = ev?.data?.sessionID;
|
|
203
|
+
if (typeof sessionID !== "string" || sessionID.length === 0)
|
|
204
|
+
continue;
|
|
205
|
+
enqueueCapture(sessionID);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
catch (err) {
|
|
209
|
+
if (!controller.signal.aborted) {
|
|
210
|
+
log.debug(`event subscription error: ${err instanceof Error ? err.message : String(err)}`);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
void consumeEvents();
|
|
215
|
+
// ---- Flush before compaction -----------------------------------------
|
|
216
|
+
const compactionRegistration = await rawCtx.session.hook("compaction", async (input) => {
|
|
217
|
+
if (!core)
|
|
218
|
+
return;
|
|
219
|
+
const sessionID = input.sessionID;
|
|
220
|
+
await withTimeoutGuard(async () => {
|
|
221
|
+
const scope = {
|
|
222
|
+
session_id: sessionID.slice(0, 128),
|
|
223
|
+
app_id: core.scopeBase.appId,
|
|
224
|
+
project_id: core.scopeBase.projectId,
|
|
225
|
+
};
|
|
226
|
+
await core.client.flushMemory(scope);
|
|
227
|
+
log.debug(`flushed before compaction (${sessionID})`);
|
|
228
|
+
}, sessionID);
|
|
229
|
+
});
|
|
230
|
+
// ---- Agent tools (everos_search / everos_add / everos_flush) ----------
|
|
231
|
+
// Optional domain: hosts without ctx.tool simply get no tools.
|
|
232
|
+
const toolsRegistration = core
|
|
233
|
+
? await registerTools(rawCtx, {
|
|
234
|
+
client: core.client,
|
|
235
|
+
scopeBase: core.scopeBase,
|
|
236
|
+
recallMethod: config.recallMethod,
|
|
237
|
+
defaultTopK: config.topK,
|
|
238
|
+
log,
|
|
239
|
+
})
|
|
240
|
+
: undefined;
|
|
241
|
+
// ---- Cleanup ----------------------------------------------------------
|
|
242
|
+
return () => {
|
|
243
|
+
controller.abort();
|
|
244
|
+
void recallRegistration.dispose();
|
|
245
|
+
void compactionRegistration.dispose();
|
|
246
|
+
void toolsRegistration?.dispose();
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
export { EverosClient } from "./everos.js";
|
|
250
|
+
export { extractTranscript } from "./extract.js";
|
|
251
|
+
export { formatRecall, formatEpisodeLines } from "./inject.js";
|
|
252
|
+
export { buildTools, everosToolNames, registerTools } from "./tools.js";
|
|
253
|
+
export { slugify, resolveIdentity } from "./identity.js";
|
|
254
|
+
export default {
|
|
255
|
+
// Matches the V2 plugin object contract ({ id, setup }); kept structural so
|
|
256
|
+
// this module imports cleanly without the heavy SDK runtime in tests.
|
|
257
|
+
id: "everos-opencode",
|
|
258
|
+
setup: (ctx) => setupPlugin(ctx),
|
|
259
|
+
};
|
package/dist/inject.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Recall formatting: EverOS episodes → compact system-prompt block.
|
|
3
|
+
* Empty input yields "" (caller skips injection entirely).
|
|
4
|
+
*/
|
|
5
|
+
import type { EverosEpisode } from "./everos.js";
|
|
6
|
+
/**
|
|
7
|
+
* Render episodes as `- summary [score X (age)]` lines — the single
|
|
8
|
+
* representation shared by system-prompt recall and the agent tools.
|
|
9
|
+
* Empty input yields [].
|
|
10
|
+
*/
|
|
11
|
+
export declare function formatEpisodeLines(episodes: EverosEpisode[], opts?: {
|
|
12
|
+
topK?: number;
|
|
13
|
+
now?: number;
|
|
14
|
+
}): string[];
|
|
15
|
+
export declare function formatRecall(episodes: EverosEpisode[], opts?: {
|
|
16
|
+
topK?: number;
|
|
17
|
+
now?: number;
|
|
18
|
+
}): string;
|
package/dist/inject.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Recall formatting: EverOS episodes → compact system-prompt block.
|
|
3
|
+
* Empty input yields "" (caller skips injection entirely).
|
|
4
|
+
*/
|
|
5
|
+
function relativeDate(ts, now) {
|
|
6
|
+
if (typeof ts !== "number" || !Number.isFinite(ts) || ts <= 0)
|
|
7
|
+
return "";
|
|
8
|
+
const days = Math.floor((now - ts) / 86_400_000);
|
|
9
|
+
if (days <= 0)
|
|
10
|
+
return "today";
|
|
11
|
+
if (days === 1)
|
|
12
|
+
return "yesterday";
|
|
13
|
+
if (days < 30)
|
|
14
|
+
return `${days}d ago`;
|
|
15
|
+
const months = Math.floor(days / 30);
|
|
16
|
+
if (months < 12)
|
|
17
|
+
return `${months}mo ago`;
|
|
18
|
+
return `${Math.floor(months / 12)}y ago`;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Render episodes as `- summary [score X (age)]` lines — the single
|
|
22
|
+
* representation shared by system-prompt recall and the agent tools.
|
|
23
|
+
* Empty input yields [].
|
|
24
|
+
*/
|
|
25
|
+
export function formatEpisodeLines(episodes, opts = {}) {
|
|
26
|
+
const top = episodes
|
|
27
|
+
.slice(0, Math.max(1, opts.topK ?? 5))
|
|
28
|
+
.filter((e) => typeof e?.summary === "string" && e.summary.trim().length > 0);
|
|
29
|
+
if (top.length === 0)
|
|
30
|
+
return [];
|
|
31
|
+
const now = opts.now ?? Date.now();
|
|
32
|
+
return top.map((e) => {
|
|
33
|
+
const date = relativeDate(e.timestamp, now);
|
|
34
|
+
const score = typeof e.score === "number" ? e.score.toFixed(2) : "?";
|
|
35
|
+
const dateSuffix = date.length > 0 ? ` (${date})` : "";
|
|
36
|
+
return `- ${e.summary.trim()} [score ${score}${dateSuffix}]`;
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
export function formatRecall(episodes, opts = {}) {
|
|
40
|
+
const lines = formatEpisodeLines(episodes, opts);
|
|
41
|
+
if (lines.length === 0)
|
|
42
|
+
return "";
|
|
43
|
+
return [
|
|
44
|
+
"<everos-recall>",
|
|
45
|
+
"Relevant memories from previous sessions (may be imperfect; verify before relying on them):",
|
|
46
|
+
...lines,
|
|
47
|
+
"</everos-recall>",
|
|
48
|
+
].join("\n");
|
|
49
|
+
}
|
package/dist/log.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Once-only stderr logging, gated by log level. */
|
|
2
|
+
export type LogLevel = "debug" | "info" | "error" | "silent";
|
|
3
|
+
export declare class Logger {
|
|
4
|
+
private readonly threshold;
|
|
5
|
+
private readonly seen;
|
|
6
|
+
constructor(level?: LogLevel);
|
|
7
|
+
private emit;
|
|
8
|
+
debug(message: string): void;
|
|
9
|
+
info(key: string, message: string): void;
|
|
10
|
+
error(key: string, message: string): void;
|
|
11
|
+
}
|
package/dist/log.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** Once-only stderr logging, gated by log level. */
|
|
2
|
+
const order = {
|
|
3
|
+
debug: 10,
|
|
4
|
+
info: 20,
|
|
5
|
+
error: 30,
|
|
6
|
+
silent: 99,
|
|
7
|
+
};
|
|
8
|
+
export class Logger {
|
|
9
|
+
threshold;
|
|
10
|
+
seen = new Set();
|
|
11
|
+
constructor(level = "info") {
|
|
12
|
+
this.threshold = order[level] ?? order.info;
|
|
13
|
+
}
|
|
14
|
+
emit(level, key, message) {
|
|
15
|
+
if (order[level] < this.threshold)
|
|
16
|
+
return;
|
|
17
|
+
if (level === "info" || level === "error") {
|
|
18
|
+
// once-only latch for info/error notices (e.g. degraded latch)
|
|
19
|
+
if (this.seen.has(key))
|
|
20
|
+
return;
|
|
21
|
+
this.seen.add(key);
|
|
22
|
+
}
|
|
23
|
+
process.stderr.write(`[everos-opencode] ${message}\n`);
|
|
24
|
+
}
|
|
25
|
+
debug(message) {
|
|
26
|
+
this.emit("debug", `debug:${message}`, message);
|
|
27
|
+
}
|
|
28
|
+
info(key, message) {
|
|
29
|
+
this.emit("info", key, message);
|
|
30
|
+
}
|
|
31
|
+
error(key, message) {
|
|
32
|
+
this.emit("error", key, message);
|
|
33
|
+
}
|
|
34
|
+
}
|
package/dist/tools.d.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent-facing memory tools (OpenCode V2 `ctx.tool.transform`).
|
|
3
|
+
*
|
|
4
|
+
* The passive path (capture + recall injection) is automatic; these tools give
|
|
5
|
+
* the agent an explicit query/write surface — mirroring the mem0 plugin's
|
|
6
|
+
* tool-based memory access:
|
|
7
|
+
* everos_search — query memories on demand (BM25/vector recall server-side)
|
|
8
|
+
* everos_add — store a fact now (add + synchronous extraction via flush)
|
|
9
|
+
* everos_flush — force extraction of the session's deferred capture buffer
|
|
10
|
+
*
|
|
11
|
+
* Tool definitions are plain structural objects: `input` is a JSON Schema and
|
|
12
|
+
* `execute` returns `{content}` — no SDK runtime import, keeping the plugin
|
|
13
|
+
* unit-testable with synthetic contexts.
|
|
14
|
+
*/
|
|
15
|
+
import type { EverosClient } from "./everos.js";
|
|
16
|
+
import type { Logger } from "./log.js";
|
|
17
|
+
/** JSON-Schema-backed tool definition (structural subset of V2 Tool.Info). */
|
|
18
|
+
export interface EverosToolDef {
|
|
19
|
+
readonly name: string;
|
|
20
|
+
readonly description: string;
|
|
21
|
+
readonly input: Record<string, unknown>;
|
|
22
|
+
execute(input: unknown, context: {
|
|
23
|
+
sessionID?: string;
|
|
24
|
+
}): Promise<ToolOutput>;
|
|
25
|
+
}
|
|
26
|
+
/** Structural `Tool.Result`: the model sees `content`. */
|
|
27
|
+
export interface ToolOutput {
|
|
28
|
+
readonly content: string;
|
|
29
|
+
readonly metadata?: Record<string, unknown>;
|
|
30
|
+
}
|
|
31
|
+
export interface ToolEditorLike {
|
|
32
|
+
add(tool: EverosToolDef): void;
|
|
33
|
+
}
|
|
34
|
+
export interface ToolDomainLike {
|
|
35
|
+
transform(callback: (editor: ToolEditorLike) => void): Promise<{
|
|
36
|
+
dispose(): Promise<void> | void;
|
|
37
|
+
}>;
|
|
38
|
+
}
|
|
39
|
+
export interface ToolDeps {
|
|
40
|
+
readonly client: EverosClient;
|
|
41
|
+
/** Identity resolved at setup: stable user/app/project scope base. */
|
|
42
|
+
readonly scopeBase: {
|
|
43
|
+
userId: string;
|
|
44
|
+
appId: string;
|
|
45
|
+
projectId: string;
|
|
46
|
+
};
|
|
47
|
+
readonly recallMethod: string;
|
|
48
|
+
readonly defaultTopK: number;
|
|
49
|
+
readonly log: Logger;
|
|
50
|
+
}
|
|
51
|
+
/** All tool names this plugin registers (exported for tests/diagnostics). */
|
|
52
|
+
export declare const everosToolNames: readonly string[];
|
|
53
|
+
/** Build the tool definitions (exported for tests). */
|
|
54
|
+
export declare function buildTools(deps: ToolDeps): EverosToolDef[];
|
|
55
|
+
/**
|
|
56
|
+
* Register the tools via `ctx.tool.transform`. Returns the registration, or
|
|
57
|
+
* `undefined` when the host exposes no tool domain (older hosts / tests).
|
|
58
|
+
*/
|
|
59
|
+
export declare function registerTools(ctx: {
|
|
60
|
+
tool?: ToolDomainLike;
|
|
61
|
+
}, deps: ToolDeps): Promise<{
|
|
62
|
+
dispose(): Promise<void> | void;
|
|
63
|
+
} | undefined>;
|