humemory 0.2.3 → 0.2.5
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 +1 -1
- package/CHANGELOG.md +32 -0
- package/README.md +75 -6
- package/dist/agent/claude-hook.js +8 -3
- package/dist/agent/codex-import.d.ts +40 -0
- package/dist/agent/codex-import.js +97 -0
- package/dist/agent/codex-rollout-parser.d.ts +30 -0
- package/dist/agent/codex-rollout-parser.js +111 -0
- package/dist/agent/maintenance-queue.js +2 -2
- package/dist/agent/session-context.js +6 -0
- package/dist/agent/session-parser.d.ts +17 -0
- package/dist/agent/session-parser.js +28 -0
- package/dist/api/cors.d.ts +21 -0
- package/dist/api/cors.js +39 -0
- package/dist/api/dream-routes.js +2 -1
- package/dist/api/errors.d.ts +22 -0
- package/dist/api/errors.js +34 -0
- package/dist/api/intentions-routes.js +27 -6
- package/dist/api/limits.d.ts +58 -0
- package/dist/api/limits.js +80 -0
- package/dist/api/memory-routes.js +82 -29
- package/dist/api/scripts-routes.js +20 -6
- package/dist/api/security-headers.d.ts +19 -0
- package/dist/api/security-headers.js +47 -0
- package/dist/api/server.d.ts +4 -1
- package/dist/api/server.js +20 -10
- package/dist/cli/index.js +36 -0
- package/dist/core/cues.d.ts +16 -0
- package/dist/core/cues.js +56 -3
- package/dist/core/llm-cli-client.d.ts +43 -0
- package/dist/core/llm-cli-client.js +108 -0
- package/dist/store/sqlite.d.ts +9 -1
- package/dist/store/sqlite.js +9 -2
- package/package.json +2 -1
- package/public/app/index-95ffty7j.js +12 -0
- package/public/app/index.html +1 -1
- package/scripts/maintenance-worker.ts +9 -1
- package/public/app/index-nqr7bd0a.js +0 -12
package/dist/api/server.d.ts
CHANGED
|
@@ -29,5 +29,8 @@
|
|
|
29
29
|
* POST /cues/resolve - Sweep: expire overdue loops, fire due deadlines
|
|
30
30
|
*/
|
|
31
31
|
import { Hono } from 'hono';
|
|
32
|
-
|
|
32
|
+
import type { SecureHeadersVariables } from 'hono/secure-headers';
|
|
33
|
+
declare const app: Hono<{
|
|
34
|
+
Variables: SecureHeadersVariables;
|
|
35
|
+
}, import("hono/types").BlankSchema, "/">;
|
|
33
36
|
export { app };
|
package/dist/api/server.js
CHANGED
|
@@ -30,6 +30,11 @@
|
|
|
30
30
|
*/
|
|
31
31
|
import { Hono } from 'hono';
|
|
32
32
|
import { cors } from 'hono/cors';
|
|
33
|
+
import { bodyLimit } from 'hono/body-limit';
|
|
34
|
+
import { secureHeaders } from 'hono/secure-headers';
|
|
35
|
+
import { MAX_BODY_BYTES } from './limits.js';
|
|
36
|
+
import { makeOriginChecker } from './cors.js';
|
|
37
|
+
import { SECURE_HEADERS_OPTIONS, injectNonce } from './security-headers.js';
|
|
33
38
|
import { serve } from '@hono/node-server';
|
|
34
39
|
import { SQLiteStore } from '../store/sqlite.js';
|
|
35
40
|
import { createIntentionRoutes } from './intentions-routes.js';
|
|
@@ -64,15 +69,20 @@ const allowedOrigins = process.env.NODE_ENV === 'production'
|
|
|
64
69
|
? (process.env.CORS_ORIGINS || 'http://localhost:3456').split(',')
|
|
65
70
|
: ['http://localhost:3456', 'http://localhost:3000', 'http://127.0.0.1:3456'];
|
|
66
71
|
const app = new Hono();
|
|
72
|
+
// Transport-level cap, ahead of any route (SECURITY_AUDIT.md M-02). The
|
|
73
|
+
// per-field caps in `limits.ts` are the business-level floor underneath it.
|
|
74
|
+
app.use('*', bodyLimit({
|
|
75
|
+
maxSize: MAX_BODY_BYTES,
|
|
76
|
+
onError: (c) => c.json({ success: false, error: 'Request body too large' }, 413),
|
|
77
|
+
}));
|
|
67
78
|
app.use('*', cors({
|
|
68
|
-
origin: (
|
|
69
|
-
if (!origin)
|
|
70
|
-
return '*'; // Allow requests without origin (like mobile apps, curl, etc)
|
|
71
|
-
return allowedOrigins.some(allowed => origin.includes(allowed.trim())) ? origin : undefined;
|
|
72
|
-
},
|
|
79
|
+
origin: makeOriginChecker(allowedOrigins),
|
|
73
80
|
credentials: true,
|
|
74
81
|
maxAge: 600,
|
|
75
82
|
}));
|
|
83
|
+
// === BROWSER DEFENCE HEADERS (SECURITY_AUDIT.md M-04) ===
|
|
84
|
+
// Policy and nonce stamping live in ./security-headers.ts so they stay testable.
|
|
85
|
+
app.use('*', secureHeaders(SECURE_HEADERS_OPTIONS));
|
|
76
86
|
// === AUTH (SECURITY_AUDIT.md H-01) ===
|
|
77
87
|
// HUMEMORY_API_TOKEN, when set, is required (Bearer or x-humemory-token) on every
|
|
78
88
|
// data/mutation route. Static dashboard assets and /health stay open so the front
|
|
@@ -111,13 +121,13 @@ const APP_DIR = join(PUBLIC_DIR, 'app');
|
|
|
111
121
|
* `/app/`, the browser resolves them against the root and finds nothing — so they
|
|
112
122
|
* are absolutised to `/app/`.
|
|
113
123
|
*/
|
|
114
|
-
function reactAppHtml() {
|
|
124
|
+
function reactAppHtml(nonce) {
|
|
115
125
|
const html = readFileSync(join(APP_DIR, 'index.html'), 'utf-8');
|
|
116
|
-
return html.replace(/(src|href)="\.\//g, '$1="/app/');
|
|
126
|
+
return injectNonce(html.replace(/(src|href)="\.\//g, '$1="/app/'), nonce);
|
|
117
127
|
}
|
|
118
128
|
app.get('/', (c) => {
|
|
119
129
|
try {
|
|
120
|
-
return c.html(reactAppHtml());
|
|
130
|
+
return c.html(reactAppHtml(c.get('secureHeadersNonce') ?? ''));
|
|
121
131
|
}
|
|
122
132
|
catch {
|
|
123
133
|
// Missing bundle: say what to run rather than serve a dead page.
|
|
@@ -126,7 +136,7 @@ app.get('/', (c) => {
|
|
|
126
136
|
});
|
|
127
137
|
app.get('/session', (c) => {
|
|
128
138
|
const html = readFileSync(join(PUBLIC_DIR, 'session.html'), 'utf-8');
|
|
129
|
-
return c.html(html);
|
|
139
|
+
return c.html(injectNonce(html, c.get('secureHeadersNonce') ?? ''));
|
|
130
140
|
});
|
|
131
141
|
// React front end (web/ → public/app/ through `pnpm build:web`), served at / and /app.
|
|
132
142
|
const APP_MIME = {
|
|
@@ -140,7 +150,7 @@ const APP_MIME = {
|
|
|
140
150
|
};
|
|
141
151
|
app.get('/app', (c) => {
|
|
142
152
|
try {
|
|
143
|
-
return c.html(reactAppHtml());
|
|
153
|
+
return c.html(reactAppHtml(c.get('secureHeadersNonce') ?? ''));
|
|
144
154
|
}
|
|
145
155
|
catch {
|
|
146
156
|
// Missing bundle: say what to run rather than a silent 404.
|
package/dist/cli/index.js
CHANGED
|
@@ -12,6 +12,8 @@ const __dirname = dirname(__filename);
|
|
|
12
12
|
// Shared store. HUMEMORY_DB points at another database — same convention as the
|
|
13
13
|
// hooks, and required to exercise the CLI without touching production.
|
|
14
14
|
const DB_PATH = process.env.HUMEMORY_DB ?? join(__dirname, '../../data/humemory.db');
|
|
15
|
+
// Same inbox the agent hooks write to — the CLI only ever queues, never encodes.
|
|
16
|
+
const QUEUE_DIR = process.env.HUMEMORY_QUEUE ?? join(__dirname, '../../data/maintenance-queue');
|
|
15
17
|
let store;
|
|
16
18
|
function getStore() {
|
|
17
19
|
if (!store) {
|
|
@@ -794,6 +796,40 @@ for (const verb of ['approve', 'reject']) {
|
|
|
794
796
|
const sources = program
|
|
795
797
|
.command('sources')
|
|
796
798
|
.description('Discover local AI agent runtimes without reading their sessions');
|
|
799
|
+
sources
|
|
800
|
+
.command('import-codex')
|
|
801
|
+
.description('Queue Codex CLI rollouts for maintenance (nothing is encoded until the worker runs)')
|
|
802
|
+
.option('--since <days>', 'Only rollouts touched in the last N days', '7')
|
|
803
|
+
.option('--all', 'Every rollout ever recorded, ignoring --since')
|
|
804
|
+
.option('--limit <n>', 'Stop after N queued sessions')
|
|
805
|
+
.option('--include-subagents', 'Also import threads codex spawned for itself')
|
|
806
|
+
.option('--dry-run', 'Report what would be queued, write nothing')
|
|
807
|
+
.option('--sessions-dir <dir>', 'Override $CODEX_HOME/sessions')
|
|
808
|
+
.action(async (options) => {
|
|
809
|
+
const { importCodexRollouts, defaultCodexSessionsDir } = await import('../agent/codex-import.js');
|
|
810
|
+
const sessionsDir = options.sessionsDir ? resolve(options.sessionsDir) : defaultCodexSessionsDir();
|
|
811
|
+
const days = Number(options.since);
|
|
812
|
+
const since = options.all || !Number.isFinite(days)
|
|
813
|
+
? undefined
|
|
814
|
+
: new Date(Date.now() - days * 24 * 60 * 60 * 1000);
|
|
815
|
+
console.log(`⏳ Scanning ${sessionsDir}${since ? ` (last ${days} day(s))` : ' (all)'}...`);
|
|
816
|
+
const result = await importCodexRollouts({
|
|
817
|
+
queueDir: QUEUE_DIR,
|
|
818
|
+
sessionsDir,
|
|
819
|
+
since,
|
|
820
|
+
limit: options.limit ? parseInt(options.limit) : undefined,
|
|
821
|
+
includeSubagents: options.includeSubagents,
|
|
822
|
+
dryRun: options.dryRun,
|
|
823
|
+
});
|
|
824
|
+
console.log(`\n${options.dryRun ? 'Would queue' : '✓ Queued'} ${result.queued} session(s)` +
|
|
825
|
+
`${options.dryRun ? '' : ` (${result.created} new)`} out of ${result.scanned} scanned.`);
|
|
826
|
+
console.log(` skipped — ${result.skippedOld} older than the window, ` +
|
|
827
|
+
`${result.skippedSubagent} subagent thread(s), ${result.skippedEmpty} without a turn, ` +
|
|
828
|
+
`${result.unreadable} unreadable`);
|
|
829
|
+
if (!options.dryRun && result.queued > 0) {
|
|
830
|
+
console.log('\nRun `pnpm maintenance` to encode them (or wait for the scheduled pass).');
|
|
831
|
+
}
|
|
832
|
+
});
|
|
797
833
|
sources
|
|
798
834
|
.command('discover', { isDefault: true })
|
|
799
835
|
.description('Show known runtimes and the local evidence found for each one')
|
package/dist/core/cues.d.ts
CHANGED
|
@@ -63,6 +63,22 @@ export declare function cronMatches(parsed: ParsedCron, date: Date): boolean;
|
|
|
63
63
|
export declare const CRON_CATCHUP_MINUTES: number;
|
|
64
64
|
/** True when a cron occurrence exists in the half-open interval (since, now]. */
|
|
65
65
|
export declare function cronDueSince(expr: string, since: Date, now: Date): boolean;
|
|
66
|
+
/**
|
|
67
|
+
* Hard caps on regex evaluation (SECURITY_AUDIT.md M-01). The pattern and the
|
|
68
|
+
* event text both come from unauthenticated callers, and the native RegExp engine
|
|
69
|
+
* backtracks: `^(a+)+$` against a long non-matching string pins the event loop.
|
|
70
|
+
* The engine cannot be given a deadline, so the inputs are bounded instead and
|
|
71
|
+
* the shapes that make catastrophic backtracking possible are refused outright.
|
|
72
|
+
*/
|
|
73
|
+
export declare const MAX_PATTERN_LENGTH = 200;
|
|
74
|
+
export declare const MAX_MATCH_TEXT_LENGTH = 10000;
|
|
75
|
+
/**
|
|
76
|
+
* Detects a quantifier applied to a group that itself contains a quantifier —
|
|
77
|
+
* the `(a+)+` / `(a*)*` / `(a+|b)*` family behind exponential backtracking.
|
|
78
|
+
* Conservative: it can reject a benign pattern, which only costs a fallback to
|
|
79
|
+
* literal search, never a hang.
|
|
80
|
+
*/
|
|
81
|
+
export declare function isDangerousPattern(pattern: string): boolean;
|
|
66
82
|
/** True when this event trigger matches this event. */
|
|
67
83
|
export declare function eventTriggerMatches(spec: EventTriggerSpec, event: AppEvent): boolean;
|
|
68
84
|
/** Length of the UUID prefix used as a readable loop identifier. */
|
package/dist/core/cues.js
CHANGED
|
@@ -144,13 +144,66 @@ function directoryMatches(intentionDir, eventDir) {
|
|
|
144
144
|
const b = normalizePath(eventDir).replace(/\/$/, '');
|
|
145
145
|
return b === a || b.startsWith(`${a}/`) || a.startsWith(`${b}/`);
|
|
146
146
|
}
|
|
147
|
-
/**
|
|
147
|
+
/**
|
|
148
|
+
* Hard caps on regex evaluation (SECURITY_AUDIT.md M-01). The pattern and the
|
|
149
|
+
* event text both come from unauthenticated callers, and the native RegExp engine
|
|
150
|
+
* backtracks: `^(a+)+$` against a long non-matching string pins the event loop.
|
|
151
|
+
* The engine cannot be given a deadline, so the inputs are bounded instead and
|
|
152
|
+
* the shapes that make catastrophic backtracking possible are refused outright.
|
|
153
|
+
*/
|
|
154
|
+
export const MAX_PATTERN_LENGTH = 200;
|
|
155
|
+
export const MAX_MATCH_TEXT_LENGTH = 10_000;
|
|
156
|
+
/**
|
|
157
|
+
* Detects a quantifier applied to a group that itself contains a quantifier —
|
|
158
|
+
* the `(a+)+` / `(a*)*` / `(a+|b)*` family behind exponential backtracking.
|
|
159
|
+
* Conservative: it can reject a benign pattern, which only costs a fallback to
|
|
160
|
+
* literal search, never a hang.
|
|
161
|
+
*/
|
|
162
|
+
export function isDangerousPattern(pattern) {
|
|
163
|
+
if (pattern.length > MAX_PATTERN_LENGTH)
|
|
164
|
+
return true;
|
|
165
|
+
// Walk the groups, tracking whether each holds an unescaped quantifier, and
|
|
166
|
+
// flag any group that is itself quantified on close.
|
|
167
|
+
const stack = [];
|
|
168
|
+
for (let i = 0; i < pattern.length; i++) {
|
|
169
|
+
const ch = pattern[i];
|
|
170
|
+
if (ch === '\\') {
|
|
171
|
+
i++; // escaped char: never a quantifier or a group delimiter
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
if (ch === '(') {
|
|
175
|
+
stack.push(false);
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
if (ch === ')') {
|
|
179
|
+
const innerHadQuantifier = stack.pop() ?? false;
|
|
180
|
+
const next = pattern[i + 1];
|
|
181
|
+
const outerQuantified = next === '+' || next === '*' || next === '{';
|
|
182
|
+
if (innerHadQuantifier && outerQuantified)
|
|
183
|
+
return true;
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
if (ch === '+' || ch === '*' || ch === '{') {
|
|
187
|
+
if (stack.length > 0)
|
|
188
|
+
stack[stack.length - 1] = true;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return false;
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Tests an error pattern. A pattern that is invalid, oversized or shaped for
|
|
195
|
+
* catastrophic backtracking falls back to a literal, non-backtracking search.
|
|
196
|
+
*/
|
|
148
197
|
function errorPatternMatches(pattern, text) {
|
|
198
|
+
const bounded = text.length > MAX_MATCH_TEXT_LENGTH ? text.slice(0, MAX_MATCH_TEXT_LENGTH) : text;
|
|
199
|
+
if (isDangerousPattern(pattern)) {
|
|
200
|
+
return bounded.toLowerCase().includes(pattern.toLowerCase());
|
|
201
|
+
}
|
|
149
202
|
try {
|
|
150
|
-
return new RegExp(pattern, 'i').test(
|
|
203
|
+
return new RegExp(pattern, 'i').test(bounded);
|
|
151
204
|
}
|
|
152
205
|
catch {
|
|
153
|
-
return
|
|
206
|
+
return bounded.toLowerCase().includes(pattern.toLowerCase());
|
|
154
207
|
}
|
|
155
208
|
}
|
|
156
209
|
/** True when this event trigger matches this event. */
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `LLMClient` backed by a local agent CLI instead of a hosted API key.
|
|
3
|
+
*
|
|
4
|
+
* humemory's consolidation path is deterministic and network-free by default;
|
|
5
|
+
* this adapter exists for machines that have no `ANTHROPIC_API_KEY` but do have
|
|
6
|
+
* a logged-in coding agent on the PATH. It is opt-in
|
|
7
|
+
* (`HUMEMORY_MAINTENANCE_LLM=codex`) and every failure falls back to the
|
|
8
|
+
* deterministic extractor upstream, so a missing binary is never fatal.
|
|
9
|
+
*
|
|
10
|
+
* Three flags matter and none of them are cosmetic:
|
|
11
|
+
* --ephemeral no rollout is written under ~/.codex/sessions. Without
|
|
12
|
+
* it, each consolidation leaves a session that humemory
|
|
13
|
+
* would later ingest as a trace — memory eating itself.
|
|
14
|
+
* --ignore-user-config skips the user's skills, plugins and hooks. Cheaper
|
|
15
|
+
* (~2k fewer tokens per call, half the latency) and it
|
|
16
|
+
* stops a humemory Stop hook wired into codex from
|
|
17
|
+
* re-entering humemory while maintenance is running.
|
|
18
|
+
* -s read-only consolidation summarises text; it never needs a write.
|
|
19
|
+
*/
|
|
20
|
+
import type { LLMClient } from './llm-generator.js';
|
|
21
|
+
/** Runs one non-interactive agent turn and resolves with its final message. */
|
|
22
|
+
export type CliRunner = (prompt: string, opts: {
|
|
23
|
+
timeoutMs: number;
|
|
24
|
+
}) => Promise<string>;
|
|
25
|
+
export interface CodexClientOptions {
|
|
26
|
+
/** Model id. Unset means the CLI's own default — mini models are rejected on ChatGPT accounts. */
|
|
27
|
+
model?: string;
|
|
28
|
+
/** Wall-clock budget for one turn. Agent start-up alone is several seconds. */
|
|
29
|
+
timeoutMs?: number;
|
|
30
|
+
/** Injected in tests; the default spawns the real `codex` binary. */
|
|
31
|
+
runner?: CliRunner;
|
|
32
|
+
}
|
|
33
|
+
/** Strips the ```json fences a chat-tuned model wraps around structured output. */
|
|
34
|
+
export declare function unfence(text: string): string;
|
|
35
|
+
/** Flattens an Anthropic-shaped request into one prompt string for a CLI turn. */
|
|
36
|
+
export declare function flattenPrompt(params: any): string;
|
|
37
|
+
export declare function codexArgs(outputPath: string, model?: string): string[];
|
|
38
|
+
/**
|
|
39
|
+
* Wraps a coding-agent CLI in the `LLMClient` shape the consolidation path expects.
|
|
40
|
+
* Only the fields `generateMemoryLevels` reads are honoured — this is a duck, not
|
|
41
|
+
* an SDK: no streaming, no tools, no token accounting.
|
|
42
|
+
*/
|
|
43
|
+
export declare function createCodexClient(options?: CodexClientOptions): LLMClient;
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `LLMClient` backed by a local agent CLI instead of a hosted API key.
|
|
3
|
+
*
|
|
4
|
+
* humemory's consolidation path is deterministic and network-free by default;
|
|
5
|
+
* this adapter exists for machines that have no `ANTHROPIC_API_KEY` but do have
|
|
6
|
+
* a logged-in coding agent on the PATH. It is opt-in
|
|
7
|
+
* (`HUMEMORY_MAINTENANCE_LLM=codex`) and every failure falls back to the
|
|
8
|
+
* deterministic extractor upstream, so a missing binary is never fatal.
|
|
9
|
+
*
|
|
10
|
+
* Three flags matter and none of them are cosmetic:
|
|
11
|
+
* --ephemeral no rollout is written under ~/.codex/sessions. Without
|
|
12
|
+
* it, each consolidation leaves a session that humemory
|
|
13
|
+
* would later ingest as a trace — memory eating itself.
|
|
14
|
+
* --ignore-user-config skips the user's skills, plugins and hooks. Cheaper
|
|
15
|
+
* (~2k fewer tokens per call, half the latency) and it
|
|
16
|
+
* stops a humemory Stop hook wired into codex from
|
|
17
|
+
* re-entering humemory while maintenance is running.
|
|
18
|
+
* -s read-only consolidation summarises text; it never needs a write.
|
|
19
|
+
*/
|
|
20
|
+
import { mkdtempSync, readFileSync, rmSync } from 'fs';
|
|
21
|
+
import { tmpdir } from 'os';
|
|
22
|
+
import { join } from 'path';
|
|
23
|
+
/** Strips the ```json fences a chat-tuned model wraps around structured output. */
|
|
24
|
+
export function unfence(text) {
|
|
25
|
+
const fenced = text.trim().match(/^```(?:json)?\s*\n([\s\S]*?)\n?```$/);
|
|
26
|
+
return (fenced ? fenced[1] : text).trim();
|
|
27
|
+
}
|
|
28
|
+
/** Flattens an Anthropic-shaped request into one prompt string for a CLI turn. */
|
|
29
|
+
export function flattenPrompt(params) {
|
|
30
|
+
const blocks = [];
|
|
31
|
+
const system = params?.system;
|
|
32
|
+
if (typeof system === 'string')
|
|
33
|
+
blocks.push(system);
|
|
34
|
+
else if (Array.isArray(system)) {
|
|
35
|
+
for (const part of system)
|
|
36
|
+
if (typeof part?.text === 'string')
|
|
37
|
+
blocks.push(part.text);
|
|
38
|
+
}
|
|
39
|
+
for (const message of params?.messages ?? []) {
|
|
40
|
+
const content = message?.content;
|
|
41
|
+
if (typeof content === 'string')
|
|
42
|
+
blocks.push(content);
|
|
43
|
+
else if (Array.isArray(content)) {
|
|
44
|
+
for (const part of content)
|
|
45
|
+
if (typeof part?.text === 'string')
|
|
46
|
+
blocks.push(part.text);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return blocks.join('\n\n');
|
|
50
|
+
}
|
|
51
|
+
export function codexArgs(outputPath, model) {
|
|
52
|
+
return [
|
|
53
|
+
'exec',
|
|
54
|
+
'--ephemeral',
|
|
55
|
+
'--ignore-user-config',
|
|
56
|
+
'--ignore-rules',
|
|
57
|
+
'--skip-git-repo-check',
|
|
58
|
+
'-s', 'read-only',
|
|
59
|
+
'-c', 'model_reasoning_effort="low"',
|
|
60
|
+
'-c', 'model_verbosity="low"',
|
|
61
|
+
...(model ? ['-m', model] : []),
|
|
62
|
+
'--color', 'never',
|
|
63
|
+
'-o', outputPath,
|
|
64
|
+
'-',
|
|
65
|
+
];
|
|
66
|
+
}
|
|
67
|
+
const spawnCodex = async (prompt, { timeoutMs }) => {
|
|
68
|
+
const dir = mkdtempSync(join(tmpdir(), 'humemory-codex-'));
|
|
69
|
+
const outputPath = join(dir, 'last-message.txt');
|
|
70
|
+
try {
|
|
71
|
+
const proc = Bun.spawn(['codex', ...codexArgs(outputPath, process.env.HUMEMORY_LLM_MODEL)], {
|
|
72
|
+
stdin: new TextEncoder().encode(prompt),
|
|
73
|
+
stdout: 'ignore',
|
|
74
|
+
stderr: 'pipe',
|
|
75
|
+
});
|
|
76
|
+
const timer = setTimeout(() => proc.kill(), timeoutMs);
|
|
77
|
+
let code;
|
|
78
|
+
try {
|
|
79
|
+
code = await proc.exited;
|
|
80
|
+
}
|
|
81
|
+
finally {
|
|
82
|
+
clearTimeout(timer);
|
|
83
|
+
}
|
|
84
|
+
if (code !== 0)
|
|
85
|
+
throw new Error(`codex exec exited ${code}: ${(await new Response(proc.stderr).text()).slice(0, 200)}`);
|
|
86
|
+
return readFileSync(outputPath, 'utf-8');
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
rmSync(dir, { recursive: true, force: true });
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
/**
|
|
93
|
+
* Wraps a coding-agent CLI in the `LLMClient` shape the consolidation path expects.
|
|
94
|
+
* Only the fields `generateMemoryLevels` reads are honoured — this is a duck, not
|
|
95
|
+
* an SDK: no streaming, no tools, no token accounting.
|
|
96
|
+
*/
|
|
97
|
+
export function createCodexClient(options = {}) {
|
|
98
|
+
const runner = options.runner ?? spawnCodex;
|
|
99
|
+
const timeoutMs = options.timeoutMs ?? 60_000;
|
|
100
|
+
return {
|
|
101
|
+
messages: {
|
|
102
|
+
create: async (params) => {
|
|
103
|
+
const text = await runner(flattenPrompt(params), { timeoutMs });
|
|
104
|
+
return { content: [{ type: 'text', text: unfence(text) }] };
|
|
105
|
+
},
|
|
106
|
+
},
|
|
107
|
+
};
|
|
108
|
+
}
|
package/dist/store/sqlite.d.ts
CHANGED
|
@@ -45,7 +45,15 @@ export declare class SQLiteStore implements MemoryStore, IntentionStore, ScriptS
|
|
|
45
45
|
private loadIntoMemory;
|
|
46
46
|
private rowToMemory;
|
|
47
47
|
private memoryToRow;
|
|
48
|
-
|
|
48
|
+
/**
|
|
49
|
+
* `createdAt` defaults to now, but a caller encoding an *older* session — a
|
|
50
|
+
* rollout swept days later — passes the instant it was lived. Age is what
|
|
51
|
+
* decay runs on, so a backdated trace arrives already degraded, exactly as if
|
|
52
|
+
* it had been encoded on the day.
|
|
53
|
+
*/
|
|
54
|
+
add(memory: Omit<Memory, 'id' | 'createdAt' | 'recallCount' | 'decayRate' | 'currentLevel' | 'saillance'> & {
|
|
55
|
+
createdAt?: Date;
|
|
56
|
+
}, options?: {
|
|
49
57
|
autoGenerate?: boolean;
|
|
50
58
|
}): Promise<Memory>;
|
|
51
59
|
getById(id: string): Promise<Memory | null>;
|
package/dist/store/sqlite.js
CHANGED
|
@@ -493,9 +493,16 @@ export class SQLiteStore {
|
|
|
493
493
|
$refuted_count: memory.refutedCount ?? 0,
|
|
494
494
|
};
|
|
495
495
|
}
|
|
496
|
+
/**
|
|
497
|
+
* `createdAt` defaults to now, but a caller encoding an *older* session — a
|
|
498
|
+
* rollout swept days later — passes the instant it was lived. Age is what
|
|
499
|
+
* decay runs on, so a backdated trace arrives already degraded, exactly as if
|
|
500
|
+
* it had been encoded on the day.
|
|
501
|
+
*/
|
|
496
502
|
async add(memory, options = {}) {
|
|
497
503
|
const id = crypto.randomUUID();
|
|
498
504
|
const now = this.clock.now();
|
|
505
|
+
const createdAt = memory.createdAt ?? now;
|
|
499
506
|
let generatedLevels = {};
|
|
500
507
|
if (options.autoGenerate && !memory.level1Summary) {
|
|
501
508
|
const memType = (memory.memoryType || 'semantic');
|
|
@@ -506,11 +513,11 @@ export class SQLiteStore {
|
|
|
506
513
|
...memory,
|
|
507
514
|
...generatedLevels,
|
|
508
515
|
id,
|
|
509
|
-
createdAt
|
|
516
|
+
createdAt,
|
|
510
517
|
recallCount: 0,
|
|
511
518
|
decayRate: calculateDecayRate(memory.content, memory.keywords),
|
|
512
519
|
currentLevel: 0,
|
|
513
|
-
saillance: calculateSaillance({ ...memory, id, createdAt
|
|
520
|
+
saillance: calculateSaillance({ ...memory, id, createdAt, recallCount: 0, decayRate: 0.5 }, now),
|
|
514
521
|
// Phase 6.0.1 — provenance defaults
|
|
515
522
|
source: memory.source ?? 'agent',
|
|
516
523
|
verified: memory.verified ?? false,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "humemory",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.5",
|
|
4
4
|
"description": "Memory for AI agents that forgets like a human — decaying traces, inverse search, and prospective loops that resurface on a cue",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -66,6 +66,7 @@
|
|
|
66
66
|
},
|
|
67
67
|
"devDependencies": {
|
|
68
68
|
"@happy-dom/global-registrator": "^20.11.1",
|
|
69
|
+
"@medyll/idae-pnpm-release": "1.0.46",
|
|
69
70
|
"@testing-library/dom": "^10.4.1",
|
|
70
71
|
"@testing-library/react": "^16.3.2",
|
|
71
72
|
"@types/d3": "^7.4.3",
|