@totalreclaw/mcp-server 3.3.0-rc.2 → 3.3.0-rc.4

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/dist/index.js CHANGED
@@ -72,6 +72,7 @@ const accounts_2 = require("permissionless/accounts");
72
72
  const account_abstraction_1 = require("viem/account-abstraction");
73
73
  const node_crypto_1 = __importDefault(require("node:crypto"));
74
74
  const fs = __importStar(require("node:fs"));
75
+ const os = __importStar(require("node:os"));
75
76
  const setup_js_1 = require("./cli/setup.js");
76
77
  // ── Configuration ───────────────────────────────────────────────────────────
77
78
  const SERVER_URL = process.env.TOTALRECLAW_SERVER_URL || 'https://api.totalreclaw.xyz';
@@ -771,30 +772,91 @@ async function handleRememberSubgraph(state, args) {
771
772
  */
772
773
  async function handleDebriefSubgraph(state, args) {
773
774
  const input = args;
775
+ // ── Crystal path (am-1, preferred) ──────────────────────────────────────
776
+ if (input?.crystal !== undefined) {
777
+ const raw = input.crystal;
778
+ const narrative = typeof raw?.narrative === 'string' ? raw.narrative.trim().slice(0, 512) : '';
779
+ if (narrative.length < 10) {
780
+ return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: 'crystal.narrative (10+ chars) is required' }) }] };
781
+ }
782
+ const strList = (key) => {
783
+ const v = raw[key];
784
+ if (!Array.isArray(v))
785
+ return [];
786
+ return v.map((x) => String(x).trim()).filter((x) => x.length > 0).slice(0, 10);
787
+ };
788
+ let importance = typeof raw?.importance === 'number' ? raw.importance : 8;
789
+ importance = Math.max(1, Math.min(10, Math.round(importance)));
790
+ const crystalMetadata = {
791
+ subtype: 'session_crystal',
792
+ key_outcomes: strList('key_outcomes'),
793
+ open_threads: strList('open_threads'),
794
+ lessons: strList('lessons'),
795
+ };
796
+ const filesAffected = strList('files_affected');
797
+ if (filesAffected.length > 0)
798
+ crystalMetadata.files_affected = filesAffected;
799
+ if (typeof raw?.session_id === 'string' && raw.session_id)
800
+ crystalMetadata.session_id = raw.session_id;
801
+ try {
802
+ const wordIndices = (0, crypto_js_1.generateBlindIndices)(narrative);
803
+ const embedding = await (0, embedding_js_1.generateEmbedding)(narrative);
804
+ const lshIndices = state.lshHasher.hash(embedding);
805
+ const allIndices = [...wordIndices, ...lshIndices];
806
+ const blobPlaintext = (0, claims_helper_js_1.buildV1ClaimBlob)({
807
+ text: narrative,
808
+ type: 'summary',
809
+ source: 'derived',
810
+ importance,
811
+ metadata: crystalMetadata,
812
+ });
813
+ const encryptedBlob = (0, crypto_js_1.encrypt)(blobPlaintext, state.encryptionKey);
814
+ const contentFp = (0, crypto_js_1.generateContentFingerprint)(narrative, state.dedupKey);
815
+ const encryptedEmb = encryptEmbedding(embedding, state.encryptionKey);
816
+ const factId = node_crypto_1.default.randomUUID();
817
+ const factPayload = {
818
+ id: factId,
819
+ timestamp: new Date().toISOString(),
820
+ owner: state.smartAccountAddress,
821
+ encryptedBlob: Buffer.from(encryptedBlob, 'base64').toString('hex'),
822
+ blindIndices: allIndices,
823
+ decayScore: importance / 10,
824
+ source: 'mcp_debrief',
825
+ contentFp,
826
+ agentId: 'mcp-server',
827
+ encryptedEmbedding: encryptedEmb,
828
+ };
829
+ const batchConfig = (0, store_js_1.getSubgraphConfig)({
830
+ relayUrl: state.serverUrl,
831
+ mnemonic: state.mnemonic,
832
+ authKeyHex: Buffer.from(state.authKey).toString('hex'),
833
+ walletAddress: state.smartAccountAddress,
834
+ });
835
+ const batchResult = await (0, store_js_1.submitFactBatchOnChain)([(0, store_js_1.encodeFactProtobuf)(factPayload)], batchConfig);
836
+ console.error(`Crystal debrief stored (tx=${batchResult.txHash.slice(0, 10)}...)`);
837
+ return {
838
+ content: [{ type: 'text', text: JSON.stringify({ success: batchResult.success, stored: batchResult.success ? 1 : 0, fact_id: factId, tx_hash: batchResult.txHash, crystal: true }) }],
839
+ };
840
+ }
841
+ catch (error) {
842
+ console.error(`Crystal debrief failed: ${error instanceof Error ? error.message : String(error)}`);
843
+ return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: String(error) }) }] };
844
+ }
845
+ }
846
+ // ── Legacy facts array path (backward compat) ────────────────────────────
774
847
  const factsInput = input?.facts;
775
848
  if (!Array.isArray(factsInput) || factsInput.length === 0) {
776
849
  return {
777
850
  content: [{
778
851
  type: 'text',
779
- text: JSON.stringify({
780
- success: false,
781
- error: 'Invalid input: "facts" array is required and must not be empty',
782
- }),
852
+ text: JSON.stringify({ success: false, error: 'Provide either "crystal" (preferred) or "facts" array' }),
783
853
  }],
784
854
  };
785
855
  }
786
- // Validate through the canonical parser
787
856
  const validated = (0, index_js_2.parseDebriefResponse)(JSON.stringify(factsInput));
788
857
  if (validated.length === 0) {
789
858
  return {
790
- content: [{
791
- type: 'text',
792
- text: JSON.stringify({
793
- success: true,
794
- stored: 0,
795
- message: 'No valid debrief items to store (filtered by validation)',
796
- }),
797
- }],
859
+ content: [{ type: 'text', text: JSON.stringify({ success: true, stored: 0, message: 'No valid debrief items to store (filtered by validation)' }) }],
798
860
  };
799
861
  }
800
862
  const pendingPayloads = [];
@@ -805,15 +867,6 @@ async function handleDebriefSubgraph(state, args) {
805
867
  const embedding = await (0, embedding_js_1.generateEmbedding)(item.text);
806
868
  const lshIndices = state.lshHasher.hash(embedding);
807
869
  const allIndices = [...wordIndices, ...lshIndices];
808
- // Memory Taxonomy v1: emit v1 inner blob with `type: 'summary'` (both
809
- // tool-level 'summary' and 'context' map here — per spec §type-semantics,
810
- // summary absorbs session-level synthesis regardless of whether the tool
811
- // called it "summary" or "context"). `source: 'derived'` marks this as a
812
- // derived-from-conversation claim (spec requires summary ∈ {derived,
813
- // assistant}; derived is the better fit here).
814
- //
815
- // TOTALRECLAW_CLAIM_FORMAT=legacy was removed in v1; raw-text blobs are
816
- // no longer produced on the write path.
817
870
  const blobPlaintext = (0, claims_helper_js_1.buildV1ClaimBlob)({
818
871
  text: item.text,
819
872
  type: 'summary',
@@ -854,11 +907,7 @@ async function handleDebriefSubgraph(state, args) {
854
907
  });
855
908
  const batchResult = await (0, store_js_1.submitFactBatchOnChain)(pendingPayloads, batchConfig);
856
909
  for (const meta of pendingFactMeta) {
857
- results.push({
858
- success: batchResult.success,
859
- fact_id: meta.factId,
860
- tx_hash: batchResult.txHash,
861
- });
910
+ results.push({ success: batchResult.success, fact_id: meta.factId, tx_hash: batchResult.txHash });
862
911
  }
863
912
  console.error(`Debrief: submitted ${batchResult.batchSize} items (tx=${batchResult.txHash.slice(0, 10)}...)`);
864
913
  }
@@ -871,15 +920,7 @@ async function handleDebriefSubgraph(state, args) {
871
920
  }
872
921
  const stored = results.filter((r) => r.success).length;
873
922
  return {
874
- content: [{
875
- type: 'text',
876
- text: JSON.stringify({
877
- success: stored > 0,
878
- stored,
879
- total: validated.length,
880
- results,
881
- }),
882
- }],
923
+ content: [{ type: 'text', text: JSON.stringify({ success: stored > 0, stored, total: validated.length, results }) }],
883
924
  };
884
925
  }
885
926
  /**
@@ -2011,7 +2052,7 @@ async function main() {
2011
2052
  else {
2012
2053
  console.error('TotalReclaw MCP server started (unconfigured — set TOTALRECLAW_RECOVERY_PHRASE in the MCP host config; see docs/guides/claude-code-setup.md)');
2013
2054
  }
2014
- // ── Trajectory poller (mcp-server 3.3.0-rc.2) ─────────────────────────
2055
+ // ── Trajectory poller (mcp-server 3.3.0-rc.3) ─────────────────────────
2015
2056
  // Auto-extraction without relying on OpenClaw plugin's `agent_end` hook
2016
2057
  // (which 2026.5.4+ silently blocks for non-bundled plugins). The poller
2017
2058
  // scans `~/.openclaw/agents/<agent>/sessions/*.trajectory.jsonl` every
@@ -2019,13 +2060,14 @@ async function main() {
2019
2060
  // {role, content}[] turns, and calls runExtraction() when the turn-
2020
2061
  // accumulator threshold is met.
2021
2062
  //
2022
- // 3.3.0-rc.2: poller is wired with a stub `runExtraction` that returns
2023
- // [] (no LLM extraction in MCP-only mode yet — full extractor + LLM
2024
- // client port lands in a follow-up RC). The architecturally meaningful
2025
- // pieces (file discovery, offset tracking, stale-skip, cap=1, gating
2026
- // on pairing/import) are LIVE so SKILL.md's "auto-extraction is on"
2027
- // claim holds true. Until the LLM port lands, agents MUST drive
2028
- // explicit `totalreclaw_remember` calls — see SKILL.md.
2063
+ // 3.3.0-rc.3: real LLM-driven extraction wired in. The plugin's
2064
+ // extractor + llm-client + auth-profile reader were ported into
2065
+ // `src/extraction/` and feed the poller's `runExtraction` dep.
2066
+ // Persistence routes through `handleRememberSubgraph` so the on-chain
2067
+ // pipeline (protobuf v4 + store-time dedup + batch UserOp) is shared
2068
+ // with the explicit `totalreclaw_remember` tool. Phrase-safety: the
2069
+ // recovery phrase never crosses into the extraction LLM — see the
2070
+ // top-of-file rationale in `extraction/extractor.ts`.
2029
2071
  startPollerSafely();
2030
2072
  const transport = new stdio_js_1.StdioServerTransport();
2031
2073
  await server.connect(transport);
@@ -2036,12 +2078,42 @@ function startPollerSafely() {
2036
2078
  // calling main()) don't pay the import cost.
2037
2079
  // eslint-disable-next-line @typescript-eslint/no-var-requires
2038
2080
  const { startTrajectoryPoller } = require('./trajectory-poller.js');
2081
+ // 3.3.0-rc.3: live LLM-driven extraction wired in. The plugin's
2082
+ // extractor + llm-client + auth-profile reader were ported into
2083
+ // `mcp/src/extraction/` and are imported here.
2084
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
2085
+ const extraction = require('./extraction/extractor.js');
2086
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
2087
+ const llmClient = require('./extraction/llm-client.js');
2088
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
2089
+ const profileReader = require('./extraction/llm-profile-reader.js');
2039
2090
  const logger = {
2040
2091
  info: (m) => console.error(`[trajectory-poller] ${m}`),
2041
2092
  warn: (m) => console.error(`[trajectory-poller] WARN ${m}`),
2042
2093
  error: (m) => console.error(`[trajectory-poller] ERROR ${m}`),
2043
2094
  };
2044
- let warnedNoLlm = false;
2095
+ // ── Initialize the extraction LLM client ────────────────────────────────
2096
+ // Resolution cascade (highest priority first):
2097
+ // 1. Plugin-config override — N/A in MCP-only mode (no plugin manifest).
2098
+ // 2. SDK-passed openclawProviders — N/A in MCP-only mode.
2099
+ // 3. ~/.openclaw/agents/<agent>/agent/auth-profiles.json (or models.json
2100
+ // legacy fallback). This is the primary source for MCP-only users
2101
+ // because it's where their OpenClaw install already stores the keys.
2102
+ // 4. Env-var fallback (ZAI_API_KEY, OPENAI_API_KEY, ANTHROPIC_API_KEY,
2103
+ // ...) for self-hosted / dev setups.
2104
+ //
2105
+ // The `primaryModel` hint is left undefined — MCP-only mode has no
2106
+ // single primary chat model concept (the user could be running
2107
+ // OpenClaw with Claude Sonnet AND z.ai GLM-4.6 across different
2108
+ // sessions). The cascade picks the first available cheap model from
2109
+ // the priority list (zai > openai > anthropic > ...).
2110
+ const authProfileKeys = profileReader.readAllProfileKeys({
2111
+ root: profileReader.defaultAuthProfilesRoot(os.homedir()),
2112
+ });
2113
+ llmClient.initLLMClient({
2114
+ authProfileKeys,
2115
+ logger,
2116
+ });
2045
2117
  startTrajectoryPoller({
2046
2118
  logger,
2047
2119
  ensureInitialized: async () => {
@@ -2061,23 +2133,82 @@ function startPollerSafely() {
2061
2133
  const parsed = raw ? parseInt(raw, 10) : NaN;
2062
2134
  return Number.isFinite(parsed) && parsed > 0 ? parsed : 6;
2063
2135
  },
2136
+ // Dedup-via-existing-memories is OFF for rc.3. Turn-extraction always
2137
+ // sees the full conversation + the importance bumps, so we drop a
2138
+ // few "did we already store this?" UPDATE/NOOP signals; downstream
2139
+ // store-time dedup (in handleRememberSubgraph) catches the actual
2140
+ // duplicates via cosine-similarity. Wiring an MCP-side dedup pass is
2141
+ // a follow-up — would call handleRecallSubgraph(state, {query: convText, k: 20})
2142
+ // and pass the decrypted candidates here.
2064
2143
  isDedupEnabled: () => false,
2065
2144
  getDedupCandidates: async () => [],
2066
- // 3.3.0-rc.2: stub runExtraction. The full LLM-driven extractor +
2067
- // llm-client port lands in a follow-up RC. Phrase-safety hard rail:
2068
- // when porting, the recovery phrase MUST NEVER cross into the
2069
- // extraction prompt — only chat messages are passed in.
2070
- runExtraction: async () => {
2071
- if (!warnedNoLlm) {
2072
- warnedNoLlm = true;
2073
- logger.warn('MCP-only auto-extraction LLM not yet wired (3.3.0-rc.2 ships poller scaffold only). ' +
2074
- 'Agents MUST call `totalreclaw_remember` explicitly per the SKILL.md trigger-phrase rules. ' +
2075
- 'Plugin install path retains full LLM-driven extraction.');
2145
+ // ── runExtraction: the real LLM-driven extractor ──
2146
+ // Phrase-safety: `messages` is `{role, content}[]` parsed by the
2147
+ // poller from OpenClaw's trajectory JSONL — user prompts +
2148
+ // assistant replies only. The recovery phrase NEVER crosses this
2149
+ // boundary; it lives in `subgraphState.mnemonic` (different call
2150
+ // stack, used only for HD wallet derivation in subgraph/store.ts).
2151
+ runExtraction: async (messages, mode) => {
2152
+ const facts = await extraction.extractFacts(messages, mode, undefined, // existingMemories — wired via getDedupCandidates path when isDedupEnabled() flips to true
2153
+ undefined, // profileContext (no plugin profile in MCP-only mode)
2154
+ logger);
2155
+ return facts;
2156
+ },
2157
+ filterByImportance: (facts) => {
2158
+ // The extractor already filters at parse-time (importance >= 6 unless
2159
+ // DELETE). Trust that floor here — only drop the obvious noise that
2160
+ // slipped through (e.g. 0/NaN sentinels). Same shape as the plugin's
2161
+ // hook-side filter.
2162
+ const kept = [];
2163
+ let dropped = 0;
2164
+ for (const f of facts) {
2165
+ const imp = typeof f.importance === 'number' && Number.isFinite(f.importance) ? f.importance : 0;
2166
+ if (imp >= 6)
2167
+ kept.push(f);
2168
+ else
2169
+ dropped++;
2170
+ }
2171
+ return { kept, dropped };
2172
+ },
2173
+ // ── persistFacts: route through handleRememberSubgraph ──
2174
+ // Encryption + protobuf v4 + on-chain submit + store-time dedup all
2175
+ // live there. Calling it with a `facts` batch (NOT the explicit
2176
+ // single-fact form) means batch-mode dedup logic runs (skip vs
2177
+ // supersede heuristics). Returns the `created` count for the
2178
+ // poller log line.
2179
+ persistFacts: async (facts) => {
2180
+ if (!subgraphState) {
2181
+ logger.warn('persistFacts: subgraphState not yet resolved — skipping persist');
2182
+ return 0;
2183
+ }
2184
+ // Map ExtractedFact → handleRememberSubgraph's batch-fact shape.
2185
+ const factsArray = facts.map((f) => {
2186
+ const fact = f;
2187
+ return {
2188
+ text: String(fact.text),
2189
+ importance: typeof fact.importance === 'number' ? fact.importance : 5,
2190
+ type: typeof fact.type === 'string' ? fact.type : 'claim',
2191
+ scope: typeof fact.scope === 'string' ? fact.scope : 'unspecified',
2192
+ reasoning: typeof fact.reasoning === 'string' ? fact.reasoning : undefined,
2193
+ };
2194
+ });
2195
+ try {
2196
+ const res = await handleRememberSubgraph(subgraphState, { facts: factsArray });
2197
+ // handleRememberSubgraph returns MCP tool-response shape; parse
2198
+ // the inner JSON to recover `created`.
2199
+ const inner = res.content?.[0]?.text;
2200
+ if (typeof inner === 'string') {
2201
+ const parsed = JSON.parse(inner);
2202
+ return typeof parsed.created === 'number' ? parsed.created : 0;
2203
+ }
2204
+ return 0;
2205
+ }
2206
+ catch (err) {
2207
+ const msg = err instanceof Error ? err.message : String(err);
2208
+ logger.warn(`persistFacts: handleRememberSubgraph threw: ${msg}`);
2209
+ return 0;
2076
2210
  }
2077
- return [];
2078
2211
  },
2079
- filterByImportance: (facts) => ({ kept: facts, dropped: 0 }),
2080
- persistFacts: async () => 0,
2081
2212
  });
2082
2213
  }
2083
2214
  catch (err) {