negotium 0.23.4 → 0.23.6

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.
Files changed (62) hide show
  1. package/dist/agent-helpers.js +29 -4
  2. package/dist/agent-helpers.js.map +9 -9
  3. package/dist/background-bash.js +2 -1
  4. package/dist/background-bash.js.map +3 -3
  5. package/dist/browser-runtime.js +2 -1
  6. package/dist/browser-runtime.js.map +3 -3
  7. package/dist/{chunk-qekt5bnd.js → chunk-ad7kxsaq.js} +4 -2
  8. package/dist/{chunk-qekt5bnd.js.map → chunk-ad7kxsaq.js.map} +1 -1
  9. package/dist/{chunk-ggdwn8d5.js → chunk-dtmsberv.js} +3 -3
  10. package/dist/{chunk-ggdwn8d5.js.map → chunk-dtmsberv.js.map} +2 -2
  11. package/dist/chunk-f7p0h1gs.js.map +1 -1
  12. package/dist/{chunk-jarf6nb2.js → chunk-mxxwx5mg.js} +3 -2
  13. package/dist/{chunk-jarf6nb2.js.map → chunk-mxxwx5mg.js.map} +3 -3
  14. package/dist/{chunk-vtd5kn4n.js → chunk-n6crwk1s.js} +26 -2
  15. package/dist/{chunk-vtd5kn4n.js.map → chunk-n6crwk1s.js.map} +7 -7
  16. package/dist/{chunk-pwafy9bb.js → chunk-ztcj9grz.js} +1 -1
  17. package/dist/hosted-agent.js +29 -5
  18. package/dist/hosted-agent.js.map +6 -6
  19. package/dist/main.js +368 -36
  20. package/dist/main.js.map +13 -12
  21. package/dist/mcp-catalog.js +3 -2
  22. package/dist/mcp-catalog.js.map +3 -3
  23. package/dist/mcp-factories.js +344 -32
  24. package/dist/mcp-factories.js.map +11 -10
  25. package/dist/mcp-servers.js +3 -1
  26. package/dist/mcp-servers.js.map +3 -3
  27. package/dist/media.js +2 -1
  28. package/dist/media.js.map +3 -3
  29. package/dist/prompts.js +2 -1
  30. package/dist/prompts.js.map +3 -3
  31. package/dist/query-runtime.js +2 -1
  32. package/dist/query-runtime.js.map +3 -3
  33. package/dist/registry.js +3 -3
  34. package/dist/rollout.js +2 -2
  35. package/dist/runtime/src/mcp/canonical-bridge-config.ts +1 -1
  36. package/dist/runtime/src/mcp/canonical-proxy-server.ts +39 -1
  37. package/dist/runtime/src/mcp/factories/index.ts +4 -0
  38. package/dist/runtime/src/mcp/factories/session-history.ts +388 -0
  39. package/dist/runtime/src/mcp/runtime-spec.ts +1 -0
  40. package/dist/runtime/src/mcp/session-history-server.ts +27 -0
  41. package/dist/runtime/src/platform/config.ts +2 -0
  42. package/dist/runtime/src/platform/mcp-catalog-policy.ts +5 -0
  43. package/dist/runtime/src/platform/mcp-config.ts +30 -0
  44. package/dist/runtime/src/storage/topic-archive.ts +4 -2
  45. package/dist/runtime/src/version.ts +1 -1
  46. package/dist/runtime-helpers.js +2 -1
  47. package/dist/runtime-helpers.js.map +3 -3
  48. package/dist/storage.js +5 -1
  49. package/dist/storage.js.map +3 -3
  50. package/dist/types/apps/negotium/src/mcp-servers.d.ts +1 -1
  51. package/dist/types/packages/core/src/mcp/canonical-bridge-config.d.ts +1 -1
  52. package/dist/types/packages/core/src/mcp/factories/index.d.ts +1 -0
  53. package/dist/types/packages/core/src/mcp/factories/session-history.d.ts +11 -0
  54. package/dist/types/packages/core/src/mcp/runtime-spec.d.ts +1 -1
  55. package/dist/types/packages/core/src/platform/config.d.ts +1 -0
  56. package/dist/types/packages/core/src/platform/mcp-catalog-policy.d.ts +4 -0
  57. package/dist/types/packages/core/src/storage/topic-archive.d.ts +5 -0
  58. package/dist/types/packages/core/src/version.d.ts +1 -1
  59. package/dist/vault.js +2 -1
  60. package/dist/vault.js.map +3 -3
  61. package/package.json +1 -1
  62. /package/dist/{chunk-pwafy9bb.js.map → chunk-ztcj9grz.js.map} +0 -0
package/dist/main.js CHANGED
@@ -123,6 +123,7 @@ __export(exports_config, {
123
123
  SHARED_WIKI_DIR: () => SHARED_WIKI_DIR,
124
124
  SESSION_WORKSPACE_DIR: () => SESSION_WORKSPACE_DIR,
125
125
  SESSION_INBOX_DIR: () => SESSION_INBOX_DIR,
126
+ SESSION_HISTORY_SERVER: () => SESSION_HISTORY_SERVER,
126
127
  SESSION_COMM_SERVER: () => SESSION_COMM_SERVER,
127
128
  SESSION_ASKS_DIR: () => SESSION_ASKS_DIR,
128
129
  SESSIONS_DB: () => SESSIONS_DB,
@@ -383,7 +384,7 @@ function resolveWhisperBackend() {
383
384
  function codexAuthFilePath() {
384
385
  return process.env.NEGOTIUM_CODEX_AUTH_FILE || join(process.env.CODEX_HOME || join(homedir(), ".codex"), "auth.json");
385
386
  }
386
- var HOME, PROJECT_ROOT, STATE_DIR, WORKSPACE_DIR, TOPIC_WORKSPACE_DIR, SHARED_WIKI_DIR, CRON_WORKSPACE_DIR, BROWSER_DIR, BROWSER_PROFILES_DIR, BINARIES_DIR, SECRETS_DIR, DM_WORKSPACE_DIR, SESSION_WORKSPACE_DIR, CLAUDE_EXECUTABLE_ENV, CLAUDE_EXECUTABLE, DEFAULT_OUTPUT_LANGUAGE = "English", BINARY_EXTENSION, BROWSER_RS_VERSION = "v0.7.7", BROWSER_RS_MIN_SECURE_VERSION = "0.2.1", BROWSER_RS_VERSION_PROBE_TIMEOUT_MS = 15000, SNIPPETS_API_URL, BROWSER_RS_BIN, BASH_RS_VERSION = "v0.1.10", BASH_RS_BIN, PLAYWRIGHT_MCP_BIN, TSX_BIN, TSX_LOADER_PATH, TSX_LOADER, TSCONFIG_PATH, SESSION_COMM_SERVER, TASK_SERVER, DECISION_SERVER, CANONICAL_MCP_PROXY_SERVER, WIKI_SERVER, TOKEN_STATS_SERVER, COMPACTION_LOG_SERVER, SYSTEM_HEALTH_SERVER, AGENT_HEALTH_SERVER, VAULT_SERVER, BG_BASH_BASE_PORT, BG_BASH_MAX_PORT, RUNTIME_MCP_SECRET, NODE_CONTROL_TOKEN, NODE_ID, VAULT_MASTER_KEY, NEGOTIUM_PORT, hostname, DATA_DIR, LOG_DIR, UPLOADS_DIR, VAULT_DIR, SESSIONS_DB, DEBUG_FILE, USERS_LOG_DIR, RUN_DIR, RUNTIME_DIR, PROGRESS_DIR, DM_CMD_DIR, DM_RESP_DIR, SESSION_INBOX_DIR, SESSION_ASKS_DIR, BASHRS_SPILL_ROOT, PLAYWRIGHT_BASE_PORT, PLAYWRIGHT_MAX_PORT, PLAYWRIGHT_PORTS_DIR, ACTIVE_QUERY_STALE_MS, AGENTS_PROMPTS_DIR, RESOURCES_DIR, ABSOLUTE_PATH_PREFIX, FILE_EXTENSIONS_REGEX, FILE_TAG_REGEX, MODEL_SONNET = "claude-sonnet-5", MODEL_OPUS = "claude-opus-5-5", MODEL_HAIKU = "claude-haiku-4-5-20251001", MODEL_FABLE = "claude-fable-5-1", MODEL_DEEPSEEK_V4_PRO = "deepseek-v4-pro", MODEL_DEEPSEEK_V4_FLASH = "deepseek-v4-flash", FALLBACK_AGENT, FALLBACK_MODEL, DEFAULT_TOPIC_EFFORT, FFMPEG_BIN, FFPROBE_BIN, PYTHON_BIN, FASTER_WHISPER_WRAPPER, WHISPER_MODEL, TESSERACT_BIN, PDFTOTEXT_BIN, WHISPER_BACKEND, MLX_WHISPER_BIN, WHISPER_MODEL_MLX, _envMaxTellDepth, MAX_TELL_DEPTH;
387
+ var HOME, PROJECT_ROOT, STATE_DIR, WORKSPACE_DIR, TOPIC_WORKSPACE_DIR, SHARED_WIKI_DIR, CRON_WORKSPACE_DIR, BROWSER_DIR, BROWSER_PROFILES_DIR, BINARIES_DIR, SECRETS_DIR, DM_WORKSPACE_DIR, SESSION_WORKSPACE_DIR, CLAUDE_EXECUTABLE_ENV, CLAUDE_EXECUTABLE, DEFAULT_OUTPUT_LANGUAGE = "English", BINARY_EXTENSION, BROWSER_RS_VERSION = "v0.7.7", BROWSER_RS_MIN_SECURE_VERSION = "0.2.1", BROWSER_RS_VERSION_PROBE_TIMEOUT_MS = 15000, SNIPPETS_API_URL, BROWSER_RS_BIN, BASH_RS_VERSION = "v0.1.10", BASH_RS_BIN, PLAYWRIGHT_MCP_BIN, TSX_BIN, TSX_LOADER_PATH, TSX_LOADER, TSCONFIG_PATH, SESSION_COMM_SERVER, TASK_SERVER, DECISION_SERVER, CANONICAL_MCP_PROXY_SERVER, WIKI_SERVER, TOKEN_STATS_SERVER, COMPACTION_LOG_SERVER, SESSION_HISTORY_SERVER, SYSTEM_HEALTH_SERVER, AGENT_HEALTH_SERVER, VAULT_SERVER, BG_BASH_BASE_PORT, BG_BASH_MAX_PORT, RUNTIME_MCP_SECRET, NODE_CONTROL_TOKEN, NODE_ID, VAULT_MASTER_KEY, NEGOTIUM_PORT, hostname, DATA_DIR, LOG_DIR, UPLOADS_DIR, VAULT_DIR, SESSIONS_DB, DEBUG_FILE, USERS_LOG_DIR, RUN_DIR, RUNTIME_DIR, PROGRESS_DIR, DM_CMD_DIR, DM_RESP_DIR, SESSION_INBOX_DIR, SESSION_ASKS_DIR, BASHRS_SPILL_ROOT, PLAYWRIGHT_BASE_PORT, PLAYWRIGHT_MAX_PORT, PLAYWRIGHT_PORTS_DIR, ACTIVE_QUERY_STALE_MS, AGENTS_PROMPTS_DIR, RESOURCES_DIR, ABSOLUTE_PATH_PREFIX, FILE_EXTENSIONS_REGEX, FILE_TAG_REGEX, MODEL_SONNET = "claude-sonnet-5", MODEL_OPUS = "claude-opus-5-5", MODEL_HAIKU = "claude-haiku-4-5-20251001", MODEL_FABLE = "claude-fable-5-1", MODEL_DEEPSEEK_V4_PRO = "deepseek-v4-pro", MODEL_DEEPSEEK_V4_FLASH = "deepseek-v4-flash", FALLBACK_AGENT, FALLBACK_MODEL, DEFAULT_TOPIC_EFFORT, FFMPEG_BIN, FFPROBE_BIN, PYTHON_BIN, FASTER_WHISPER_WRAPPER, WHISPER_MODEL, TESSERACT_BIN, PDFTOTEXT_BIN, WHISPER_BACKEND, MLX_WHISPER_BIN, WHISPER_MODEL_MLX, _envMaxTellDepth, MAX_TELL_DEPTH;
387
388
  var init_config = __esm(() => {
388
389
  init_config_helpers();
389
390
  init_logger();
@@ -419,6 +420,7 @@ var init_config = __esm(() => {
419
420
  WIKI_SERVER = resolve(PROJECT_ROOT, "src/mcp/wiki-server.ts");
420
421
  TOKEN_STATS_SERVER = resolve(PROJECT_ROOT, "src/mcp/token-stats-server.ts");
421
422
  COMPACTION_LOG_SERVER = resolve(PROJECT_ROOT, "src/mcp/compaction-log-server.ts");
423
+ SESSION_HISTORY_SERVER = resolve(PROJECT_ROOT, "src/mcp/session-history-server.ts");
422
424
  SYSTEM_HEALTH_SERVER = resolve(PROJECT_ROOT, "src/mcp/system-health-server.ts");
423
425
  AGENT_HEALTH_SERVER = resolve(PROJECT_ROOT, "src/mcp/agent-health-server.ts");
424
426
  VAULT_SERVER = resolve(PROJECT_ROOT, "src/mcp/vault-server.ts");
@@ -2794,7 +2796,8 @@ var init_runtime_spec = __esm(() => {
2794
2796
  "wiki",
2795
2797
  "skills",
2796
2798
  "session-comm",
2797
- "agent-health"
2799
+ "agent-health",
2800
+ "session-history"
2798
2801
  ];
2799
2802
  TOKEN_TTL_MS = 4 * 60 * 60 * 1000;
2800
2803
  MCP_URL_BUDGET_CHARS = 14 * 1024;
@@ -3078,7 +3081,8 @@ var init_mcp_catalog_policy = __esm(() => {
3078
3081
  "background-bash": { scopes: ["forum"], forumRequired: true },
3079
3082
  "agent-health": { scopes: ["forum", "manager", "cron"], forumRequired: true },
3080
3083
  vault: { scopes: ["dm", "forum", "manager", "cron"], forumRequired: true },
3081
- "cua-rs": { scopes: ["dm", "forum", "fork"], forumRequired: false }
3084
+ "cua-rs": { scopes: ["dm", "forum", "fork"], forumRequired: false },
3085
+ "session-history": { scopes: ["dm", "forum", "manager"], forumRequired: false }
3082
3086
  };
3083
3087
  });
3084
3088
 
@@ -5824,6 +5828,28 @@ var init_mcp_config = __esm(async () => {
5824
5828
  return buildBuiltinMcpServer("decision", ctx, () => buildStdioMcpServer(agent, DECISION_SERVER, args));
5825
5829
  }
5826
5830
  },
5831
+ "session-history": {
5832
+ ...commonRuntimeMcpPolicy("session-history"),
5833
+ build(ctx) {
5834
+ const { userId, session, topicId, queryId, agent, peerBridge } = ctx;
5835
+ if (peerBridge) {
5836
+ if (!topicId || !queryId)
5837
+ return null;
5838
+ const env = canonicalMcpBridgeEnv({
5839
+ surface: "session-history",
5840
+ userId,
5841
+ topicId,
5842
+ queryId,
5843
+ peerBridge
5844
+ });
5845
+ return env ? buildStdioMcpServer(agent, CANONICAL_MCP_PROXY_SERVER, ["--surface=session-history"], env) : null;
5846
+ }
5847
+ const args = [`--user-id=${userId}`, `--topic=${session}`];
5848
+ if (topicId)
5849
+ args.push(`--topic-id=${topicId}`);
5850
+ return buildBuiltinMcpServer("session-history", ctx, () => buildStdioMcpServer(agent, SESSION_HISTORY_SERVER, args));
5851
+ }
5852
+ },
5827
5853
  "session-comm": {
5828
5854
  ...commonRuntimeMcpPolicy("session-comm"),
5829
5855
  build(ctx) {
@@ -6607,7 +6633,7 @@ var exports_version = {};
6607
6633
  __export(exports_version, {
6608
6634
  NEGOTIUM_VERSION: () => NEGOTIUM_VERSION
6609
6635
  });
6610
- var NEGOTIUM_VERSION = "0.23.4";
6636
+ var NEGOTIUM_VERSION = "0.23.6";
6611
6637
 
6612
6638
  // ../../packages/core/src/agents/codex-native-multi-agent.ts
6613
6639
  import { spawn as spawn2 } from "child_process";
@@ -15988,6 +16014,8 @@ function formatTopicArchiveTranscriptRecord(row, topicTitle, index) {
15988
16014
  // ../../packages/core/src/storage/topic-archive.ts
15989
16015
  var exports_topic_archive = {};
15990
16016
  __export(exports_topic_archive, {
16017
+ eventText: () => eventText,
16018
+ eventSpeaker: () => eventSpeaker,
15991
16019
  archiveTopicMessages: () => archiveTopicMessages,
15992
16020
  archiveConversationEvents: () => archiveConversationEvents
15993
16021
  });
@@ -32669,14 +32697,302 @@ var init_default_host = __esm(async () => {
32669
32697
  ]);
32670
32698
  });
32671
32699
 
32700
+ // ../../packages/core/src/mcp/factories/session-history.ts
32701
+ var exports_session_history = {};
32702
+ __export(exports_session_history, {
32703
+ createSessionHistoryMcpServer: () => createSessionHistoryMcpServer
32704
+ });
32705
+ import { McpServer as McpServer7 } from "@modelcontextprotocol/sdk/server/mcp.js";
32706
+ import { z as z13 } from "zod";
32707
+ function positiveInt(value, fallback) {
32708
+ return Number.isFinite(value) && value && value > 0 ? Math.floor(value) : fallback;
32709
+ }
32710
+ function fitUtf8(text3, maxBytes) {
32711
+ if (Buffer.byteLength(text3, "utf8") <= maxBytes)
32712
+ return text3;
32713
+ const marker = `
32714
+ [... oversized entry clipped ...]
32715
+ `;
32716
+ const markerBytes = Buffer.byteLength(marker, "utf8");
32717
+ const bytes = Buffer.from(text3, "utf8");
32718
+ if (maxBytes <= markerBytes) {
32719
+ return bytes.subarray(0, maxBytes).toString("utf8").replace(/\uFFFD+$/u, "");
32720
+ }
32721
+ const available = Math.max(0, maxBytes - markerBytes);
32722
+ const headBudget = Math.ceil(available * 0.6);
32723
+ const tailBudget = available - headBudget;
32724
+ const head = bytes.subarray(0, headBudget).toString("utf8").replace(/\uFFFD+$/u, "");
32725
+ const tail = bytes.subarray(Math.max(0, bytes.length - tailBudget)).toString("utf8").replace(/^\uFFFD+/u, "");
32726
+ return `${head}${marker}${tail}`;
32727
+ }
32728
+ function escapeRegExp4(value) {
32729
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
32730
+ }
32731
+ function renderEntry(entry, index) {
32732
+ const speaker = eventSpeaker(entry.event, entry.agent);
32733
+ const text3 = eventText(entry.event);
32734
+ return `[${index}] ${entry.ts} ${speaker}: ${text3}`;
32735
+ }
32736
+ function deriveBoundaries(entries) {
32737
+ const boundaries = [];
32738
+ entries.forEach((entry, i) => {
32739
+ if (entry.event.type !== "session")
32740
+ return;
32741
+ const index = i + 1;
32742
+ const previous = boundaries.at(-1);
32743
+ if (previous && previous.sessionId === entry.event.sessionId)
32744
+ return;
32745
+ if (previous) {
32746
+ previous.endedAt = entry.ts;
32747
+ previous.endedBy = previous.agent === entry.agent ? "compacted" : "agent-switch";
32748
+ }
32749
+ boundaries.push({
32750
+ entryIndex: index,
32751
+ sessionId: entry.event.sessionId,
32752
+ agent: entry.agent,
32753
+ startedAt: entry.ts,
32754
+ endedBy: "active"
32755
+ });
32756
+ });
32757
+ if (boundaries.length === 0 && entries.length > 0) {
32758
+ boundaries.push({
32759
+ entryIndex: 1,
32760
+ sessionId: "(unknown \u2014 no session event found)",
32761
+ agent: entries[0]?.agent ?? "unknown",
32762
+ startedAt: entries[0]?.ts ?? "",
32763
+ endedBy: "active"
32764
+ });
32765
+ }
32766
+ return boundaries;
32767
+ }
32768
+ function createSessionHistoryMcpServer(context) {
32769
+ const maxCalls = positiveInt(context.maxCalls, DEFAULT_MAX_CALLS);
32770
+ const maxTotalBytes = positiveInt(context.maxTotalBytes, DEFAULT_MAX_TOTAL_BYTES);
32771
+ const maxChunkBytes = positiveInt(context.maxChunkBytes, DEFAULT_MAX_CHUNK_BYTES);
32772
+ let calls = 0;
32773
+ let totalBytes = 0;
32774
+ const server = new McpServer7({ name: "session-history", version: "1.0.0" });
32775
+ const requireContext = () => {
32776
+ if (!context.userId || !context.topic) {
32777
+ return mcpError("Error: missing userId/topic context.");
32778
+ }
32779
+ return null;
32780
+ };
32781
+ const budgetExceeded = () => {
32782
+ if (calls > maxCalls || totalBytes >= maxTotalBytes) {
32783
+ return mcpError(JSON.stringify({
32784
+ error: "session-history read budget exhausted for this turn; answer with what you already read",
32785
+ calls,
32786
+ max_calls: maxCalls,
32787
+ total_read_bytes: totalBytes,
32788
+ max_total_bytes: maxTotalBytes
32789
+ }));
32790
+ }
32791
+ return null;
32792
+ };
32793
+ server.tool("list_session_boundaries", [
32794
+ "List every provider session this topic has had, in order, from the append-only raw",
32795
+ "conversation manifest (survives /compact and agent switches \u2014 nothing is ever deleted",
32796
+ "from it). Each entry gives the 1-based entry-index range covering that session, whether",
32797
+ "it ended via compaction or an agent switch, and its provider sessionId. Call this BEFORE",
32798
+ "read_session_history or search_session_history so you know which entry range to target",
32799
+ "instead of scanning from entry 1."
32800
+ ].join(" "), {}, async () => {
32801
+ const guard = requireContext();
32802
+ if (guard)
32803
+ return guard;
32804
+ calls += 1;
32805
+ const budget = budgetExceeded();
32806
+ if (budget)
32807
+ return budget;
32808
+ try {
32809
+ const entries = readRawConversation(context.userId, context.topic);
32810
+ const boundaries = deriveBoundaries(entries);
32811
+ const payload = JSON.stringify({ total_entries: entries.length, sessions: boundaries }, null, 2);
32812
+ totalBytes += Buffer.byteLength(payload, "utf8");
32813
+ return mcpOk(payload);
32814
+ } catch (error2) {
32815
+ return mcpError(`list_session_boundaries failed: ${errMsg(error2)}`);
32816
+ }
32817
+ });
32818
+ server.tool("read_session_history", [
32819
+ "Read the full-fidelity raw conversation manifest in bounded chunks \u2014 includes everything",
32820
+ "that ever happened in this topic (messages, tool calls, reasoning, session/compact",
32821
+ "boundaries), even content a /compact summarized away from the active context. Entry",
32822
+ "numbers are 1-based positions, as returned by list_session_boundaries. Start by calling",
32823
+ "list_session_boundaries, then pass sessionId to read only that session's range instead of",
32824
+ "paging through the whole topic."
32825
+ ].join(" "), {
32826
+ offset: z13.number().optional().describe("One-based entry number. Defaults to 1."),
32827
+ limit: z13.number().optional().describe(`Number of entries. Defaults to ${DEFAULT_LINE_LIMIT}, max ${MAX_LINE_LIMIT}.`),
32828
+ sessionId: z13.string().optional().describe("Restrict to one session's entry range (see list_session_boundaries).")
32829
+ }, async ({ offset: rawOffset, limit: rawLimit, sessionId }) => {
32830
+ const guard = requireContext();
32831
+ if (guard)
32832
+ return guard;
32833
+ calls += 1;
32834
+ const budget = budgetExceeded();
32835
+ if (budget)
32836
+ return budget;
32837
+ try {
32838
+ const entries = readRawConversation(context.userId, context.topic);
32839
+ let lower = 0;
32840
+ let upper = entries.length;
32841
+ if (sessionId) {
32842
+ const boundaries = deriveBoundaries(entries);
32843
+ const match = boundaries.find((b) => b.sessionId === sessionId);
32844
+ if (!match)
32845
+ return mcpError(`Unknown sessionId: ${sessionId}`);
32846
+ lower = match.entryIndex - 1;
32847
+ const next = boundaries.find((b) => b.entryIndex > match.entryIndex);
32848
+ upper = next ? next.entryIndex - 1 : entries.length;
32849
+ }
32850
+ const offset = positiveInt(rawOffset, 1);
32851
+ const limit = Math.min(positiveInt(rawLimit, DEFAULT_LINE_LIMIT), MAX_LINE_LIMIT);
32852
+ const start = Math.max(lower, offset - 1);
32853
+ if (start >= upper) {
32854
+ return mcpOk(JSON.stringify({
32855
+ content: "(end of range)",
32856
+ offset,
32857
+ returned_entries: 0,
32858
+ total_entries: entries.length,
32859
+ calls
32860
+ }));
32861
+ }
32862
+ const rendered = [];
32863
+ let returnedBytes = 0;
32864
+ let index = start;
32865
+ const callBudget = Math.min(maxChunkBytes, Math.max(1, maxTotalBytes - totalBytes));
32866
+ while (index < upper && rendered.length < limit) {
32867
+ const line = fitUtf8(renderEntry(entries[index], index + 1), Math.max(1, callBudget));
32868
+ const separatorBytes = rendered.length > 0 ? 1 : 0;
32869
+ const lineBytes = Buffer.byteLength(line, "utf8");
32870
+ if (rendered.length > 0 && returnedBytes + separatorBytes + lineBytes > callBudget)
32871
+ break;
32872
+ rendered.push(line);
32873
+ returnedBytes += separatorBytes + lineBytes;
32874
+ index += 1;
32875
+ if (returnedBytes >= callBudget)
32876
+ break;
32877
+ }
32878
+ totalBytes += returnedBytes;
32879
+ return mcpOk(JSON.stringify({
32880
+ content: rendered.join(`
32881
+ `),
32882
+ offset,
32883
+ returned_entries: rendered.length,
32884
+ returned_bytes: returnedBytes,
32885
+ total_entries: entries.length,
32886
+ total_read_bytes: totalBytes,
32887
+ calls,
32888
+ ...index < upper ? { next_offset: index + 1 } : {},
32889
+ ...calls >= maxCalls || totalBytes >= maxTotalBytes ? { note: "Read budget nearly exhausted; wrap up with what you have." } : {}
32890
+ }));
32891
+ } catch (error2) {
32892
+ return mcpError(`read_session_history failed: ${errMsg(error2)}`);
32893
+ }
32894
+ });
32895
+ server.tool("search_session_history", [
32896
+ "Keyword-search the full raw conversation manifest (case-insensitive substring match)",
32897
+ "across every session this topic has ever had, including content a /compact summarized",
32898
+ "away. Returns matching entry numbers with a short snippet around the match \u2014 pass one",
32899
+ "into read_session_history to see full context. Plain linear scan, no index: fine at this",
32900
+ "topic's size, but prefer sessionId to narrow the scan when you already know which session",
32901
+ "from list_session_boundaries."
32902
+ ].join(" "), {
32903
+ query: z13.string().min(1).describe("Case-insensitive substring to search for."),
32904
+ sessionId: z13.string().optional().describe("Restrict the scan to one session's range."),
32905
+ limit: z13.number().optional().describe(`Max matches to return. Defaults to ${DEFAULT_SEARCH_LIMIT}, max ${MAX_SEARCH_LIMIT}.`)
32906
+ }, async ({ query: query2, sessionId, limit: rawLimit }) => {
32907
+ const guard = requireContext();
32908
+ if (guard)
32909
+ return guard;
32910
+ calls += 1;
32911
+ const budget = budgetExceeded();
32912
+ if (budget)
32913
+ return budget;
32914
+ try {
32915
+ const entries = readRawConversation(context.userId, context.topic);
32916
+ let lower = 0;
32917
+ let upper = entries.length;
32918
+ if (sessionId) {
32919
+ const boundaries2 = deriveBoundaries(entries);
32920
+ const match = boundaries2.find((b) => b.sessionId === sessionId);
32921
+ if (!match)
32922
+ return mcpError(`Unknown sessionId: ${sessionId}`);
32923
+ lower = match.entryIndex - 1;
32924
+ const next = boundaries2.find((b) => b.entryIndex > match.entryIndex);
32925
+ upper = next ? next.entryIndex - 1 : entries.length;
32926
+ }
32927
+ const limit = Math.min(positiveInt(rawLimit, DEFAULT_SEARCH_LIMIT), MAX_SEARCH_LIMIT);
32928
+ const needleRegex = new RegExp(escapeRegExp4(query2), "i");
32929
+ const matches = [];
32930
+ const boundaries = sessionId ? undefined : deriveBoundaries(entries);
32931
+ let returnedBytes = 0;
32932
+ let budgetStopped = false;
32933
+ const callBudget = Math.min(maxChunkBytes, Math.max(1, maxTotalBytes - totalBytes));
32934
+ for (let i = lower;i < upper && matches.length < limit; i++) {
32935
+ const entry = entries[i];
32936
+ const text3 = eventText(entry.event);
32937
+ const found = needleRegex.exec(text3);
32938
+ if (!found)
32939
+ continue;
32940
+ const at = found.index;
32941
+ const start = Math.max(0, at - SEARCH_SNIPPET_RADIUS);
32942
+ const end = Math.min(text3.length, at + found[0].length + SEARCH_SNIPPET_RADIUS);
32943
+ const snippet = `${start > 0 ? "\u2026" : ""}${text3.slice(start, end)}${end < text3.length ? "\u2026" : ""}`;
32944
+ const matchedSessionId = sessionId ?? boundaries?.findLast((b) => b.entryIndex <= i + 1)?.sessionId;
32945
+ const candidate = {
32946
+ entry: i + 1,
32947
+ sessionId: matchedSessionId,
32948
+ agent: entry.agent,
32949
+ ts: entry.ts,
32950
+ snippet
32951
+ };
32952
+ const lineBytes = Buffer.byteLength(JSON.stringify(candidate), "utf8");
32953
+ if (returnedBytes + lineBytes > callBudget) {
32954
+ budgetStopped = true;
32955
+ break;
32956
+ }
32957
+ returnedBytes += lineBytes;
32958
+ matches.push(candidate);
32959
+ }
32960
+ totalBytes += returnedBytes;
32961
+ return mcpOk(JSON.stringify({
32962
+ query: query2,
32963
+ matches,
32964
+ match_count: matches.length,
32965
+ total_entries: entries.length,
32966
+ calls,
32967
+ ...matches.length >= limit ? { note: "Hit the match limit; narrow the query or pass sessionId for more." } : budgetStopped ? {
32968
+ note: "Read budget ran out before the scan finished; this result is incomplete, not necessarily 'no matches'."
32969
+ } : {}
32970
+ }));
32971
+ } catch (error2) {
32972
+ return mcpError(`search_session_history failed: ${errMsg(error2)}`);
32973
+ }
32974
+ });
32975
+ return server;
32976
+ }
32977
+ var DEFAULT_MAX_CALLS = 20, DEFAULT_MAX_TOTAL_BYTES, DEFAULT_MAX_CHUNK_BYTES, DEFAULT_LINE_LIMIT = 300, MAX_LINE_LIMIT = 500, DEFAULT_SEARCH_LIMIT = 20, MAX_SEARCH_LIMIT = 50, SEARCH_SNIPPET_RADIUS = 160;
32978
+ var init_session_history = __esm(async () => {
32979
+ init_mcp_helpers();
32980
+ await __promiseAll([
32981
+ init_conversations(),
32982
+ init_topic_archive()
32983
+ ]);
32984
+ DEFAULT_MAX_TOTAL_BYTES = 768 * 1024;
32985
+ DEFAULT_MAX_CHUNK_BYTES = 64 * 1024;
32986
+ });
32987
+
32672
32988
  // ../../packages/core/src/mcp/factories/vault.ts
32673
32989
  var exports_vault = {};
32674
32990
  __export(exports_vault, {
32675
32991
  createVaultMcpServer: () => createVaultMcpServer
32676
32992
  });
32677
- import { McpServer as McpServer7 } from "@modelcontextprotocol/sdk/server/mcp.js";
32993
+ import { McpServer as McpServer8 } from "@modelcontextprotocol/sdk/server/mcp.js";
32678
32994
  function createVaultMcpServer(context, host2) {
32679
- const server = new McpServer7({ name: "vault", version: "1.0.0" });
32995
+ const server = new McpServer8({ name: "vault", version: "1.0.0" });
32680
32996
  server.tool("vault_list", "List the user's Vault keys and descriptions without exposing values. Use {{KEY}} placeholders directly in supported transient tool inputs.", {}, () => {
32681
32997
  if (!context.userId)
32682
32998
  return mcpOk("(vault unavailable: no user context)");
@@ -35375,6 +35691,8 @@ __export(exports_storage_public, {
35375
35691
  findThreadRootsByPrefix: () => findThreadRootsByPrefix,
35376
35692
  findRecentUserMessage: () => findRecentUserMessage,
35377
35693
  findLastSessionIdForAgent: () => findLastSessionIdForAgent,
35694
+ eventText: () => eventText,
35695
+ eventSpeaker: () => eventSpeaker,
35378
35696
  describePendingAskState: () => describePendingAskState,
35379
35697
  deleteTopicStats: () => deleteTopicStats,
35380
35698
  deleteTopicBrief: () => deleteTopicBrief,
@@ -35536,6 +35854,14 @@ async function buildHostedSurfaceServer(surface, context) {
35536
35854
  optionalMcpServers: core.OPTIONAL_FORUM_MCP_SERVERS
35537
35855
  });
35538
35856
  }
35857
+ case "session-history": {
35858
+ const { createSessionHistoryMcpServer: createSessionHistoryMcpServer2 } = await init_session_history().then(() => exports_session_history);
35859
+ return createSessionHistoryMcpServer2({
35860
+ userId: context.userId,
35861
+ topic: context.topicTitle,
35862
+ topicId: context.topicId
35863
+ });
35864
+ }
35539
35865
  case "vault": {
35540
35866
  const [{ createVaultMcpServer: createVaultMcpServer2 }, vault] = await Promise.all([
35541
35867
  Promise.resolve().then(() => (init_vault2(), exports_vault)),
@@ -35583,7 +35909,8 @@ var init_hosted_surfaces = __esm(() => {
35583
35909
  "wiki",
35584
35910
  "skills",
35585
35911
  "agent-health",
35586
- "session-comm"
35912
+ "session-comm",
35913
+ "session-history"
35587
35914
  ];
35588
35915
  });
35589
35916
 
@@ -35696,9 +36023,9 @@ var init_sse_transport = () => {};
35696
36023
  import { createHash as createHash16, randomUUID as randomUUID28 } from "crypto";
35697
36024
  import { statSync as statSync17 } from "fs";
35698
36025
  import { basename as basename10, extname as extname3, resolve as resolve21 } from "path";
35699
- import { McpServer as McpServer8 } from "@modelcontextprotocol/sdk/server/mcp.js";
36026
+ import { McpServer as McpServer9 } from "@modelcontextprotocol/sdk/server/mcp.js";
35700
36027
  import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
35701
- import { z as z13 } from "zod";
36028
+ import { z as z14 } from "zod";
35702
36029
  function requireTopicAccess(ctx) {
35703
36030
  const topic = getTopic(ctx.topicId);
35704
36031
  if (!topic)
@@ -35806,7 +36133,7 @@ function appendAutoContinue(ctx, field) {
35806
36133
  });
35807
36134
  }
35808
36135
  function buildNegotiumMcpServer(ctx) {
35809
- const server = new McpServer8({ name: RUNTIME_MCP_KEY, version: "1.0.0" });
36136
+ const server = new McpServer9({ name: RUNTIME_MCP_KEY, version: "1.0.0" });
35810
36137
  if (ctx.visualTools === true) {
35811
36138
  for (const def of [...visualToolDefinitions, showPngTool]) {
35812
36139
  const handler = ctx.peerBridge && (def.name === "show_html" || def.name === "show_mermaid") ? async () => textResult("Visual queued for ordered display on the canonical hub.") : isVisualsShowImageTool(def.name) ? async (input) => {
@@ -35935,8 +36262,8 @@ function buildNegotiumMcpServer(ctx) {
35935
36262
  }
35936
36263
  }
35937
36264
  if (ctx.fileDeliveryTools === true) {
35938
- server.tool("send_file", "Send a local file to the user in the chat. Use this when you want to share a file (image, document, PDF, code, etc.) with the user. The file will appear as a downloadable item in the chat.", { file_path: z13.string().describe("Absolute path to the file to send") }, async ({ file_path }) => deliverFile(ctx, file_path));
35939
- server.tool("send_files", "Send multiple local files to the user in the chat at once.", { file_paths: z13.array(z13.string()).describe("Array of absolute file paths to send") }, async ({ file_paths }) => {
36265
+ server.tool("send_file", "Send a local file to the user in the chat. Use this when you want to share a file (image, document, PDF, code, etc.) with the user. The file will appear as a downloadable item in the chat.", { file_path: z14.string().describe("Absolute path to the file to send") }, async ({ file_path }) => deliverFile(ctx, file_path));
36266
+ server.tool("send_files", "Send multiple local files to the user in the chat at once.", { file_paths: z14.array(z14.string()).describe("Array of absolute file paths to send") }, async ({ file_paths }) => {
35940
36267
  const results = await Promise.all(file_paths.map((filePath) => deliverFile(ctx, filePath)));
35941
36268
  const hasError = results.some((result) => ("isError" in result) && result.isError);
35942
36269
  return {
@@ -35962,8 +36289,8 @@ function registerThreadTools(server, ctx) {
35962
36289
  return;
35963
36290
  const topicId = ctx.topicId;
35964
36291
  server.tool("thread_read", "Read one thread of this room in full, oldest message first. Call it with no arguments to get the thread the current message was sent in \u2014 useful when a message is tagged (in thread #id) but the conversation behind that tag is no longer in your context.", {
35965
- thread_id: z13.string().optional().describe("Thread tag (#a3f1c8) or full root message id. Omit to read the thread this turn is answering in."),
35966
- limit: z13.number().int().optional().describe(`Most recent replies to include (default ${THREAD_READ_DEFAULT_LIMIT}, max ${THREAD_READ_MAX_LIMIT}).`)
36292
+ thread_id: z14.string().optional().describe("Thread tag (#a3f1c8) or full root message id. Omit to read the thread this turn is answering in."),
36293
+ limit: z14.number().int().optional().describe(`Most recent replies to include (default ${THREAD_READ_DEFAULT_LIMIT}, max ${THREAD_READ_MAX_LIMIT}).`)
35967
36294
  }, async ({ thread_id, limit }) => {
35968
36295
  const requested = thread_id?.trim();
35969
36296
  if (!requested && !ctx.threadRootId) {
@@ -35984,7 +36311,7 @@ function registerThreadTools(server, ctx) {
35984
36311
  return textResult(rendered);
35985
36312
  });
35986
36313
  server.tool("thread_list", "List the threads in this room with their tag, reply count and root message, most recently active first. Use it to find a thread the user refers to by subject rather than by tag.", {
35987
- limit: z13.number().int().optional().describe("Threads to list (default 20).")
36314
+ limit: z14.number().int().optional().describe("Threads to list (default 20).")
35988
36315
  }, async ({ limit }) => textResult(renderTopicThreadList(topicId, limit ?? 20)));
35989
36316
  }
35990
36317
  function resolveThreadRootId(topicId, requested) {
@@ -36279,23 +36606,23 @@ function defaultManifestFile() {
36279
36606
  var init_paths2 = () => {};
36280
36607
 
36281
36608
  // ../../packages/mcp-host/src/spec.ts
36282
- import { z as z14 } from "zod";
36609
+ import { z as z15 } from "zod";
36283
36610
  var KEY_PATTERN, portSchema, mcpServerSpecSchema;
36284
36611
  var init_spec = __esm(() => {
36285
36612
  KEY_PATTERN = /^[a-zA-Z0-9._-]+$/;
36286
- portSchema = z14.number().int().min(1).max(65535);
36287
- mcpServerSpecSchema = z14.object({
36288
- key: z14.string().min(1).regex(KEY_PATTERN, "key may only contain [a-zA-Z0-9._-]").refine((k) => k !== "." && k !== "..", "key may not be a dot path"),
36289
- transport: z14.enum(["stdio", "http"]),
36290
- command: z14.string().min(1),
36291
- args: z14.array(z14.string()).optional(),
36292
- env: z14.record(z14.string(), z14.string()).optional(),
36293
- cwd: z14.string().optional(),
36294
- portRange: z14.object({ base: portSchema, max: portSchema }).optional(),
36295
- scope: z14.enum(["node", "instance"]),
36296
- readyTimeoutMs: z14.number().int().positive().optional(),
36297
- idleEvictMs: z14.number().int().positive().optional(),
36298
- healthIntervalMs: z14.number().int().positive().optional()
36613
+ portSchema = z15.number().int().min(1).max(65535);
36614
+ mcpServerSpecSchema = z15.object({
36615
+ key: z15.string().min(1).regex(KEY_PATTERN, "key may only contain [a-zA-Z0-9._-]").refine((k) => k !== "." && k !== "..", "key may not be a dot path"),
36616
+ transport: z15.enum(["stdio", "http"]),
36617
+ command: z15.string().min(1),
36618
+ args: z15.array(z15.string()).optional(),
36619
+ env: z15.record(z15.string(), z15.string()).optional(),
36620
+ cwd: z15.string().optional(),
36621
+ portRange: z15.object({ base: portSchema, max: portSchema }).optional(),
36622
+ scope: z15.enum(["node", "instance"]),
36623
+ readyTimeoutMs: z15.number().int().positive().optional(),
36624
+ idleEvictMs: z15.number().int().positive().optional(),
36625
+ healthIntervalMs: z15.number().int().positive().optional()
36299
36626
  }).superRefine((spec, ctx) => {
36300
36627
  if (spec.transport === "http") {
36301
36628
  if (!spec.portRange) {
@@ -36318,7 +36645,7 @@ var init_spec = __esm(() => {
36318
36645
  // ../../packages/mcp-host/src/manifest.ts
36319
36646
  import { existsSync as existsSync34, mkdirSync as mkdirSync28, readFileSync as readFileSync25, renameSync as renameSync14, writeFileSync as writeFileSync22 } from "fs";
36320
36647
  import { dirname as dirname20 } from "path";
36321
- import { z as z15 } from "zod";
36648
+ import { z as z16 } from "zod";
36322
36649
 
36323
36650
  class McpManifest {
36324
36651
  file;
@@ -36400,13 +36727,13 @@ var manifestEntrySchema, manifestFileSchema;
36400
36727
  var init_manifest = __esm(() => {
36401
36728
  init_paths2();
36402
36729
  init_spec();
36403
- manifestEntrySchema = z15.object({
36730
+ manifestEntrySchema = z16.object({
36404
36731
  spec: mcpServerSpecSchema,
36405
- enabled: z15.boolean()
36732
+ enabled: z16.boolean()
36406
36733
  });
36407
- manifestFileSchema = z15.object({
36408
- version: z15.literal(1),
36409
- servers: z15.array(manifestEntrySchema)
36734
+ manifestFileSchema = z16.object({
36735
+ version: z16.literal(1),
36736
+ servers: z16.array(manifestEntrySchema)
36410
36737
  });
36411
36738
  });
36412
36739
 
@@ -53909,6 +54236,11 @@ var init_canonical_mcp_bridge = __esm(async () => {
53909
54236
  "wiki_last_conversation",
53910
54237
  "wiki_write",
53911
54238
  "index_upsert"
54239
+ ]),
54240
+ "session-history": new Set([
54241
+ "list_session_boundaries",
54242
+ "read_session_history",
54243
+ "search_session_history"
53912
54244
  ])
53913
54245
  };
53914
54246
  });
@@ -60574,4 +60906,4 @@ switch (command) {
60574
60906
  }
60575
60907
  }
60576
60908
 
60577
- //# debugId=7009B5CBB966BCAA64756E2164756E21
60909
+ //# debugId=5BD76CD7A4E266D164756E2164756E21