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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  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:
  378. | { model: ModelSelection; messages: ModelInputMessage[]; options?: ModelOptions }
  379. | undefined;
  380. const context = createToolContext(targetSessionId, {
  381. messages: createTranscript(targetSessionId),
  382. modelSelection,
  383. generateText: async (request) => {
  384. capturedRequest = {
  385. model: modelSelection,
  386. messages: request.messages,
  387. options: request.options,
  388. };
  389. return modelTextResult("Use packages/services/src/auth-refresh.ts; rerun auth tests.");
  390. },
  391. });
  392. const output = await readSessionContextHandler(
  393. {
  394. sessionId: targetSessionId,
  395. query: "auth refresh fix",
  396. strategy: "relevant",
  397. maxTokens: 2000,
  398. },
  399. context,
  400. );
  401. expect(output).toMatchObject({
  402. status: "success",
  403. source: "lite",
  404. content: "Use packages/services/src/auth-refresh.ts; rerun auth tests.",
  405. });
  406. expect(capturedRequest?.model).toEqual(modelSelection);
  407. expect(capturedRequest?.options).toEqual({
  408. maxOutputTokens: 2_000,
  409. reasoningLevel: "low",
  410. });
  411. expect(
  412. capturedRequest?.messages
  413. .map((message) => modelMessageContentToText(message.content))
  414. .join("\n"),
  415. ).toContain("auth-refresh.ts");
  416. });
  417. });
  418. function createToolContext(
  419. targetSessionId: SessionId,
  420. options: {
  421. generateText?: (request: {
  422. model: ModelSelection;
  423. messages: ModelInputMessage[];
  424. options?: ModelOptions;
  425. }) => Promise<ModelTextResult>;
  426. messages: MessageWithParts[];
  427. modelSelection?: ModelSelection;
  428. },
  429. ): ToolExecutionContext {
  430. const session = createSession(targetSessionId);
  431. return {
  432. toolCallId: "tool_read_session_context",
  433. traceId: createTraceId(),
  434. abortSignal: new AbortController().signal,
  435. workingDirectory: session.directory,
  436. workspaceRoot: session.directory,
  437. sessionId: createSessionId("current"),
  438. modelSelection: options.modelSelection,
  439. model:
  440. options.generateText && options.modelSelection
  441. ? createTestModel(options.modelSelection, options.generateText)
  442. : undefined,
  443. sessionStore: {
  444. async getSession(sessionId: SessionId) {
  445. return sessionId === targetSessionId ? session : null;
  446. },
  447. async messages(input: { sessionID: SessionId }) {
  448. return input.sessionID === targetSessionId ? options.messages : [];
  449. },
  450. } as never,
  451. };
  452. }
  453. function createSession(sessionId: SessionId): SessionInfo {
  454. const now = Date.UTC(2026, 0, 1);
  455. return {
  456. id: sessionId,
  457. projectID: createProjectId("read-session-context"),
  458. taskType: "interactive",
  459. slug: "read-session-context",
  460. directory: "/repo",
  461. title: "Auth refresh investigation",
  462. version: "test",
  463. time: {
  464. created: now,
  465. updated: now,
  466. },
  467. };
  468. }
  469. function createTranscript(sessionId: SessionId): MessageWithParts[] {
  470. return [
  471. userMessage(sessionId, "user-1", "Please investigate the auth refresh bug."),
  472. assistantMessage(
  473. sessionId,
  474. "assistant-1",
  475. "The root fix is in packages/services/src/auth-refresh.ts. Add a test for token expiry.",
  476. ),
  477. userMessage(sessionId, "user-2", "internal model-only secret", {
  478. visibility: "model-only",
  479. }),
  480. ];
  481. }
  482. function userMessage(
  483. sessionId: SessionId,
  484. id: string,
  485. text: string,
  486. options: {
  487. metadata?: Record<string, unknown>;
  488. source?: string;
  489. synthetic?: boolean;
  490. visibility?: "model-only" | "user-visible";
  491. } = {},
  492. ): MessageWithParts {
  493. const messageId = createMessageId(id);
  494. return {
  495. info: {
  496. id: messageId,
  497. sessionID: sessionId,
  498. role: "user",
  499. time: {
  500. created: Date.UTC(2026, 0, 1),
  501. },
  502. agent: "codex",
  503. model: {
  504. providerID: createModelProviderId("test"),
  505. modelID: createModelId("main"),
  506. },
  507. source: options.source,
  508. synthetic: options.synthetic,
  509. visibility: options.visibility,
  510. },
  511. parts: [
  512. {
  513. id: createPartId(`${id}-text`),
  514. sessionID: sessionId,
  515. messageID: messageId,
  516. type: "text",
  517. text,
  518. metadata: options.metadata,
  519. synthetic: options.synthetic,
  520. },
  521. ],
  522. };
  523. }
  524. function assistantMessage(sessionId: SessionId, id: string, text: string): MessageWithParts {
  525. const messageId = createMessageId(id);
  526. return {
  527. info: {
  528. id: messageId,
  529. sessionID: sessionId,
  530. role: "assistant",
  531. time: {
  532. created: Date.UTC(2026, 0, 1, 0, 1),
  533. },
  534. parentID: createMessageId(`${id}-parent`),
  535. modelID: createModelId("main"),
  536. providerID: createModelProviderId("test"),
  537. mode: "default",
  538. agent: "codex",
  539. path: {
  540. cwd: "/repo",
  541. root: "/repo",
  542. },
  543. cost: 0,
  544. tokens: {
  545. input: 0,
  546. output: 0,
  547. reasoning: 0,
  548. cache: {
  549. read: 0,
  550. write: 0,
  551. },
  552. },
  553. },
  554. parts: [
  555. {
  556. id: createPartId(`${id}-text`),
  557. sessionID: sessionId,
  558. messageID: messageId,
  559. type: "text",
  560. text,
  561. },
  562. ],
  563. };
  564. }
  565. function modelTextResult(text: string): ModelTextResult {
  566. return {
  567. model: {
  568. providerId: createModelProviderId("test"),
  569. modelId: createModelId("lite"),
  570. },
  571. text,
  572. finishReason: "stop",
  573. usage: {},
  574. };
  575. }
  576. function createTestModel(
  577. modelSelection: ModelSelection,
  578. generateText: NonNullable<Parameters<typeof createToolContext>[1]["generateText"]>,
  579. ): Model {
  580. return {
  581. providerId: modelSelection.providerId,
  582. modelId: modelSelection.modelId,
  583. properties: {
  584. contextWindow: 200_000,
  585. ...createTestModelFormatProperties(),
  586. supportsToolCall: true,
  587. supportsJsonSchemaOutput: true,
  588. supportsNativeWebSearch: false,
  589. supportsMidConversationSystem: true,
  590. },
  591. optionSpecs: {
  592. reasoningLevel: { values: ["low", "high"] },
  593. maxOutputTokens: { max: 32_000 },
  594. },
  595. options: { maxOutputTokens: 32_000, reasoningLevel: "high" },
  596. bind() {
  597. return this;
  598. },
  599. generateText(request) {
  600. return generateText({
  601. model: modelSelection,
  602. messages: request.messages,
  603. options: request.options,
  604. });
  605. },
  606. streamText() {
  607. throw new Error("streamText should not be called");
  608. },
  609. };
  610. }