@unson/brainbase-mcp 0.51.0 → 0.51.2

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.
@@ -72,6 +72,8 @@ export interface TranscriptReadOptions {
72
72
  conversationId: string;
73
73
  allowedTranscriptRoots?: readonly string[];
74
74
  env?: NodeJS.ProcessEnv;
75
+ /** Optional tool_use_id / tool_call_id hint when resolving truncated or shifted tool results. */
76
+ toolUseId?: string;
75
77
  /** Override for the Linux `openat2` helper executable path (strictly for tests). */
76
78
  openatHelperBinary?: string;
77
79
  /** Override runtime platform check (strictly for tests). */
@@ -105,9 +107,12 @@ export declare function isAntigravityHookConfigText(text: string): boolean;
105
107
  export declare function normalizeAntigravityToolName(name: string, args?: unknown): string;
106
108
  interface TranscriptEntry {
107
109
  step_index?: unknown;
110
+ tool_use_id?: unknown;
111
+ tool_call_id?: unknown;
108
112
  source?: unknown;
109
113
  type?: unknown;
110
114
  content?: unknown;
115
+ truncated_fields?: unknown;
111
116
  }
112
117
  interface TranscriptOpenatTestFaults {
113
118
  /** Force Linux openat2(2) to fail with the specified errno to verify immediate fail-closed rejection (no fallback). */
@@ -143,7 +148,25 @@ export declare function extractLatestNonSystemUserInput(transcriptPath: unknown,
143
148
  content: string;
144
149
  } | null;
145
150
  export declare function extractLastAssistantMessage(transcriptPath: unknown, options?: TranscriptReadOptions): string | undefined;
151
+ /**
152
+ * Splits whitespace/newline-concatenated top-level JSON objects/arrays (`{...}` / `[...]`)
153
+ * in a single strict O(n) character scan without regex backtracking.
154
+ *
155
+ * Antigravity CLI concatenates multiple MCP text content blocks with `\n` when writing
156
+ * `steps/<n>/output.txt` and `transcript*.jsonl` (for example, a primary tool result JSON
157
+ * followed by a trailing `{"connection_scope":{...}}` block). When 2+ top-level JSON
158
+ * containers are found and every block validates via `JSON.parse`, returns the individual
159
+ * blocks so `tool_response.content` restores the original multi-block MCP structure.
160
+ * For a single JSON value, non-JSON text, or any malformed/partial block, fails open and
161
+ * returns `[text]`.
162
+ */
163
+ export declare function splitConcatenatedJsonTextBlocks(text: string): string[];
146
164
  export declare function extractToolResultFromTranscript(transcriptPath: unknown, stepIdx: unknown, options?: TranscriptReadOptions): string | null;
165
+ /**
166
+ * Extracts a tool result from the authorized transcript / step output and restores
167
+ * whitespace/newline-concatenated MCP JSON text blocks into individual text block strings.
168
+ */
169
+ export declare function extractToolResultTextBlocksFromTranscript(transcriptPath: unknown, stepIdx: unknown, options?: TranscriptReadOptions): string[] | null;
147
170
  declare function turnKey(conversationId: string, configPath: string): string;
148
171
  declare function statePath(env: NodeJS.ProcessEnv, key: string): string;
149
172
  declare function lockPathFor(env: NodeJS.ProcessEnv, key: string): string;
@@ -26,7 +26,8 @@ import { spawn, spawnSync } from 'node:child_process';
26
26
  import { createHash, randomUUID } from 'node:crypto';
27
27
  import { accessSync, closeSync, constants as fsConstants, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
28
28
  import { homedir } from 'node:os';
29
- import { delimiter, isAbsolute, join, relative, resolve, sep } from 'node:path';
29
+ import { delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
30
+ import { fileURLToPath } from 'node:url';
30
31
  import { BrainbaseLoginError, getAccessTokenOfLogin } from './brainbase-login.js';
31
32
  import { PRE_TOOL_USE_TOOLS, REGISTRATION_ID, bearerTransportSafe, canonicalFilePath, canonicalRepositoryIdentifier, digestSummary, forwardedStopPayload, hostCanMapRepository, resolveRepositoryScope, shellQuote, singleQuotedWords, } from './claude-code-judgment-hook.js';
32
33
  export const ANTIGRAVITY_HOOK_CONFIG_SCHEMA = 'brainbase-antigravity-judgment-hook-v1';
@@ -41,6 +42,8 @@ export const DEFAULT_ANTIGRAVITY_TIMEOUTS_MS = {
41
42
  const TURN_SCHEMA = 'brainbase-antigravity-judgment-turn-v1';
42
43
  const PROJECT_CODE_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/u;
43
44
  const TRANSCRIPT_TAIL_MAX_BYTES = 256 * 1024;
45
+ const TRANSCRIPT_FULL_TAIL_MAX_BYTES = 1024 * 1024;
46
+ const TRANSCRIPT_TOOL_RESULT_MAX_BYTES = 512 * 1024;
44
47
  const TRANSCRIPT_OPENAT_TIMEOUT_MS = 1_500;
45
48
  const MAX_PENDING_MESSAGES = 8;
46
49
  const DEFAULT_STALE_TURN_MS = 30 * 60 * 1000;
@@ -676,7 +679,7 @@ function resolveAuthorizedTranscriptTarget(transcriptPath, options) {
676
679
  function resolveAuthorizedTranscriptPath(transcriptPath, options) {
677
680
  return resolveAuthorizedTranscriptTarget(transcriptPath, options)?.canonicalPath ?? null;
678
681
  }
679
- function buildPythonOpenatTailReader(faults) {
682
+ function buildPythonOpenatReader(faults, mode = 'tail') {
680
683
  const forceOpenat2Errno = faults?.forceOpenat2Errno;
681
684
  const renameAfterRead = faults?.renameAfterTailRead;
682
685
  const lines = [
@@ -759,8 +762,16 @@ function buildPythonOpenatTailReader(faults) {
759
762
  ' verify_fd_exact_path(file_fd, expected_exact_path)',
760
763
  ' size = st.st_size',
761
764
  ' if size <= 0: sys.exit(0)',
762
- ' read_size = min(size, max_bytes)',
763
- ' offset = size - read_size',
765
+ ...(mode === 'full'
766
+ ? [
767
+ ' if size > max_bytes: fail()',
768
+ ' read_size = size',
769
+ ' offset = 0',
770
+ ]
771
+ : [
772
+ ' read_size = min(size, max_bytes)',
773
+ ' offset = size - read_size',
774
+ ]),
764
775
  ' chunks = []',
765
776
  ' remaining = read_size',
766
777
  ' pos = offset',
@@ -777,12 +788,22 @@ function buildPythonOpenatTailReader(faults) {
777
788
  ? [` os.rename(${JSON.stringify(renameAfterRead.from)}, ${JSON.stringify(renameAfterRead.to)})`]
778
789
  : []),
779
790
  ' verify_fd_exact_path(file_fd, expected_exact_path)',
780
- ' if not stat.S_ISREG(os.fstat(file_fd).st_mode): fail()',
791
+ ' post_st = os.fstat(file_fd)',
792
+ ' if not stat.S_ISREG(post_st.st_mode): fail()',
793
+ ...(mode === 'full'
794
+ ? [' if post_st.st_size > max_bytes: fail()']
795
+ : []),
781
796
  ' data = b"".join(chunks)',
782
- ' if offset > 0:',
783
- ' nl = data.find(b"\\n")',
784
- ' if nl < 0: sys.exit(0)',
785
- ' data = data[nl + 1:]',
797
+ ...(mode === 'tail'
798
+ ? [
799
+ ' if offset > 0:',
800
+ ' nl = data.find(b"\\n")',
801
+ ' if nl < 0: sys.exit(0)',
802
+ ' data = data[nl + 1:]',
803
+ ]
804
+ : [
805
+ ' if len(data) > max_bytes: fail()',
806
+ ]),
786
807
  ' if data:',
787
808
  ' sys.stdout.buffer.write(data)',
788
809
  ' sys.stdout.buffer.flush()',
@@ -798,7 +819,8 @@ function buildPythonOpenatTailReader(faults) {
798
819
  ];
799
820
  return lines.join('\n');
800
821
  }
801
- const PYTHON_OPENAT_TAIL_READER = buildPythonOpenatTailReader();
822
+ const PYTHON_OPENAT_TAIL_READER = buildPythonOpenatReader(undefined, 'tail');
823
+ const PYTHON_OPENAT_FULL_READER = buildPythonOpenatReader(undefined, 'full');
802
824
  const DEFAULT_OPENAT_HELPER_CANDIDATES = [
803
825
  '/usr/bin/python3',
804
826
  '/usr/local/bin/python3',
@@ -860,9 +882,10 @@ function readTailViaKernelOpenat(canonicalRoot, segments, maxBytes, options) {
860
882
  return null;
861
883
  }
862
884
  const timeoutMs = options?.helperTimeoutMs ?? TRANSCRIPT_OPENAT_TIMEOUT_MS;
885
+ const mode = options?.mode ?? 'tail';
863
886
  const helperScript = options?.openatTestFaults
864
- ? buildPythonOpenatTailReader(options.openatTestFaults)
865
- : PYTHON_OPENAT_TAIL_READER;
887
+ ? buildPythonOpenatReader(options.openatTestFaults, mode)
888
+ : (mode === 'full' ? PYTHON_OPENAT_FULL_READER : PYTHON_OPENAT_TAIL_READER);
866
889
  try {
867
890
  const result = spawnSync(helperBin, ['-I', '-c', helperScript, canonicalRoot, String(maxBytes), ...segments], {
868
891
  encoding: 'buffer',
@@ -883,18 +906,16 @@ function readTailViaKernelOpenat(canonicalRoot, segments, maxBytes, options) {
883
906
  return null;
884
907
  }
885
908
  }
886
- function readTranscriptTailEntries(transcriptPath, options, testHooks) {
887
- const target = resolveAuthorizedTranscriptTarget(transcriptPath, options);
888
- if (!target || !options)
889
- return [];
909
+ function readTranscriptEntriesFromTarget(target, options, maxBytes, testHooks) {
890
910
  try {
891
911
  testHooks?.onBeforeOpen?.(target.canonicalPath);
892
- const rawTail = readTailViaKernelOpenat(target.canonicalRoot, target.segments, TRANSCRIPT_TAIL_MAX_BYTES, {
912
+ const rawTail = readTailViaKernelOpenat(target.canonicalRoot, target.segments, maxBytes, {
893
913
  openatHelperBinary: testHooks?.openatHelperBinary ?? options.openatHelperBinary,
894
914
  openatHelperCandidates: testHooks?.openatHelperCandidates,
895
915
  helperTimeoutMs: testHooks?.helperTimeoutMs,
896
916
  platform: testHooks?.platform ?? options.platform,
897
917
  openatTestFaults: testHooks?.openatTestFaults,
918
+ mode: 'tail',
898
919
  });
899
920
  if (rawTail === null || rawTail.length === 0)
900
921
  return [];
@@ -920,6 +941,12 @@ function readTranscriptTailEntries(transcriptPath, options, testHooks) {
920
941
  return [];
921
942
  }
922
943
  }
944
+ function readTranscriptTailEntries(transcriptPath, options, testHooks) {
945
+ const target = resolveAuthorizedTranscriptTarget(transcriptPath, options);
946
+ if (!target || !options)
947
+ return [];
948
+ return readTranscriptEntriesFromTarget(target, options, TRANSCRIPT_TAIL_MAX_BYTES, testHooks);
949
+ }
923
950
  function stripUserRequestWrapper(text) {
924
951
  const trimmed = text.trim();
925
952
  const match = /^<USER_REQUEST>\s*([\s\S]*?)\s*<\/USER_REQUEST>/u.exec(trimmed);
@@ -982,12 +1009,275 @@ function stripToolTimestampHeader(text) {
982
1009
  const body = lines.slice(index).join('\n').trim();
983
1010
  return body || text.trim();
984
1011
  }
985
- export function extractToolResultFromTranscript(transcriptPath, stepIdx, options) {
986
- if (typeof stepIdx !== 'number' || !Number.isSafeInteger(stepIdx))
1012
+ const TOOL_OUTPUT_TRUNCATION_BANNER_PATTERN = /^The tool's output was truncated due to being too long\./u;
1013
+ const INLINE_TRUNCATION_MARKER_PATTERN = /<truncated\s+\d+(?:\s+of\s+\d+)?\s+bytes(?:\s[^><\r\n]{0,256})?>/iu;
1014
+ const TRUNCATED_OUTPUT_FILE_URL_PATTERN = /^The tool's output was truncated due to being too long\.\s+You can find the full output in (?:a )?file at (file:\/\/[^\s"'<>]+)/u;
1015
+ function entryToolUseId(entry) {
1016
+ if (typeof entry.tool_use_id === 'string' && entry.tool_use_id.trim()) {
1017
+ return entry.tool_use_id.trim();
1018
+ }
1019
+ if (typeof entry.tool_call_id === 'string' && entry.tool_call_id.trim()) {
1020
+ return entry.tool_call_id.trim();
1021
+ }
1022
+ return null;
1023
+ }
1024
+ function hasTruncatedContentField(entry) {
1025
+ return Array.isArray(entry.truncated_fields) && entry.truncated_fields.includes('content');
1026
+ }
1027
+ function isJsonWhitespaceCode(code) {
1028
+ return code === 0x20 || code === 0x09 || code === 0x0a || code === 0x0d;
1029
+ }
1030
+ function isValidJsonText(text) {
1031
+ try {
1032
+ JSON.parse(text);
1033
+ return true;
1034
+ }
1035
+ catch {
1036
+ return false;
1037
+ }
1038
+ }
1039
+ /**
1040
+ * Splits whitespace/newline-concatenated top-level JSON objects/arrays (`{...}` / `[...]`)
1041
+ * in a single strict O(n) character scan without regex backtracking.
1042
+ *
1043
+ * Antigravity CLI concatenates multiple MCP text content blocks with `\n` when writing
1044
+ * `steps/<n>/output.txt` and `transcript*.jsonl` (for example, a primary tool result JSON
1045
+ * followed by a trailing `{"connection_scope":{...}}` block). When 2+ top-level JSON
1046
+ * containers are found and every block validates via `JSON.parse`, returns the individual
1047
+ * blocks so `tool_response.content` restores the original multi-block MCP structure.
1048
+ * For a single JSON value, non-JSON text, or any malformed/partial block, fails open and
1049
+ * returns `[text]`.
1050
+ */
1051
+ export function splitConcatenatedJsonTextBlocks(text) {
1052
+ const length = text.length;
1053
+ if (length === 0)
1054
+ return [text];
1055
+ let i = 0;
1056
+ while (i < length && isJsonWhitespaceCode(text.charCodeAt(i))) {
1057
+ i += 1;
1058
+ }
1059
+ if (i >= length)
1060
+ return [text];
1061
+ const firstCode = text.charCodeAt(i);
1062
+ if (firstCode !== 0x7b && firstCode !== 0x5b) {
1063
+ return [text];
1064
+ }
1065
+ const candidates = [];
1066
+ const closeStack = [];
1067
+ while (i < length) {
1068
+ const start = i;
1069
+ const openCode = text.charCodeAt(i);
1070
+ if (openCode === 0x7b) {
1071
+ closeStack.push(0x7d);
1072
+ }
1073
+ else if (openCode === 0x5b) {
1074
+ closeStack.push(0x5d);
1075
+ }
1076
+ else {
1077
+ return [text];
1078
+ }
1079
+ i += 1;
1080
+ let inString = false;
1081
+ let escaped = false;
1082
+ while (i < length && closeStack.length > 0) {
1083
+ const code = text.charCodeAt(i);
1084
+ if (inString) {
1085
+ if (escaped) {
1086
+ escaped = false;
1087
+ }
1088
+ else if (code === 0x5c) {
1089
+ escaped = true;
1090
+ }
1091
+ else if (code === 0x22) {
1092
+ inString = false;
1093
+ }
1094
+ }
1095
+ else if (code === 0x22) {
1096
+ inString = true;
1097
+ }
1098
+ else if (code === 0x7b) {
1099
+ closeStack.push(0x7d);
1100
+ }
1101
+ else if (code === 0x5b) {
1102
+ closeStack.push(0x5d);
1103
+ }
1104
+ else if (code === 0x7d || code === 0x5d) {
1105
+ if (closeStack[closeStack.length - 1] !== code) {
1106
+ return [text];
1107
+ }
1108
+ closeStack.pop();
1109
+ }
1110
+ i += 1;
1111
+ }
1112
+ if (closeStack.length !== 0 || inString) {
1113
+ return [text];
1114
+ }
1115
+ candidates.push(text.slice(start, i));
1116
+ const wsStart = i;
1117
+ while (i < length && isJsonWhitespaceCode(text.charCodeAt(i))) {
1118
+ i += 1;
1119
+ }
1120
+ if (i < length && i === wsStart) {
1121
+ return [text];
1122
+ }
1123
+ }
1124
+ if (candidates.length < 2) {
1125
+ return [text];
1126
+ }
1127
+ for (const block of candidates) {
1128
+ if (!isValidJsonText(block)) {
1129
+ return [text];
1130
+ }
1131
+ }
1132
+ return candidates;
1133
+ }
1134
+ function isValidJsonOrConcatenatedJsonText(text) {
1135
+ if (isValidJsonText(text))
1136
+ return true;
1137
+ return splitConcatenatedJsonTextBlocks(text).length > 1;
1138
+ }
1139
+ function isTruncatedToolResult(entry, strippedContent) {
1140
+ if (hasTruncatedContentField(entry))
1141
+ return true;
1142
+ if (TOOL_OUTPUT_TRUNCATION_BANNER_PATTERN.test(strippedContent))
1143
+ return true;
1144
+ if (INLINE_TRUNCATION_MARKER_PATTERN.test(strippedContent) && !isValidJsonOrConcatenatedJsonText(strippedContent)) {
1145
+ return true;
1146
+ }
1147
+ return false;
1148
+ }
1149
+ function trimTrailingUrlPunctuation(rawUrl) {
1150
+ let end = rawUrl.length;
1151
+ while (end > 0) {
1152
+ const ch = rawUrl[end - 1];
1153
+ if (ch === '.' || ch === ',' || ch === ';' || ch === ')' || ch === ']') {
1154
+ end -= 1;
1155
+ }
1156
+ else {
1157
+ break;
1158
+ }
1159
+ }
1160
+ return rawUrl.slice(0, end);
1161
+ }
1162
+ function extractTruncatedOutputFileUrl(text) {
1163
+ const match = TRUNCATED_OUTPUT_FILE_URL_PATTERN.exec(text);
1164
+ if (!match)
987
1165
  return null;
988
- const entries = readTranscriptTailEntries(transcriptPath, options);
989
- // Prefer exact step_index match, then immediate neighbor (+1) if wrapper shifted index.
990
- for (const targetStep of [stepIdx, stepIdx + 1]) {
1166
+ const cleaned = trimTrailingUrlPunctuation(match[1]);
1167
+ return cleaned || null;
1168
+ }
1169
+ function parseLocalFileUrlPath(rawUrl) {
1170
+ let url;
1171
+ try {
1172
+ url = new URL(rawUrl);
1173
+ }
1174
+ catch {
1175
+ return null;
1176
+ }
1177
+ if (url.protocol !== 'file:' || url.hostname || url.search || url.hash) {
1178
+ return null;
1179
+ }
1180
+ try {
1181
+ const filePath = fileURLToPath(url);
1182
+ if (!filePath || !isAbsolute(filePath) || filePath.includes('\0')) {
1183
+ return null;
1184
+ }
1185
+ return filePath;
1186
+ }
1187
+ catch {
1188
+ return null;
1189
+ }
1190
+ }
1191
+ function systemGeneratedPrefixSegments(target, conversationId) {
1192
+ const segs = target.segments;
1193
+ if (segs.length === 4
1194
+ && segs[0] === conversationId
1195
+ && segs[1] === '.system_generated'
1196
+ && segs[2] === 'logs') {
1197
+ return [conversationId, '.system_generated'];
1198
+ }
1199
+ if (segs.length === 5
1200
+ && segs[0] === 'brain'
1201
+ && segs[1] === conversationId
1202
+ && segs[2] === '.system_generated'
1203
+ && segs[3] === 'logs') {
1204
+ return ['brain', conversationId, '.system_generated'];
1205
+ }
1206
+ return null;
1207
+ }
1208
+ function resolveSiblingFullTranscriptTarget(baseTarget, options) {
1209
+ if (baseTarget.segments[baseTarget.segments.length - 1] !== 'transcript.jsonl') {
1210
+ return null;
1211
+ }
1212
+ const baseDir = dirname(baseTarget.canonicalPath);
1213
+ const candidatePath = join(baseDir, 'transcript_full.jsonl');
1214
+ const fullTarget = resolveAuthorizedTranscriptTarget(candidatePath, options);
1215
+ if (!fullTarget)
1216
+ return null;
1217
+ if (fullTarget.canonicalRoot !== baseTarget.canonicalRoot)
1218
+ return null;
1219
+ if (dirname(fullTarget.canonicalPath) !== baseDir)
1220
+ return null;
1221
+ return fullTarget;
1222
+ }
1223
+ function resolveAuthorizedStepOutputTarget(baseTarget, conversationId, candidatePath) {
1224
+ if (!candidatePath || !isAbsolute(candidatePath) || candidatePath.includes('\0')) {
1225
+ return null;
1226
+ }
1227
+ const sysGenSegments = systemGeneratedPrefixSegments(baseTarget, conversationId);
1228
+ if (!sysGenSegments)
1229
+ return null;
1230
+ const stepsDirRaw = join(baseTarget.canonicalRoot, ...sysGenSegments, 'steps');
1231
+ try {
1232
+ const stepsDirStat = lstatSync(stepsDirRaw);
1233
+ if (stepsDirStat.isSymbolicLink() || !stepsDirStat.isDirectory())
1234
+ return null;
1235
+ const stepsDir = realpathSync(stepsDirRaw);
1236
+ if (stepsDir !== stepsDirRaw || !isStrictDescendantPath(baseTarget.canonicalRoot, stepsDir)) {
1237
+ return null;
1238
+ }
1239
+ const candidateParentStat = lstatSync(dirname(candidatePath));
1240
+ if (candidateParentStat.isSymbolicLink() || !candidateParentStat.isDirectory())
1241
+ return null;
1242
+ const candidateStat = lstatSync(candidatePath);
1243
+ if (candidateStat.isSymbolicLink() || !candidateStat.isFile())
1244
+ return null;
1245
+ const canonicalFile = realpathSync(candidatePath);
1246
+ if (!isStrictDescendantPath(stepsDir, canonicalFile))
1247
+ return null;
1248
+ const relFromSteps = relative(stepsDir, canonicalFile).split(sep);
1249
+ if (relFromSteps.length !== 2 || !/^\d+$/u.test(relFromSteps[0]) || relFromSteps[1] !== 'output.txt') {
1250
+ return null;
1251
+ }
1252
+ if (!verifyNoSymlinkPathUnderRoot(baseTarget.canonicalRoot, canonicalFile).ok) {
1253
+ return null;
1254
+ }
1255
+ return {
1256
+ canonicalRoot: baseTarget.canonicalRoot,
1257
+ canonicalPath: canonicalFile,
1258
+ segments: [...sysGenSegments, 'steps', relFromSteps[0], 'output.txt'],
1259
+ };
1260
+ }
1261
+ catch {
1262
+ return null;
1263
+ }
1264
+ }
1265
+ function findToolEntryInTranscript(entries, stepCandidates, toolUseId) {
1266
+ const normalizedToolUseId = typeof toolUseId === 'string' && toolUseId.trim() ? toolUseId.trim() : null;
1267
+ for (const targetStep of stepCandidates) {
1268
+ if (normalizedToolUseId !== null) {
1269
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
1270
+ const entry = entries[index];
1271
+ if (entry.step_index !== targetStep)
1272
+ continue;
1273
+ if (entry.type === 'USER_INPUT' || entry.type === 'PLANNER_RESPONSE')
1274
+ continue;
1275
+ if (typeof entry.content !== 'string' || !entry.content.trim())
1276
+ continue;
1277
+ if (entryToolUseId(entry) === normalizedToolUseId)
1278
+ return entry;
1279
+ }
1280
+ }
991
1281
  for (let index = entries.length - 1; index >= 0; index -= 1) {
992
1282
  const entry = entries[index];
993
1283
  if (entry.step_index !== targetStep)
@@ -996,11 +1286,143 @@ export function extractToolResultFromTranscript(transcriptPath, stepIdx, options
996
1286
  continue;
997
1287
  if (typeof entry.content !== 'string' || !entry.content.trim())
998
1288
  continue;
999
- return stripToolTimestampHeader(entry.content);
1289
+ return entry;
1290
+ }
1291
+ }
1292
+ if (normalizedToolUseId !== null) {
1293
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
1294
+ const entry = entries[index];
1295
+ if (entry.type === 'USER_INPUT' || entry.type === 'PLANNER_RESPONSE')
1296
+ continue;
1297
+ if (typeof entry.content !== 'string' || !entry.content.trim())
1298
+ continue;
1299
+ if (entryToolUseId(entry) === normalizedToolUseId)
1300
+ return entry;
1000
1301
  }
1001
1302
  }
1002
1303
  return null;
1003
1304
  }
1305
+ function readStepOutputFallback(baseTarget, conversationId, referenceTexts, candidateSteps, options) {
1306
+ let explicitUrl = null;
1307
+ for (const text of referenceTexts) {
1308
+ const found = extractTruncatedOutputFileUrl(text);
1309
+ if (found) {
1310
+ explicitUrl = found;
1311
+ break;
1312
+ }
1313
+ }
1314
+ const readTarget = (stepTarget) => {
1315
+ const raw = readTailViaKernelOpenat(stepTarget.canonicalRoot, stepTarget.segments, TRANSCRIPT_TOOL_RESULT_MAX_BYTES, {
1316
+ openatHelperBinary: options.openatHelperBinary,
1317
+ platform: options.platform,
1318
+ mode: 'full',
1319
+ });
1320
+ if (raw === null || raw.length === 0)
1321
+ return null;
1322
+ const decoded = raw.toString('utf8');
1323
+ const stripped = stripToolTimestampHeader(decoded);
1324
+ if (!stripped)
1325
+ return null;
1326
+ if (Buffer.byteLength(stripped, 'utf8') > TRANSCRIPT_TOOL_RESULT_MAX_BYTES)
1327
+ return null;
1328
+ if (isTruncatedToolResult({ content: decoded }, stripped))
1329
+ return null;
1330
+ return stripped;
1331
+ };
1332
+ if (explicitUrl !== null) {
1333
+ const filePath = parseLocalFileUrlPath(explicitUrl);
1334
+ if (!filePath)
1335
+ return null;
1336
+ const stepTarget = resolveAuthorizedStepOutputTarget(baseTarget, conversationId, filePath);
1337
+ if (!stepTarget)
1338
+ return null;
1339
+ return readTarget(stepTarget);
1340
+ }
1341
+ const sysGenSegments = systemGeneratedPrefixSegments(baseTarget, conversationId);
1342
+ if (!sysGenSegments)
1343
+ return null;
1344
+ const stepsDir = join(baseTarget.canonicalRoot, ...sysGenSegments, 'steps');
1345
+ const seenSteps = new Set();
1346
+ for (const stepNum of candidateSteps) {
1347
+ if (!Number.isSafeInteger(stepNum) || stepNum < 0 || seenSteps.has(stepNum))
1348
+ continue;
1349
+ seenSteps.add(stepNum);
1350
+ const candidatePath = join(stepsDir, String(stepNum), 'output.txt');
1351
+ const stepTarget = resolveAuthorizedStepOutputTarget(baseTarget, conversationId, candidatePath);
1352
+ if (!stepTarget)
1353
+ continue;
1354
+ const recovered = readTarget(stepTarget);
1355
+ if (recovered !== null)
1356
+ return recovered;
1357
+ }
1358
+ return null;
1359
+ }
1360
+ export function extractToolResultFromTranscript(transcriptPath, stepIdx, options) {
1361
+ const hasStepIdx = typeof stepIdx === 'number' && Number.isSafeInteger(stepIdx);
1362
+ const hintToolUseId = typeof options?.toolUseId === 'string' && options.toolUseId.trim()
1363
+ ? options.toolUseId.trim()
1364
+ : undefined;
1365
+ if (!hasStepIdx && !hintToolUseId)
1366
+ return null;
1367
+ const baseTarget = resolveAuthorizedTranscriptTarget(transcriptPath, options);
1368
+ if (!baseTarget || !options)
1369
+ return null;
1370
+ const conversationId = options.conversationId.trim();
1371
+ const baseEntries = readTranscriptEntriesFromTarget(baseTarget, options, TRANSCRIPT_TAIL_MAX_BYTES);
1372
+ // Prefer exact step_index match, then immediate neighbor (+1) if wrapper shifted index.
1373
+ const stepCandidates = hasStepIdx ? [stepIdx, stepIdx + 1] : [];
1374
+ const matchedEntry = findToolEntryInTranscript(baseEntries, stepCandidates, hintToolUseId);
1375
+ if (!matchedEntry || typeof matchedEntry.content !== 'string')
1376
+ return null;
1377
+ const baseStripped = stripToolTimestampHeader(matchedEntry.content);
1378
+ if (!baseStripped)
1379
+ return null;
1380
+ if (!isTruncatedToolResult(matchedEntry, baseStripped)) {
1381
+ return Buffer.byteLength(baseStripped, 'utf8') <= TRANSCRIPT_TOOL_RESULT_MAX_BYTES
1382
+ ? baseStripped
1383
+ : null;
1384
+ }
1385
+ const matchedStep = typeof matchedEntry.step_index === 'number' && Number.isSafeInteger(matchedEntry.step_index)
1386
+ ? matchedEntry.step_index
1387
+ : null;
1388
+ const effectiveStepCandidates = [
1389
+ ...(matchedStep !== null ? [matchedStep] : []),
1390
+ ...stepCandidates.filter((step) => step !== matchedStep),
1391
+ ];
1392
+ const effectiveToolUseId = entryToolUseId(matchedEntry) ?? hintToolUseId;
1393
+ // 1. Prefer sibling `transcript_full.jsonl` in the exact same authorized logs directory.
1394
+ let fullStripped = null;
1395
+ const fullTarget = resolveSiblingFullTranscriptTarget(baseTarget, options);
1396
+ if (fullTarget) {
1397
+ const fullEntries = readTranscriptEntriesFromTarget(fullTarget, options, TRANSCRIPT_FULL_TAIL_MAX_BYTES);
1398
+ const fullEntry = findToolEntryInTranscript(fullEntries, effectiveStepCandidates, effectiveToolUseId);
1399
+ if (fullEntry && typeof fullEntry.content === 'string') {
1400
+ const candidateStripped = stripToolTimestampHeader(fullEntry.content);
1401
+ if (candidateStripped) {
1402
+ if (!isTruncatedToolResult(fullEntry, candidateStripped)) {
1403
+ return Buffer.byteLength(candidateStripped, 'utf8') <= TRANSCRIPT_TOOL_RESULT_MAX_BYTES
1404
+ ? candidateStripped
1405
+ : null;
1406
+ }
1407
+ fullStripped = candidateStripped;
1408
+ }
1409
+ }
1410
+ }
1411
+ // 2. Fallback to authorized `<conversation>/.system_generated/steps/<n>/output.txt`
1412
+ // (strictly confined by realpath + no-symlink + Linux openat2 RESOLVE_BENEATH).
1413
+ const referenceTexts = fullStripped !== null ? [fullStripped, baseStripped] : [baseStripped];
1414
+ return readStepOutputFallback(baseTarget, conversationId, referenceTexts, effectiveStepCandidates, options);
1415
+ }
1416
+ /**
1417
+ * Extracts a tool result from the authorized transcript / step output and restores
1418
+ * whitespace/newline-concatenated MCP JSON text blocks into individual text block strings.
1419
+ */
1420
+ export function extractToolResultTextBlocksFromTranscript(transcriptPath, stepIdx, options) {
1421
+ const extracted = extractToolResultFromTranscript(transcriptPath, stepIdx, options);
1422
+ if (extracted === null)
1423
+ return null;
1424
+ return splitConcatenatedJsonTextBlocks(extracted);
1425
+ }
1004
1426
  // ---- Turn state persistence & exclusive lock ----
1005
1427
  function turnDirectory(env) {
1006
1428
  return env.BRAINBASE_ANTIGRAVITY_JUDGMENT_TURN_DIR
@@ -1348,17 +1770,24 @@ function extractHostMessages(output) {
1348
1770
  * the header binds it to the current `turn_id` and explicitly supersedes earlier turns.
1349
1771
  */
1350
1772
  function buildSystemMessageStep(turnId, additionalContext, userMarkdown) {
1351
- if (!additionalContext && !userMarkdown)
1773
+ const normalizedContext = typeof additionalContext === 'string' && additionalContext.trim()
1774
+ ? additionalContext.trim()
1775
+ : undefined;
1776
+ const normalizedMarkdown = typeof userMarkdown === 'string' && userMarkdown.trim()
1777
+ ? userMarkdown.trim()
1778
+ : undefined;
1779
+ if (!normalizedContext && !normalizedMarkdown)
1352
1780
  return null;
1353
1781
  const guardHeader = [
1354
1782
  `[Brainbase Judgment Turn: ${turnId}]`,
1355
1783
  `※この判断契約・先頭監査行は当ターン(${turnId})のみ有効です。過去のターンに注入された旧ターンの判断契約・先頭監査行は上書きされ無効です。`,
1356
1784
  ].join('\n');
1357
- const modelText = additionalContext ? `${guardHeader}\n\n${additionalContext}` : '';
1785
+ const modelBody = normalizedContext ?? normalizedMarkdown;
1786
+ const modelText = modelBody ? `${guardHeader}\n\n${modelBody}` : '';
1358
1787
  return {
1359
1788
  systemMessage: {
1360
1789
  systemMessage: modelText,
1361
- ...(userMarkdown ? { metadata: { user_markdown: userMarkdown } } : {}),
1790
+ ...(normalizedMarkdown ? { metadata: { user_markdown: normalizedMarkdown } } : {}),
1362
1791
  },
1363
1792
  };
1364
1793
  }
@@ -1727,10 +2156,11 @@ async function handlePostToolUse(payload, conversationId, context) {
1727
2156
  let errorField;
1728
2157
  if (isBrainbase) {
1729
2158
  toolInput = normalizedToolInput(rawName, normalizedName, toolCall?.args);
1730
- const transcriptText = extractToolResultFromTranscript(payload.transcriptPath, payload.stepIdx, transcriptOpts);
1731
- if (transcriptText !== null) {
2159
+ const toolCallId = typeof toolCall?.id === 'string' && toolCall.id.trim() ? toolCall.id.trim() : undefined;
2160
+ const transcriptBlocks = extractToolResultTextBlocksFromTranscript(payload.transcriptPath, payload.stepIdx, toolCallId ? { ...transcriptOpts, toolUseId: toolCallId } : transcriptOpts);
2161
+ if (transcriptBlocks !== null) {
1732
2162
  toolResponse = {
1733
- content: [{ type: 'text', text: transcriptText }],
2163
+ content: transcriptBlocks.map((text) => ({ type: 'text', text })),
1734
2164
  isError: hasError,
1735
2165
  };
1736
2166
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unson/brainbase-mcp",
3
- "version": "0.51.0",
3
+ "version": "0.51.2",
4
4
  "description": "Local-first Brainbase judgment OS that lets supported AI agents reuse a user's approved goals, priorities, decisions, and judgment criteria.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -669,5 +669,5 @@
669
669
  "url": "https://github.com/Unson-LLC/brainbase/issues"
670
670
  },
671
671
  "homepage": "https://github.com/Unson-LLC/brainbase#readme",
672
- "gitHead": "8b9acad360928fd94db972da5861ea90044ea481"
672
+ "gitHead": "4a7abf68a2e2f8da4b59d3f0c3efd7c5098eb64b"
673
673
  }