negotium 0.23.8 → 0.23.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.
Files changed (30) hide show
  1. package/dist/agent-helpers.js +4 -3
  2. package/dist/agent-helpers.js.map +4 -4
  3. package/dist/{chunk-g5etvfj3.js → chunk-jsv1te9a.js} +2 -2
  4. package/dist/{chunk-g5etvfj3.js.map → chunk-jsv1te9a.js.map} +2 -2
  5. package/dist/hosted-agent.js +2 -2
  6. package/dist/hosted-agent.js.map +2 -2
  7. package/dist/main.js +477 -338
  8. package/dist/main.js.map +12 -8
  9. package/dist/mcp-factories.js +310 -255
  10. package/dist/mcp-factories.js.map +10 -7
  11. package/dist/prompts.js +3 -2
  12. package/dist/prompts.js.map +3 -3
  13. package/dist/registry.js +1 -1
  14. package/dist/runtime/src/mcp/factories/session-comm.ts +16 -2
  15. package/dist/runtime/src/mcp/factories/session-history.ts +21 -306
  16. package/dist/runtime/src/mcp/session-comm/default-host.ts +14 -0
  17. package/dist/runtime/src/mcp/session-comm/history-target.ts +89 -0
  18. package/dist/runtime/src/mcp/session-comm/history-tools.ts +113 -0
  19. package/dist/runtime/src/mcp/session-comm/server.ts +16 -2
  20. package/dist/runtime/src/mcp/session-history-limits.ts +36 -0
  21. package/dist/runtime/src/mcp/session-history-reader.ts +359 -0
  22. package/dist/runtime/src/mcp/session-history-server.ts +2 -10
  23. package/dist/runtime/src/prompts/builders.ts +2 -1
  24. package/dist/runtime/src/version.ts +1 -1
  25. package/dist/types/packages/core/src/mcp/factories/session-comm.d.ts +6 -0
  26. package/dist/types/packages/core/src/mcp/session-comm/history-tools.d.ts +31 -0
  27. package/dist/types/packages/core/src/mcp/session-history-limits.d.ts +20 -0
  28. package/dist/types/packages/core/src/mcp/session-history-reader.d.ts +35 -0
  29. package/dist/types/packages/core/src/version.d.ts +1 -1
  30. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -6636,7 +6636,7 @@ var exports_version = {};
6636
6636
  __export(exports_version, {
6637
6637
  NEGOTIUM_VERSION: () => NEGOTIUM_VERSION
6638
6638
  });
6639
- var NEGOTIUM_VERSION = "0.23.8";
6639
+ var NEGOTIUM_VERSION = "0.23.9";
6640
6640
 
6641
6641
  // ../../packages/core/src/agents/codex-native-multi-agent.ts
6642
6642
  import { spawn as spawn2 } from "child_process";
@@ -15173,8 +15173,9 @@ function buildRuntimeToolSection(opts, extensions) {
15173
15173
  "The session-comm MCP server is the only cross-topic messaging surface. Its canonical tools are `list_sessions`, `peek_session`, `tell_session`, `ask_session`, and `abort_session`.",
15174
15174
  "`list_sessions` inspects topics; `ask_session` is for read-only questions whose answer must return here; `tell_session` is one-way delegation/handoff with no reply back. Do not call `tell_session` bidirectional, and do not claim `ask_session` is unavailable without first checking the session-comm tools."
15175
15175
  ],
15176
+ "To hand over context, point instead of pasting: in `tell_session`/`ask_session`, state the instruction and cite the relevant part of your own history (an entry range from `list_session_boundaries`, or a `sessionId`) rather than copying long transcripts. A session that receives such a message (`[from <topic>]`) reads the sender's history with `read_session_history_of`/`search_session_history_of` (`to` = the sender as `list_sessions` shows it). Only sessions listed by `list_sessions` are readable; if the sender is not listed, ask for the details instead.",
15176
15177
  ...agentKind === "maestro" ? [
15177
- subagentParentTitle ? "Session-comm schemas may initially be deferred. Activate `mcp__session-comm__list_sessions` and `mcp__session-comm__tell_session` with ToolSearch before use." : 'Session-comm schemas may initially be deferred. Before using or judging availability, call ToolSearch("select:mcp__session-comm__list_sessions,mcp__session-comm__peek_session,mcp__session-comm__tell_session,mcp__session-comm__ask_session,mcp__session-comm__abort_session") to activate the exact tools. Never substitute a similarly described runtime tool.'
15178
+ subagentParentTitle ? "Session-comm schemas may initially be deferred. Activate `mcp__session-comm__list_sessions` and `mcp__session-comm__tell_session` with ToolSearch before use." : 'Session-comm schemas may initially be deferred. Before using or judging availability, call ToolSearch("select:mcp__session-comm__list_sessions,mcp__session-comm__peek_session,mcp__session-comm__tell_session,mcp__session-comm__ask_session,mcp__session-comm__abort_session,mcp__session-comm__read_session_history_of,mcp__session-comm__search_session_history_of") to activate the exact tools. Never substitute a similarly described runtime tool.'
15178
15179
  ] : [],
15179
15180
  "Do not use session communication to make another topic perform destructive changes without the user's clear intent.",
15180
15181
  ...spawnSubagentSection,
@@ -32038,6 +32039,69 @@ var init_agent_health = __esm(async () => {
32038
32039
  activeCheckAllUsers = new Set;
32039
32040
  });
32040
32041
 
32042
+ // ../../packages/core/src/mcp/session-history-limits.ts
32043
+ function sessionHistoryBudgetFromEnv(env = process.env) {
32044
+ const positive = (name) => {
32045
+ const raw = env[name];
32046
+ if (!raw)
32047
+ return;
32048
+ const value = Number.parseInt(raw, 10);
32049
+ return Number.isInteger(value) && value > 0 ? value : undefined;
32050
+ };
32051
+ return {
32052
+ maxCalls: positive("NEGOTIUM_SESSION_HISTORY_MAX_CALLS"),
32053
+ maxTotalBytes: positive("NEGOTIUM_SESSION_HISTORY_MAX_TOTAL_BYTES"),
32054
+ maxChunkBytes: positive("NEGOTIUM_SESSION_HISTORY_MAX_CHUNK_BYTES")
32055
+ };
32056
+ }
32057
+ var SESSION_HISTORY_DEFAULT_MAX_CALLS = 20, SESSION_HISTORY_DEFAULT_MAX_TOTAL_BYTES, SESSION_HISTORY_DEFAULT_MAX_CHUNK_BYTES, SESSION_HISTORY_DEFAULT_LINE_LIMIT = 300, SESSION_HISTORY_MAX_LINE_LIMIT = 500, SESSION_HISTORY_DEFAULT_SEARCH_LIMIT = 20, SESSION_HISTORY_MAX_SEARCH_LIMIT = 50;
32058
+ var init_session_history_limits = __esm(() => {
32059
+ SESSION_HISTORY_DEFAULT_MAX_TOTAL_BYTES = 768 * 1024;
32060
+ SESSION_HISTORY_DEFAULT_MAX_CHUNK_BYTES = 64 * 1024;
32061
+ });
32062
+
32063
+ // ../../packages/core/src/mcp/session-comm/history-tools.ts
32064
+ import { z as z12 } from "zod";
32065
+ function registerSessionHistoryOfTools(server, reader) {
32066
+ server.tool("list_session_boundaries_of", [
32067
+ "Like list_session_boundaries, but for ANOTHER local session you can see in list_sessions:",
32068
+ "lists that topic's provider sessions (compactions, agent switches) with their 1-based",
32069
+ "entry ranges from its append-only raw conversation manifest. Call this before",
32070
+ "read_session_history_of / search_session_history_of to target a range. Read-only: the",
32071
+ "other session is not notified and nothing is injected into it. Use your own",
32072
+ "list_session_boundaries for the current topic."
32073
+ ].join(" "), { to }, async (args) => reader.listBoundaries(args.to));
32074
+ server.tool("read_session_history_of", [
32075
+ "Read ANOTHER local session's full-fidelity raw conversation manifest in bounded chunks",
32076
+ "(messages, tool calls, reasoning \u2014 including what its /compact summarized away). Use it",
32077
+ "when a tell_session/ask_session message points you at the sender's history (an entry",
32078
+ "range or sessionId) instead of pasting it, or when you need another topic's exact prior",
32079
+ "context. Only sessions listed by list_sessions are readable. Shares this turn's read",
32080
+ "budget with the other *_of tools."
32081
+ ].join(" "), {
32082
+ to,
32083
+ offset: z12.number().optional().describe("One-based entry number. Defaults to 1."),
32084
+ limit: z12.number().optional().describe(`Number of entries. Defaults to ${SESSION_HISTORY_DEFAULT_LINE_LIMIT}, max ${SESSION_HISTORY_MAX_LINE_LIMIT}.`),
32085
+ sessionId: z12.string().optional().describe("Restrict to one session's entry range (see list_session_boundaries_of).")
32086
+ }, async ({ to: target, ...args }) => reader.read(target, args));
32087
+ server.tool("search_session_history_of", [
32088
+ "Keyword-search ANOTHER local session's full raw conversation manifest (case-insensitive",
32089
+ "substring). Returns matching entry numbers with snippets \u2014 pass one to",
32090
+ "read_session_history_of for full context. Only sessions listed by list_sessions are",
32091
+ "searchable."
32092
+ ].join(" "), {
32093
+ to,
32094
+ query: z12.string().min(1).describe("Case-insensitive substring to search for."),
32095
+ sessionId: z12.string().optional().describe("Restrict the scan to one session's range."),
32096
+ limit: z12.number().optional().describe(`Max matches to return. Defaults to ${SESSION_HISTORY_DEFAULT_SEARCH_LIMIT}, max ${SESSION_HISTORY_MAX_SEARCH_LIMIT}.`)
32097
+ }, async ({ to: target, ...args }) => reader.search(target, args));
32098
+ }
32099
+ var to;
32100
+ var init_history_tools = __esm(() => {
32101
+ init_session_history_limits();
32102
+ to = z12.string().describe("Target session/topic name, exactly as list_sessions shows it (local sessions only).");
32103
+ });
32104
+
32041
32105
  // ../../packages/core/src/mcp/session-comm/tell-permissions.ts
32042
32106
  function resolveSubagentTellIdentity(currentTopicId, assertedParentTopicId) {
32043
32107
  const record2 = currentTopicId ? getTopic(currentTopicId) : undefined;
@@ -32077,7 +32141,7 @@ __export(exports_session_comm, {
32077
32141
  createSessionCommMcpServer: () => createSessionCommMcpServer
32078
32142
  });
32079
32143
  import { McpServer as McpServer6 } from "@modelcontextprotocol/sdk/server/mcp.js";
32080
- import { z as z12 } from "zod";
32144
+ import { z as z13 } from "zod";
32081
32145
  function createSessionCommMcpServer(context, host2, options = {}) {
32082
32146
  const server = new McpServer6({ name: "session-comm", version: "2.0.0" });
32083
32147
  const required = options.requiredMcpServers?.join(", ") || "none";
@@ -32085,29 +32149,32 @@ function createSessionCommMcpServer(context, host2, options = {}) {
32085
32149
  const subagentIdentity = resolveSubagentTellIdentity(context.currentTopicId, context.subagentParentTopicId);
32086
32150
  server.tool("list_sessions", "List available sessions and remote peer sessions for inter-session communication.", {}, async () => host2.listSessions(context));
32087
32151
  server.tool("configure_mcp", `Configure optional MCP servers for the current topic. Required: ${required}. Optional: ${optional}.`, {
32088
- enabled: z12.array(z12.string()).nullable().optional()
32152
+ enabled: z13.array(z13.string()).nullable().optional()
32089
32153
  }, async ({ enabled }) => host2.configureMcp(context, enabled));
32090
32154
  server.tool("get_mcp_config", "Get the current topic MCP configuration.", {}, async () => host2.getMcpConfig(context));
32091
32155
  if (host2.getBrowserProfile) {
32092
32156
  server.tool("get_browser_profile", "Get this topic's browser profile and the profiles owned by the same user.", {}, async () => host2.getBrowserProfile(context));
32093
32157
  }
32094
32158
  if (host2.setBrowserProfile) {
32095
- server.tool("set_browser_profile", "Assign this topic to a named shared browser profile. Takes effect next turn.", { profile: z12.string() }, async ({ profile }) => host2.setBrowserProfile(context, profile));
32159
+ server.tool("set_browser_profile", "Assign this topic to a named shared browser profile. Takes effect next turn.", { profile: z13.string() }, async ({ profile }) => host2.setBrowserProfile(context, profile));
32096
32160
  }
32097
32161
  if (host2.deleteBrowserProfile) {
32098
- server.tool("delete_browser_profile", "Delete an unused named browser profile and its on-disk data. The default or an assigned profile cannot be deleted.", { profile: z12.string() }, async ({ profile }) => host2.deleteBrowserProfile(context, profile));
32162
+ server.tool("delete_browser_profile", "Delete an unused named browser profile and its on-disk data. The default or an assigned profile cannot be deleted.", { profile: z13.string() }, async ({ profile }) => host2.deleteBrowserProfile(context, profile));
32099
32163
  }
32100
32164
  server.tool("peek_session", "Inspect running and idle sessions, including pending ask_session calls.", {}, async () => host2.peekSession(context));
32101
- server.tool("set_description", "Set the current session description used as a routing hint.", { description: z12.string() }, async ({ description }) => host2.setDescription(context, description));
32165
+ server.tool("set_description", "Set the current session description used as a routing hint.", { description: z13.string() }, async ({ description }) => host2.setDescription(context, description));
32166
+ if (host2.sessionHistoryOf) {
32167
+ registerSessionHistoryOfTools(server, host2.sessionHistoryOf(context));
32168
+ }
32102
32169
  if (!context.replyOnly) {
32103
32170
  if (!subagentIdentity.restricted) {
32104
- server.tool("ask_session", "Ask another local or remote session a question and wait for its answer.", { to: z12.string(), message: z12.string() }, async (input) => host2.askSession(context, input));
32105
- server.tool("ask_cron", "Ask this topic's shared Cron session a question. The answer is injected asynchronously into the current conversation.", { message: z12.string() }, async ({ message: message2 }) => host2.askCron(context, message2));
32171
+ server.tool("ask_session", "Ask another local or remote session a question and wait for its answer. To hand over long context, cite an entry range or sessionId of your own history (list_session_boundaries) instead of pasting it \u2014 the target can read it with read_session_history_of.", { to: z13.string(), message: z13.string() }, async (input) => host2.askSession(context, input));
32172
+ server.tool("ask_cron", "Ask this topic's shared Cron session a question. The answer is injected asynchronously into the current conversation.", { message: z13.string() }, async ({ message: message2 }) => host2.askCron(context, message2));
32106
32173
  }
32107
32174
  if (!subagentIdentity.restricted) {
32108
- server.tool("abort_session", "Abort the active query in another session.", { to: z12.string() }, async ({ to }) => host2.abortSession(context, to));
32175
+ server.tool("abort_session", "Abort the active query in another session.", { to: z13.string() }, async ({ to: to2 }) => host2.abortSession(context, to2));
32109
32176
  }
32110
- server.tool("tell_session", "Send a one-way message to another local or remote session.", { to: z12.string(), message: z12.string() }, async (input) => {
32177
+ server.tool("tell_session", "Send a one-way message to another local or remote session. To hand over long context, cite an entry range or sessionId of your own history (list_session_boundaries) instead of pasting it \u2014 the target can read it with read_session_history_of.", { to: z13.string(), message: z13.string() }, async (input) => {
32111
32178
  if (subagentIdentity.restricted && !canSubagentTellTargetByName(subagentIdentity, input.to)) {
32112
32179
  return {
32113
32180
  content: [
@@ -32125,9 +32192,300 @@ function createSessionCommMcpServer(context, host2, options = {}) {
32125
32192
  return server;
32126
32193
  }
32127
32194
  var init_session_comm = __esm(async () => {
32195
+ init_history_tools();
32128
32196
  await init_tell_permissions();
32129
32197
  });
32130
32198
 
32199
+ // ../../packages/core/src/mcp/session-history-reader.ts
32200
+ function positiveInt(value, fallback) {
32201
+ return Number.isFinite(value) && value && value > 0 ? Math.floor(value) : fallback;
32202
+ }
32203
+ function fitUtf8(text3, maxBytes) {
32204
+ if (Buffer.byteLength(text3, "utf8") <= maxBytes)
32205
+ return text3;
32206
+ const marker = `
32207
+ [... oversized entry clipped ...]
32208
+ `;
32209
+ const markerBytes = Buffer.byteLength(marker, "utf8");
32210
+ const bytes = Buffer.from(text3, "utf8");
32211
+ if (maxBytes <= markerBytes) {
32212
+ return bytes.subarray(0, maxBytes).toString("utf8").replace(/\uFFFD+$/u, "");
32213
+ }
32214
+ const available = Math.max(0, maxBytes - markerBytes);
32215
+ const headBudget = Math.ceil(available * 0.6);
32216
+ const tailBudget = available - headBudget;
32217
+ const head = bytes.subarray(0, headBudget).toString("utf8").replace(/\uFFFD+$/u, "");
32218
+ const tail = bytes.subarray(Math.max(0, bytes.length - tailBudget)).toString("utf8").replace(/^\uFFFD+/u, "");
32219
+ return `${head}${marker}${tail}`;
32220
+ }
32221
+ function escapeRegExp4(value) {
32222
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
32223
+ }
32224
+ function renderEntry(entry, index) {
32225
+ const speaker = eventSpeaker(entry.event, entry.agent);
32226
+ const text3 = eventText(entry.event);
32227
+ return `[${index}] ${entry.ts} ${speaker}: ${text3}`;
32228
+ }
32229
+ function deriveBoundaries(entries) {
32230
+ const boundaries = [];
32231
+ entries.forEach((entry, i) => {
32232
+ if (entry.event.type !== "session")
32233
+ return;
32234
+ const index = i + 1;
32235
+ const previous = boundaries.at(-1);
32236
+ if (previous && previous.sessionId === entry.event.sessionId)
32237
+ return;
32238
+ if (previous) {
32239
+ previous.endedAt = entry.ts;
32240
+ previous.endedBy = previous.agent === entry.agent ? "compacted" : "agent-switch";
32241
+ }
32242
+ boundaries.push({
32243
+ entryIndex: index,
32244
+ sessionId: entry.event.sessionId,
32245
+ agent: entry.agent,
32246
+ startedAt: entry.ts,
32247
+ endedBy: "active"
32248
+ });
32249
+ });
32250
+ if (boundaries.length === 0 && entries.length > 0) {
32251
+ boundaries.push({
32252
+ entryIndex: 1,
32253
+ sessionId: "(unknown \u2014 no session event found)",
32254
+ agent: entries[0]?.agent ?? "unknown",
32255
+ startedAt: entries[0]?.ts ?? "",
32256
+ endedBy: "active"
32257
+ });
32258
+ }
32259
+ return boundaries;
32260
+ }
32261
+ function sessionRange(entries, sessionId) {
32262
+ if (!sessionId)
32263
+ return { lower: 0, upper: entries.length };
32264
+ const boundaries = deriveBoundaries(entries);
32265
+ const match = boundaries.find((b) => b.sessionId === sessionId);
32266
+ if (!match)
32267
+ return null;
32268
+ const next = boundaries.find((b) => b.entryIndex > match.entryIndex);
32269
+ return { lower: match.entryIndex - 1, upper: next ? next.entryIndex - 1 : entries.length };
32270
+ }
32271
+ function topicField(target) {
32272
+ return target.label ? { topic: target.label } : {};
32273
+ }
32274
+ function createSessionHistoryReader(budget = {}) {
32275
+ const maxCalls = positiveInt(budget.maxCalls, SESSION_HISTORY_DEFAULT_MAX_CALLS);
32276
+ const maxTotalBytes = positiveInt(budget.maxTotalBytes, SESSION_HISTORY_DEFAULT_MAX_TOTAL_BYTES);
32277
+ const maxChunkBytes = positiveInt(budget.maxChunkBytes, SESSION_HISTORY_DEFAULT_MAX_CHUNK_BYTES);
32278
+ let calls = 0;
32279
+ let totalBytes = 0;
32280
+ const spendCall = () => {
32281
+ calls += 1;
32282
+ if (calls > maxCalls || totalBytes >= maxTotalBytes) {
32283
+ return mcpError(JSON.stringify({
32284
+ error: "session-history read budget exhausted for this turn; answer with what you already read",
32285
+ calls,
32286
+ max_calls: maxCalls,
32287
+ total_read_bytes: totalBytes,
32288
+ max_total_bytes: maxTotalBytes
32289
+ }));
32290
+ }
32291
+ return null;
32292
+ };
32293
+ return {
32294
+ listBoundaries(target) {
32295
+ const budgetError = spendCall();
32296
+ if (budgetError)
32297
+ return budgetError;
32298
+ try {
32299
+ const entries = readRawConversation(target.userId, target.topic);
32300
+ const boundaries = deriveBoundaries(entries);
32301
+ const payload = JSON.stringify({ ...topicField(target), total_entries: entries.length, sessions: boundaries }, null, 2);
32302
+ totalBytes += Buffer.byteLength(payload, "utf8");
32303
+ return mcpOk(payload);
32304
+ } catch (error) {
32305
+ return mcpError(`list_session_boundaries failed: ${errMsg(error)}`);
32306
+ }
32307
+ },
32308
+ read(target, { offset: rawOffset, limit: rawLimit, sessionId }) {
32309
+ const budgetError = spendCall();
32310
+ if (budgetError)
32311
+ return budgetError;
32312
+ try {
32313
+ const entries = readRawConversation(target.userId, target.topic);
32314
+ const range = sessionRange(entries, sessionId);
32315
+ if (!range)
32316
+ return mcpError(`Unknown sessionId: ${sessionId}`);
32317
+ const { lower, upper } = range;
32318
+ const offset = positiveInt(rawOffset, 1);
32319
+ const limit = Math.min(positiveInt(rawLimit, SESSION_HISTORY_DEFAULT_LINE_LIMIT), SESSION_HISTORY_MAX_LINE_LIMIT);
32320
+ const start = Math.max(lower, offset - 1);
32321
+ if (start >= upper) {
32322
+ return mcpOk(JSON.stringify({
32323
+ ...topicField(target),
32324
+ content: "(end of range)",
32325
+ offset,
32326
+ returned_entries: 0,
32327
+ total_entries: entries.length,
32328
+ calls
32329
+ }));
32330
+ }
32331
+ const rendered = [];
32332
+ let returnedBytes = 0;
32333
+ let index = start;
32334
+ const callBudget = Math.min(maxChunkBytes, Math.max(1, maxTotalBytes - totalBytes));
32335
+ while (index < upper && rendered.length < limit) {
32336
+ const line = fitUtf8(renderEntry(entries[index], index + 1), Math.max(1, callBudget));
32337
+ const separatorBytes = rendered.length > 0 ? 1 : 0;
32338
+ const lineBytes = Buffer.byteLength(line, "utf8");
32339
+ if (rendered.length > 0 && returnedBytes + separatorBytes + lineBytes > callBudget)
32340
+ break;
32341
+ rendered.push(line);
32342
+ returnedBytes += separatorBytes + lineBytes;
32343
+ index += 1;
32344
+ if (returnedBytes >= callBudget)
32345
+ break;
32346
+ }
32347
+ totalBytes += returnedBytes;
32348
+ return mcpOk(JSON.stringify({
32349
+ ...topicField(target),
32350
+ content: rendered.join(`
32351
+ `),
32352
+ offset,
32353
+ returned_entries: rendered.length,
32354
+ returned_bytes: returnedBytes,
32355
+ total_entries: entries.length,
32356
+ total_read_bytes: totalBytes,
32357
+ calls,
32358
+ ...index < upper ? { next_offset: index + 1 } : {},
32359
+ ...calls >= maxCalls || totalBytes >= maxTotalBytes ? { note: "Read budget nearly exhausted; wrap up with what you have." } : {}
32360
+ }));
32361
+ } catch (error) {
32362
+ return mcpError(`read_session_history failed: ${errMsg(error)}`);
32363
+ }
32364
+ },
32365
+ search(target, { query: query2, sessionId, limit: rawLimit }) {
32366
+ const budgetError = spendCall();
32367
+ if (budgetError)
32368
+ return budgetError;
32369
+ try {
32370
+ const entries = readRawConversation(target.userId, target.topic);
32371
+ const range = sessionRange(entries, sessionId);
32372
+ if (!range)
32373
+ return mcpError(`Unknown sessionId: ${sessionId}`);
32374
+ const { lower, upper } = range;
32375
+ const limit = Math.min(positiveInt(rawLimit, SESSION_HISTORY_DEFAULT_SEARCH_LIMIT), SESSION_HISTORY_MAX_SEARCH_LIMIT);
32376
+ const needleRegex = new RegExp(escapeRegExp4(query2), "i");
32377
+ const matches = [];
32378
+ const boundaries = sessionId ? undefined : deriveBoundaries(entries);
32379
+ let returnedBytes = 0;
32380
+ let budgetStopped = false;
32381
+ const callBudget = Math.min(maxChunkBytes, Math.max(1, maxTotalBytes - totalBytes));
32382
+ for (let i = lower;i < upper && matches.length < limit; i++) {
32383
+ const entry = entries[i];
32384
+ const text3 = eventText(entry.event);
32385
+ const found = needleRegex.exec(text3);
32386
+ if (!found)
32387
+ continue;
32388
+ const at = found.index;
32389
+ const start = Math.max(0, at - SEARCH_SNIPPET_RADIUS);
32390
+ const end = Math.min(text3.length, at + found[0].length + SEARCH_SNIPPET_RADIUS);
32391
+ const snippet = `${start > 0 ? "\u2026" : ""}${text3.slice(start, end)}${end < text3.length ? "\u2026" : ""}`;
32392
+ const matchedSessionId = sessionId ?? boundaries?.findLast((b) => b.entryIndex <= i + 1)?.sessionId;
32393
+ const candidate = {
32394
+ entry: i + 1,
32395
+ sessionId: matchedSessionId,
32396
+ agent: entry.agent,
32397
+ ts: entry.ts,
32398
+ snippet
32399
+ };
32400
+ const lineBytes = Buffer.byteLength(JSON.stringify(candidate), "utf8");
32401
+ if (returnedBytes + lineBytes > callBudget) {
32402
+ budgetStopped = true;
32403
+ break;
32404
+ }
32405
+ returnedBytes += lineBytes;
32406
+ matches.push(candidate);
32407
+ }
32408
+ totalBytes += returnedBytes;
32409
+ return mcpOk(JSON.stringify({
32410
+ ...topicField(target),
32411
+ query: query2,
32412
+ matches,
32413
+ match_count: matches.length,
32414
+ total_entries: entries.length,
32415
+ calls,
32416
+ ...matches.length >= limit ? { note: "Hit the match limit; narrow the query or pass sessionId for more." } : budgetStopped ? {
32417
+ note: "Read budget ran out before the scan finished; this result is incomplete, not necessarily 'no matches'."
32418
+ } : {}
32419
+ }));
32420
+ } catch (error) {
32421
+ return mcpError(`search_session_history failed: ${errMsg(error)}`);
32422
+ }
32423
+ }
32424
+ };
32425
+ }
32426
+ var SEARCH_SNIPPET_RADIUS = 160;
32427
+ var init_session_history_reader = __esm(async () => {
32428
+ init_mcp_helpers();
32429
+ init_session_history_limits();
32430
+ await __promiseAll([
32431
+ init_conversations(),
32432
+ init_topic_archive()
32433
+ ]);
32434
+ });
32435
+
32436
+ // ../../packages/core/src/mcp/session-comm/history-target.ts
32437
+ function resolveSessionHistoryTarget(input, to2) {
32438
+ const validation = input.validateTarget(to2);
32439
+ if (!validation.ok)
32440
+ return { ok: false, error: validation.error };
32441
+ const topicId = validation.target.topicId;
32442
+ if (!topicId)
32443
+ return { ok: false, error: mcpError(`Error: "${to2}" has no topic id.`) };
32444
+ if (!canSubagentTellTarget(input.subagentIdentity, topicId)) {
32445
+ return {
32446
+ ok: false,
32447
+ error: mcpError("Error: subagents can read session history only of topics they may tell_session (direct parents, direct children, or topics explicitly granted by an ancestor).")
32448
+ };
32449
+ }
32450
+ const topic = getTopic(topicId);
32451
+ const principal = roomStatusPrincipal({
32452
+ callerUserId: input.callerUserId,
32453
+ targetParticipants: topic?.participants
32454
+ }) ?? input.callerUserId;
32455
+ return {
32456
+ ok: true,
32457
+ target: { userId: principal, topic: topic?.title ?? validation.target.name, label: to2 }
32458
+ };
32459
+ }
32460
+ function createSessionHistoryOfReader(input) {
32461
+ const reader = createSessionHistoryReader(input.budget ?? sessionHistoryBudgetFromEnv());
32462
+ const resolve19 = (to2) => resolveSessionHistoryTarget(input, to2);
32463
+ return {
32464
+ listBoundaries(to2) {
32465
+ const resolved = resolve19(to2);
32466
+ return resolved.ok ? reader.listBoundaries(resolved.target) : resolved.error;
32467
+ },
32468
+ read(to2, args) {
32469
+ const resolved = resolve19(to2);
32470
+ return resolved.ok ? reader.read(resolved.target, args) : resolved.error;
32471
+ },
32472
+ search(to2, args) {
32473
+ const resolved = resolve19(to2);
32474
+ return resolved.ok ? reader.search(resolved.target, args) : resolved.error;
32475
+ }
32476
+ };
32477
+ }
32478
+ var init_history_target = __esm(async () => {
32479
+ init_mcp_helpers();
32480
+ init_session_history_limits();
32481
+ await __promiseAll([
32482
+ init_session_history_reader(),
32483
+ init_api_topics(),
32484
+ init_actor_policy(),
32485
+ init_tell_permissions()
32486
+ ]);
32487
+ });
32488
+
32131
32489
  // ../../packages/core/src/mcp/session-comm/topic-catalog.ts
32132
32490
  function createSessionTargetCatalog(host2) {
32133
32491
  const { currentTopicId, currentTopicName, isAgent, listRows } = host2;
@@ -32182,9 +32540,9 @@ function createSessionTargetCatalog(host2) {
32182
32540
  }
32183
32541
  return result;
32184
32542
  }
32185
- function validateTarget(to) {
32543
+ function validateTarget(to2) {
32186
32544
  const topics = getTopics2();
32187
- const target = topics[to];
32545
+ const target = topics[to2];
32188
32546
  if (target)
32189
32547
  return { ok: true, target };
32190
32548
  const available = listTargets().filter(({ topic }) => Boolean(topic.agent)).map(({ key }) => key);
@@ -32194,7 +32552,7 @@ function createSessionTargetCatalog(host2) {
32194
32552
  content: [
32195
32553
  {
32196
32554
  type: "text",
32197
- text: `Error: Session "${to}" not found.
32555
+ text: `Error: Session "${to2}" not found.
32198
32556
  Available: ${available.join(", ") || "none"}`
32199
32557
  }
32200
32558
  ],
@@ -32284,13 +32642,13 @@ function currentRef(context) {
32284
32642
  const topic = currentTopic(context);
32285
32643
  return topic ? { key: `${topic.kind}:${topic.title}`, title: topic.title, topicId: topic.id } : { key: context.currentTopic, title: context.currentTopic, topicId: context.currentTopicId };
32286
32644
  }
32287
- function remoteTarget(context, to) {
32288
- if (targetCatalog(context).getTopics()[to]?.topicId)
32645
+ function remoteTarget(context, to2) {
32646
+ if (targetCatalog(context).getTopics()[to2]?.topicId)
32289
32647
  return null;
32290
- const slash = to.indexOf("/");
32291
- if (slash <= 0 || slash === to.length - 1)
32648
+ const slash = to2.indexOf("/");
32649
+ if (slash <= 0 || slash === to2.length - 1)
32292
32650
  return null;
32293
- return { node: to.slice(0, slash), topic: to.slice(slash + 1) };
32651
+ return { node: to2.slice(0, slash), topic: to2.slice(slash + 1) };
32294
32652
  }
32295
32653
  function deliveryPrincipal(context, targetTopicId) {
32296
32654
  return localDeliveryPrincipal({
@@ -32494,16 +32852,16 @@ ${entries.join(`
32494
32852
  upsertTopic({ ...topic, description });
32495
32853
  return ok2(`Description set for "${topic.title}".`);
32496
32854
  },
32497
- async askSession(context, { to, message: message2 }) {
32855
+ async askSession(context, { to: to2, message: message2 }) {
32498
32856
  if (message2.length > MAX_MESSAGE_LENGTH)
32499
32857
  return error("Error: message too long.");
32500
32858
  const from2 = currentRef(context);
32501
- const remote = remoteTarget(context, to);
32859
+ const remote = remoteTarget(context, to2);
32502
32860
  const requestId = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
32503
- const createAsk = () => createPendingAsk({ userId: context.userId, from: from2.key, to, requestId });
32504
- const alreadyPending = () => error(`Error: an ask_session request to "${to}" is already pending.`);
32505
- const clearAsk = () => clearPendingAsk({ userId: context.userId, from: from2.key, to, requestId });
32506
- const releaseAsk = () => releasePendingAsk({ userId: context.userId, from: from2.key, to, requestId });
32861
+ const createAsk = () => createPendingAsk({ userId: context.userId, from: from2.key, to: to2, requestId });
32862
+ const alreadyPending = () => error(`Error: an ask_session request to "${to2}" is already pending.`);
32863
+ const clearAsk = () => clearPendingAsk({ userId: context.userId, from: from2.key, to: to2, requestId });
32864
+ const releaseAsk = () => releasePendingAsk({ userId: context.userId, from: from2.key, to: to2, requestId });
32507
32865
  if (remote) {
32508
32866
  const route = remoteRoute(context);
32509
32867
  if (route.kind === "refused")
@@ -32518,13 +32876,13 @@ ${entries.join(`
32518
32876
  callerTopicId: from2.topicId,
32519
32877
  userId: context.userId,
32520
32878
  fromKey: from2.key,
32521
- toKey: to,
32879
+ toKey: to2,
32522
32880
  ...context.currentThreadRootId ? { callerThreadRootId: context.currentThreadRootId } : {},
32523
32881
  createMarker: () => createAsk().ok,
32524
32882
  releaseMarker: releaseAsk
32525
32883
  });
32526
32884
  } catch (err2) {
32527
- logger.warn({ err: err2, requestId, to }, "session-comm: could not record remote ask");
32885
+ logger.warn({ err: err2, requestId, to: to2 }, "session-comm: could not record remote ask");
32528
32886
  return error("Error: could not record the remote ask; nothing was sent.");
32529
32887
  }
32530
32888
  if (begun === "pending")
@@ -32538,13 +32896,13 @@ ${entries.join(`
32538
32896
  });
32539
32897
  if (!sent.ok) {
32540
32898
  if (sent.uncertain) {
32541
- return ok2(`Ask sent to "${to}" (delivery unconfirmed: ${sent.error}). request_id: ${requestId}`);
32899
+ return ok2(`Ask sent to "${to2}" (delivery unconfirmed: ${sent.error}). request_id: ${requestId}`);
32542
32900
  }
32543
32901
  abandonRemoteSessionAsk(requestId, releaseAsk);
32544
32902
  return error(`Error: ${sent.error}`);
32545
32903
  }
32546
32904
  markRemoteSessionAskSent(requestId);
32547
- return ok2(`Ask sent to "${to}". request_id: ${requestId}`);
32905
+ return ok2(`Ask sent to "${to2}". request_id: ${requestId}`);
32548
32906
  }
32549
32907
  if (!createAsk().ok)
32550
32908
  return alreadyPending();
@@ -32566,16 +32924,16 @@ ${entries.join(`
32566
32924
  return error(`Error: ${result.error}`);
32567
32925
  }
32568
32926
  } else {
32569
- const validation = targetCatalog(context).validateTarget(to);
32927
+ const validation = targetCatalog(context).validateTarget(to2);
32570
32928
  if (!validation.ok)
32571
32929
  return validation.error;
32572
32930
  if (!validation.target.agent)
32573
- return error(`Error: "${to}" has no AI agent.`);
32931
+ return error(`Error: "${to2}" has no AI agent.`);
32574
32932
  const targetTopicId = validation.target.topicId;
32575
32933
  if (!targetTopicId)
32576
- return error(`Error: "${to}" has no topic id.`);
32934
+ return error(`Error: "${to2}" has no topic id.`);
32577
32935
  if (deliveryPrincipal(context, targetTopicId) !== context.userId) {
32578
- return error(crossPrincipalRefusal("ask_session", to));
32936
+ return error(crossPrincipalRefusal("ask_session", to2));
32579
32937
  }
32580
32938
  if (!createAsk().ok)
32581
32939
  return alreadyPending();
@@ -32600,7 +32958,7 @@ ${entries.join(`
32600
32958
  throw err2;
32601
32959
  }
32602
32960
  }
32603
- return ok2(`Ask sent to "${to}". request_id: ${requestId}`);
32961
+ return ok2(`Ask sent to "${to2}". request_id: ${requestId}`);
32604
32962
  },
32605
32963
  askCron(context, message2) {
32606
32964
  if (message2.length > MAX_MESSAGE_LENGTH)
@@ -32649,15 +33007,15 @@ request_id: ${requestId}
32649
33007
 
32650
33008
  \uC751\uB2F5\uC740 '[Reply from ${topic.title}:cron]' \uD615\uC2DD\uC73C\uB85C \uC774 \uC138\uC158\uC5D0 \uC790\uB3D9\uC73C\uB85C \uB3CC\uC544\uC635\uB2C8\uB2E4. \uC751\uB2F5\uC774 \uB3C4\uCC29\uD560 \uB54C\uAE4C\uC9C0 \uAC19\uC740 \uC694\uCCAD\uC73C\uB85C ask_cron\uC744 \uC7AC\uD638\uCD9C\uD558\uC9C0 \uB9C8\uC138\uC694.`);
32651
33009
  },
32652
- async abortSession(context, to) {
32653
- const remote = remoteTarget(context, to);
33010
+ async abortSession(context, to2) {
33011
+ const remote = remoteTarget(context, to2);
32654
33012
  if (remote) {
32655
33013
  const route = remoteRoute(context);
32656
33014
  if (route.kind === "refused")
32657
33015
  return error(route.error);
32658
33016
  if (route.kind === "hub") {
32659
33017
  const sent = await hubRemoteAbort(route.grant, { requestId: newRequestId(), to: remote });
32660
- return sent.ok ? ok2(`Abort sent to "${to}".`) : error(`Error: ${sent.error}`);
33018
+ return sent.ok ? ok2(`Abort sent to "${to2}".`) : error(`Error: ${sent.error}`);
32661
33019
  }
32662
33020
  const result = await forwardToPeer({
32663
33021
  action: "abort",
@@ -32666,14 +33024,14 @@ request_id: ${requestId}
32666
33024
  userId: context.userId,
32667
33025
  ...context.peerHostQueryId ? { sourceQueryId: context.peerHostQueryId } : {}
32668
33026
  });
32669
- return result.ok ? ok2(`Abort sent to "${to}".`) : error(`Error: ${result.error}`);
33027
+ return result.ok ? ok2(`Abort sent to "${to2}".`) : error(`Error: ${result.error}`);
32670
33028
  }
32671
- const validation = targetCatalog(context).validateTarget(to);
33029
+ const validation = targetCatalog(context).validateTarget(to2);
32672
33030
  if (!validation.ok)
32673
33031
  return validation.error;
32674
33032
  const targetTopicId = validation.target.topicId;
32675
33033
  if (!targetTopicId)
32676
- return error(`Error: "${to}" has no topic id.`);
33034
+ return error(`Error: "${to2}" has no topic id.`);
32677
33035
  if (targetTopicId === context.currentTopicId)
32678
33036
  return error("Error: cannot abort self.");
32679
33037
  const refused = abortTargetRefusal({
@@ -32681,12 +33039,12 @@ request_id: ${requestId}
32681
33039
  currentTopicId: context.currentTopicId,
32682
33040
  actorTopicScope: context.actorTopicScope,
32683
33041
  targetTopicId,
32684
- to
33042
+ to: to2
32685
33043
  });
32686
33044
  if (refused)
32687
33045
  return error(refused);
32688
33046
  if (deliveryPrincipal(context, targetTopicId) !== context.userId) {
32689
- return error(crossPrincipalRefusal("abort_session", to));
33047
+ return error(crossPrincipalRefusal("abort_session", to2));
32690
33048
  }
32691
33049
  enqueueSessionInbox({
32692
33050
  userId: context.userId,
@@ -32696,15 +33054,15 @@ request_id: ${requestId}
32696
33054
  timestamp: new Date().toISOString()
32697
33055
  }
32698
33056
  });
32699
- return ok2(`Abort sent to "${to}".`);
33057
+ return ok2(`Abort sent to "${to2}".`);
32700
33058
  },
32701
- async tellSession(context, { to, message: message2 }) {
33059
+ async tellSession(context, { to: to2, message: message2 }) {
32702
33060
  if (message2.length > MAX_MESSAGE_LENGTH)
32703
33061
  return error("Error: message too long.");
32704
33062
  if (context.depth + 1 > MAX_TELL_DEPTH)
32705
33063
  return error("Error: depth limit reached.");
32706
33064
  const from2 = currentRef(context);
32707
- const remote = remoteTarget(context, to);
33065
+ const remote = remoteTarget(context, to2);
32708
33066
  if (remote) {
32709
33067
  const route = remoteRoute(context);
32710
33068
  if (route.kind === "refused")
@@ -32720,11 +33078,11 @@ request_id: ${requestId}
32720
33078
  });
32721
33079
  if (!sent.ok) {
32722
33080
  if (sent.uncertain) {
32723
- return ok2(`Message sent to "${to}" (delivery unconfirmed: ${sent.error}). request_id: ${requestId2}`);
33081
+ return ok2(`Message sent to "${to2}" (delivery unconfirmed: ${sent.error}). request_id: ${requestId2}`);
32724
33082
  }
32725
33083
  return error(`Error: ${sent.error}`);
32726
33084
  }
32727
- return ok2(`Message sent to "${to}". request_id: ${requestId2}`);
33085
+ return ok2(`Message sent to "${to2}". request_id: ${requestId2}`);
32728
33086
  }
32729
33087
  const result = await forwardToPeer({
32730
33088
  action: "tell",
@@ -32739,22 +33097,22 @@ request_id: ${requestId}
32739
33097
  depth: context.depth + 1,
32740
33098
  ...context.peerHostQueryId ? { sourceQueryId: context.peerHostQueryId } : {}
32741
33099
  });
32742
- return result.ok ? ok2(`Message sent to "${to}".`) : error(`Error: ${result.error}`);
33100
+ return result.ok ? ok2(`Message sent to "${to2}".`) : error(`Error: ${result.error}`);
32743
33101
  }
32744
- const validation = targetCatalog(context).validateTarget(to);
33102
+ const validation = targetCatalog(context).validateTarget(to2);
32745
33103
  if (!validation.ok)
32746
33104
  return validation.error;
32747
33105
  if (!validation.target.agent)
32748
- return error(`Error: "${to}" has no AI agent.`);
33106
+ return error(`Error: "${to2}" has no AI agent.`);
32749
33107
  const targetTopicId = validation.target.topicId;
32750
33108
  if (!targetTopicId)
32751
- return error(`Error: "${to}" has no topic id.`);
33109
+ return error(`Error: "${to2}" has no topic id.`);
32752
33110
  const identity = resolveSubagentTellIdentity(context.currentTopicId, context.subagentParentTopicId);
32753
33111
  if (!canSubagentTellTarget(identity, targetTopicId)) {
32754
33112
  return error("Error: subagent tell_session target is not permitted.");
32755
33113
  }
32756
33114
  if (deliveryPrincipal(context, targetTopicId) !== context.userId) {
32757
- return error(crossPrincipalRefusal("tell_session", to));
33115
+ return error(crossPrincipalRefusal("tell_session", to2));
32758
33116
  }
32759
33117
  const requestId = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
32760
33118
  enqueueSessionInbox({
@@ -32771,7 +33129,14 @@ request_id: ${requestId}
32771
33129
  timestamp: new Date().toISOString()
32772
33130
  }
32773
33131
  });
32774
- return ok2(`Message sent to "${to}". request_id: ${requestId}`);
33132
+ return ok2(`Message sent to "${to2}". request_id: ${requestId}`);
33133
+ },
33134
+ sessionHistoryOf(context) {
33135
+ return createSessionHistoryOfReader({
33136
+ callerUserId: context.userId,
33137
+ validateTarget: (to2) => targetCatalog(context).validateTarget(to2),
33138
+ subagentIdentity: resolveSubagentTellIdentity(context.currentTopicId, context.subagentParentTopicId)
33139
+ });
32775
33140
  }
32776
33141
  };
32777
33142
  }
@@ -32785,6 +33150,7 @@ var init_default_host = __esm(async () => {
32785
33150
  init_types();
32786
33151
  await __promiseAll([
32787
33152
  init_actor_policy(),
33153
+ init_history_target(),
32788
33154
  init_peer_forward(),
32789
33155
  init_tell_permissions(),
32790
33156
  init_mcp_config(),
@@ -32806,74 +33172,14 @@ __export(exports_session_history, {
32806
33172
  createSessionHistoryMcpServer: () => createSessionHistoryMcpServer
32807
33173
  });
32808
33174
  import { McpServer as McpServer7 } from "@modelcontextprotocol/sdk/server/mcp.js";
32809
- import { z as z13 } from "zod";
32810
- function positiveInt(value, fallback) {
32811
- return Number.isFinite(value) && value && value > 0 ? Math.floor(value) : fallback;
32812
- }
32813
- function fitUtf8(text3, maxBytes) {
32814
- if (Buffer.byteLength(text3, "utf8") <= maxBytes)
32815
- return text3;
32816
- const marker = `
32817
- [... oversized entry clipped ...]
32818
- `;
32819
- const markerBytes = Buffer.byteLength(marker, "utf8");
32820
- const bytes = Buffer.from(text3, "utf8");
32821
- if (maxBytes <= markerBytes) {
32822
- return bytes.subarray(0, maxBytes).toString("utf8").replace(/\uFFFD+$/u, "");
32823
- }
32824
- const available = Math.max(0, maxBytes - markerBytes);
32825
- const headBudget = Math.ceil(available * 0.6);
32826
- const tailBudget = available - headBudget;
32827
- const head = bytes.subarray(0, headBudget).toString("utf8").replace(/\uFFFD+$/u, "");
32828
- const tail = bytes.subarray(Math.max(0, bytes.length - tailBudget)).toString("utf8").replace(/^\uFFFD+/u, "");
32829
- return `${head}${marker}${tail}`;
32830
- }
32831
- function escapeRegExp4(value) {
32832
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
32833
- }
32834
- function renderEntry(entry, index) {
32835
- const speaker = eventSpeaker(entry.event, entry.agent);
32836
- const text3 = eventText(entry.event);
32837
- return `[${index}] ${entry.ts} ${speaker}: ${text3}`;
32838
- }
32839
- function deriveBoundaries(entries) {
32840
- const boundaries = [];
32841
- entries.forEach((entry, i) => {
32842
- if (entry.event.type !== "session")
32843
- return;
32844
- const index = i + 1;
32845
- const previous = boundaries.at(-1);
32846
- if (previous && previous.sessionId === entry.event.sessionId)
32847
- return;
32848
- if (previous) {
32849
- previous.endedAt = entry.ts;
32850
- previous.endedBy = previous.agent === entry.agent ? "compacted" : "agent-switch";
32851
- }
32852
- boundaries.push({
32853
- entryIndex: index,
32854
- sessionId: entry.event.sessionId,
32855
- agent: entry.agent,
32856
- startedAt: entry.ts,
32857
- endedBy: "active"
32858
- });
32859
- });
32860
- if (boundaries.length === 0 && entries.length > 0) {
32861
- boundaries.push({
32862
- entryIndex: 1,
32863
- sessionId: "(unknown \u2014 no session event found)",
32864
- agent: entries[0]?.agent ?? "unknown",
32865
- startedAt: entries[0]?.ts ?? "",
32866
- endedBy: "active"
32867
- });
32868
- }
32869
- return boundaries;
32870
- }
33175
+ import { z as z14 } from "zod";
32871
33176
  function createSessionHistoryMcpServer(context) {
32872
- const maxCalls = positiveInt(context.maxCalls, DEFAULT_MAX_CALLS);
32873
- const maxTotalBytes = positiveInt(context.maxTotalBytes, DEFAULT_MAX_TOTAL_BYTES);
32874
- const maxChunkBytes = positiveInt(context.maxChunkBytes, DEFAULT_MAX_CHUNK_BYTES);
32875
- let calls = 0;
32876
- let totalBytes = 0;
33177
+ const reader = createSessionHistoryReader({
33178
+ maxCalls: context.maxCalls,
33179
+ maxTotalBytes: context.maxTotalBytes,
33180
+ maxChunkBytes: context.maxChunkBytes
33181
+ });
33182
+ const self = { userId: context.userId, topic: context.topic };
32877
33183
  const server = new McpServer7({ name: "session-history", version: "1.0.0" });
32878
33184
  const requireContext = () => {
32879
33185
  if (!context.userId || !context.topic) {
@@ -32881,18 +33187,6 @@ function createSessionHistoryMcpServer(context) {
32881
33187
  }
32882
33188
  return null;
32883
33189
  };
32884
- const budgetExceeded = () => {
32885
- if (calls > maxCalls || totalBytes >= maxTotalBytes) {
32886
- return mcpError(JSON.stringify({
32887
- error: "session-history read budget exhausted for this turn; answer with what you already read",
32888
- calls,
32889
- max_calls: maxCalls,
32890
- total_read_bytes: totalBytes,
32891
- max_total_bytes: maxTotalBytes
32892
- }));
32893
- }
32894
- return null;
32895
- };
32896
33190
  server.tool("list_session_boundaries", [
32897
33191
  "List every provider session this topic has had, in order, from the append-only raw",
32898
33192
  "conversation manifest (survives /compact and agent switches \u2014 nothing is ever deleted",
@@ -32900,24 +33194,7 @@ function createSessionHistoryMcpServer(context) {
32900
33194
  "it ended via compaction or an agent switch, and its provider sessionId. Call this BEFORE",
32901
33195
  "read_session_history or search_session_history so you know which entry range to target",
32902
33196
  "instead of scanning from entry 1."
32903
- ].join(" "), {}, async () => {
32904
- const guard = requireContext();
32905
- if (guard)
32906
- return guard;
32907
- calls += 1;
32908
- const budget = budgetExceeded();
32909
- if (budget)
32910
- return budget;
32911
- try {
32912
- const entries = readRawConversation(context.userId, context.topic);
32913
- const boundaries = deriveBoundaries(entries);
32914
- const payload = JSON.stringify({ total_entries: entries.length, sessions: boundaries }, null, 2);
32915
- totalBytes += Buffer.byteLength(payload, "utf8");
32916
- return mcpOk(payload);
32917
- } catch (error2) {
32918
- return mcpError(`list_session_boundaries failed: ${errMsg(error2)}`);
32919
- }
32920
- });
33197
+ ].join(" "), {}, async () => requireContext() ?? reader.listBoundaries(self));
32921
33198
  server.tool("read_session_history", [
32922
33199
  "Read the full-fidelity raw conversation manifest in bounded chunks \u2014 includes everything",
32923
33200
  "that ever happened in this topic (messages, tool calls, reasoning, session/compact",
@@ -32926,75 +33203,10 @@ function createSessionHistoryMcpServer(context) {
32926
33203
  "list_session_boundaries, then pass sessionId to read only that session's range instead of",
32927
33204
  "paging through the whole topic."
32928
33205
  ].join(" "), {
32929
- offset: z13.number().optional().describe("One-based entry number. Defaults to 1."),
32930
- limit: z13.number().optional().describe(`Number of entries. Defaults to ${DEFAULT_LINE_LIMIT}, max ${MAX_LINE_LIMIT}.`),
32931
- sessionId: z13.string().optional().describe("Restrict to one session's entry range (see list_session_boundaries).")
32932
- }, async ({ offset: rawOffset, limit: rawLimit, sessionId }) => {
32933
- const guard = requireContext();
32934
- if (guard)
32935
- return guard;
32936
- calls += 1;
32937
- const budget = budgetExceeded();
32938
- if (budget)
32939
- return budget;
32940
- try {
32941
- const entries = readRawConversation(context.userId, context.topic);
32942
- let lower = 0;
32943
- let upper = entries.length;
32944
- if (sessionId) {
32945
- const boundaries = deriveBoundaries(entries);
32946
- const match = boundaries.find((b) => b.sessionId === sessionId);
32947
- if (!match)
32948
- return mcpError(`Unknown sessionId: ${sessionId}`);
32949
- lower = match.entryIndex - 1;
32950
- const next = boundaries.find((b) => b.entryIndex > match.entryIndex);
32951
- upper = next ? next.entryIndex - 1 : entries.length;
32952
- }
32953
- const offset = positiveInt(rawOffset, 1);
32954
- const limit = Math.min(positiveInt(rawLimit, DEFAULT_LINE_LIMIT), MAX_LINE_LIMIT);
32955
- const start = Math.max(lower, offset - 1);
32956
- if (start >= upper) {
32957
- return mcpOk(JSON.stringify({
32958
- content: "(end of range)",
32959
- offset,
32960
- returned_entries: 0,
32961
- total_entries: entries.length,
32962
- calls
32963
- }));
32964
- }
32965
- const rendered = [];
32966
- let returnedBytes = 0;
32967
- let index = start;
32968
- const callBudget = Math.min(maxChunkBytes, Math.max(1, maxTotalBytes - totalBytes));
32969
- while (index < upper && rendered.length < limit) {
32970
- const line = fitUtf8(renderEntry(entries[index], index + 1), Math.max(1, callBudget));
32971
- const separatorBytes = rendered.length > 0 ? 1 : 0;
32972
- const lineBytes = Buffer.byteLength(line, "utf8");
32973
- if (rendered.length > 0 && returnedBytes + separatorBytes + lineBytes > callBudget)
32974
- break;
32975
- rendered.push(line);
32976
- returnedBytes += separatorBytes + lineBytes;
32977
- index += 1;
32978
- if (returnedBytes >= callBudget)
32979
- break;
32980
- }
32981
- totalBytes += returnedBytes;
32982
- return mcpOk(JSON.stringify({
32983
- content: rendered.join(`
32984
- `),
32985
- offset,
32986
- returned_entries: rendered.length,
32987
- returned_bytes: returnedBytes,
32988
- total_entries: entries.length,
32989
- total_read_bytes: totalBytes,
32990
- calls,
32991
- ...index < upper ? { next_offset: index + 1 } : {},
32992
- ...calls >= maxCalls || totalBytes >= maxTotalBytes ? { note: "Read budget nearly exhausted; wrap up with what you have." } : {}
32993
- }));
32994
- } catch (error2) {
32995
- return mcpError(`read_session_history failed: ${errMsg(error2)}`);
32996
- }
32997
- });
33206
+ offset: z14.number().optional().describe("One-based entry number. Defaults to 1."),
33207
+ limit: z14.number().optional().describe(`Number of entries. Defaults to ${SESSION_HISTORY_DEFAULT_LINE_LIMIT}, max ${SESSION_HISTORY_MAX_LINE_LIMIT}.`),
33208
+ sessionId: z14.string().optional().describe("Restrict to one session's entry range (see list_session_boundaries).")
33209
+ }, async (args) => requireContext() ?? reader.read(self, args));
32998
33210
  server.tool("search_session_history", [
32999
33211
  "Keyword-search the full raw conversation manifest (case-insensitive substring match)",
33000
33212
  "across every session this topic has ever had, including content a /compact summarized",
@@ -33003,89 +33215,16 @@ function createSessionHistoryMcpServer(context) {
33003
33215
  "topic's size, but prefer sessionId to narrow the scan when you already know which session",
33004
33216
  "from list_session_boundaries."
33005
33217
  ].join(" "), {
33006
- query: z13.string().min(1).describe("Case-insensitive substring to search for."),
33007
- sessionId: z13.string().optional().describe("Restrict the scan to one session's range."),
33008
- limit: z13.number().optional().describe(`Max matches to return. Defaults to ${DEFAULT_SEARCH_LIMIT}, max ${MAX_SEARCH_LIMIT}.`)
33009
- }, async ({ query: query2, sessionId, limit: rawLimit }) => {
33010
- const guard = requireContext();
33011
- if (guard)
33012
- return guard;
33013
- calls += 1;
33014
- const budget = budgetExceeded();
33015
- if (budget)
33016
- return budget;
33017
- try {
33018
- const entries = readRawConversation(context.userId, context.topic);
33019
- let lower = 0;
33020
- let upper = entries.length;
33021
- if (sessionId) {
33022
- const boundaries2 = deriveBoundaries(entries);
33023
- const match = boundaries2.find((b) => b.sessionId === sessionId);
33024
- if (!match)
33025
- return mcpError(`Unknown sessionId: ${sessionId}`);
33026
- lower = match.entryIndex - 1;
33027
- const next = boundaries2.find((b) => b.entryIndex > match.entryIndex);
33028
- upper = next ? next.entryIndex - 1 : entries.length;
33029
- }
33030
- const limit = Math.min(positiveInt(rawLimit, DEFAULT_SEARCH_LIMIT), MAX_SEARCH_LIMIT);
33031
- const needleRegex = new RegExp(escapeRegExp4(query2), "i");
33032
- const matches = [];
33033
- const boundaries = sessionId ? undefined : deriveBoundaries(entries);
33034
- let returnedBytes = 0;
33035
- let budgetStopped = false;
33036
- const callBudget = Math.min(maxChunkBytes, Math.max(1, maxTotalBytes - totalBytes));
33037
- for (let i = lower;i < upper && matches.length < limit; i++) {
33038
- const entry = entries[i];
33039
- const text3 = eventText(entry.event);
33040
- const found = needleRegex.exec(text3);
33041
- if (!found)
33042
- continue;
33043
- const at = found.index;
33044
- const start = Math.max(0, at - SEARCH_SNIPPET_RADIUS);
33045
- const end = Math.min(text3.length, at + found[0].length + SEARCH_SNIPPET_RADIUS);
33046
- const snippet = `${start > 0 ? "\u2026" : ""}${text3.slice(start, end)}${end < text3.length ? "\u2026" : ""}`;
33047
- const matchedSessionId = sessionId ?? boundaries?.findLast((b) => b.entryIndex <= i + 1)?.sessionId;
33048
- const candidate = {
33049
- entry: i + 1,
33050
- sessionId: matchedSessionId,
33051
- agent: entry.agent,
33052
- ts: entry.ts,
33053
- snippet
33054
- };
33055
- const lineBytes = Buffer.byteLength(JSON.stringify(candidate), "utf8");
33056
- if (returnedBytes + lineBytes > callBudget) {
33057
- budgetStopped = true;
33058
- break;
33059
- }
33060
- returnedBytes += lineBytes;
33061
- matches.push(candidate);
33062
- }
33063
- totalBytes += returnedBytes;
33064
- return mcpOk(JSON.stringify({
33065
- query: query2,
33066
- matches,
33067
- match_count: matches.length,
33068
- total_entries: entries.length,
33069
- calls,
33070
- ...matches.length >= limit ? { note: "Hit the match limit; narrow the query or pass sessionId for more." } : budgetStopped ? {
33071
- note: "Read budget ran out before the scan finished; this result is incomplete, not necessarily 'no matches'."
33072
- } : {}
33073
- }));
33074
- } catch (error2) {
33075
- return mcpError(`search_session_history failed: ${errMsg(error2)}`);
33076
- }
33077
- });
33218
+ query: z14.string().min(1).describe("Case-insensitive substring to search for."),
33219
+ sessionId: z14.string().optional().describe("Restrict the scan to one session's range."),
33220
+ limit: z14.number().optional().describe(`Max matches to return. Defaults to ${SESSION_HISTORY_DEFAULT_SEARCH_LIMIT}, max ${SESSION_HISTORY_MAX_SEARCH_LIMIT}.`)
33221
+ }, async (args) => requireContext() ?? reader.search(self, args));
33078
33222
  return server;
33079
33223
  }
33080
- 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;
33081
33224
  var init_session_history = __esm(async () => {
33082
33225
  init_mcp_helpers();
33083
- await __promiseAll([
33084
- init_conversations(),
33085
- init_topic_archive()
33086
- ]);
33087
- DEFAULT_MAX_TOTAL_BYTES = 768 * 1024;
33088
- DEFAULT_MAX_CHUNK_BYTES = 64 * 1024;
33226
+ init_session_history_limits();
33227
+ await init_session_history_reader();
33089
33228
  });
33090
33229
 
33091
33230
  // ../../packages/core/src/mcp/factories/vault.ts
@@ -36128,7 +36267,7 @@ import { statSync as statSync17 } from "fs";
36128
36267
  import { basename as basename10, extname as extname3, resolve as resolve21 } from "path";
36129
36268
  import { McpServer as McpServer9 } from "@modelcontextprotocol/sdk/server/mcp.js";
36130
36269
  import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
36131
- import { z as z14 } from "zod";
36270
+ import { z as z15 } from "zod";
36132
36271
  function requireTopicAccess(ctx) {
36133
36272
  const topic = getTopic(ctx.topicId);
36134
36273
  if (!topic)
@@ -36374,8 +36513,8 @@ function buildNegotiumMcpServer(ctx) {
36374
36513
  }
36375
36514
  }
36376
36515
  if (ctx.fileDeliveryTools === true) {
36377
- 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));
36378
- 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 }) => {
36516
+ 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: z15.string().describe("Absolute path to the file to send") }, async ({ file_path }) => deliverFile(ctx, file_path));
36517
+ server.tool("send_files", "Send multiple local files to the user in the chat at once.", { file_paths: z15.array(z15.string()).describe("Array of absolute file paths to send") }, async ({ file_paths }) => {
36379
36518
  const results = await Promise.all(file_paths.map((filePath) => deliverFile(ctx, filePath)));
36380
36519
  const hasError = results.some((result) => ("isError" in result) && result.isError);
36381
36520
  return {
@@ -36401,8 +36540,8 @@ function registerThreadTools(server, ctx) {
36401
36540
  return;
36402
36541
  const topicId = ctx.topicId;
36403
36542
  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.", {
36404
- thread_id: z14.string().optional().describe("Thread tag (#a3f1c8) or full root message id. Omit to read the thread this turn is answering in."),
36405
- limit: z14.number().int().optional().describe(`Most recent replies to include (default ${THREAD_READ_DEFAULT_LIMIT}, max ${THREAD_READ_MAX_LIMIT}).`)
36543
+ thread_id: z15.string().optional().describe("Thread tag (#a3f1c8) or full root message id. Omit to read the thread this turn is answering in."),
36544
+ limit: z15.number().int().optional().describe(`Most recent replies to include (default ${THREAD_READ_DEFAULT_LIMIT}, max ${THREAD_READ_MAX_LIMIT}).`)
36406
36545
  }, async ({ thread_id, limit }) => {
36407
36546
  const requested = thread_id?.trim();
36408
36547
  if (!requested && !ctx.threadRootId) {
@@ -36423,7 +36562,7 @@ function registerThreadTools(server, ctx) {
36423
36562
  return textResult(rendered);
36424
36563
  });
36425
36564
  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.", {
36426
- limit: z14.number().int().optional().describe("Threads to list (default 20).")
36565
+ limit: z15.number().int().optional().describe("Threads to list (default 20).")
36427
36566
  }, async ({ limit }) => textResult(renderTopicThreadList(topicId, limit ?? 20)));
36428
36567
  }
36429
36568
  function resolveThreadRootId(topicId, requested) {
@@ -36718,23 +36857,23 @@ function defaultManifestFile() {
36718
36857
  var init_paths2 = () => {};
36719
36858
 
36720
36859
  // ../../packages/mcp-host/src/spec.ts
36721
- import { z as z15 } from "zod";
36860
+ import { z as z16 } from "zod";
36722
36861
  var KEY_PATTERN, portSchema, mcpServerSpecSchema;
36723
36862
  var init_spec = __esm(() => {
36724
36863
  KEY_PATTERN = /^[a-zA-Z0-9._-]+$/;
36725
- portSchema = z15.number().int().min(1).max(65535);
36726
- mcpServerSpecSchema = z15.object({
36727
- 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"),
36728
- transport: z15.enum(["stdio", "http"]),
36729
- command: z15.string().min(1),
36730
- args: z15.array(z15.string()).optional(),
36731
- env: z15.record(z15.string(), z15.string()).optional(),
36732
- cwd: z15.string().optional(),
36733
- portRange: z15.object({ base: portSchema, max: portSchema }).optional(),
36734
- scope: z15.enum(["node", "instance"]),
36735
- readyTimeoutMs: z15.number().int().positive().optional(),
36736
- idleEvictMs: z15.number().int().positive().optional(),
36737
- healthIntervalMs: z15.number().int().positive().optional()
36864
+ portSchema = z16.number().int().min(1).max(65535);
36865
+ mcpServerSpecSchema = z16.object({
36866
+ key: z16.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"),
36867
+ transport: z16.enum(["stdio", "http"]),
36868
+ command: z16.string().min(1),
36869
+ args: z16.array(z16.string()).optional(),
36870
+ env: z16.record(z16.string(), z16.string()).optional(),
36871
+ cwd: z16.string().optional(),
36872
+ portRange: z16.object({ base: portSchema, max: portSchema }).optional(),
36873
+ scope: z16.enum(["node", "instance"]),
36874
+ readyTimeoutMs: z16.number().int().positive().optional(),
36875
+ idleEvictMs: z16.number().int().positive().optional(),
36876
+ healthIntervalMs: z16.number().int().positive().optional()
36738
36877
  }).superRefine((spec, ctx) => {
36739
36878
  if (spec.transport === "http") {
36740
36879
  if (!spec.portRange) {
@@ -36757,7 +36896,7 @@ var init_spec = __esm(() => {
36757
36896
  // ../../packages/mcp-host/src/manifest.ts
36758
36897
  import { existsSync as existsSync34, mkdirSync as mkdirSync28, readFileSync as readFileSync25, renameSync as renameSync14, writeFileSync as writeFileSync22 } from "fs";
36759
36898
  import { dirname as dirname20 } from "path";
36760
- import { z as z16 } from "zod";
36899
+ import { z as z17 } from "zod";
36761
36900
 
36762
36901
  class McpManifest {
36763
36902
  file;
@@ -36839,13 +36978,13 @@ var manifestEntrySchema, manifestFileSchema;
36839
36978
  var init_manifest = __esm(() => {
36840
36979
  init_paths2();
36841
36980
  init_spec();
36842
- manifestEntrySchema = z16.object({
36981
+ manifestEntrySchema = z17.object({
36843
36982
  spec: mcpServerSpecSchema,
36844
- enabled: z16.boolean()
36983
+ enabled: z17.boolean()
36845
36984
  });
36846
- manifestFileSchema = z16.object({
36847
- version: z16.literal(1),
36848
- servers: z16.array(manifestEntrySchema)
36985
+ manifestFileSchema = z17.object({
36986
+ version: z17.literal(1),
36987
+ servers: z17.array(manifestEntrySchema)
36849
36988
  });
36850
36989
  });
36851
36990
 
@@ -47587,21 +47726,21 @@ function ordered(selection) {
47587
47726
  function attachesToPreviousCell(character) {
47588
47727
  return displayWidth(character) === 0;
47589
47728
  }
47590
- function columnSlice(value, from2, to) {
47729
+ function columnSlice(value, from2, to2) {
47591
47730
  let output = "";
47592
47731
  let column = 0;
47593
- let lastIncluded = from2 <= 0 && to > 0;
47732
+ let lastIncluded = from2 <= 0 && to2 > 0;
47594
47733
  for (const character of stripAnsi(value)) {
47595
47734
  if (attachesToPreviousCell(character)) {
47596
47735
  if (lastIncluded)
47597
47736
  output += character;
47598
47737
  continue;
47599
47738
  }
47600
- if (column >= to)
47739
+ if (column >= to2)
47601
47740
  break;
47602
47741
  const width = displayWidth(character);
47603
47742
  const next = column + width;
47604
- lastIncluded = next > from2 && column < to;
47743
+ lastIncluded = next > from2 && column < to2;
47605
47744
  if (lastIncluded)
47606
47745
  output += character;
47607
47746
  column = next;
@@ -47618,18 +47757,18 @@ function screenSelectionText(lines, selection) {
47618
47757
  const rowFrom = row === start.y ? Math.max(0, start.x - 1) : 0;
47619
47758
  const rowTo = row === end.y ? Math.max(rowFrom, end.x) : Number.POSITIVE_INFINITY;
47620
47759
  const from2 = Math.max(rowFrom, clipFrom);
47621
- const to = Math.min(rowTo, clipTo);
47622
- selected.push(to > from2 ? columnSlice(value, from2, to).trimEnd() : "");
47760
+ const to2 = Math.min(rowTo, clipTo);
47761
+ selected.push(to2 > from2 ? columnSlice(value, from2, to2).trimEnd() : "");
47623
47762
  }
47624
47763
  return selected.join(`
47625
47764
  `).replace(/\n+$/, "");
47626
47765
  }
47627
- function highlightRow(value, from2, to) {
47766
+ function highlightRow(value, from2, to2) {
47628
47767
  let output = "";
47629
47768
  let column = 0;
47630
47769
  let inverse = false;
47631
47770
  let index = 0;
47632
- let lastSelected = from2 <= 0 && to > 0;
47771
+ let lastSelected = from2 <= 0 && to2 > 0;
47633
47772
  while (index < value.length) {
47634
47773
  ANSI_PATTERN.lastIndex = index;
47635
47774
  const ansi = ANSI_PATTERN.exec(value);
@@ -47643,7 +47782,7 @@ function highlightRow(value, from2, to) {
47643
47782
  break;
47644
47783
  const character = String.fromCodePoint(codePoint);
47645
47784
  const width = displayWidth(character);
47646
- const selected = attachesToPreviousCell(character) ? lastSelected : column + width > from2 && column < to;
47785
+ const selected = attachesToPreviousCell(character) ? lastSelected : column + width > from2 && column < to2;
47647
47786
  lastSelected = selected;
47648
47787
  if (selected && !inverse) {
47649
47788
  output += "\x1B[7m";
@@ -47670,8 +47809,8 @@ function highlightScreenSelection(frame, selection) {
47670
47809
  const rowFrom = row === start.y ? Math.max(0, start.x - 1) : 0;
47671
47810
  const rowTo = row === end.y ? Math.max(rowFrom, end.x) : Number.POSITIVE_INFINITY;
47672
47811
  const from2 = Math.max(rowFrom, clipFrom);
47673
- const to = Math.min(rowTo, clipTo);
47674
- return to > from2 ? highlightRow(line2, from2, to) : line2;
47812
+ const to2 = Math.min(rowTo, clipTo);
47813
+ return to2 > from2 ? highlightRow(line2, from2, to2) : line2;
47675
47814
  }).join(`
47676
47815
  `);
47677
47816
  }
@@ -59073,8 +59212,8 @@ var init_safe_fs = __esm(() => {
59073
59212
  closeSync7(fd);
59074
59213
  }
59075
59214
  },
59076
- renameNoClobber(from2, to) {
59077
- linkSync3(from2, to);
59215
+ renameNoClobber(from2, to2) {
59216
+ linkSync3(from2, to2);
59078
59217
  unlinkSync25(from2);
59079
59218
  }
59080
59219
  };
@@ -61194,4 +61333,4 @@ switch (command) {
61194
61333
  }
61195
61334
  }
61196
61335
 
61197
- //# debugId=9DF88694EA59FD9264756E2164756E21
61336
+ //# debugId=26080B805BD14DD264756E2164756E21