humemory 0.2.7 → 0.2.9
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 +14 -7
- package/CHANGELOG.md +23 -0
- package/README.md +66 -12
- package/dist/agent/kimi-import.d.ts +19 -0
- package/dist/agent/kimi-import.js +111 -0
- package/dist/agent/kimi-session-parser.d.ts +3 -0
- package/dist/agent/kimi-session-parser.js +102 -0
- package/dist/agent/maintenance-queue.d.ts +2 -1
- package/dist/agent/maintenance-queue.js +36 -62
- package/dist/agent/maintenance-runner.d.ts +17 -4
- package/dist/agent/maintenance-runner.js +45 -10
- package/dist/agent/mcp-client-setup.d.ts +16 -0
- package/dist/agent/mcp-client-setup.js +108 -0
- package/dist/agent/opencode-import.d.ts +22 -0
- package/dist/agent/opencode-import.js +71 -0
- package/dist/agent/opencode-session-parser.d.ts +3 -0
- package/dist/agent/opencode-session-parser.js +35 -0
- package/dist/agent/session-parser.d.ts +8 -0
- package/dist/agent/session-parser.js +18 -0
- package/dist/agent/source-registry.js +1 -1
- package/dist/api/memory-routes.js +1 -1
- package/dist/api/server.js +3 -2
- package/dist/cli/index.js +117 -6
- package/dist/core/cues.d.ts +1 -0
- package/dist/core/cues.js +19 -7
- package/dist/core/doctor.d.ts +28 -0
- package/dist/core/doctor.js +320 -0
- package/dist/core/embeddings.d.ts +0 -10
- package/dist/core/embeddings.js +2 -1
- package/dist/core/hybrid.d.ts +7 -3
- package/dist/core/hybrid.js +7 -3
- package/dist/core/llm-generator.d.ts +2 -10
- package/dist/core/paths.d.ts +12 -0
- package/dist/core/paths.js +36 -0
- package/dist/core/project-path.d.ts +3 -0
- package/dist/core/project-path.js +14 -0
- package/dist/core/search.d.ts +1 -1
- package/dist/core/search.js +7 -9
- package/dist/core/types.d.ts +13 -1
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/store/sqlite.d.ts +37 -0
- package/dist/store/sqlite.js +94 -42
- package/docs/PORTABILITY.md +84 -0
- package/package.json +5 -3
- package/public/app/{index-95ffty7j.js → index-n2qg9hyr.js} +6 -6
- package/public/app/index.html +1 -1
- package/scripts/consolidate.js +4 -4
- package/scripts/hook-post-commit.ts +2 -1
- package/scripts/hook-session-start.ts +2 -1
- package/scripts/hook-session.ts +2 -1
- package/scripts/maintenance-worker.ts +7 -2
- package/src/agent/claude-hook.ts +126 -0
- package/src/agent/codex-import.ts +129 -0
- package/src/agent/codex-rollout-parser.ts +121 -0
- package/src/agent/commit-closer.ts +173 -0
- package/src/agent/kimi-import.ts +128 -0
- package/src/agent/kimi-session-parser.ts +127 -0
- package/src/agent/learning-extractor.ts +128 -0
- package/src/agent/maintenance-queue.ts +544 -0
- package/src/agent/maintenance-runner.ts +322 -0
- package/src/agent/maintenance-state.ts +168 -0
- package/src/agent/mcp-client-setup.ts +125 -0
- package/src/agent/opencode-import.ts +96 -0
- package/src/agent/opencode-session-parser.ts +53 -0
- package/src/agent/session-context.ts +302 -0
- package/src/agent/session-parser.ts +155 -0
- package/src/agent/source-registry.ts +135 -0
- package/src/api/cors.ts +42 -0
- package/src/api/dream-routes.ts +46 -0
- package/src/api/errors.ts +45 -0
- package/src/api/intentions-routes.ts +348 -0
- package/src/api/limits.ts +90 -0
- package/src/api/maintenance-routes.ts +73 -0
- package/src/api/memory-routes.ts +391 -0
- package/src/api/scripts-routes.ts +176 -0
- package/src/api/security-headers.ts +54 -0
- package/src/api/server.ts +292 -0
- package/src/cli/index.ts +1195 -0
- package/src/core/clock.ts +64 -0
- package/src/core/cue-arg.ts +79 -0
- package/src/core/cues.ts +511 -0
- package/src/core/decay.ts +198 -0
- package/src/core/doctor.ts +362 -0
- package/src/core/dreamer.ts +494 -0
- package/src/core/embeddings.ts +157 -0
- package/src/core/event-bus.ts +100 -0
- package/src/core/hybrid.ts +82 -0
- package/src/core/llm-cli-client.ts +118 -0
- package/src/core/llm-generator.ts +90 -0
- package/src/core/paths.ts +38 -0
- package/src/core/project-path.ts +14 -0
- package/src/core/sanitize.ts +116 -0
- package/src/core/scripts.ts +112 -0
- package/src/core/search.ts +189 -0
- package/src/core/trust.ts +67 -0
- package/src/core/types.ts +393 -0
- package/src/core/vector-clusterer.ts +131 -0
- package/src/index.ts +40 -0
- package/src/mcp/HTTP_TRANSPORT.md +359 -0
- package/src/mcp/server.ts +202 -0
- package/src/store/sqlite.ts +1958 -0
|
@@ -17,6 +17,8 @@ import type { LLMClient } from '../core/llm-generator.js';
|
|
|
17
17
|
import type { Clock } from '../core/clock.js';
|
|
18
18
|
import { type WorkerResult } from './maintenance-queue.js';
|
|
19
19
|
import { type CodexImportResult } from './codex-import.js';
|
|
20
|
+
import { type KimiImportResult } from './kimi-import.js';
|
|
21
|
+
import { type OpenCodeCommandRunner, type OpenCodeImportResult } from './opencode-import.js';
|
|
20
22
|
export declare const DEFAULT_INTERVAL_MS: number;
|
|
21
23
|
export interface MaintenancePassOptions {
|
|
22
24
|
queueDir?: string;
|
|
@@ -26,6 +28,15 @@ export interface MaintenancePassOptions {
|
|
|
26
28
|
codexSinceDays?: number | false;
|
|
27
29
|
/** Overrides `$CODEX_HOME/sessions`; mainly a test seam. */
|
|
28
30
|
codexSessionsDir?: string;
|
|
31
|
+
/** Days of Kimi Code sessions to sweep in. `false` skips Kimi. */
|
|
32
|
+
kimiSinceDays?: number | false;
|
|
33
|
+
/** Overrides `$KIMI_CODE_HOME`; mainly a test seam. */
|
|
34
|
+
kimiHome?: string;
|
|
35
|
+
/** Days of OpenCode sessions to sweep in. `false` skips OpenCode. */
|
|
36
|
+
opencodeSinceDays?: number | false;
|
|
37
|
+
/** Test seam for the otherwise local, logged-in OpenCode CLI. */
|
|
38
|
+
opencodeRun?: OpenCodeCommandRunner;
|
|
39
|
+
opencodeCommand?: string;
|
|
29
40
|
client?: LLMClient;
|
|
30
41
|
llmTimeoutMs?: number;
|
|
31
42
|
maxJobs?: number;
|
|
@@ -35,8 +46,11 @@ export interface MaintenancePassOptions {
|
|
|
35
46
|
}
|
|
36
47
|
export interface MaintenancePassResult {
|
|
37
48
|
codex?: CodexImportResult;
|
|
38
|
-
/** Set when the codex import failed; the queue is still drained regardless. */
|
|
39
49
|
codexError?: string;
|
|
50
|
+
kimi?: KimiImportResult;
|
|
51
|
+
kimiError?: string;
|
|
52
|
+
opencode?: OpenCodeImportResult;
|
|
53
|
+
opencodeError?: string;
|
|
40
54
|
worker: WorkerResult;
|
|
41
55
|
}
|
|
42
56
|
export declare function defaultQueueDir(): string;
|
|
@@ -50,9 +64,8 @@ export declare function configuredIntervalMs(): number;
|
|
|
50
64
|
*/
|
|
51
65
|
export declare function resolveMaintenanceClient(timeoutMs?: number): Promise<LLMClient | undefined>;
|
|
52
66
|
/**
|
|
53
|
-
* Import, then drain, then record.
|
|
54
|
-
*
|
|
55
|
-
* from every other source.
|
|
67
|
+
* Import, then drain, then record. Every producer is isolated: a missing or
|
|
68
|
+
* unreadable runtime must never stall the queue or another producer.
|
|
56
69
|
*
|
|
57
70
|
* Throws only if the queue itself could not be drained — the caller records
|
|
58
71
|
* that failure and stays alive.
|
|
@@ -13,20 +13,23 @@
|
|
|
13
13
|
* it succeeds or fails, so a loop that has silently stopped is detectable from
|
|
14
14
|
* the CLI and the API instead of being noticed weeks later.
|
|
15
15
|
*/
|
|
16
|
-
import { dirname
|
|
16
|
+
import { dirname } from 'path';
|
|
17
17
|
import { fileURLToPath } from 'url';
|
|
18
18
|
import { systemClock } from '../core/clock.js';
|
|
19
|
+
import { databasePath, queueDirectory } from '../core/paths.js';
|
|
19
20
|
import { createCodexClient } from '../core/llm-cli-client.js';
|
|
20
21
|
import { processMaintenanceQueue } from './maintenance-queue.js';
|
|
21
22
|
import { importCodexRollouts, defaultCodexSessionsDir } from './codex-import.js';
|
|
23
|
+
import { importKimiSessions, defaultKimiHome } from './kimi-import.js';
|
|
24
|
+
import { importOpenCodeSessions, } from './opencode-import.js';
|
|
22
25
|
import { defaultStatePath, recordMaintenanceRun } from './maintenance-state.js';
|
|
23
26
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
24
27
|
export const DEFAULT_INTERVAL_MS = 15 * 60 * 1000;
|
|
25
28
|
export function defaultQueueDir() {
|
|
26
|
-
return
|
|
29
|
+
return queueDirectory();
|
|
27
30
|
}
|
|
28
31
|
export function defaultDbPath() {
|
|
29
|
-
return
|
|
32
|
+
return databasePath();
|
|
30
33
|
}
|
|
31
34
|
export function defaultLlmTimeoutMs() {
|
|
32
35
|
return Number(process.env.HUMEMORY_MAINTENANCE_TIMEOUT_MS ?? 8_000);
|
|
@@ -54,9 +57,8 @@ export async function resolveMaintenanceClient(timeoutMs = defaultLlmTimeoutMs()
|
|
|
54
57
|
return undefined;
|
|
55
58
|
}
|
|
56
59
|
/**
|
|
57
|
-
* Import, then drain, then record.
|
|
58
|
-
*
|
|
59
|
-
* from every other source.
|
|
60
|
+
* Import, then drain, then record. Every producer is isolated: a missing or
|
|
61
|
+
* unreadable runtime must never stall the queue or another producer.
|
|
60
62
|
*
|
|
61
63
|
* Throws only if the queue itself could not be drained — the caller records
|
|
62
64
|
* that failure and stays alive.
|
|
@@ -67,16 +69,18 @@ export async function runMaintenancePass(options = {}) {
|
|
|
67
69
|
const dbPath = options.dbPath ?? defaultDbPath();
|
|
68
70
|
const statePath = options.statePath ?? defaultStatePath(queueDir);
|
|
69
71
|
const llmTimeoutMs = options.llmTimeoutMs ?? defaultLlmTimeoutMs();
|
|
70
|
-
const
|
|
72
|
+
const codexSinceDays = options.codexSinceDays ?? 1;
|
|
73
|
+
const kimiSinceDays = options.kimiSinceDays ?? 1;
|
|
74
|
+
const opencodeSinceDays = options.opencodeSinceDays ?? 1;
|
|
71
75
|
const startedAt = clock.now();
|
|
72
76
|
let codex;
|
|
73
77
|
let codexError;
|
|
74
|
-
if (
|
|
78
|
+
if (codexSinceDays !== false) {
|
|
75
79
|
try {
|
|
76
80
|
codex = await importCodexRollouts({
|
|
77
81
|
queueDir,
|
|
78
82
|
sessionsDir: options.codexSessionsDir ?? defaultCodexSessionsDir(),
|
|
79
|
-
since: new Date(startedAt.getTime() -
|
|
83
|
+
since: new Date(startedAt.getTime() - codexSinceDays * 24 * 60 * 60 * 1000),
|
|
80
84
|
});
|
|
81
85
|
}
|
|
82
86
|
catch (error) {
|
|
@@ -84,6 +88,37 @@ export async function runMaintenancePass(options = {}) {
|
|
|
84
88
|
console.error('[humemory] maintenance: codex import failed —', codexError);
|
|
85
89
|
}
|
|
86
90
|
}
|
|
91
|
+
let kimi;
|
|
92
|
+
let kimiError;
|
|
93
|
+
if (kimiSinceDays !== false) {
|
|
94
|
+
try {
|
|
95
|
+
kimi = await importKimiSessions({
|
|
96
|
+
queueDir,
|
|
97
|
+
kimiHome: options.kimiHome ?? defaultKimiHome(),
|
|
98
|
+
since: new Date(startedAt.getTime() - kimiSinceDays * 24 * 60 * 60 * 1000),
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
kimiError = error.message;
|
|
103
|
+
console.error('[humemory] maintenance: Kimi import failed —', kimiError);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
let opencode;
|
|
107
|
+
let opencodeError;
|
|
108
|
+
if (opencodeSinceDays !== false) {
|
|
109
|
+
try {
|
|
110
|
+
opencode = await importOpenCodeSessions({
|
|
111
|
+
queueDir,
|
|
112
|
+
since: new Date(startedAt.getTime() - opencodeSinceDays * 24 * 60 * 60 * 1000),
|
|
113
|
+
run: options.opencodeRun,
|
|
114
|
+
command: options.opencodeCommand,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
opencodeError = error.message;
|
|
119
|
+
console.error('[humemory] maintenance: OpenCode import failed —', opencodeError);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
87
122
|
try {
|
|
88
123
|
const worker = await processMaintenanceQueue({
|
|
89
124
|
queueDir,
|
|
@@ -119,7 +154,7 @@ export async function runMaintenancePass(options = {}) {
|
|
|
119
154
|
aborted: worker.aborted,
|
|
120
155
|
},
|
|
121
156
|
});
|
|
122
|
-
return { codex, codexError, worker };
|
|
157
|
+
return { codex, codexError, kimi, kimiError, opencode, opencodeError, worker };
|
|
123
158
|
}
|
|
124
159
|
catch (error) {
|
|
125
160
|
await recordMaintenanceRun({ path: statePath, startedAt, clock, runner: options.runner, error });
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export type HumemoryMcpClient = 'kimi' | 'opencode';
|
|
2
|
+
export interface McpClientSetupOptions {
|
|
3
|
+
clients: HumemoryMcpClient[];
|
|
4
|
+
projectRoot: string;
|
|
5
|
+
dbPath?: string;
|
|
6
|
+
bunPath?: string;
|
|
7
|
+
kimiHome?: string;
|
|
8
|
+
openCodeConfig?: string;
|
|
9
|
+
dryRun?: boolean;
|
|
10
|
+
}
|
|
11
|
+
export interface McpClientSetupEntry {
|
|
12
|
+
client: HumemoryMcpClient;
|
|
13
|
+
path: string;
|
|
14
|
+
changed: boolean;
|
|
15
|
+
}
|
|
16
|
+
export declare function setupHumemoryMcpClients(options: McpClientSetupOptions): Promise<McpClientSetupEntry[]>;
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/** Safe, merge-only MCP registration for locally installed agent clients. */
|
|
2
|
+
import { mkdir, readFile, writeFile, rename, rm } from 'fs/promises';
|
|
3
|
+
import { randomUUID } from 'crypto';
|
|
4
|
+
import { dirname, join, resolve } from 'path';
|
|
5
|
+
import { homedir } from 'os';
|
|
6
|
+
import { databasePath } from '../core/paths.js';
|
|
7
|
+
import { AdvisoryLock } from '../store/sqlite.js';
|
|
8
|
+
async function readOptional(path) {
|
|
9
|
+
try {
|
|
10
|
+
return await readFile(path, 'utf8');
|
|
11
|
+
}
|
|
12
|
+
catch (error) {
|
|
13
|
+
if (error?.code === 'ENOENT')
|
|
14
|
+
return null;
|
|
15
|
+
throw error;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function readJson(raw, path) {
|
|
19
|
+
if (raw === null)
|
|
20
|
+
return {};
|
|
21
|
+
try {
|
|
22
|
+
const parsed = JSON.parse(raw);
|
|
23
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
24
|
+
throw new Error('expected an object');
|
|
25
|
+
for (const key of ['mcp', 'mcpServers']) {
|
|
26
|
+
if (key in parsed && (!parsed[key] || typeof parsed[key] !== 'object' || Array.isArray(parsed[key]))) {
|
|
27
|
+
throw new Error(`${key} must be an object`);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return parsed;
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
throw new Error(`Refusing to rewrite invalid or commented JSON: ${path} (${error.message})`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
async function mergeFile(path, update, dryRun) {
|
|
37
|
+
const apply = async () => {
|
|
38
|
+
const original = await readOptional(path);
|
|
39
|
+
const current = readJson(original, path);
|
|
40
|
+
const before = JSON.stringify(current);
|
|
41
|
+
const next = update(current);
|
|
42
|
+
const changed = before !== JSON.stringify(next);
|
|
43
|
+
if (changed && !dryRun) {
|
|
44
|
+
await mkdir(dirname(path), { recursive: true });
|
|
45
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
46
|
+
try {
|
|
47
|
+
await writeFile(temporary, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
|
|
48
|
+
if (original !== null)
|
|
49
|
+
await writeFile(`${path}.${randomUUID()}.bak`, original, { mode: 0o600, flag: 'wx' });
|
|
50
|
+
if (await readOptional(path) !== original)
|
|
51
|
+
throw new Error(`Configuration changed during setup: ${path}`);
|
|
52
|
+
await rename(temporary, path);
|
|
53
|
+
}
|
|
54
|
+
finally {
|
|
55
|
+
await rm(temporary, { force: true });
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return changed;
|
|
59
|
+
};
|
|
60
|
+
if (dryRun)
|
|
61
|
+
return apply();
|
|
62
|
+
await mkdir(dirname(path), { recursive: true });
|
|
63
|
+
return new AdvisoryLock(path + '.setup', 50).withLock(apply);
|
|
64
|
+
}
|
|
65
|
+
export async function setupHumemoryMcpClients(options) {
|
|
66
|
+
const projectRoot = resolve(options.projectRoot);
|
|
67
|
+
const serverPath = join(projectRoot, 'src', 'mcp', 'server.ts');
|
|
68
|
+
const configuredDb = options.dbPath ?? databasePath();
|
|
69
|
+
const dbPath = configuredDb === ':memory:' ? configuredDb : resolve(configuredDb);
|
|
70
|
+
const bunPath = resolve(options.bunPath ?? process.execPath);
|
|
71
|
+
const dryRun = options.dryRun ?? false;
|
|
72
|
+
const entries = [];
|
|
73
|
+
for (const client of [...new Set(options.clients)]) {
|
|
74
|
+
if (client === 'kimi') {
|
|
75
|
+
const path = join(options.kimiHome ?? process.env.KIMI_CODE_HOME ?? join(homedir(), '.kimi-code'), 'mcp.json');
|
|
76
|
+
const changed = await mergeFile(path, (current) => ({
|
|
77
|
+
...current,
|
|
78
|
+
mcpServers: {
|
|
79
|
+
...(current.mcpServers ?? {}),
|
|
80
|
+
humemory: {
|
|
81
|
+
command: bunPath,
|
|
82
|
+
args: ['run', serverPath],
|
|
83
|
+
env: { HUMEMORY_AGENT: 'kimi', HUMEMORY_DB: dbPath },
|
|
84
|
+
},
|
|
85
|
+
},
|
|
86
|
+
}), dryRun);
|
|
87
|
+
entries.push({ client, path, changed });
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
const path = options.openCodeConfig ?? process.env.OPENCODE_CONFIG ??
|
|
91
|
+
join(homedir(), '.config', 'opencode', 'opencode.json');
|
|
92
|
+
const changed = await mergeFile(path, (current) => ({
|
|
93
|
+
...current,
|
|
94
|
+
$schema: current.$schema ?? 'https://opencode.ai/config.json',
|
|
95
|
+
mcp: {
|
|
96
|
+
...(current.mcp ?? {}),
|
|
97
|
+
humemory: {
|
|
98
|
+
type: 'local',
|
|
99
|
+
command: [bunPath, 'run', serverPath],
|
|
100
|
+
enabled: true,
|
|
101
|
+
environment: { HUMEMORY_AGENT: 'opencode', HUMEMORY_DB: dbPath },
|
|
102
|
+
},
|
|
103
|
+
},
|
|
104
|
+
}), dryRun);
|
|
105
|
+
entries.push({ client, path, changed });
|
|
106
|
+
}
|
|
107
|
+
return entries;
|
|
108
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export declare const OPENCODE_SOURCE = "opencode-session";
|
|
2
|
+
export type OpenCodeCommandRunner = (args: string[]) => Promise<string>;
|
|
3
|
+
export interface OpenCodeImportOptions {
|
|
4
|
+
queueDir: string;
|
|
5
|
+
since?: Date;
|
|
6
|
+
limit?: number;
|
|
7
|
+
includeSubagents?: boolean;
|
|
8
|
+
dryRun?: boolean;
|
|
9
|
+
maxLearnings?: number;
|
|
10
|
+
command?: string;
|
|
11
|
+
run?: OpenCodeCommandRunner;
|
|
12
|
+
}
|
|
13
|
+
export interface OpenCodeImportResult {
|
|
14
|
+
scanned: number;
|
|
15
|
+
queued: number;
|
|
16
|
+
created: number;
|
|
17
|
+
skippedEmpty: number;
|
|
18
|
+
unreadable: number;
|
|
19
|
+
}
|
|
20
|
+
export declare function defaultOpenCodeCommand(): string;
|
|
21
|
+
export declare function createOpenCodeRunner(command?: string): OpenCodeCommandRunner;
|
|
22
|
+
export declare function importOpenCodeSessions(options: OpenCodeImportOptions): Promise<OpenCodeImportResult>;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/** Import OpenCode's public session exports into the maintenance queue. */
|
|
2
|
+
import { execFile } from 'child_process';
|
|
3
|
+
import { promisify } from 'util';
|
|
4
|
+
import { enqueueSession } from './maintenance-queue.js';
|
|
5
|
+
import { parseOpenCodeExport } from './opencode-session-parser.js';
|
|
6
|
+
import { serializeAgentSession } from './session-parser.js';
|
|
7
|
+
const execFileAsync = promisify(execFile);
|
|
8
|
+
export const OPENCODE_SOURCE = 'opencode-session';
|
|
9
|
+
export function defaultOpenCodeCommand() {
|
|
10
|
+
return process.env.HUMEMORY_OPENCODE_COMMAND ?? (process.platform === 'win32' ? 'opencode.cmd' : 'opencode');
|
|
11
|
+
}
|
|
12
|
+
export function createOpenCodeRunner(command = defaultOpenCodeCommand()) {
|
|
13
|
+
return async (args) => {
|
|
14
|
+
const { stdout } = await execFileAsync(command, args, {
|
|
15
|
+
encoding: 'utf8',
|
|
16
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
17
|
+
windowsHide: true,
|
|
18
|
+
});
|
|
19
|
+
return stdout;
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
export async function importOpenCodeSessions(options) {
|
|
23
|
+
const run = options.run ?? createOpenCodeRunner(options.command);
|
|
24
|
+
const conditions = [];
|
|
25
|
+
if (options.since)
|
|
26
|
+
conditions.push(`time_updated >= ${options.since.getTime()}`);
|
|
27
|
+
if (!options.includeSubagents)
|
|
28
|
+
conditions.push('parent_id IS NULL');
|
|
29
|
+
const where = conditions.length ? ` WHERE ${conditions.join(' AND ')}` : '';
|
|
30
|
+
const sql = `SELECT id, directory FROM session${where} ORDER BY time_updated ASC`;
|
|
31
|
+
const rows = JSON.parse(await run(['db', sql, '--format', 'json']));
|
|
32
|
+
const result = {
|
|
33
|
+
scanned: rows.length,
|
|
34
|
+
queued: 0,
|
|
35
|
+
created: 0,
|
|
36
|
+
skippedEmpty: 0,
|
|
37
|
+
unreadable: 0,
|
|
38
|
+
};
|
|
39
|
+
for (const row of rows) {
|
|
40
|
+
if (options.limit !== undefined && result.queued >= options.limit)
|
|
41
|
+
break;
|
|
42
|
+
if (!row.id) {
|
|
43
|
+
result.unreadable += 1;
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
try {
|
|
47
|
+
const parsed = parseOpenCodeExport(await run(['export', row.id]), row.directory ?? process.cwd());
|
|
48
|
+
if (!parsed.messages.some((message) => message.role === 'user') ||
|
|
49
|
+
!parsed.messages.some((message) => message.role === 'assistant')) {
|
|
50
|
+
result.skippedEmpty += 1;
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
result.queued += 1;
|
|
54
|
+
if (options.dryRun)
|
|
55
|
+
continue;
|
|
56
|
+
const queued = await enqueueSession(serializeAgentSession(parsed), {
|
|
57
|
+
queueDir: options.queueDir,
|
|
58
|
+
directory: parsed.directory,
|
|
59
|
+
source: OPENCODE_SOURCE,
|
|
60
|
+
agent: 'opencode',
|
|
61
|
+
maxLearnings: options.maxLearnings,
|
|
62
|
+
});
|
|
63
|
+
if (queued.created)
|
|
64
|
+
result.created += 1;
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
result.unreadable += 1;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return result;
|
|
71
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
function timestamp(value) {
|
|
2
|
+
if (value === undefined)
|
|
3
|
+
return undefined;
|
|
4
|
+
const date = typeof value === 'number' ? new Date(value) : new Date(value);
|
|
5
|
+
return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
|
|
6
|
+
}
|
|
7
|
+
/** Parse the public `opencode export` JSON shape, excluding tools and reasoning. */
|
|
8
|
+
export function parseOpenCodeExport(raw, fallbackDirectory) {
|
|
9
|
+
const payload = JSON.parse(raw);
|
|
10
|
+
const messages = [];
|
|
11
|
+
for (const entry of payload.messages ?? []) {
|
|
12
|
+
const role = entry.info?.role;
|
|
13
|
+
if (role !== 'user' && role !== 'assistant')
|
|
14
|
+
continue;
|
|
15
|
+
const content = (entry.parts ?? [])
|
|
16
|
+
.filter((part) => part.type === 'text' && typeof part.text === 'string')
|
|
17
|
+
.map((part) => part.text.trim())
|
|
18
|
+
.filter(Boolean)
|
|
19
|
+
.join('\n');
|
|
20
|
+
if (!content)
|
|
21
|
+
continue;
|
|
22
|
+
messages.push({ role, content, timestamp: timestamp(entry.info?.time?.created) });
|
|
23
|
+
}
|
|
24
|
+
const occurredAt = [...messages]
|
|
25
|
+
.reverse()
|
|
26
|
+
.map((message) => message.timestamp ? new Date(message.timestamp) : undefined)
|
|
27
|
+
.find((date) => date && !Number.isNaN(date.getTime()));
|
|
28
|
+
return {
|
|
29
|
+
sessionId: payload.info?.id ?? 'opencode-unknown-session',
|
|
30
|
+
directory: payload.info?.directory ?? payload.info?.path ?? fallbackDirectory,
|
|
31
|
+
messages,
|
|
32
|
+
rawText: messages.map((message) => `${message.role}: ${message.content}`).join('\n\n'),
|
|
33
|
+
occurredAt,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
@@ -16,6 +16,14 @@ export interface ParsedSession {
|
|
|
16
16
|
*/
|
|
17
17
|
occurredAt?: Date;
|
|
18
18
|
}
|
|
19
|
+
/**
|
|
20
|
+
* Canonical acquisition envelope consumed by the maintenance queue.
|
|
21
|
+
*
|
|
22
|
+
* Source-specific importers normalize their private formats once, then reuse
|
|
23
|
+
* the same parser/checkpoint path as the live Claude hook. Keeping the envelope
|
|
24
|
+
* here prevents every importer from inventing a subtly different transcript.
|
|
25
|
+
*/
|
|
26
|
+
export declare function serializeAgentSession(session: ParsedSession): string;
|
|
19
27
|
/** The instant a transcript line carries, when it carries a usable one. */
|
|
20
28
|
export declare function messageTime(message: SessionMessage | undefined): Date | undefined;
|
|
21
29
|
/** The last usable instant in a run of messages — the session's own clock. */
|
|
@@ -1,4 +1,22 @@
|
|
|
1
1
|
import { isCodexRollout, parseCodexRollout } from './codex-rollout-parser.js';
|
|
2
|
+
/**
|
|
3
|
+
* Canonical acquisition envelope consumed by the maintenance queue.
|
|
4
|
+
*
|
|
5
|
+
* Source-specific importers normalize their private formats once, then reuse
|
|
6
|
+
* the same parser/checkpoint path as the live Claude hook. Keeping the envelope
|
|
7
|
+
* here prevents every importer from inventing a subtly different transcript.
|
|
8
|
+
*/
|
|
9
|
+
export function serializeAgentSession(session) {
|
|
10
|
+
return JSON.stringify({
|
|
11
|
+
session_id: session.sessionId,
|
|
12
|
+
cwd: session.directory,
|
|
13
|
+
transcript: session.messages.map((message) => ({
|
|
14
|
+
role: message.role,
|
|
15
|
+
content: message.content,
|
|
16
|
+
timestamp: message.timestamp,
|
|
17
|
+
})),
|
|
18
|
+
});
|
|
19
|
+
}
|
|
2
20
|
/** The instant a transcript line carries, when it carries a usable one. */
|
|
3
21
|
export function messageTime(message) {
|
|
4
22
|
if (!message?.timestamp)
|
|
@@ -21,7 +21,7 @@ export const KNOWN_AGENT_SOURCES = [
|
|
|
21
21
|
},
|
|
22
22
|
{
|
|
23
23
|
id: 'opencode', name: 'OpenCode', vendor: 'SST', commands: ['opencode'],
|
|
24
|
-
roots: [home('.opencode'), appData('opencode'), localAppData('opencode')],
|
|
24
|
+
roots: [home('.opencode'), home('.local', 'share', 'opencode'), home('.config', 'opencode'), appData('opencode'), localAppData('opencode')],
|
|
25
25
|
},
|
|
26
26
|
{
|
|
27
27
|
id: 'qwen-code', name: 'Qwen Code', vendor: 'Alibaba Cloud', commands: ['qwen'],
|
|
@@ -29,7 +29,7 @@ export function createMemoryRoutes(store) {
|
|
|
29
29
|
maxItemLength: MAX_KEYWORD_LENGTH,
|
|
30
30
|
name: 'keywords',
|
|
31
31
|
});
|
|
32
|
-
// level3Keywords is the flat
|
|
32
|
+
// level3Keywords is the flat lexical keyword line, not an array (core/types.ts).
|
|
33
33
|
const level3Keywords = boundedOptionalString(body.level3Keywords, MAX_CONTENT_LENGTH, 'level3Keywords');
|
|
34
34
|
const directory = boundedOptionalString(body.directory, MAX_SHORT_FIELD_LENGTH, 'directory');
|
|
35
35
|
const day = boundedOptionalString(body.day, MAX_SHORT_FIELD_LENGTH, 'day');
|
package/dist/api/server.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { databasePath, queueDirectory } from '../core/paths.js';
|
|
1
2
|
/**
|
|
2
3
|
* API HTTP pour humemory
|
|
3
4
|
*
|
|
@@ -64,10 +65,10 @@ function safeJoin(baseDir, ...segments) {
|
|
|
64
65
|
}
|
|
65
66
|
// HUMEMORY_DB: same convention as the CLI and the hooks. Without it, the API
|
|
66
67
|
// cannot be pointed at a demo database without writing to production.
|
|
67
|
-
const DB_PATH =
|
|
68
|
+
const DB_PATH = databasePath();
|
|
68
69
|
const store = new SQLiteStore(DB_PATH);
|
|
69
70
|
const PUBLIC_DIR = join(__dirname, '../../public');
|
|
70
|
-
const QUEUE_DIR =
|
|
71
|
+
const QUEUE_DIR = queueDirectory();
|
|
71
72
|
const MAINTENANCE_STATE_PATH = defaultStatePath(QUEUE_DIR);
|
|
72
73
|
// Assigned only when this process hosts the loop; the routes read it to report
|
|
73
74
|
// whether maintenance lives here and whether a pass is in flight right now.
|