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

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