humemory 0.2.1 → 0.2.3
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/AGENTS.md +9 -5
- package/CHANGELOG.md +12 -0
- package/README.md +94 -7
- package/dist/agent/claude-hook.d.ts +13 -0
- package/dist/agent/claude-hook.js +48 -5
- package/dist/agent/learning-extractor.d.ts +2 -0
- package/dist/agent/learning-extractor.js +41 -12
- package/dist/agent/maintenance-queue.d.ts +47 -0
- package/dist/agent/maintenance-queue.js +246 -0
- package/dist/agent/session-context.js +15 -4
- package/dist/agent/source-registry.d.ts +34 -0
- package/dist/agent/source-registry.js +89 -0
- package/dist/api/server.js +46 -3
- package/dist/cli/index.js +20 -1
- package/dist/core/llm-generator.d.ts +2 -1
- package/dist/core/llm-generator.js +35 -34
- package/dist/index.d.ts +6 -2
- package/dist/index.js +4 -2
- package/dist/mcp/server.js +13 -3
- package/dist/store/sqlite.js +1 -0
- package/docs/TESTING.md +3 -2
- package/package.json +7 -5
- package/public/app/{galaxy-f42190mq.js → galaxy-cgbkc6e1.js} +1 -1
- package/public/app/index-5kwkpwkp.js +2 -0
- package/public/app/index-kv9v6ty0.css +1 -0
- package/public/app/{index-f9h80bzq.js → index-nqr7bd0a.js} +9 -9
- package/public/app/index.html +1 -1
- package/public/app/{promenade-cnzzpm73.js → promenade-fa0tb6jx.js} +1 -1
- package/public/app/river-01hs4f06.js +5 -0
- package/scripts/hook-session.ts +11 -10
- package/scripts/maintenance-worker.ts +37 -0
- package/public/app/index-2cf31xxn.css +0 -1
- package/public/app/index-kvhc17mz.js +0 -2
- package/public/app/river-tyawhh8w.js +0 -13
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'crypto';
|
|
2
|
+
import { mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from 'fs/promises';
|
|
3
|
+
import { join } from 'path';
|
|
4
|
+
import { processSession } from './claude-hook.js';
|
|
5
|
+
import { parseClaudeHookPayload } from './session-parser.js';
|
|
6
|
+
const DEFAULT_LOCK_STALE_MS = 5 * 60 * 1000;
|
|
7
|
+
const DEFAULT_MAX_ATTEMPTS = 5;
|
|
8
|
+
const DEAD_LETTER_SUFFIX = '.dead.json';
|
|
9
|
+
const PROCESSING_SUFFIX = '.processing';
|
|
10
|
+
const CHECKPOINT_DIR = 'checkpoints';
|
|
11
|
+
function jobPath(queueDir, id) {
|
|
12
|
+
return join(queueDir, `${id}.json`);
|
|
13
|
+
}
|
|
14
|
+
function checkpointPath(queueDir, id) {
|
|
15
|
+
return join(queueDir, CHECKPOINT_DIR, `${id}.json`);
|
|
16
|
+
}
|
|
17
|
+
async function readCheckpoint(queueDir, id) {
|
|
18
|
+
try {
|
|
19
|
+
return JSON.parse(await readFile(checkpointPath(queueDir, id), 'utf8'));
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
async function atomicWrite(path, content) {
|
|
26
|
+
const temporary = `${path}.${process.pid}.tmp`;
|
|
27
|
+
await writeFile(temporary, content, { encoding: 'utf8', mode: 0o600 });
|
|
28
|
+
try {
|
|
29
|
+
await rename(temporary, path);
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
if (error?.code !== 'EEXIST' && error?.code !== 'EPERM')
|
|
33
|
+
throw error;
|
|
34
|
+
await rm(path, { force: true });
|
|
35
|
+
await rename(temporary, path);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
export async function enqueueSession(rawTranscript, options) {
|
|
39
|
+
const raw = rawTranscript.trim();
|
|
40
|
+
if (!raw)
|
|
41
|
+
throw new Error('Cannot queue an empty session');
|
|
42
|
+
const directory = options.directory ?? process.cwd();
|
|
43
|
+
const parsed = parseClaudeHookPayload(rawTranscript, directory);
|
|
44
|
+
const source = options.source ?? 'claude-code';
|
|
45
|
+
// Keyed on session, not transcript content: `Stop` fires once per turn and the
|
|
46
|
+
// transcript grows each time, so hashing the raw text would enqueue one job
|
|
47
|
+
// per turn instead of one per session. Re-enqueuing overwrites with the
|
|
48
|
+
// latest (fuller) transcript and resets attempts — new content, new chance.
|
|
49
|
+
const id = createHash('sha256').update(`${source}\0${parsed.sessionId}`).digest('hex');
|
|
50
|
+
const path = jobPath(options.queueDir, id);
|
|
51
|
+
const now = options.now ?? (() => new Date());
|
|
52
|
+
const job = {
|
|
53
|
+
version: 1,
|
|
54
|
+
id,
|
|
55
|
+
source,
|
|
56
|
+
agent: options.agent ?? source,
|
|
57
|
+
sessionId: parsed.sessionId,
|
|
58
|
+
directory: parsed.directory,
|
|
59
|
+
rawTranscript,
|
|
60
|
+
maxLearnings: options.maxLearnings ?? 5,
|
|
61
|
+
queuedAt: now().toISOString(),
|
|
62
|
+
attempts: 0,
|
|
63
|
+
};
|
|
64
|
+
await mkdir(options.queueDir, { recursive: true });
|
|
65
|
+
let created = true;
|
|
66
|
+
try {
|
|
67
|
+
await readFile(path, 'utf8');
|
|
68
|
+
created = false;
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
if (error?.code !== 'ENOENT')
|
|
72
|
+
throw error;
|
|
73
|
+
}
|
|
74
|
+
await atomicWrite(path, JSON.stringify(job));
|
|
75
|
+
return { job, created, path };
|
|
76
|
+
}
|
|
77
|
+
export async function processMaintenanceQueue(options) {
|
|
78
|
+
await mkdir(options.queueDir, { recursive: true });
|
|
79
|
+
await mkdir(join(options.queueDir, CHECKPOINT_DIR), { recursive: true });
|
|
80
|
+
const now = options.now ?? (() => new Date());
|
|
81
|
+
const lockPath = join(options.queueDir, '.worker.lock');
|
|
82
|
+
const token = `${process.pid}-${randomUUID()}`;
|
|
83
|
+
let lock;
|
|
84
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
85
|
+
try {
|
|
86
|
+
lock = await open(lockPath, 'wx', 0o600);
|
|
87
|
+
await lock.writeFile(JSON.stringify({ pid: process.pid, token, startedAt: now().toISOString() }));
|
|
88
|
+
break;
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
if (error?.code !== 'EEXIST')
|
|
92
|
+
throw error;
|
|
93
|
+
const age = now().getTime() - (await stat(lockPath)).mtimeMs;
|
|
94
|
+
if (attempt === 0 && age > (options.lockStaleMs ?? DEFAULT_LOCK_STALE_MS)) {
|
|
95
|
+
// Atomic takeover: renaming the stale lock away can only succeed once,
|
|
96
|
+
// so two workers seeing the same stale lock cannot both reclaim it. A
|
|
97
|
+
// plain unlink would instead delete a lock the winner just acquired.
|
|
98
|
+
try {
|
|
99
|
+
await rename(lockPath, `${lockPath}.stale.${token}`);
|
|
100
|
+
await rm(`${lockPath}.stale.${token}`, { force: true });
|
|
101
|
+
}
|
|
102
|
+
catch (renameError) {
|
|
103
|
+
if (renameError?.code !== 'ENOENT')
|
|
104
|
+
throw renameError;
|
|
105
|
+
// Another worker won the takeover; the retry below will see its lock.
|
|
106
|
+
}
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
return { discovered: 0, processed: 0, failed: 0, deadLettered: 0, memoriesStored: 0, busy: true };
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (!lock)
|
|
113
|
+
return { discovered: 0, processed: 0, failed: 0, deadLettered: 0, memoriesStored: 0, busy: true };
|
|
114
|
+
try {
|
|
115
|
+
const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
|
|
116
|
+
// We hold the exclusive lock, so any leftover `.processing` file belongs to
|
|
117
|
+
// a worker that died mid-job. Restore it unless a newer session arrived in
|
|
118
|
+
// the meantime, in which case the newer transcript supersedes it.
|
|
119
|
+
for (const orphan of (await readdir(options.queueDir)).filter((file) => file.endsWith(PROCESSING_SUFFIX))) {
|
|
120
|
+
const orphanPath = join(options.queueDir, orphan);
|
|
121
|
+
const restored = join(options.queueDir, orphan.slice(0, -PROCESSING_SUFFIX.length));
|
|
122
|
+
try {
|
|
123
|
+
await stat(restored);
|
|
124
|
+
await rm(orphanPath, { force: true });
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
await rename(orphanPath, restored).catch(() => undefined);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
const candidates = (await readdir(options.queueDir)).filter((file) => file.endsWith('.json') && !file.endsWith(DEAD_LETTER_SUFFIX));
|
|
131
|
+
const withMeta = await Promise.all(candidates.map(async (file) => {
|
|
132
|
+
const path = join(options.queueDir, file);
|
|
133
|
+
try {
|
|
134
|
+
const job = JSON.parse(await readFile(path, 'utf8'));
|
|
135
|
+
return { file, path, queuedAt: job.queuedAt ?? '' };
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
return { file, path, queuedAt: '' };
|
|
139
|
+
}
|
|
140
|
+
}));
|
|
141
|
+
// Oldest-first: queuedAt is the enqueue timestamp, not the filename (a
|
|
142
|
+
// sha256 id sorts arbitrarily and would starve unlucky hashes forever).
|
|
143
|
+
const files = withMeta
|
|
144
|
+
.sort((a, b) => a.queuedAt.localeCompare(b.queuedAt))
|
|
145
|
+
.slice(0, options.maxJobs ?? 20)
|
|
146
|
+
.map((entry) => entry.file);
|
|
147
|
+
const result = {
|
|
148
|
+
discovered: files.length,
|
|
149
|
+
processed: 0,
|
|
150
|
+
failed: 0,
|
|
151
|
+
deadLettered: 0,
|
|
152
|
+
memoriesStored: 0,
|
|
153
|
+
busy: false,
|
|
154
|
+
};
|
|
155
|
+
for (const file of files) {
|
|
156
|
+
const path = join(options.queueDir, file);
|
|
157
|
+
// Claim the job by moving it aside. The hook may enqueue a newer, longer
|
|
158
|
+
// transcript for the same session while we work; it lands on the now-free
|
|
159
|
+
// job path and survives, instead of being deleted by our own cleanup.
|
|
160
|
+
const claimed = `${path}${PROCESSING_SUFFIX}`;
|
|
161
|
+
try {
|
|
162
|
+
await rename(path, claimed);
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
continue; // Vanished between listing and claiming — nothing to do.
|
|
166
|
+
}
|
|
167
|
+
let job;
|
|
168
|
+
try {
|
|
169
|
+
job = JSON.parse(await readFile(claimed, 'utf8'));
|
|
170
|
+
if (job.version !== 1 || !job.rawTranscript)
|
|
171
|
+
throw new Error('Unsupported maintenance job');
|
|
172
|
+
const checkpoint = await readCheckpoint(options.queueDir, job.id);
|
|
173
|
+
const processed = await processSession(job.rawTranscript, {
|
|
174
|
+
dbPath: options.dbPath,
|
|
175
|
+
directory: job.directory,
|
|
176
|
+
maxLearnings: job.maxLearnings,
|
|
177
|
+
client: options.client,
|
|
178
|
+
llmTimeoutMs: options.llmTimeoutMs,
|
|
179
|
+
source: 'hook',
|
|
180
|
+
agent: job.agent,
|
|
181
|
+
sinceMessage: checkpoint?.messagesSeen ?? 0,
|
|
182
|
+
});
|
|
183
|
+
// Record how far this session has been encoded before dropping the job,
|
|
184
|
+
// so a later `Stop` resending the full transcript only adds the delta.
|
|
185
|
+
await atomicWrite(checkpointPath(options.queueDir, job.id), JSON.stringify({ sessionId: job.sessionId, messagesSeen: processed.messagesSeen, updatedAt: now().toISOString() }));
|
|
186
|
+
await rm(claimed, { force: true });
|
|
187
|
+
result.processed += 1;
|
|
188
|
+
result.memoriesStored += processed.memoriesStored;
|
|
189
|
+
}
|
|
190
|
+
catch (error) {
|
|
191
|
+
result.failed += 1;
|
|
192
|
+
const lastError = error instanceof Error ? error.message.slice(0, 500) : String(error).slice(0, 500);
|
|
193
|
+
try {
|
|
194
|
+
if (!job) {
|
|
195
|
+
// Unparseable on disk: no attempt counter can live in it, so retrying
|
|
196
|
+
// is pointless. Dead-letter the raw bytes immediately rather than
|
|
197
|
+
// failing this file on every future pass.
|
|
198
|
+
await rename(claimed, join(options.queueDir, `${file.replace(/\.json$/, '')}${DEAD_LETTER_SUFFIX}`));
|
|
199
|
+
result.deadLettered += 1;
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
job.attempts = (job.attempts ?? 0) + 1;
|
|
203
|
+
job.lastError = lastError;
|
|
204
|
+
if (job.attempts >= maxAttempts) {
|
|
205
|
+
// Exhausted retries: move out of the active queue so it stops being
|
|
206
|
+
// picked up and stops inflating `failed` on every future pass, but
|
|
207
|
+
// keep the raw transcript on disk for manual inspection.
|
|
208
|
+
await atomicWrite(join(options.queueDir, `${job.id}${DEAD_LETTER_SUFFIX}`), JSON.stringify(job));
|
|
209
|
+
await rm(claimed, { force: true });
|
|
210
|
+
result.deadLettered += 1;
|
|
211
|
+
}
|
|
212
|
+
else {
|
|
213
|
+
// Restore for a later pass — unless a newer transcript already took
|
|
214
|
+
// the slot, which supersedes this one.
|
|
215
|
+
try {
|
|
216
|
+
await stat(path);
|
|
217
|
+
await rm(claimed, { force: true });
|
|
218
|
+
}
|
|
219
|
+
catch {
|
|
220
|
+
await atomicWrite(path, JSON.stringify(job));
|
|
221
|
+
await rm(claimed, { force: true });
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
// Never erase evidence: the claimed file stays for manual inspection
|
|
227
|
+
// and the orphan sweep restores it on the next pass.
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
return result;
|
|
232
|
+
}
|
|
233
|
+
finally {
|
|
234
|
+
await lock.close();
|
|
235
|
+
// Only release a lock still held by this worker: if ours went stale and was
|
|
236
|
+
// reclaimed, the file now belongs to whoever took over.
|
|
237
|
+
try {
|
|
238
|
+
const held = JSON.parse(await readFile(lockPath, 'utf8'));
|
|
239
|
+
if (held?.token === token)
|
|
240
|
+
await rm(lockPath, { force: true });
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
// Already gone or unreadable — nothing of ours left to release.
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
@@ -154,10 +154,12 @@ function renderMarkdown(input) {
|
|
|
154
154
|
// per-step id of its own.
|
|
155
155
|
if (desc.escapedMarkers > 0)
|
|
156
156
|
escapeAttempts.push({ memoryId: script.id, count: desc.escapedMarkers });
|
|
157
|
-
lines.push(`> ${oneLine(desc.text)}`);
|
|
158
157
|
// Same injection rules as traces (6.0.3): human-authored renders bare,
|
|
159
|
-
// agent/dreamer-authored stays wrapped.
|
|
158
|
+
// agent/dreamer-authored stays wrapped. The description used to render
|
|
159
|
+
// bare unconditionally while the steps below were correctly gated
|
|
160
|
+
// (SECURITY_AUDIT.md H-03) — both now share the same `bare` check.
|
|
160
161
|
const bare = script.source === 'human';
|
|
162
|
+
lines.push(`> ${bare ? oneLine(desc.text) : wrapUntrusted(oneLine(desc.text), { source: script.source, agent: script.agent, id: script.id })}`);
|
|
161
163
|
script.steps.slice(0, SCRIPT_STEP_CAP).forEach((step, i) => {
|
|
162
164
|
const s = sanitizeTrace(step);
|
|
163
165
|
if (s.escapedMarkers > 0)
|
|
@@ -171,11 +173,20 @@ function renderMarkdown(input) {
|
|
|
171
173
|
lines.push(`_… ${script.steps.length - SCRIPT_STEP_CAP} more steps — \`pnpm cli script fire ${script.id.slice(0, 8)}\` for the full drill._`);
|
|
172
174
|
}
|
|
173
175
|
}
|
|
176
|
+
// Intentions carry the same provenance shape as memories (6.0.1) but used to
|
|
177
|
+
// render bare unconditionally regardless of it (SECURITY_AUDIT.md H-03).
|
|
178
|
+
// Only a human-verified loop skips the untrusted wrapper now.
|
|
179
|
+
const renderIntentionBody = (i, s) => {
|
|
180
|
+
const bare = i.verified === true && i.verificationReason === 'human';
|
|
181
|
+
return bare
|
|
182
|
+
? oneLine(s.text)
|
|
183
|
+
: wrapUntrusted(oneLine(s.text), { source: i.source, agent: i.agent, verified: i.verified, id: i.id });
|
|
184
|
+
};
|
|
174
185
|
if (firedNow.length) {
|
|
175
186
|
lines.push('', '### ⏰ Deadlines reached', RECALLED_NOTES_PREFACE);
|
|
176
187
|
for (const i of firedNow) {
|
|
177
188
|
const s = sanitizeTrace(i.content);
|
|
178
|
-
lines.push(`- **[${loopId(i.id)}]** ${
|
|
189
|
+
lines.push(`- **[${loopId(i.id)}]** ${renderIntentionBody(i, s)}`);
|
|
179
190
|
}
|
|
180
191
|
}
|
|
181
192
|
if (openLoops.length) {
|
|
@@ -186,7 +197,7 @@ function renderMarkdown(input) {
|
|
|
186
197
|
? ` — due in ${humanizeAge(now, i.expiresAt).replace(' ago', '')}`
|
|
187
198
|
: '';
|
|
188
199
|
const s = sanitizeTrace(i.content);
|
|
189
|
-
lines.push(`- **[${loopId(i.id)}]** ${
|
|
200
|
+
lines.push(`- **[${loopId(i.id)}]** ${renderIntentionBody(i, s)} (armed ${age}${deadline})`);
|
|
190
201
|
}
|
|
191
202
|
lines.push('', `_To close a loop: mention \`Closes ${loopId(openLoops[0].id)}\` in a commit message._`);
|
|
192
203
|
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
export type AgentSourceId = 'claude-code' | 'codex' | 'kimi-code' | 'kimi-desktop' | 'opencode' | 'qwen-code' | 'mistral-vibe' | 'gemini-cli' | 'github-copilot-cli' | 'aider' | 'cursor' | 'windsurf';
|
|
2
|
+
export interface AgentSourceDefinition {
|
|
3
|
+
id: AgentSourceId;
|
|
4
|
+
name: string;
|
|
5
|
+
vendor: string;
|
|
6
|
+
commands: string[];
|
|
7
|
+
/** Known local roots. Discovery only: no file below these roots is read. */
|
|
8
|
+
roots: RootCandidate[];
|
|
9
|
+
}
|
|
10
|
+
type RootCandidate = {
|
|
11
|
+
base: 'home' | 'appData' | 'localAppData';
|
|
12
|
+
parts: string[];
|
|
13
|
+
} | {
|
|
14
|
+
base: 'env';
|
|
15
|
+
variable: string;
|
|
16
|
+
parts?: string[];
|
|
17
|
+
};
|
|
18
|
+
export interface DiscoveredAgentSource extends AgentSourceDefinition {
|
|
19
|
+
installed: boolean;
|
|
20
|
+
evidence: string[];
|
|
21
|
+
}
|
|
22
|
+
export interface DiscoveryOptions {
|
|
23
|
+
homeDir?: string;
|
|
24
|
+
env?: Record<string, string | undefined>;
|
|
25
|
+
platform?: NodeJS.Platform;
|
|
26
|
+
exists?: (path: string) => boolean;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Non-exhaustive catalog of local AI agent runtimes. A catalog entry means
|
|
30
|
+
* "discoverable", not "its private session format is already importable".
|
|
31
|
+
*/
|
|
32
|
+
export declare const KNOWN_AGENT_SOURCES: readonly AgentSourceDefinition[];
|
|
33
|
+
export declare function discoverLocalAgentSources(options?: DiscoveryOptions): DiscoveredAgentSource[];
|
|
34
|
+
export {};
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { existsSync } from 'fs';
|
|
2
|
+
import { posix, win32 } from 'path';
|
|
3
|
+
const home = (...parts) => ({ base: 'home', parts });
|
|
4
|
+
const appData = (...parts) => ({ base: 'appData', parts });
|
|
5
|
+
const localAppData = (...parts) => ({ base: 'localAppData', parts });
|
|
6
|
+
const envRoot = (variable, ...parts) => ({ base: 'env', variable, parts });
|
|
7
|
+
/**
|
|
8
|
+
* Non-exhaustive catalog of local AI agent runtimes. A catalog entry means
|
|
9
|
+
* "discoverable", not "its private session format is already importable".
|
|
10
|
+
*/
|
|
11
|
+
export const KNOWN_AGENT_SOURCES = [
|
|
12
|
+
{ id: 'claude-code', name: 'Claude Code', vendor: 'Anthropic', commands: ['claude'], roots: [home('.claude')] },
|
|
13
|
+
{ id: 'codex', name: 'Codex', vendor: 'OpenAI', commands: ['codex'], roots: [home('.codex')] },
|
|
14
|
+
{
|
|
15
|
+
id: 'kimi-code', name: 'Kimi Code', vendor: 'Moonshot AI', commands: ['kimi'],
|
|
16
|
+
roots: [home('.kimi-code'), home('.kimi-work'), localAppData('kimi-code')],
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
id: 'kimi-desktop', name: 'Kimi Desktop', vendor: 'Moonshot AI', commands: [],
|
|
20
|
+
roots: [appData('kimi-desktop'), localAppData('kimi-desktop-updater')],
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
id: 'opencode', name: 'OpenCode', vendor: 'SST', commands: ['opencode'],
|
|
24
|
+
roots: [home('.opencode'), appData('opencode'), localAppData('opencode')],
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
id: 'qwen-code', name: 'Qwen Code', vendor: 'Alibaba Cloud', commands: ['qwen'],
|
|
28
|
+
roots: [envRoot('QWEN_RUNTIME_DIR'), envRoot('QWEN_HOME'), home('.qwen')],
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
id: 'mistral-vibe', name: 'Mistral Vibe', vendor: 'Mistral AI', commands: ['vibe'],
|
|
32
|
+
roots: [envRoot('VIBE_HOME'), home('.vibe')],
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
id: 'gemini-cli', name: 'Gemini CLI', vendor: 'Google', commands: ['gemini'],
|
|
36
|
+
roots: [envRoot('GEMINI_CLI_HOME', '.gemini'), home('.gemini')],
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
id: 'github-copilot-cli', name: 'GitHub Copilot CLI', vendor: 'GitHub', commands: ['copilot'],
|
|
40
|
+
roots: [home('.copilot')],
|
|
41
|
+
},
|
|
42
|
+
{ id: 'aider', name: 'Aider', vendor: 'Aider-AI', commands: ['aider'], roots: [home('.aider.conf.yml')] },
|
|
43
|
+
{ id: 'cursor', name: 'Cursor', vendor: 'Anysphere', commands: ['cursor'], roots: [appData('Cursor')] },
|
|
44
|
+
{ id: 'windsurf', name: 'Windsurf', vendor: 'Cognition', commands: ['windsurf'], roots: [appData('Windsurf')] },
|
|
45
|
+
];
|
|
46
|
+
function resolveRoot(candidate, context) {
|
|
47
|
+
let base;
|
|
48
|
+
if (candidate.base === 'home')
|
|
49
|
+
base = context.homeDir;
|
|
50
|
+
else if (candidate.base === 'appData')
|
|
51
|
+
base = context.env.APPDATA;
|
|
52
|
+
else if (candidate.base === 'localAppData')
|
|
53
|
+
base = context.env.LOCALAPPDATA;
|
|
54
|
+
else if (candidate.base === 'env')
|
|
55
|
+
base = context.env[candidate.variable];
|
|
56
|
+
if (!base)
|
|
57
|
+
return null;
|
|
58
|
+
return context.join(base, ...(candidate.parts ?? []));
|
|
59
|
+
}
|
|
60
|
+
function executableCandidates(command, env, platform, join) {
|
|
61
|
+
const separator = platform === 'win32' ? ';' : ':';
|
|
62
|
+
const pathEntries = (env.PATH ?? env.Path ?? '').split(separator).filter(Boolean);
|
|
63
|
+
const extensions = platform === 'win32'
|
|
64
|
+
? (env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean)
|
|
65
|
+
: [''];
|
|
66
|
+
return pathEntries.flatMap((entry) => extensions.map((extension) => join(entry, `${command}${extension.toLowerCase()}`)));
|
|
67
|
+
}
|
|
68
|
+
export function discoverLocalAgentSources(options = {}) {
|
|
69
|
+
const env = options.env ?? process.env;
|
|
70
|
+
const platform = options.platform ?? process.platform;
|
|
71
|
+
const pathApi = platform === 'win32' ? win32 : posix;
|
|
72
|
+
const homeDir = options.homeDir ?? env.USERPROFILE ?? env.HOME ?? '';
|
|
73
|
+
const exists = options.exists ?? existsSync;
|
|
74
|
+
const join = pathApi.join;
|
|
75
|
+
return KNOWN_AGENT_SOURCES.map((source) => {
|
|
76
|
+
const evidence = new Set();
|
|
77
|
+
for (const root of source.roots) {
|
|
78
|
+
const resolved = resolveRoot(root, { homeDir, env, join });
|
|
79
|
+
if (resolved && exists(resolved))
|
|
80
|
+
evidence.add(resolved);
|
|
81
|
+
}
|
|
82
|
+
for (const command of source.commands) {
|
|
83
|
+
const executable = executableCandidates(command, env, platform, join).find(exists);
|
|
84
|
+
if (executable)
|
|
85
|
+
evidence.add(executable);
|
|
86
|
+
}
|
|
87
|
+
return { ...source, installed: evidence.size > 0, evidence: [...evidence] };
|
|
88
|
+
});
|
|
89
|
+
}
|
package/dist/api/server.js
CHANGED
|
@@ -39,6 +39,7 @@ import { createScriptRoutes } from './scripts-routes.js';
|
|
|
39
39
|
import { join, dirname, resolve, sep } from 'path';
|
|
40
40
|
import { fileURLToPath } from 'url';
|
|
41
41
|
import { readFileSync } from 'fs';
|
|
42
|
+
import { timingSafeEqual } from 'crypto';
|
|
42
43
|
const __filename = fileURLToPath(import.meta.url);
|
|
43
44
|
const __dirname = dirname(__filename);
|
|
44
45
|
/**
|
|
@@ -72,6 +73,35 @@ app.use('*', cors({
|
|
|
72
73
|
credentials: true,
|
|
73
74
|
maxAge: 600,
|
|
74
75
|
}));
|
|
76
|
+
// === AUTH (SECURITY_AUDIT.md H-01) ===
|
|
77
|
+
// HUMEMORY_API_TOKEN, when set, is required (Bearer or x-humemory-token) on every
|
|
78
|
+
// data/mutation route. Static dashboard assets and /health stay open so the front
|
|
79
|
+
// end can load; the front end then attaches the token to its own API calls.
|
|
80
|
+
const API_TOKEN = process.env.HUMEMORY_API_TOKEN;
|
|
81
|
+
const PUBLIC_PATHS = new Set(['/health']);
|
|
82
|
+
function isPublicPath(path) {
|
|
83
|
+
return PUBLIC_PATHS.has(path) || path === '/' || path === '/app' || path === '/session' || path.startsWith('/app/');
|
|
84
|
+
}
|
|
85
|
+
function tokenMatches(supplied, expected) {
|
|
86
|
+
if (!supplied)
|
|
87
|
+
return false;
|
|
88
|
+
const a = Buffer.from(supplied);
|
|
89
|
+
const b = Buffer.from(expected);
|
|
90
|
+
// Constant-time compare requires equal length; a length check alone leaks
|
|
91
|
+
// little (token lengths aren't secret), and avoids throwing on mismatch.
|
|
92
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
93
|
+
}
|
|
94
|
+
app.use('*', async (c, next) => {
|
|
95
|
+
if (!API_TOKEN || isPublicPath(c.req.path))
|
|
96
|
+
return next();
|
|
97
|
+
const header = c.req.header('authorization');
|
|
98
|
+
const bearer = header?.startsWith('Bearer ') ? header.slice(7) : undefined;
|
|
99
|
+
const supplied = bearer ?? c.req.header('x-humemory-token');
|
|
100
|
+
if (!tokenMatches(supplied, API_TOKEN)) {
|
|
101
|
+
return c.json({ error: 'Unauthorized' }, 401);
|
|
102
|
+
}
|
|
103
|
+
return next();
|
|
104
|
+
});
|
|
75
105
|
// Static files (dashboard)
|
|
76
106
|
const APP_DIR = join(PUBLIC_DIR, 'app');
|
|
77
107
|
/**
|
|
@@ -151,7 +181,20 @@ export { app };
|
|
|
151
181
|
// raise a server or seize the port.
|
|
152
182
|
if (import.meta.main) {
|
|
153
183
|
const port = parseInt(process.env.PORT || '3456');
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
184
|
+
// Default loopback-only (SECURITY_AUDIT.md H-01): the previous code passed no
|
|
185
|
+
// hostname, which node-server forwards straight to server.listen(), binding
|
|
186
|
+
// every interface while the log line still claimed "localhost".
|
|
187
|
+
const hostname = process.env.HUMEMORY_HOST || '127.0.0.1';
|
|
188
|
+
const isLoopback = hostname === '127.0.0.1' || hostname === 'localhost' || hostname === '::1';
|
|
189
|
+
if (!isLoopback && !API_TOKEN) {
|
|
190
|
+
console.error(`Refusing to start: HUMEMORY_HOST=${hostname} exposes the API beyond loopback ` +
|
|
191
|
+
`without HUMEMORY_API_TOKEN set. Set a token or unset HUMEMORY_HOST.`);
|
|
192
|
+
process.exit(1);
|
|
193
|
+
}
|
|
194
|
+
console.log(`🧠 humemory API running on http://${hostname}:${port}`);
|
|
195
|
+
console.log(`📊 Dashboard: http://${hostname}:${port}/`);
|
|
196
|
+
if (!API_TOKEN) {
|
|
197
|
+
console.warn('⚠️ HUMEMORY_API_TOKEN not set — data routes are unauthenticated (loopback only).');
|
|
198
|
+
}
|
|
199
|
+
serve({ fetch: app.fetch, port, hostname });
|
|
157
200
|
}
|
package/dist/cli/index.js
CHANGED
|
@@ -6,6 +6,7 @@ import { parseCueArg, formatTriggerSpec } from '../core/cue-arg.js';
|
|
|
6
6
|
import { join, dirname, resolve } from 'path';
|
|
7
7
|
import { fileURLToPath } from 'url';
|
|
8
8
|
import { readFileSync } from 'fs';
|
|
9
|
+
import { discoverLocalAgentSources } from '../agent/source-registry.js';
|
|
9
10
|
const __filename = fileURLToPath(import.meta.url);
|
|
10
11
|
const __dirname = dirname(__filename);
|
|
11
12
|
// Shared store. HUMEMORY_DB points at another database — same convention as the
|
|
@@ -37,7 +38,7 @@ program
|
|
|
37
38
|
.option('-l2, --level2 <essential>', 'Gist for consolidation level 2')
|
|
38
39
|
.option('-l3, --level3 <keywords>', 'Keywords for fast level 3 retrieval')
|
|
39
40
|
.option('-t, --type <type>', 'Memory type (episodic/semantic/procedural)', 'semantic')
|
|
40
|
-
.option('--auto', 'Auto-generate levels 1-3
|
|
41
|
+
.option('--auto', 'Auto-generate levels 1-3 locally (an injected LLM may enhance them)')
|
|
41
42
|
.option('--photographic', 'Photographic mode — disable decay')
|
|
42
43
|
.option('--agent <name>', 'Who is encoding (claude/codex/kimi/…)', 'cli')
|
|
43
44
|
.action(async (content, options) => {
|
|
@@ -789,6 +790,24 @@ for (const verb of ['approve', 'reject']) {
|
|
|
789
790
|
}
|
|
790
791
|
});
|
|
791
792
|
}
|
|
793
|
+
// === LOCAL AGENT SOURCES ===
|
|
794
|
+
const sources = program
|
|
795
|
+
.command('sources')
|
|
796
|
+
.description('Discover local AI agent runtimes without reading their sessions');
|
|
797
|
+
sources
|
|
798
|
+
.command('discover', { isDefault: true })
|
|
799
|
+
.description('Show known runtimes and the local evidence found for each one')
|
|
800
|
+
.option('--installed-only', 'Hide known runtimes that were not found')
|
|
801
|
+
.action((options) => {
|
|
802
|
+
const discovered = discoverLocalAgentSources()
|
|
803
|
+
.filter((source) => !options.installedOnly || source.installed);
|
|
804
|
+
console.log('\nLocal AI sources (discovery only — no session was read):\n');
|
|
805
|
+
for (const source of discovered) {
|
|
806
|
+
console.log(`${source.installed ? '✓' : '·'} ${source.name} — ${source.vendor}`);
|
|
807
|
+
for (const evidence of source.evidence)
|
|
808
|
+
console.log(` ${evidence}`);
|
|
809
|
+
}
|
|
810
|
+
});
|
|
792
811
|
// Parse and run
|
|
793
812
|
program.parse();
|
|
794
813
|
// Cleanup
|
|
@@ -14,5 +14,6 @@ export interface LLMClient {
|
|
|
14
14
|
}>;
|
|
15
15
|
};
|
|
16
16
|
}
|
|
17
|
-
export declare function setLLMClient(client: LLMClient): void;
|
|
17
|
+
export declare function setLLMClient(client: LLMClient | null): void;
|
|
18
|
+
export declare function generateMemoryLevelsDeterministic(content: string): GeneratedLevels;
|
|
18
19
|
export declare function generateMemoryLevels(content: string, memoryType?: MemoryType, client?: LLMClient): Promise<GeneratedLevels>;
|
|
@@ -1,39 +1,46 @@
|
|
|
1
|
-
import Anthropic from '@anthropic-ai/sdk';
|
|
2
1
|
const SYSTEM_PROMPT = `You are a memory consolidation system.
|
|
3
2
|
For each trace, produce 3 decay levels as strict JSON.
|
|
4
3
|
Write the levels in the same language as the trace itself.
|
|
5
4
|
Answer with a JSON object ONLY — no markdown, no explanation.`;
|
|
6
5
|
let _client = null;
|
|
7
|
-
function getClient() {
|
|
8
|
-
if (!_client) {
|
|
9
|
-
_client = new Anthropic();
|
|
10
|
-
}
|
|
11
|
-
return _client;
|
|
12
|
-
}
|
|
13
6
|
export function setLLMClient(client) {
|
|
14
7
|
_client = client;
|
|
15
8
|
}
|
|
9
|
+
export function generateMemoryLevelsDeterministic(content) {
|
|
10
|
+
const compact = content.trim().replace(/\s+/g, ' ');
|
|
11
|
+
const keywords = [...new Set(compact.toLocaleLowerCase().match(/[\p{L}\p{N}_-]{3,}/gu) ?? [])]
|
|
12
|
+
.slice(0, 12)
|
|
13
|
+
.join(' ');
|
|
14
|
+
return {
|
|
15
|
+
level1Summary: compact.slice(0, 300),
|
|
16
|
+
level2Essential: compact.slice(0, 100),
|
|
17
|
+
level3Keywords: keywords || compact.split(/\s+/).slice(0, 10).join(' '),
|
|
18
|
+
};
|
|
19
|
+
}
|
|
16
20
|
export async function generateMemoryLevels(content, memoryType = 'semantic', client) {
|
|
17
|
-
const llm = client ??
|
|
21
|
+
const llm = client ?? _client;
|
|
22
|
+
if (!llm)
|
|
23
|
+
return generateMemoryLevelsDeterministic(content);
|
|
18
24
|
const typeHints = {
|
|
19
25
|
episodic: 'a lived event, with its temporal and spatial context',
|
|
20
26
|
semantic: 'a fact or a concept',
|
|
21
27
|
procedural: 'know-how or a procedure',
|
|
22
28
|
};
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
29
|
+
try {
|
|
30
|
+
const response = await llm.messages.create({
|
|
31
|
+
model: process.env.HUMEMORY_LLM_MODEL ?? 'claude-haiku-4-5-20251001',
|
|
32
|
+
max_tokens: 512,
|
|
33
|
+
system: [
|
|
34
|
+
{
|
|
35
|
+
type: 'text',
|
|
36
|
+
text: SYSTEM_PROMPT,
|
|
37
|
+
cache_control: { type: 'ephemeral' },
|
|
38
|
+
},
|
|
39
|
+
],
|
|
40
|
+
messages: [
|
|
41
|
+
{
|
|
42
|
+
role: 'user',
|
|
43
|
+
content: `Memory type: ${typeHints[memoryType]}
|
|
37
44
|
|
|
38
45
|
Trace to consolidate:
|
|
39
46
|
"""
|
|
@@ -46,11 +53,10 @@ Produce exactly this JSON:
|
|
|
46
53
|
"level2Essential": "<1 sentence, the irreducible information>",
|
|
47
54
|
"level3Keywords": "<8-12 BM25 keywords separated by spaces>"
|
|
48
55
|
}`,
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
try {
|
|
56
|
+
},
|
|
57
|
+
],
|
|
58
|
+
});
|
|
59
|
+
const text = response.content[0].type === 'text' ? (response.content[0].text ?? '') : '';
|
|
54
60
|
const parsed = JSON.parse(text.trim());
|
|
55
61
|
if (!parsed.level1Summary || !parsed.level2Essential || !parsed.level3Keywords) {
|
|
56
62
|
throw new Error('Missing fields in LLM response');
|
|
@@ -58,12 +64,7 @@ Produce exactly this JSON:
|
|
|
58
64
|
return parsed;
|
|
59
65
|
}
|
|
60
66
|
catch {
|
|
61
|
-
//
|
|
62
|
-
|
|
63
|
-
return {
|
|
64
|
-
level1Summary: content.slice(0, 300),
|
|
65
|
-
level2Essential: content.slice(0, 100),
|
|
66
|
-
level3Keywords: words,
|
|
67
|
-
};
|
|
67
|
+
// Invalid output, quota, timeout, or network loss: consolidation still proceeds locally.
|
|
68
|
+
return generateMemoryLevelsDeterministic(content);
|
|
68
69
|
}
|
|
69
70
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
export { SQLiteStore } from './store/sqlite.js';
|
|
8
8
|
export { InverseSearchEngine } from './core/search.js';
|
|
9
9
|
export { calculateDecayLevel, calculateSaillance, calculateDecayRate, updateAllDecay, DECAY_CONFIG } from './core/decay.js';
|
|
10
|
-
export { generateMemoryLevels, setLLMClient } from './core/llm-generator.js';
|
|
10
|
+
export { generateMemoryLevels, generateMemoryLevelsDeterministic, setLLMClient } from './core/llm-generator.js';
|
|
11
11
|
export { systemClock, FakeClock } from './core/clock.js';
|
|
12
12
|
export { InMemoryEventBus } from './core/event-bus.js';
|
|
13
13
|
export { SqliteCueResolver, attachResolverToBus, intentionSaillance, parseCron, cronMatches, cronDueSince, eventTriggerMatches, loopId, extractLoopIds, matchIntentionByShortId } from './core/cues.js';
|
|
@@ -15,7 +15,9 @@ export { parseCueArg, formatTriggerSpec, CueArgError } from './core/cue-arg.js';
|
|
|
15
15
|
export { buildSessionContext, humanizeAge, DEFAULT_SESSION_BUDGET, DEFAULT_SAILLANCE_THRESHOLD } from './agent/session-context.js';
|
|
16
16
|
export { processSession } from './agent/claude-hook.js';
|
|
17
17
|
export { parseClaudeHookPayload } from './agent/session-parser.js';
|
|
18
|
-
export { extractLearnings } from './agent/learning-extractor.js';
|
|
18
|
+
export { extractLearnings, extractLearningsDeterministic } from './agent/learning-extractor.js';
|
|
19
|
+
export { enqueueSession, processMaintenanceQueue } from './agent/maintenance-queue.js';
|
|
20
|
+
export { discoverLocalAgentSources, KNOWN_AGENT_SOURCES } from './agent/source-registry.js';
|
|
19
21
|
export type { Memory, SearchQuery, SearchResult, DecayLevel, MemoryStore, MergeResult, Intention, Cue, IntentionStatus, CueStatus, CueKind, TriggerSpec, TimeTriggerSpec, EventTriggerSpec, NewIntention, NewCue, IntentionStore } from './core/types.js';
|
|
20
22
|
export type { StoreOptions } from './store/sqlite.js';
|
|
21
23
|
export type { Clock } from './core/clock.js';
|
|
@@ -26,3 +28,5 @@ export type { GeneratedLevels, LLMClient } from './core/llm-generator.js';
|
|
|
26
28
|
export type { ParsedSession, SessionMessage } from './agent/session-parser.js';
|
|
27
29
|
export type { ExtractedLearning } from './agent/learning-extractor.js';
|
|
28
30
|
export type { HookOptions, HookResult } from './agent/claude-hook.js';
|
|
31
|
+
export type { MaintenanceJob, EnqueueOptions, QueueResult, WorkerOptions, WorkerResult } from './agent/maintenance-queue.js';
|
|
32
|
+
export type { AgentSourceDefinition, AgentSourceId, DiscoveredAgentSource, DiscoveryOptions } from './agent/source-registry.js';
|