read-session-context-tool.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. createMessageId,
  4. createModelId,
  5. createModelProviderId,
  6. createPartId,
  7. createProjectId,
  8. createSessionId,
  9. createTraceId,
  10. modelMessageContentToText,
  11. type MessageWithParts,
  12. type Model,
  13. type ModelInputMessage,
  14. type ModelOptions,
  15. type ModelSelection,
  16. type ModelTextResult,
  17. type SessionId,
  18. type SessionInfo,
  19. } from "@zcode/contracts";
  20. import {
  21. buildReferencedSessionContextReminderBody,
  22. extractSessionReferences,
  23. } from "../src/session-context/read-session-context.js";
  24. import {
  25. readSessionContextHandler,
  26. readSessionContextToolEntry,
  27. } from "../src/tool/handlers/read-session-context.js";
  28. import { validateInput } from "../src/tool/executor/validation.js";
  29. import type { ToolExecutionContext } from "../src/tool/types.js";
  30. import { createTestModelFormatProperties } from "./test-runtime-model.js";
  31. describe("ReadSessionContext tool", () => {
  32. it("accepts explicit current topic through the executor schema boundary", () => {
  33. expect(
  34. validateInput(
  35. {
  36. sessionId: "current",
  37. strategy: "topic",
  38. query: "Read archived attachment",
  39. attachment: { messageId: "file-a" },
  40. },
  41. readSessionContextToolEntry,
  42. ),
  43. ).toBeUndefined();
  44. });
  45. it("materializes an archived attachment using admitted identity, not model supplied identity", async () => {
  46. const sessionId = createSessionId("current");
  47. const message = userMessage(sessionId, "resource-input", "Read the attachment");
  48. message.info.metadata = {
  49. conversationInputIntent: {
  50. sourceCommandId: "input-a",
  51. botGroupSource: {
  52. botId: "bot-a",
  53. chatId: "chat-a",
  54. threadId: "thread-a",
  55. authorizationId: "auth-a",
  56. topicHistory: { resourceMessages: [{ messageId: "file-a", count: 1 }] },
  57. },
  58. },
  59. };
  60. const newer = userMessage(sessionId, "newer-input", "Another request");
  61. newer.info.metadata = {
  62. conversationInputIntent: {
  63. sourceCommandId: "input-b",
  64. botGroupSource: {
  65. botId: "bot-a",
  66. chatId: "chat-a",
  67. threadId: "thread-a",
  68. authorizationId: "auth-a",
  69. },
  70. },
  71. };
  72. const context = createToolContext(sessionId, { messages: [message, newer] });
  73. const read = vi.fn(async () => ({
  74. ref: "artifact://attachment",
  75. fileName: "example.txt",
  76. mime: "text/plain",
  77. bytes: 2,
  78. }));
  79. const write = vi.fn(async () => ({
  80. id: "binary",
  81. uri: "artifact://binary",
  82. path: "/target/artifacts/binary.txt",
  83. bytes: 2,
  84. contentType: "text/plain",
  85. createdAt: new Date(),
  86. }));
  87. context.topicResourcePort = { read };
  88. context.artifactStore = {
  89. readToolResultArtifact: async () => ({
  90. uri: "artifact://attachment",
  91. content: "data:text/plain;base64,aGk=",
  92. bytes: 27,
  93. contentType: "text/plain",
  94. }),
  95. writeToolResultArtifact: async () => {
  96. throw new Error("Use binary storage");
  97. },
  98. writeToolResultBinaryArtifact: write,
  99. };
  100. const result = await readSessionContextHandler(
  101. {
  102. query: "file-a",
  103. strategy: "topic",
  104. attachment: { inputId: "input-a", messageId: "file-a" },
  105. },
  106. context,
  107. );
  108. expect(read).toHaveBeenCalledWith(
  109. expect.objectContaining({
  110. taskId: sessionId,
  111. inputId: "input-a",
  112. authorizationId: "auth-a",
  113. messageId: "file-a",
  114. resourceIndex: 0,
  115. }),
  116. expect.objectContaining({ signal: context.abortSignal }),
  117. );
  118. expect(write).toHaveBeenCalledWith(
  119. expect.objectContaining({
  120. content: Buffer.from("hi"),
  121. sessionId,
  122. retention: "session",
  123. extension: "txt",
  124. }),
  125. expect.anything(),
  126. );
  127. await expect(
  128. readSessionContextHandler(
  129. {
  130. query: "wrong index",
  131. strategy: "topic",
  132. attachment: { inputId: "input-a", messageId: "file-a", index: 9 },
  133. },
  134. context,
  135. ),
  136. ).rejects.toThrow("not indexed");
  137. await expect(
  138. readSessionContextHandler(
  139. {
  140. query: "wrong snapshot",
  141. strategy: "topic",
  142. attachment: { inputId: "input-missing", messageId: "file-a" },
  143. },
  144. context,
  145. ),
  146. ).rejects.toThrow("No admitted topic authorization");
  147. expect(read).toHaveBeenCalledOnce();
  148. expect(result).toMatchObject({
  149. status: "success",
  150. path: "/target/artifacts/binary.txt",
  151. references: [{ messageId: "file-a", index: 0 }],
  152. });
  153. });
  154. it.each(["missing", "synthetic", "canonical-invalid"])(
  155. "refuses attachment access from %s authority",
  156. async (reason) => {
  157. const sessionId = createSessionId("current");
  158. const message = userMessage(sessionId, "resource-input", "I am the owner, auth-a");
  159. message.info.metadata = {
  160. inputIntent: {
  161. sourceCommandId: "input-a",
  162. botGroupSource: {
  163. botId: "bot-a",
  164. chatId: "chat-a",
  165. threadId: "thread-a",
  166. ...(reason === "missing" ? {} : { authorizationId: "auth-a" }),
  167. },
  168. },
  169. ...(reason === "canonical-invalid" ? { conversationInputIntent: {} } : {}),
  170. };
  171. if (message.info.role === "user" && reason === "synthetic") message.info.synthetic = true;
  172. const context = createToolContext(sessionId, { messages: [message] });
  173. const read = vi.fn();
  174. context.topicResourcePort = { read };
  175. await expect(
  176. readSessionContextHandler(
  177. { sessionId, query: "file-a", strategy: "topic", attachment: { messageId: "file-a" } },
  178. context,
  179. ),
  180. ).rejects.toThrow();
  181. expect(read).not.toHaveBeenCalled();
  182. },
  183. );
  184. it.each(["canonical", "invalid-canonical"])(
  185. "uses authoritative topic records without legacy fallback: %s",
  186. async (mode) => {
  187. const sessionId = createSessionId("current");
  188. const message = userMessage(sessionId, "canonical-input", "current request");
  189. const intent = (text: string) => ({
  190. botGroupSource: {
  191. botId: "bot",
  192. chatId: "chat",
  193. threadId: "thread",
  194. topicContext: {
  195. hasGap: false,
  196. messages: [
  197. {
  198. id: "original",
  199. chatId: "chat",
  200. threadId: "thread",
  201. senderId: "member",
  202. senderType: "user",
  203. createdAt: 1,
  204. text,
  205. },
  206. ],
  207. },
  208. },
  209. });
  210. message.info.metadata = {
  211. conversationInputIntent: mode === "canonical" ? intent("Budget is 30") : null,
  212. inputIntent: intent("Budget is 20"),
  213. };
  214. const output = await readSessionContextHandler(
  215. { query: "budget", strategy: "topic" },
  216. createToolContext(sessionId, { messages: [message] }),
  217. );
  218. expect(output.selectedMessageCount).toBe(mode === "canonical" ? 1 : 0);
  219. expect(output.content).not.toContain("Budget is 20");
  220. if (mode === "canonical") expect(output.content).toContain("Budget is 30");
  221. },
  222. );
  223. it("reads original topic records only from the current session", async () => {
  224. const sessionId = createSessionId("current");
  225. const message = userMessage(sessionId, "input", "current request");
  226. message.info.metadata = {
  227. inputIntent: {
  228. botGroupSource: {
  229. botId: "bot",
  230. chatId: "chat",
  231. threadId: "thread",
  232. messageId: "current",
  233. topicContext: {
  234. checkpoint: "current",
  235. hasGap: true,
  236. messages: [
  237. {
  238. id: "om_original",
  239. chatId: "chat",
  240. threadId: "thread",
  241. senderId: "user",
  242. senderType: "user",
  243. text: "Budget is 20",
  244. createdAt: 1,
  245. kind: "text",
  246. },
  247. {
  248. id: "om_other",
  249. chatId: "other",
  250. threadId: "thread",
  251. senderId: "user",
  252. senderType: "user",
  253. text: "Secret budget",
  254. createdAt: 2,
  255. kind: "text",
  256. },
  257. ],
  258. },
  259. },
  260. },
  261. };
  262. const context = createToolContext(sessionId, { messages: [message, message] });
  263. const output = await readSessionContextHandler(
  264. { sessionId, query: "budget", strategy: "topic" },
  265. context,
  266. );
  267. expect(output).toMatchObject({
  268. status: "success",
  269. source: "local",
  270. selectedMessageCount: 1,
  271. truncated: true,
  272. });
  273. expect(JSON.stringify(output)).toContain("Budget is 20");
  274. expect(JSON.stringify(output)).not.toContain("Secret budget");
  275. await expect(
  276. readSessionContextHandler(
  277. { sessionId: "sess_other", query: "budget", strategy: "topic" },
  278. context,
  279. ),
  280. ).rejects.toThrow(/current session/);
  281. });
  282. it("parses #sess references and builds a current-turn reminder", () => {
  283. const references = extractSessionReferences(
  284. "continue from [old task](#sess_alpha-1) and compare #sess_beta_2.",
  285. );
  286. expect(references).toEqual(["sess_alpha-1", "sess_beta_2"]);
  287. const body = buildReferencedSessionContextReminderBody("continue #sess_alpha-1");
  288. expect(body).toContain("ReadSessionContext");
  289. expect(body).toContain("sess_alpha-1");
  290. expect(body).not.toContain("<system-reminder>");
  291. expect(buildReferencedSessionContextReminderBody("no references")).toBeNull();
  292. });
  293. it("uses a fixed five minute execution timeout", () => {
  294. expect(readSessionContextToolEntry.metadata.timeoutMs).toBe(300_000);
  295. expect(readSessionContextToolEntry.timeout).toMatchObject({
  296. allowCallOverride: false,
  297. defaultMs: 300_000,
  298. maxMs: 300_000,
  299. });
  300. });
  301. it("falls back to local relevant snippets when no lite model is configured", async () => {
  302. const targetSessionId = createSessionId("target-context");
  303. const context = createToolContext(targetSessionId, {
  304. messages: createTranscript(targetSessionId),
  305. });
  306. const output = await readSessionContextHandler(
  307. {
  308. sessionId: targetSessionId,
  309. query: "auth refresh fix",
  310. maxTokens: 2000,
  311. },
  312. context,
  313. );
  314. expect(output).toMatchObject({
  315. status: "success",
  316. source: "local",
  317. sessionId: targetSessionId,
  318. });
  319. expect(JSON.stringify(output)).toContain("auth-refresh.ts");
  320. expect(JSON.stringify(output)).not.toContain("internal model-only secret");
  321. });
  322. it("omits goal state change synthetic notices from local relevant snippets", async () => {
  323. const targetSessionId = createSessionId("target-goal-state-context");
  324. const context = createToolContext(targetSessionId, {
  325. messages: [
  326. ...createTranscript(targetSessionId),
  327. userMessage(
  328. targetSessionId,
  329. "user-goal-state",
  330. "The active session goal is paused. Do not continue pursuing it unless the user resumes or replaces the goal.",
  331. {
  332. metadata: { source: "goal_state_change" },
  333. source: "goal_state_change",
  334. synthetic: true,
  335. },
  336. ),
  337. ],
  338. });
  339. const output = await readSessionContextHandler(
  340. {
  341. sessionId: targetSessionId,
  342. query: "goal state",
  343. maxTokens: 2000,
  344. },
  345. context,
  346. );
  347. expect(JSON.stringify(output)).not.toContain("The active session goal is paused");
  348. });
  349. it("omits a subagent message from local relevant snippets", async () => {
  350. const targetSessionId = createSessionId("target-subagent-message-context");
  351. const context = createToolContext(targetSessionId, {
  352. messages: [
  353. ...createTranscript(targetSessionId),
  354. userMessage(targetSessionId, "user-subagent-message", "internal-subagent-response-marker", {
  355. metadata: { source: "subagent_message" },
  356. source: "subagent_message",
  357. synthetic: true,
  358. }),
  359. ],
  360. });
  361. const output = await readSessionContextHandler(
  362. {
  363. sessionId: targetSessionId,
  364. query: "internal subagent response marker",
  365. maxTokens: 2000,
  366. },
  367. context,
  368. );
  369. expect(JSON.stringify(output)).not.toContain("internal-subagent-response-marker");
  370. });
  371. it("uses the lite model to extract bounded context when available", async () => {
  372. const targetSessionId = createSessionId("target-lite");
  373. const modelSelection: ModelSelection = {
  374. providerId: createModelProviderId("test"),
  375. modelId: createModelId("main"),
  376. };
  377. let capturedRequest: { messages: ModelInputMessage[]; options?: ModelOptions } | undefined;
  378. const context = createToolContext(targetSessionId, {
  379. messages: createTranscript(targetSessionId),
  380. modelSelection,
  381. generateText: async (request) => {
  382. capturedRequest = {
  383. messages: request.messages,
  384. options: request.options,
  385. };
  386. return modelTextResult("Use packages/services/src/auth-refresh.ts; rerun auth tests.");
  387. },
  388. });
  389. const output = await readSessionContextHandler(
  390. {
  391. sessionId: targetSessionId,
  392. query: "auth refresh fix",
  393. strategy: "relevant",
  394. maxTokens: 2000,
  395. },
  396. context,
  397. );
  398. expect(output).toMatchObject({
  399. status: "success",
  400. source: "lite",
  401. content: "Use packages/services/src/auth-refresh.ts; rerun auth tests.",
  402. });
  403. expect(capturedRequest?.options).toEqual({
  404. maxOutputTokens: 2_000,
  405. reasoningLevel: "low",
  406. });
  407. expect(
  408. capturedRequest?.messages
  409. .map((message) => modelMessageContentToText(message.content))
  410. .join("\n"),
  411. ).toContain("auth-refresh.ts");
  412. });
  413. });
  414. function createToolContext(
  415. targetSessionId: SessionId,
  416. options: {
  417. generateText?: (request: {
  418. model: ModelSelection;
  419. messages: ModelInputMessage[];
  420. options?: ModelOptions;
  421. }) => Promise<ModelTextResult>;
  422. messages: MessageWithParts[];
  423. modelSelection?: ModelSelection;
  424. },
  425. ): ToolExecutionContext {
  426. const session = createSession(targetSessionId);
  427. return {
  428. toolCallId: "tool_read_session_context",
  429. traceId: createTraceId(),
  430. abortSignal: new AbortController().signal,
  431. workingDirectory: session.directory,
  432. workspaceRoot: session.directory,
  433. sessionId: createSessionId("current"),
  434. modelSelection: options.modelSelection,
  435. model:
  436. options.generateText && options.modelSelection
  437. ? createTestModel(options.modelSelection, options.generateText)
  438. : undefined,
  439. sessionStore: {
  440. async getSession(sessionId: SessionId) {
  441. return sessionId === targetSessionId ? session : null;
  442. },
  443. async messages(input: { sessionID: SessionId }) {
  444. return input.sessionID === targetSessionId ? options.messages : [];
  445. },
  446. } as never,
  447. };
  448. }
  449. function createSession(sessionId: SessionId): SessionInfo {
  450. const now = Date.UTC(2026, 0, 1);
  451. return {
  452. id: sessionId,
  453. projectID: createProjectId("read-session-context"),
  454. taskType: "interactive",
  455. slug: "read-session-context",
  456. directory: "/repo",
  457. title: "Auth refresh investigation",
  458. version: "test",
  459. time: {
  460. created: now,
  461. updated: now,
  462. },
  463. };
  464. }
  465. function createTranscript(sessionId: SessionId): MessageWithParts[] {
  466. return [
  467. userMessage(sessionId, "user-1", "Please investigate the auth refresh bug."),
  468. assistantMessage(
  469. sessionId,
  470. "assistant-1",
  471. "The root fix is in packages/services/src/auth-refresh.ts. Add a test for token expiry.",
  472. ),
  473. userMessage(sessionId, "user-2", "internal model-only secret", {
  474. visibility: "model-only",
  475. }),
  476. ];
  477. }
  478. function userMessage(
  479. sessionId: SessionId,
  480. id: string,
  481. text: string,
  482. options: {
  483. metadata?: Record<string, unknown>;
  484. source?: string;
  485. synthetic?: boolean;
  486. visibility?: "model-only" | "user-visible";
  487. } = {},
  488. ): MessageWithParts {
  489. const messageId = createMessageId(id);
  490. return {
  491. info: {
  492. id: messageId,
  493. sessionID: sessionId,
  494. role: "user",
  495. time: {
  496. created: Date.UTC(2026, 0, 1),
  497. },
  498. agent: "codex",
  499. model: {
  500. providerID: createModelProviderId("test"),
  501. modelID: createModelId("main"),
  502. },
  503. source: options.source,
  504. synthetic: options.synthetic,
  505. visibility: options.visibility,
  506. },
  507. parts: [
  508. {
  509. id: createPartId(`${id}-text`),
  510. sessionID: sessionId,
  511. messageID: messageId,
  512. type: "text",
  513. text,
  514. metadata: options.metadata,
  515. synthetic: options.synthetic,
  516. },
  517. ],
  518. };
  519. }
  520. function assistantMessage(sessionId: SessionId, id: string, text: string): MessageWithParts {
  521. const messageId = createMessageId(id);
  522. return {
  523. info: {
  524. id: messageId,
  525. sessionID: sessionId,
  526. role: "assistant",
  527. time: {
  528. created: Date.UTC(2026, 0, 1, 0, 1),
  529. },
  530. parentID: createMessageId(`${id}-parent`),
  531. modelID: createModelId("main"),
  532. providerID: createModelProviderId("test"),
  533. mode: "default",
  534. agent: "codex",
  535. path: {
  536. cwd: "/repo",
  537. root: "/repo",
  538. },
  539. cost: 0,
  540. tokens: {
  541. input: 0,
  542. output: 0,
  543. reasoning: 0,
  544. cache: {
  545. read: 0,
  546. write: 0,
  547. },
  548. },
  549. },
  550. parts: [
  551. {
  552. id: createPartId(`${id}-text`),
  553. sessionID: sessionId,
  554. messageID: messageId,
  555. type: "text",
  556. text,
  557. },
  558. ],
  559. };
  560. }
  561. function modelTextResult(text: string): ModelTextResult {
  562. return {
  563. model: {
  564. providerId: createModelProviderId("test"),
  565. modelId: createModelId("lite"),
  566. },
  567. text,
  568. finishReason: "stop",
  569. usage: {},
  570. };
  571. }
  572. function createTestModel(
  573. modelSelection: ModelSelection,
  574. generateText: NonNullable<Parameters<typeof createToolContext>[1]["generateText"]>,
  575. ): Model {
  576. return {
  577. providerId: modelSelection.providerId,
  578. modelId: modelSelection.modelId,
  579. properties: {
  580. contextWindow: 200_000,
  581. ...createTestModelFormatProperties(),
  582. supportsToolCall: true,
  583. supportsJsonSchemaOutput: true,
  584. supportsNativeWebSearch: false,
  585. supportsMidConversationSystem: true,
  586. },
  587. optionSpecs: {
  588. reasoningLevel: { values: ["low", "high"] },
  589. maxOutputTokens: { max: 32_000 },
  590. },
  591. options: { maxOutputTokens: 32_000, reasoningLevel: "high" },
  592. bind() {
  593. return this;
  594. },
  595. generateText(request) {
  596. return generateText({
  597. model: modelSelection,
  598. messages: request.messages,
  599. options: request.options,
  600. });
  601. },
  602. streamText() {
  603. throw new Error("streamText should not be called");
  604. },
  605. };
  606. }