@facthouse/mcp 0.28.0 → 0.29.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/README.md +35 -33
- package/dist/cli/index.d.ts +5 -21
- package/dist/cli/index.d.ts.map +1 -1
- package/dist/cli/index.js +6 -783
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/init-backfill.d.ts.map +1 -1
- package/dist/cli/init-backfill.js +2 -0
- package/dist/cli/init-backfill.js.map +1 -1
- package/dist/cli/init-knobs.d.ts +12 -3
- package/dist/cli/init-knobs.d.ts.map +1 -1
- package/dist/cli/init-knobs.js +20 -5
- package/dist/cli/init-knobs.js.map +1 -1
- package/dist/cli/init-wizard.d.ts.map +1 -1
- package/dist/cli/init-wizard.js +39 -8
- package/dist/cli/init-wizard.js.map +1 -1
- package/dist/cli/init.d.ts +2 -0
- package/dist/cli/init.d.ts.map +1 -1
- package/dist/cli/init.js +23 -2
- package/dist/cli/init.js.map +1 -1
- package/dist/cli/run.d.ts +35 -0
- package/dist/cli/run.d.ts.map +1 -0
- package/dist/cli/run.js +801 -0
- package/dist/cli/run.js.map +1 -0
- package/dist/cli/settings.d.ts.map +1 -1
- package/dist/cli/settings.js +1 -1
- package/dist/cli/settings.js.map +1 -1
- package/dist/cli/web.d.ts +24 -1
- package/dist/cli/web.d.ts.map +1 -1
- package/dist/cli/web.js +235 -68
- package/dist/cli/web.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -272
- package/dist/index.js.map +1 -1
- package/dist/intelligence/cli.d.ts +11 -3
- package/dist/intelligence/cli.d.ts.map +1 -1
- package/dist/intelligence/cli.js +115 -23
- package/dist/intelligence/cli.js.map +1 -1
- package/dist/intelligence/consolidate.d.ts +4 -0
- package/dist/intelligence/consolidate.d.ts.map +1 -1
- package/dist/intelligence/consolidate.js +14 -2
- package/dist/intelligence/consolidate.js.map +1 -1
- package/dist/intelligence/types.d.ts +5 -0
- package/dist/intelligence/types.d.ts.map +1 -1
- package/dist/intelligence/usage.d.ts +1 -1
- package/dist/intelligence/usage.js +1 -1
- package/dist/paths.d.ts +7 -0
- package/dist/paths.d.ts.map +1 -1
- package/dist/paths.js +25 -0
- package/dist/paths.js.map +1 -1
- package/dist/server.d.ts +8 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +274 -0
- package/dist/server.js.map +1 -0
- package/dist/suppress-sqlite-warning.js +15 -3
- package/dist/suppress-sqlite-warning.js.map +1 -1
- package/dist/types/config.d.ts +5 -3
- package/dist/types/config.d.ts.map +1 -1
- package/dist/types/config.js +3 -1
- package/dist/types/config.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,276 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import "./suppress-sqlite-warning.js";
|
|
3
2
|
/**
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* AI memory engine exposed as an MCP server.
|
|
7
|
-
* Structured knowledge with server-side intelligence. Any AI tool can query it via MCP.
|
|
3
|
+
* Thin loader so `suppress-sqlite-warning` evaluates before `node:sqlite` is
|
|
4
|
+
* even translated. See src/cli/index.ts.
|
|
8
5
|
*/
|
|
9
|
-
import
|
|
10
|
-
import
|
|
11
|
-
import { CLI_NAME, DEFAULT_MCP_SERVER_NAME, envValue, } from "./identity.js";
|
|
12
|
-
import { dataDirFromEnvOrDefault, resolveUserPath } from "./paths.js";
|
|
13
|
-
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
14
|
-
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
15
|
-
import { closeDatabase } from "./db/connection.js";
|
|
16
|
-
import { openStore } from "./db/store.js";
|
|
17
|
-
import { applySchema } from "./db/schema.js";
|
|
18
|
-
import { ensureSelfEntity } from "./db/entities.js";
|
|
19
|
-
import { loadStoreVocabulary } from "./db/domains.js";
|
|
20
|
-
import { createEmbeddingProvider } from "./embedding/provider.js";
|
|
21
|
-
import { createSessionManager, registerSessionReadTools } from "./tools/session-manager.js";
|
|
22
|
-
import { createFactManager } from "./tools/fact-manager.js";
|
|
23
|
-
import { createHeuristicProvider } from "./intelligence/heuristic.js";
|
|
24
|
-
import { createIntelligenceProvider } from "./intelligence/provider.js";
|
|
25
|
-
import { registerReadTools } from "./tools/read-tools.js";
|
|
26
|
-
import { registerInferenceTools } from "./tools/inferences.js";
|
|
27
|
-
import { registerResources, SESSION_BOOTSTRAP_INSTRUCTIONS } from "./tools/resources.js";
|
|
28
|
-
import { startScheduler } from "./scheduler.js";
|
|
29
|
-
import { loadShippedStoreConfig, ensureBitemporalSince } from "./config.js";
|
|
30
|
-
import { startNotifyListener } from "./ipc/scheduler-ipc.js";
|
|
31
|
-
import { createCopyHeartbeat } from "./sources/copy.js";
|
|
32
|
-
// ---------------------------------------------------------------------------
|
|
33
|
-
// Parse arguments
|
|
34
|
-
// ---------------------------------------------------------------------------
|
|
35
|
-
const { values } = parseArgs({
|
|
36
|
-
options: {
|
|
37
|
-
data: {
|
|
38
|
-
type: "string",
|
|
39
|
-
default: dataDirFromEnvOrDefault(),
|
|
40
|
-
},
|
|
41
|
-
},
|
|
42
|
-
strict: false, // Allow unknown flags (MCP clients may pass extras).
|
|
43
|
-
});
|
|
44
|
-
const dataDir = resolveUserPath(values.data);
|
|
45
|
-
mkdirSync(dataDir, { recursive: true });
|
|
46
|
-
// Storage check before opening an engine. Unknown providers and postgres
|
|
47
|
-
// without a URL must not create memory.db. Print the message and exit rather
|
|
48
|
-
// than dumping a stack into the MCP stdio stream.
|
|
49
|
-
let loadedConfig;
|
|
50
|
-
try {
|
|
51
|
-
loadedConfig = loadShippedStoreConfig(dataDir);
|
|
52
|
-
}
|
|
53
|
-
catch (err) {
|
|
54
|
-
console.error(err instanceof Error ? err.message : String(err));
|
|
55
|
-
process.exit(1);
|
|
56
|
-
}
|
|
57
|
-
const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf-8"));
|
|
58
|
-
// ---------------------------------------------------------------------------
|
|
59
|
-
// Lifecycle
|
|
60
|
-
// ---------------------------------------------------------------------------
|
|
61
|
-
let db;
|
|
62
|
-
let scheduler;
|
|
63
|
-
let triggers = new Set();
|
|
64
|
-
let ipcListener = null;
|
|
65
|
-
// Idempotent shutdown path — may be invoked by MCP transport close, SIGINT,
|
|
66
|
-
// or SIGTERM. Guards against double-run so concurrent signals don't race.
|
|
67
|
-
let shuttingDown = false;
|
|
68
|
-
async function shutdown() {
|
|
69
|
-
if (shuttingDown)
|
|
70
|
-
return;
|
|
71
|
-
shuttingDown = true;
|
|
72
|
-
ipcListener?.close();
|
|
73
|
-
if (scheduler && triggers.has("shutdown")) {
|
|
74
|
-
await scheduler.run("shutdown").catch(() => undefined);
|
|
75
|
-
}
|
|
76
|
-
if (db)
|
|
77
|
-
await closeDatabase(db);
|
|
78
|
-
}
|
|
79
|
-
async function main() {
|
|
80
|
-
// ---------------------------------------------------------------------------
|
|
81
|
-
// Database
|
|
82
|
-
// ---------------------------------------------------------------------------
|
|
83
|
-
let database;
|
|
84
|
-
try {
|
|
85
|
-
database = await openStore(dataDir, loadedConfig);
|
|
86
|
-
}
|
|
87
|
-
catch (err) {
|
|
88
|
-
console.error(err instanceof Error ? err.message : String(err));
|
|
89
|
-
process.exit(1);
|
|
90
|
-
return;
|
|
91
|
-
}
|
|
92
|
-
db = database;
|
|
93
|
-
await applySchema(database);
|
|
94
|
-
// Also here, not only in `facthouse init` — init is optional, and a store the
|
|
95
|
-
// server created on first boot needs the anchor just as much as one that was
|
|
96
|
-
// set up ahead of time. Idempotent.
|
|
97
|
-
await ensureSelfEntity(database);
|
|
98
|
-
// ---------------------------------------------------------------------------
|
|
99
|
-
// MCP Server
|
|
100
|
-
// ---------------------------------------------------------------------------
|
|
101
|
-
// `subscribe` must be declared here: registering a resource auto-registers
|
|
102
|
-
// `resources: { listChanged: true }`, but not subscribe, and capabilities are
|
|
103
|
-
// frozen once a transport is attached. Without it, clients can't ask to be told
|
|
104
|
-
// when the briefing changes.
|
|
105
|
-
const server = new McpServer({
|
|
106
|
-
name: DEFAULT_MCP_SERVER_NAME,
|
|
107
|
-
version: pkg.version,
|
|
108
|
-
}, {
|
|
109
|
-
capabilities: { resources: { subscribe: true, listChanged: true } },
|
|
110
|
-
// Tools-only clients never fetch memory://briefing. This is the session-start
|
|
111
|
-
// result that tells them to call get_session_context instead — same briefing.
|
|
112
|
-
instructions: SESSION_BOOTSTRAP_INSTRUCTIONS,
|
|
113
|
-
});
|
|
114
|
-
const clientSessionId = envValue("CLIENT_SESSION") ?? null;
|
|
115
|
-
const sessionManager = createSessionManager(database, clientSessionId);
|
|
116
|
-
sessionManager.registerTools(server);
|
|
117
|
-
// A store that has just switched to bi-temporal mode gets `bitemporal_since`
|
|
118
|
-
// stamped here — historical supersessions cannot be backfilled.
|
|
119
|
-
const config = ensureBitemporalSince(dataDir, loadedConfig);
|
|
120
|
-
const triggerSet = new Set(config.consolidation.triggers);
|
|
121
|
-
triggers = triggerSet;
|
|
122
|
-
// Provider selector — heuristic is always the terminal fallback. Defaults to
|
|
123
|
-
// the CLI provider: subprocess `claude -p` for real LLM consolidation
|
|
124
|
-
// via the user's own subscription. The FACTHOUSE_PROVIDER env var overrides
|
|
125
|
-
// the config.json choice (kill-switch, e.g. FACTHOUSE_PROVIDER=heuristic).
|
|
126
|
-
const storeVocabulary = await loadStoreVocabulary(database, config.domains ?? []);
|
|
127
|
-
const heuristic = createHeuristicProvider(storeVocabulary);
|
|
128
|
-
const intelligence = createIntelligenceProvider(config.intelligence, {
|
|
129
|
-
vocabulary: storeVocabulary,
|
|
130
|
-
server: server.server,
|
|
131
|
-
heuristic,
|
|
132
|
-
});
|
|
133
|
-
// Semantic search, if this store has opted in. Null is the shipped default and
|
|
134
|
-
// means keyword-only retrieval — nothing is downloaded and nothing is called.
|
|
135
|
-
// Built once at boot: resolution reads config and the environment, neither of
|
|
136
|
-
// which changes mid-process.
|
|
137
|
-
const embeddingProvider = createEmbeddingProvider(config.embedding, {
|
|
138
|
-
onUnavailable: (reason) => console.error(`[facthouse] ${reason}`),
|
|
139
|
-
});
|
|
140
|
-
// Named sources: copy new lines when a tool or resource is read if the
|
|
141
|
-
// files grew. Empty sources never walks a client home. Does not extract.
|
|
142
|
-
const heartbeat = createCopyHeartbeat({
|
|
143
|
-
db: database,
|
|
144
|
-
sources: config.sources,
|
|
145
|
-
onCopied: (copied) => {
|
|
146
|
-
console.error(`[facthouse] Copied ${copied.events_inserted} line(s) from ${copied.files} source file(s).`);
|
|
147
|
-
},
|
|
148
|
-
onError: (err) => {
|
|
149
|
-
console.error(`[facthouse] Source copy failed: ${err.message}`);
|
|
150
|
-
},
|
|
151
|
-
});
|
|
152
|
-
const beforeRead = async () => {
|
|
153
|
-
try {
|
|
154
|
-
await heartbeat.copyIfGrown();
|
|
155
|
-
}
|
|
156
|
-
catch {
|
|
157
|
-
// copyIfGrown already swallows; a throwing hook must not fail search.
|
|
158
|
-
}
|
|
159
|
-
};
|
|
160
|
-
// Resources are automatically-loaded context (memory://briefing, memory://profile).
|
|
161
|
-
// Registered before connect(), because registering one registers the resources
|
|
162
|
-
// capability and capabilities are frozen once the transport attaches.
|
|
163
|
-
const resources = registerResources(server, database, beforeRead);
|
|
164
|
-
const factManager = createFactManager(database, sessionManager, {
|
|
165
|
-
intelligence,
|
|
166
|
-
embedding: embeddingProvider,
|
|
167
|
-
serverConfig: {
|
|
168
|
-
extraction: config.extraction,
|
|
169
|
-
temporal: config.temporal,
|
|
170
|
-
intelligence: config.intelligence,
|
|
171
|
-
},
|
|
172
|
-
// Both of these shipped in the default config and never reached the code that
|
|
173
|
-
// reads them, so the hardcoded defaults always won whatever a store set.
|
|
174
|
-
captureConfig: config.capture,
|
|
175
|
-
autoLinkEvents: config.consolidation.auto_link_events,
|
|
176
|
-
sources: config.sources,
|
|
177
|
-
beforeRead,
|
|
178
|
-
// The copy step of consolidate is this same heartbeat.
|
|
179
|
-
copy: () => heartbeat.copyIfGrown({ force: true }),
|
|
180
|
-
// Consolidation is the only thing that changes integrated knowledge, so it's
|
|
181
|
-
// the only thing that can change what these resources render.
|
|
182
|
-
onConsolidated: () => resources.notifyUpdated(),
|
|
183
|
-
});
|
|
184
|
-
registerSessionReadTools(server, sessionManager, database, beforeRead);
|
|
185
|
-
factManager.registerTools(server);
|
|
186
|
-
if (config.inferences.enabled) {
|
|
187
|
-
registerInferenceTools(server, database, {
|
|
188
|
-
onConfirmed: () => resources.notifyUpdated(),
|
|
189
|
-
});
|
|
190
|
-
}
|
|
191
|
-
registerReadTools(server, database, embeddingProvider, {
|
|
192
|
-
minSimilarityRatio: config.embedding?.min_similarity_ratio,
|
|
193
|
-
minSimilarity: config.embedding?.min_similarity ?? undefined,
|
|
194
|
-
ann: config.embedding?.ann,
|
|
195
|
-
annMaxBytes: config.embedding?.ann_max_bytes,
|
|
196
|
-
}, config.temporal, config.interlocutor, beforeRead);
|
|
197
|
-
const sched = startScheduler({
|
|
198
|
-
db: database,
|
|
199
|
-
runConsolidate: (steps) => factManager.runConsolidate(steps, {
|
|
200
|
-
trigger: "scheduler",
|
|
201
|
-
project: envValue("PROJECT") ?? null,
|
|
202
|
-
}),
|
|
203
|
-
threshold: config.consolidation.threshold,
|
|
204
|
-
});
|
|
205
|
-
scheduler = sched;
|
|
206
|
-
const transport = new StdioServerTransport();
|
|
207
|
-
// Start session when the MCP handshake completes.
|
|
208
|
-
server.server.oninitialized = async () => {
|
|
209
|
-
const clientInfo = server.server.getClientVersion();
|
|
210
|
-
sessionManager.startSession(clientInfo?.name ?? null, envValue("PROJECT") ?? null);
|
|
211
|
-
// Listener for moments another process reports (threshold, compaction).
|
|
212
|
-
// The moment → steps policy is MOMENT_POLICY; the listener only relays.
|
|
213
|
-
if (triggerSet.has("threshold") || triggerSet.has("compaction")) {
|
|
214
|
-
try {
|
|
215
|
-
// A delivered moment is an explicit request from another process
|
|
216
|
-
// (a hook, `facthouse notify`); `triggers` decides whether this server
|
|
217
|
-
// listens at all, not whether it honours what it was told.
|
|
218
|
-
ipcListener = await startNotifyListener(dataDir, (moment) => {
|
|
219
|
-
void sched.run(moment);
|
|
220
|
-
});
|
|
221
|
-
if (!ipcListener.bound) {
|
|
222
|
-
console.error("[facthouse] Another MCP server is handling notifications for this data dir.");
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
catch (err) {
|
|
226
|
-
console.error(`[facthouse] Could not start IPC listener: ${err.message}. ` +
|
|
227
|
-
`Threshold / compaction triggers will not fire.`);
|
|
228
|
-
}
|
|
229
|
-
}
|
|
230
|
-
// session_start: copy, extract (capped), integrate. The copy step is the
|
|
231
|
-
// same heartbeat every tool read uses, so a first get_session_context
|
|
232
|
-
// cannot race a second walk of the same file. A large first backfill is
|
|
233
|
-
// not extracted on the lot: the cap bounds the run and the remainder is
|
|
234
|
-
// reported once.
|
|
235
|
-
if (triggerSet.has("session_start")) {
|
|
236
|
-
void sched.run("session_start").then((result) => {
|
|
237
|
-
// Only the cap earns this line: a skipped or degraded run has its own
|
|
238
|
-
// reason, and pointing at --all there would spawn the model on the lot.
|
|
239
|
-
if (result &&
|
|
240
|
-
!result.skipped &&
|
|
241
|
-
!result.extractionDegraded &&
|
|
242
|
-
result.eventsRemaining > 0) {
|
|
243
|
-
console.error(`[facthouse] ${result.eventsRemaining} line(s) still waiting to be extracted ` +
|
|
244
|
-
`after this run's cap. Run ${CLI_NAME} consolidate --all, or let the ` +
|
|
245
|
-
`next session start take the next batch.`);
|
|
246
|
-
}
|
|
247
|
-
});
|
|
248
|
-
}
|
|
249
|
-
else {
|
|
250
|
-
// No session_start trigger: still keep D current for the first read.
|
|
251
|
-
await heartbeat.copyIfGrown();
|
|
252
|
-
}
|
|
253
|
-
};
|
|
254
|
-
// The MCP SDK calls onclose synchronously and doesn't await our handler.
|
|
255
|
-
// Run the shutdown sequence explicitly and exit only after it completes —
|
|
256
|
-
// otherwise Node may exit before the shutdown-trigger integrate finishes
|
|
257
|
-
// its LLM calls and DB writes.
|
|
258
|
-
server.server.onclose = () => {
|
|
259
|
-
void shutdown().then(() => process.exit(0));
|
|
260
|
-
};
|
|
261
|
-
await server.connect(transport);
|
|
262
|
-
}
|
|
263
|
-
// Graceful shutdown — same path for SIGINT and SIGTERM.
|
|
264
|
-
process.on("SIGINT", () => {
|
|
265
|
-
void shutdown().then(() => process.exit(0));
|
|
266
|
-
});
|
|
267
|
-
process.on("SIGTERM", () => {
|
|
268
|
-
void shutdown().then(() => process.exit(0));
|
|
269
|
-
});
|
|
270
|
-
main().catch(async (error) => {
|
|
271
|
-
console.error("Fatal error:", error);
|
|
272
|
-
if (db)
|
|
273
|
-
await closeDatabase(db).catch(() => undefined);
|
|
274
|
-
process.exit(1);
|
|
275
|
-
});
|
|
6
|
+
import "./suppress-sqlite-warning.js";
|
|
7
|
+
await import("./server.js");
|
|
276
8
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAEA,OAAO,8BAA8B,CAAC;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAEA;;;GAGG;AACH,OAAO,8BAA8B,CAAC;AACtC,MAAM,MAAM,CAAC,aAAa,CAAC,CAAC"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* CLI-subprocess intelligence provider.
|
|
3
3
|
*
|
|
4
|
-
* Spawns `claude -p --output-format json --json-schema ...` for each
|
|
5
|
-
* stage of consolidation. Uses the user's existing Claude subscription via
|
|
4
|
+
* Spawns `claude -p --output-format stream-json --json-schema ...` for each
|
|
5
|
+
* semantic stage of consolidation. Uses the user's existing Claude subscription via
|
|
6
6
|
* OAuth, so no API key is needed — the subprocess inherits the parent's
|
|
7
7
|
* environment and claude's keychain/file-based credentials resolve naturally.
|
|
8
8
|
*
|
|
@@ -33,7 +33,7 @@ export interface CliProviderOpts {
|
|
|
33
33
|
command?: string[];
|
|
34
34
|
/** Model alias (passed via --model). Default: CLI_DEFAULT_MODEL. */
|
|
35
35
|
model?: string;
|
|
36
|
-
/**
|
|
36
|
+
/** Idle silence on the subprocess pipes before kill. Default: CLI_DEFAULT_TIMEOUT_MS. */
|
|
37
37
|
timeoutMs?: number;
|
|
38
38
|
/** Cwd for subprocess. Default: OS tempdir (out of project scope). */
|
|
39
39
|
cwd?: string;
|
|
@@ -48,6 +48,14 @@ export declare const CLI_EXTRACT_RETRIES = 1;
|
|
|
48
48
|
export declare const CLI_FAILURE_SLICE = 300;
|
|
49
49
|
/** Max wait after SIGKILL before the timeout result is returned. Join, not backoff. */
|
|
50
50
|
export declare const CLI_TIMEOUT_JOIN_MS = 2000;
|
|
51
|
+
/** Absolute ceiling per stage, even if the stream keeps ticking. Idle is `timeoutMs`. */
|
|
52
|
+
export declare const CLI_HARD_TIMEOUT_MS: number;
|
|
53
|
+
/**
|
|
54
|
+
* Parse `claude -p --output-format stream-json` (NDJSON) or a single JSON
|
|
55
|
+
* envelope (`--output-format json`, tests). Prefer the last `type: result`
|
|
56
|
+
* line; otherwise the last object with `structured_output`.
|
|
57
|
+
*/
|
|
58
|
+
export declare function parseClaudeCliStdout(stdout: string): Record<string, unknown>;
|
|
51
59
|
/** How the runner reports back. Only the exit status matters. */
|
|
52
60
|
export interface ProbeRun {
|
|
53
61
|
status: number | null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../../src/intelligence/cli.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAOH,OAAO,KAAK,EAAE,oBAAoB,EAA4C,MAAM,YAAY,CAAC;AAQjG,OAAO,EAGL,KAAK,SAAS,EACf,MAAM,oBAAoB,CAAC;AAe5B,MAAM,WAAW,eAAe;IAC9B,mFAAmF;IACnF,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,oEAAoE;IACpE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,
|
|
1
|
+
{"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../../src/intelligence/cli.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAOH,OAAO,KAAK,EAAE,oBAAoB,EAA4C,MAAM,YAAY,CAAC;AAQjG,OAAO,EAGL,KAAK,SAAS,EACf,MAAM,oBAAoB,CAAC;AAe5B,MAAM,WAAW,eAAe;IAC9B,mFAAmF;IACnF,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,oEAAoE;IACpE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,yFAAyF;IACzF,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,sEAAsE;IACtE,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,kFAAkF;IAClF,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,sCAAsC;IACtC,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAoDD,kFAAkF;AAClF,eAAO,MAAM,uBAAuB,uCAAwC,CAAC;AAC7E,eAAO,MAAM,mBAAmB,IAAI,CAAC;AACrC,eAAO,MAAM,iBAAiB,MAAM,CAAC;AACrC,uFAAuF;AACvF,eAAO,MAAM,mBAAmB,OAAQ,CAAC;AACzC,yFAAyF;AACzF,eAAO,MAAM,mBAAmB,QAAiB,CAAC;AAElD;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAyB5E;AAgTD,iEAAiE;AACjE,MAAM,WAAW,QAAQ;IACvB,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;CACvB;AAED,MAAM,WAAW,cAAc;IAC7B,gDAAgD;IAChD,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,0EAA0E;IAC1E,SAAS,EAAE,OAAO,CAAC;CACpB;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,gBAAgB,CAC9B,IAAI,GAAE,eAAoB,EAC1B,GAAG,GAAE,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,QAA0B,GAC/D,cAAc,CAIhB;AA0LD,wBAAgB,iBAAiB,CAC/B,QAAQ,GAAE,eAAoB,EAC9B,QAAQ,GAAE,oBAAgD;AAC1D;;;;;GAKG;AACH,UAAU,GAAE,SAAS,EAAO,GAC3B,oBAAoB,CAqbtB"}
|
package/dist/intelligence/cli.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* CLI-subprocess intelligence provider.
|
|
3
3
|
*
|
|
4
|
-
* Spawns `claude -p --output-format json --json-schema ...` for each
|
|
5
|
-
* stage of consolidation. Uses the user's existing Claude subscription via
|
|
4
|
+
* Spawns `claude -p --output-format stream-json --json-schema ...` for each
|
|
5
|
+
* semantic stage of consolidation. Uses the user's existing Claude subscription via
|
|
6
6
|
* OAuth, so no API key is needed — the subprocess inherits the parent's
|
|
7
7
|
* environment and claude's keychain/file-based credentials resolve naturally.
|
|
8
8
|
*
|
|
@@ -67,6 +67,44 @@ export const CLI_EXTRACT_RETRIES = 1; // exactly one retry; two attempts total
|
|
|
67
67
|
export const CLI_FAILURE_SLICE = 300; // same cap as invokeClaude's stderr slice
|
|
68
68
|
/** Max wait after SIGKILL before the timeout result is returned. Join, not backoff. */
|
|
69
69
|
export const CLI_TIMEOUT_JOIN_MS = 2_000;
|
|
70
|
+
/** Absolute ceiling per stage, even if the stream keeps ticking. Idle is `timeoutMs`. */
|
|
71
|
+
export const CLI_HARD_TIMEOUT_MS = 15 * 60 * 1000;
|
|
72
|
+
/**
|
|
73
|
+
* Parse `claude -p --output-format stream-json` (NDJSON) or a single JSON
|
|
74
|
+
* envelope (`--output-format json`, tests). Prefer the last `type: result`
|
|
75
|
+
* line; otherwise the last object with `structured_output`.
|
|
76
|
+
*/
|
|
77
|
+
export function parseClaudeCliStdout(stdout) {
|
|
78
|
+
const lines = stdout.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0);
|
|
79
|
+
let lastResult;
|
|
80
|
+
let lastStructured;
|
|
81
|
+
for (const line of lines) {
|
|
82
|
+
let obj;
|
|
83
|
+
try {
|
|
84
|
+
obj = JSON.parse(line);
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (obj === null || typeof obj !== "object" || Array.isArray(obj))
|
|
90
|
+
continue;
|
|
91
|
+
const rec = obj;
|
|
92
|
+
if (rec.type === "result")
|
|
93
|
+
lastResult = rec;
|
|
94
|
+
if (rec.structured_output !== undefined && rec.structured_output !== null) {
|
|
95
|
+
lastStructured = rec;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
if (lastResult)
|
|
99
|
+
return lastResult;
|
|
100
|
+
if (lastStructured)
|
|
101
|
+
return lastStructured;
|
|
102
|
+
const whole = JSON.parse(stdout);
|
|
103
|
+
if (whole === null || typeof whole !== "object" || Array.isArray(whole)) {
|
|
104
|
+
throw new SyntaxError("claude stdout is not a JSON object");
|
|
105
|
+
}
|
|
106
|
+
return whole;
|
|
107
|
+
}
|
|
70
108
|
function formatStageFailure(stageName, result, phase, extra) {
|
|
71
109
|
const bits = [
|
|
72
110
|
"[facthouse cli-provider]",
|
|
@@ -79,8 +117,15 @@ function formatStageFailure(stageName, result, phase, extra) {
|
|
|
79
117
|
bits.push(`stderr=${JSON.stringify((result.stderr ?? "").slice(0, CLI_FAILURE_SLICE))}`);
|
|
80
118
|
}
|
|
81
119
|
else if (result.error === "timeout") {
|
|
82
|
-
if (
|
|
83
|
-
bits.push(`
|
|
120
|
+
if (result.watchdog === "hard") {
|
|
121
|
+
bits.push(`hard=${CLI_HARD_TIMEOUT_MS}ms`);
|
|
122
|
+
}
|
|
123
|
+
else if (extra?.timeoutMs != null) {
|
|
124
|
+
bits.push(`idle=${extra.timeoutMs}ms`);
|
|
125
|
+
}
|
|
126
|
+
if (typeof result.elapsedMs === "number") {
|
|
127
|
+
bits.push(`elapsed=${result.elapsedMs}ms`);
|
|
128
|
+
}
|
|
84
129
|
if (result.stderr)
|
|
85
130
|
bits.push(`stderr=${JSON.stringify(result.stderr.slice(0, CLI_FAILURE_SLICE))}`);
|
|
86
131
|
}
|
|
@@ -102,7 +147,10 @@ async function invokeClaude(prompt, schema, command, opts) {
|
|
|
102
147
|
...command.slice(1),
|
|
103
148
|
"-p",
|
|
104
149
|
"--output-format",
|
|
105
|
-
"json",
|
|
150
|
+
"stream-json",
|
|
151
|
+
"--verbose",
|
|
152
|
+
// Documented trio with -p. Does not flush a block-buffered pipe.
|
|
153
|
+
"--include-partial-messages",
|
|
106
154
|
"--json-schema",
|
|
107
155
|
JSON.stringify(schema),
|
|
108
156
|
"--setting-sources",
|
|
@@ -140,12 +188,30 @@ async function invokeClaude(prompt, schema, command, opts) {
|
|
|
140
188
|
let stdout = "";
|
|
141
189
|
let stderr = "";
|
|
142
190
|
let timedOut = false;
|
|
191
|
+
let timeoutWatchdog;
|
|
192
|
+
let idleTimer;
|
|
143
193
|
let joinTimer;
|
|
144
|
-
const
|
|
194
|
+
const clearWatchdogs = () => {
|
|
195
|
+
if (idleTimer)
|
|
196
|
+
clearTimeout(idleTimer);
|
|
197
|
+
if (hardTimer)
|
|
198
|
+
clearTimeout(hardTimer);
|
|
199
|
+
if (joinTimer)
|
|
200
|
+
clearTimeout(joinTimer);
|
|
201
|
+
};
|
|
202
|
+
const fireTimeout = (watchdog) => {
|
|
145
203
|
// Kill immediately and wait for close (or the join cap) before
|
|
146
204
|
// resolving. SIGTERM-and-return used to let the retry spawn overlap
|
|
147
|
-
// a live child.
|
|
205
|
+
// a live child. Idle and hard share this path; the second must not
|
|
206
|
+
// arm another join.
|
|
207
|
+
if (timedOut || resolved)
|
|
208
|
+
return;
|
|
148
209
|
timedOut = true;
|
|
210
|
+
timeoutWatchdog = watchdog;
|
|
211
|
+
if (idleTimer)
|
|
212
|
+
clearTimeout(idleTimer);
|
|
213
|
+
if (hardTimer)
|
|
214
|
+
clearTimeout(hardTimer);
|
|
149
215
|
try {
|
|
150
216
|
child.kill("SIGKILL");
|
|
151
217
|
}
|
|
@@ -156,35 +222,53 @@ async function invokeClaude(prompt, schema, command, opts) {
|
|
|
156
222
|
finish({
|
|
157
223
|
error: "timeout",
|
|
158
224
|
stderr: stderr.slice(0, CLI_FAILURE_SLICE),
|
|
225
|
+
watchdog: timeoutWatchdog,
|
|
159
226
|
});
|
|
160
227
|
}, CLI_TIMEOUT_JOIN_MS);
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
|
|
228
|
+
};
|
|
229
|
+
const armIdle = () => {
|
|
230
|
+
if (resolved || timedOut)
|
|
231
|
+
return;
|
|
232
|
+
if (idleTimer)
|
|
233
|
+
clearTimeout(idleTimer);
|
|
234
|
+
idleTimer = setTimeout(() => fireTimeout("idle"), opts.timeoutMs);
|
|
235
|
+
};
|
|
236
|
+
armIdle();
|
|
237
|
+
const hardTimer = setTimeout(() => fireTimeout("hard"), Math.max(CLI_HARD_TIMEOUT_MS, opts.timeoutMs));
|
|
238
|
+
// Spawn and stdin-end are not silence. Windows CreateProcess plus a
|
|
239
|
+
// large extract prompt used to count against the idle window, so the
|
|
240
|
+
// first chunk died before the first stream-json line.
|
|
241
|
+
child.on("spawn", armIdle);
|
|
242
|
+
child.stdout?.on("data", (d) => {
|
|
243
|
+
stdout += d.toString();
|
|
244
|
+
armIdle();
|
|
245
|
+
});
|
|
246
|
+
child.stderr?.on("data", (d) => {
|
|
247
|
+
stderr += d.toString();
|
|
248
|
+
armIdle();
|
|
249
|
+
});
|
|
164
250
|
child.stdin?.on("error", () => {
|
|
165
251
|
// EPIPE if the child exits before consuming the prompt; close/error
|
|
166
252
|
// handlers below settle the result.
|
|
167
253
|
});
|
|
168
254
|
child.on("error", (err) => {
|
|
169
|
-
|
|
170
|
-
if (joinTimer)
|
|
171
|
-
clearTimeout(joinTimer);
|
|
255
|
+
clearWatchdogs();
|
|
172
256
|
if (timedOut) {
|
|
173
257
|
return finish({
|
|
174
258
|
error: "timeout",
|
|
175
259
|
stderr: stderr.slice(0, CLI_FAILURE_SLICE),
|
|
260
|
+
watchdog: timeoutWatchdog,
|
|
176
261
|
});
|
|
177
262
|
}
|
|
178
263
|
finish({ error: "spawn-error", detail: err.message });
|
|
179
264
|
});
|
|
180
265
|
child.on("close", (code) => {
|
|
181
|
-
|
|
182
|
-
if (joinTimer)
|
|
183
|
-
clearTimeout(joinTimer);
|
|
266
|
+
clearWatchdogs();
|
|
184
267
|
if (timedOut) {
|
|
185
268
|
return finish({
|
|
186
269
|
error: "timeout",
|
|
187
270
|
stderr: stderr.slice(0, CLI_FAILURE_SLICE),
|
|
271
|
+
watchdog: timeoutWatchdog,
|
|
188
272
|
});
|
|
189
273
|
}
|
|
190
274
|
if (code !== 0) {
|
|
@@ -196,7 +280,7 @@ async function invokeClaude(prompt, schema, command, opts) {
|
|
|
196
280
|
}
|
|
197
281
|
let envelope;
|
|
198
282
|
try {
|
|
199
|
-
envelope =
|
|
283
|
+
envelope = parseClaudeCliStdout(stdout);
|
|
200
284
|
}
|
|
201
285
|
catch (err) {
|
|
202
286
|
return finish({ error: "parse-error", detail: err.message });
|
|
@@ -221,7 +305,7 @@ async function invokeClaude(prompt, schema, command, opts) {
|
|
|
221
305
|
});
|
|
222
306
|
});
|
|
223
307
|
try {
|
|
224
|
-
child.stdin?.end(prompt, "utf8");
|
|
308
|
+
child.stdin?.end(prompt, "utf8", armIdle);
|
|
225
309
|
}
|
|
226
310
|
catch {
|
|
227
311
|
// Child already closed stdin; close/error handlers settle the result.
|
|
@@ -514,10 +598,9 @@ vocabulary = []) {
|
|
|
514
598
|
// Resolved lazily below — kept here only to satisfy the Required shape.
|
|
515
599
|
command: [],
|
|
516
600
|
model: userOpts.model ?? CLI_DEFAULT_MODEL,
|
|
517
|
-
//
|
|
518
|
-
//
|
|
519
|
-
//
|
|
520
|
-
// minutes worst case, which is still a background job.
|
|
601
|
+
// Idle silence, not wall-clock. A live stream-json child can run for
|
|
602
|
+
// minutes; CLI_HARD_TIMEOUT_MS is the ceiling. 45s with no spawn, no
|
|
603
|
+
// stdin-end, and no pipe bytes still means hung.
|
|
521
604
|
timeoutMs: userOpts.timeoutMs ?? CLI_DEFAULT_TIMEOUT_MS,
|
|
522
605
|
cwd: userOpts.cwd ?? tmpdir(),
|
|
523
606
|
maxCandidates: userOpts.maxCandidates ?? 50,
|
|
@@ -552,6 +635,7 @@ vocabulary = []) {
|
|
|
552
635
|
model: opts.model,
|
|
553
636
|
});
|
|
554
637
|
}
|
|
638
|
+
let lastStageError = null;
|
|
555
639
|
/** Standardised stage runner. Returns null on failure so callers can fall back. */
|
|
556
640
|
async function runStage(stageName, systemPrompt, userPayload, schema, retryTransient = false) {
|
|
557
641
|
// Claude's --json-schema flag expects a user prompt; we pass the system
|
|
@@ -561,9 +645,11 @@ vocabulary = []) {
|
|
|
561
645
|
// behaviour predictable.
|
|
562
646
|
const prompt = `${systemPrompt}\n\nINPUT:\n${JSON.stringify(userPayload)}`;
|
|
563
647
|
const attempt = () => invokeClaude(prompt, schema, getCommand(), opts);
|
|
648
|
+
lastStageError = null;
|
|
564
649
|
let result = await attempt();
|
|
565
650
|
recordAttempt(stageName, result);
|
|
566
651
|
if ("error" in result) {
|
|
652
|
+
lastStageError = result.error;
|
|
567
653
|
const retryable = retryTransient &&
|
|
568
654
|
CLI_EXTRACT_RETRY_KINDS.includes(result.error);
|
|
569
655
|
console.error(formatStageFailure(stageName, result, "first", {
|
|
@@ -574,11 +660,13 @@ vocabulary = []) {
|
|
|
574
660
|
result = await attempt();
|
|
575
661
|
recordAttempt(stageName, result);
|
|
576
662
|
if ("error" in result) {
|
|
663
|
+
lastStageError = result.error;
|
|
577
664
|
console.error(formatStageFailure(stageName, result, "retry", {
|
|
578
665
|
timeoutMs: result.error === "timeout" ? opts.timeoutMs : undefined,
|
|
579
666
|
}));
|
|
580
667
|
return null;
|
|
581
668
|
}
|
|
669
|
+
lastStageError = null;
|
|
582
670
|
log(`${stageName} retry ok in ${result.elapsedMs}ms`);
|
|
583
671
|
return result.structured;
|
|
584
672
|
}
|
|
@@ -625,7 +713,11 @@ vocabulary = []) {
|
|
|
625
713
|
// configured extractor never ran: these events have NOT been examined,
|
|
626
714
|
// and advancing past them would discard them permanently.
|
|
627
715
|
const fell = await fallback.extractFactsFromEvents(events, workingMemory, sessionSummary, longTermMemory, extras);
|
|
628
|
-
return {
|
|
716
|
+
return {
|
|
717
|
+
facts: fell.facts,
|
|
718
|
+
degraded: true,
|
|
719
|
+
degradedKind: lastStageError === "timeout" ? "timeout" : "other",
|
|
720
|
+
};
|
|
629
721
|
}
|
|
630
722
|
const extracted = result.facts.map((f) => ({
|
|
631
723
|
content: f.content,
|