write-tool-contract.test.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  1. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  2. import { mkdtemp, rm } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import {
  6. createFileSystemError,
  7. createRootTraceContext,
  8. createSessionId,
  9. createToolCallId,
  10. createTurnId,
  11. modelMessageContentToText,
  12. type FileSystemLineEndings,
  13. type FileSystemPort,
  14. type FileSystemReadTextRangeResult,
  15. type FileSystemReadTextResult,
  16. type FileSystemRevision,
  17. type FileSystemSearchFilesResult,
  18. type FileSystemSearchTextResult,
  19. type FileSystemStatResult,
  20. type FileSystemWriteTextRequest,
  21. type ModelMessageContent,
  22. type PermissionRuleset,
  23. } from "@zcode/contracts";
  24. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  25. import { createToolExecutor } from "../src/tool/executor.js";
  26. import { writeHandler, writeToolEntry } from "../src/tool/handlers/write.js";
  27. import { createReadFileStateKey } from "../src/tool/read-file-state.js";
  28. import { createToolRegistry } from "../src/tool/registry.js";
  29. import type { ReadFileStateMap, ToolExecutionContext } from "../src/tool/types.js";
  30. const RUN_WRITE_STRICT_CONTRACT = process.env.ZCODE_RUN_WRITE_STRICT_CONTRACT === "1";
  31. const describeWriteStrictContract = RUN_WRITE_STRICT_CONTRACT ? describe : describe.skip;
  32. const WRITE_STORAGE_SUFFIX =
  33. " (file state is current in your context \u2014 no need to Read it back)";
  34. const WRITE_USER_MODIFIED_NOTE = " The user modified your proposed content before accepting it.";
  35. let tmpDir: string;
  36. beforeEach(async () => {
  37. tmpDir = await mkdtemp(join(tmpdir(), "zcode-write-contract-"));
  38. });
  39. afterEach(async () => {
  40. await rm(tmpDir, { recursive: true, force: true });
  41. });
  42. describe("Write model-result harness", () => {
  43. it("returns executor modelContent and serialization for create results", async () => {
  44. const file = join(tmpDir, "nested", "created.txt");
  45. const fs = createMemoryFileSystem({});
  46. const result = await executeWrite(
  47. {
  48. file_path: file,
  49. content: "alpha\nbeta\n",
  50. },
  51. fs,
  52. );
  53. expect(result.success).toBe(true);
  54. expect(result.output).toEqual({
  55. type: "create",
  56. filePath: file,
  57. content: "alpha\nbeta\n",
  58. structuredPatch: [],
  59. originalFile: null,
  60. userModified: false,
  61. });
  62. expect(asModelText(result.modelContent)).toBe(
  63. `File created successfully at: ${file}${WRITE_STORAGE_SUFFIX}`,
  64. );
  65. expect(result.serialization?.content).toBe(
  66. `File created successfully at: ${file}${WRITE_STORAGE_SUFFIX}`,
  67. );
  68. expect(fs.files.get(file)).toBe("alpha\nbeta\n");
  69. expect(fs.readPaths).toEqual([file]);
  70. });
  71. it("documents update model content for existing nonempty files", async () => {
  72. const file = join(tmpDir, "existing.txt");
  73. const fs = createMemoryFileSystem({
  74. [file]: "old line\nkept line\n",
  75. });
  76. const context = contextWith(fs, {
  77. readFileState: createReadFileState(file, "old line\nkept line\n"),
  78. });
  79. const result = await writeForModel(
  80. {
  81. file_path: file,
  82. content: "new line\nkept line\n",
  83. },
  84. context,
  85. );
  86. expect(result.output).toMatchObject({
  87. type: "update",
  88. filePath: file,
  89. content: "new line\nkept line\n",
  90. originalFile: "old line\nkept line\n",
  91. userModified: false,
  92. });
  93. expect(result.output.structuredPatch[0]?.lines).toContain("-old line");
  94. expect(result.output.structuredPatch[0]?.lines).toContain("+new line");
  95. expect(asModelText(result.modelContent)).toBe(
  96. `The file ${file} has been updated successfully.${WRITE_STORAGE_SUFFIX}`,
  97. );
  98. expect(fs.files.get(file)).toBe("new line\nkept line\n");
  99. });
  100. it("adds Write performance attribution without exposing file content", async () => {
  101. const file = join(tmpDir, "perf-existing.txt");
  102. const fs = createMemoryFileSystem({
  103. [file]: "old line\n",
  104. });
  105. const context = contextWith(fs, {
  106. readFileState: createReadFileState(file, "old line\n"),
  107. });
  108. const result = await writeForModel(
  109. {
  110. file_path: file,
  111. content: "new line\nextra\n",
  112. },
  113. context,
  114. );
  115. expect(result.output).toMatchObject({
  116. type: "update",
  117. perf: {
  118. detail: {
  119. kind: "filesystem",
  120. filesystem: {
  121. readMs: expect.any(Number),
  122. writeMs: expect.any(Number),
  123. fileCount: 1,
  124. totalBytes: Buffer.byteLength("new line\nextra\n", "utf8"),
  125. maxFileBytes: Buffer.byteLength("new line\nextra\n", "utf8"),
  126. workspaceKind: "local",
  127. },
  128. },
  129. },
  130. });
  131. expect(JSON.stringify((result.output as any).perf)).not.toContain(file);
  132. expect(JSON.stringify((result.output as any).perf)).not.toContain("new line");
  133. });
  134. it("accepts a normalized read-state key when the stored display path differs", async () => {
  135. const file = join(tmpDir, "existing-normalized-key.txt");
  136. const fs = createMemoryFileSystem({
  137. [file]: "old line\n",
  138. });
  139. const revision = revisionFor(file, "old line\n");
  140. const readFileState: ReadFileStateMap = new Map([
  141. [
  142. createReadFileStateKey(file, 1, undefined),
  143. {
  144. path: `${tmpDir}/nested/../existing-normalized-key.txt`,
  145. content: "old line\n",
  146. offset: 1,
  147. limit: undefined,
  148. isPartialView: false,
  149. readAt: new Date(),
  150. revisionId: revision.id,
  151. mtimeMs: revision.mtimeMs,
  152. sizeBytes: revision.sizeBytes,
  153. },
  154. ],
  155. ]);
  156. const context = contextWith(fs, { readFileState });
  157. const result = await writeForModel(
  158. {
  159. file_path: file,
  160. content: "new line\n",
  161. },
  162. context,
  163. );
  164. expect(result.output).toMatchObject({
  165. type: "update",
  166. filePath: file,
  167. content: "new line\n",
  168. });
  169. expect(fs.files.get(file)).toBe("new line\n");
  170. });
  171. it("allows writes after an unchanged range Read in the same runtime", async () => {
  172. const file = join(tmpDir, "same-runtime-range-read.txt");
  173. const fs = createMemoryFileSystem({
  174. [file]: "line one\nline two\n",
  175. });
  176. const readFileState = createReadFileState(file, "line two\n", {
  177. limit: 1,
  178. offset: 2,
  179. revisionContent: "line one\nline two\n",
  180. });
  181. await expect(
  182. writeForModel(
  183. {
  184. file_path: file,
  185. content: "replacement\n",
  186. },
  187. contextWith(fs, { readFileState }),
  188. ),
  189. ).resolves.toMatchObject({
  190. output: {
  191. filePath: file,
  192. originalFile: "line one\nline two\n",
  193. type: "update",
  194. },
  195. });
  196. });
  197. it("allows writes after an unchanged offset-1 full Read when only mtime advances", async () => {
  198. const file = join(tmpDir, "mtime-offset-one-write.txt");
  199. const fs = createMemoryFileSystem({
  200. [file]: "same content\n",
  201. });
  202. const readFileState = createReadFileState(file, "same content\n", {
  203. offset: 1,
  204. mtimeMs: 1,
  205. });
  206. fs.setMtime(file, 2);
  207. await expect(
  208. writeForModel(
  209. {
  210. file_path: file,
  211. content: "replacement\n",
  212. },
  213. contextWith(fs, { readFileState }),
  214. ),
  215. ).resolves.toMatchObject({
  216. output: {
  217. filePath: file,
  218. originalFile: "same content\n",
  219. type: "update",
  220. },
  221. });
  222. });
  223. it("rejects writes when content changes inside the same millisecond", async () => {
  224. const file = join(tmpDir, "same-ms-content-change-default.txt");
  225. const fs = createMemoryFileSystem({
  226. [file]: "before",
  227. });
  228. const context = contextWith(fs, {
  229. readFileState: createReadFileState(file, "before", { mtimeMs: 1000.2 }),
  230. });
  231. fs.files.set(file, "after!");
  232. fs.setMtime(file, 1000.8);
  233. await expect(
  234. writeForModel(
  235. {
  236. file_path: file,
  237. content: "replacement",
  238. },
  239. context,
  240. ),
  241. ).rejects.toMatchObject({
  242. message:
  243. "File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.",
  244. });
  245. });
  246. it("rejects writes from a token-truncated partial view", async () => {
  247. const file = join(tmpDir, "partial-view-write.txt");
  248. const fs = createMemoryFileSystem({
  249. [file]: "full content\n",
  250. });
  251. await expect(
  252. writeForModel(
  253. {
  254. file_path: file,
  255. content: "replacement\n",
  256. },
  257. contextWith(fs, {
  258. readFileState: createReadFileState(file, "full", {
  259. isPartialView: true,
  260. revisionContent: "full content\n",
  261. }),
  262. }),
  263. ),
  264. ).rejects.toMatchObject({
  265. message: "File has not been read yet. Read it first before writing to it.",
  266. });
  267. });
  268. it("documents existing-empty-file behavior as create", async () => {
  269. const file = join(tmpDir, "empty-existing.txt");
  270. const fs = createMemoryFileSystem({
  271. [file]: "",
  272. });
  273. const context = contextWith(fs, {
  274. readFileState: createReadFileState(file, ""),
  275. });
  276. const result = await writeForModel(
  277. {
  278. file_path: file,
  279. content: "now filled\n",
  280. },
  281. context,
  282. );
  283. expect(fs.files.get(file)).toBe("now filled\n");
  284. expect(result.output).toEqual({
  285. type: "create",
  286. filePath: file,
  287. content: "now filled\n",
  288. structuredPatch: [],
  289. originalFile: null,
  290. userModified: false,
  291. });
  292. expect(asModelText(result.modelContent)).toBe(
  293. `File created successfully at: ${file}${WRITE_STORAGE_SUFFIX}`,
  294. );
  295. });
  296. it("documents relative path output as the original input path", async () => {
  297. const fs = createMemoryFileSystem({});
  298. const result = await writeForModel(
  299. {
  300. file_path: "relative-created.txt",
  301. content: "relative content",
  302. },
  303. contextWith(fs, {
  304. workingDirectory: tmpDir,
  305. workspaceRoot: tmpDir,
  306. }),
  307. );
  308. const absolutePath = join(tmpDir, "relative-created.txt");
  309. expect(result.output).toEqual({
  310. type: "create",
  311. filePath: "relative-created.txt",
  312. content: "relative content",
  313. structuredPatch: [],
  314. originalFile: null,
  315. userModified: false,
  316. });
  317. expect(asModelText(result.modelContent)).toBe(
  318. `File created successfully at: relative-created.txt${WRITE_STORAGE_SUFFIX}`,
  319. );
  320. expect(fs.files.get(absolutePath)).toBe("relative content");
  321. });
  322. it("documents current update writes preserving the old file line-ending style", async () => {
  323. const file = join(tmpDir, "line-endings-update.txt");
  324. const fs = createMemoryFileSystem({
  325. [file]: "first\r\nsecond\r\n",
  326. });
  327. const context = contextWith(fs, {
  328. readFileState: createReadFileState(file, "first\r\nsecond\r\n"),
  329. });
  330. const result = await writeForModel(
  331. {
  332. file_path: file,
  333. content: "first\nchanged\n",
  334. },
  335. context,
  336. );
  337. expect(result.output).toMatchObject({
  338. type: "update",
  339. originalFile: "first\nsecond\n",
  340. content: "first\nchanged\n",
  341. });
  342. expect(fs.lastWrite?.lineEndings).toBe("CRLF");
  343. expect(fs.files.get(file)).toBe("first\r\nchanged\r\n");
  344. });
  345. });
  346. describeWriteStrictContract("Write strict model-result contract", () => {
  347. it("returns an update result even when a nonempty overwrite is a no-op", async () => {
  348. const file = join(tmpDir, "same-content.txt");
  349. const fs = createMemoryFileSystem({
  350. [file]: "same\ncontent\n",
  351. });
  352. const context = contextWith(fs, {
  353. readFileState: createReadFileState(file, "same\ncontent\n"),
  354. });
  355. const result = await writeForModel(
  356. {
  357. file_path: file,
  358. content: "same\ncontent\n",
  359. },
  360. context,
  361. );
  362. expect(fs.files.get(file)).toBe("same\ncontent\n");
  363. expect(result.output).toMatchObject({
  364. type: "update",
  365. filePath: file,
  366. content: "same\ncontent\n",
  367. originalFile: "same\ncontent\n",
  368. userModified: false,
  369. });
  370. expect(asModelText(result.modelContent)).toBe(
  371. `The file ${file} has been updated successfully.${WRITE_STORAGE_SUFFIX}`,
  372. );
  373. });
  374. it("uses the user-modified note instead of the storage freshness suffix", () => {
  375. expect(
  376. asModelText(
  377. formatWriteModelContent({
  378. type: "create",
  379. filePath: "/work/user-edited.txt",
  380. content: "edited",
  381. structuredPatch: [],
  382. originalFile: null,
  383. userModified: true,
  384. }),
  385. ),
  386. ).toBe(`File created successfully at: /work/user-edited.txt${WRITE_USER_MODIFIED_NOTE}`);
  387. expect(
  388. asModelText(
  389. formatWriteModelContent({
  390. type: "update",
  391. filePath: "/work/user-edited.txt",
  392. content: "edited",
  393. structuredPatch: [],
  394. originalFile: "old",
  395. userModified: true,
  396. }),
  397. ),
  398. ).toBe(
  399. `The file /work/user-edited.txt has been updated successfully.${WRITE_USER_MODIFIED_NOTE}`,
  400. );
  401. });
  402. it("preserves explicit CRLF content when creating a file", async () => {
  403. const file = join(tmpDir, "line-endings.txt");
  404. const fs = createMemoryFileSystem({});
  405. const result = await writeForModel(
  406. {
  407. file_path: file,
  408. content: "first\r\nsecond\r\n",
  409. },
  410. contextWith(fs),
  411. );
  412. expect(fs.files.get(file)).toBe("first\r\nsecond\r\n");
  413. expect(result.output).toMatchObject({
  414. type: "create",
  415. content: "first\r\nsecond\r\n",
  416. });
  417. });
  418. it("requires an existing file to be read before writing", async () => {
  419. const file = join(tmpDir, "unread.txt");
  420. const fs = createMemoryFileSystem({
  421. [file]: "existing",
  422. });
  423. await expect(
  424. writeForModel(
  425. {
  426. file_path: file,
  427. content: "replacement",
  428. },
  429. contextWith(fs),
  430. ),
  431. ).rejects.toMatchObject({
  432. message: "File has not been read yet. Read it first before writing to it.",
  433. });
  434. });
  435. it("rejects writes when the file has changed since the cached read", async () => {
  436. const file = join(tmpDir, "stale.txt");
  437. const fs = createMemoryFileSystem({
  438. [file]: "before",
  439. });
  440. const context = contextWith(fs, {
  441. readFileState: createReadFileState(file, "before"),
  442. });
  443. fs.files.set(file, "after");
  444. await expect(
  445. writeForModel(
  446. {
  447. file_path: file,
  448. content: "replacement",
  449. },
  450. context,
  451. ),
  452. ).rejects.toMatchObject({
  453. message:
  454. "File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.",
  455. });
  456. });
  457. it("allows writes when unchanged content only drifts inside the same millisecond", async () => {
  458. const file = join(tmpDir, "mtime-sub-ms-write.txt");
  459. const fs = createMemoryFileSystem({
  460. [file]: "before",
  461. });
  462. fs.setMtime(file, 1000.8);
  463. const context = contextWith(fs, {
  464. readFileState: createReadFileState(file, "before", { mtimeMs: 1000.2 }),
  465. });
  466. await expect(
  467. writeForModel(
  468. {
  469. file_path: file,
  470. content: "replacement",
  471. },
  472. context,
  473. ),
  474. ).resolves.toMatchObject({
  475. output: {
  476. type: "update",
  477. filePath: file,
  478. originalFile: "before",
  479. },
  480. });
  481. });
  482. it("honors Edit deny rules before filesystem access", () => {
  483. const service = new PermissionService(defaultPermissionConfig);
  484. const file = join(tmpDir, "blocked", "secret.txt");
  485. const projectRules: PermissionRuleset = {
  486. version: 1,
  487. deny: [
  488. {
  489. toolName: "Edit",
  490. ruleContent: `${tmpDir}/blocked/*`,
  491. },
  492. ],
  493. };
  494. const decision = service.checkPermission(
  495. {
  496. input: {
  497. file_path: file,
  498. content: "secret",
  499. },
  500. mode: "edit",
  501. riskLevel: writeToolEntry.metadata.riskLevel,
  502. toolName: "Write",
  503. },
  504. {
  505. ...writeToolEntry.metadata,
  506. permission: writeToolEntry.permission,
  507. },
  508. projectRules,
  509. );
  510. expect(decision).toMatchObject({
  511. allowed: false,
  512. decision: "deny",
  513. });
  514. });
  515. });
  516. async function writeForModel(input: unknown, context: ToolExecutionContext) {
  517. const output = await writeHandler(input, context);
  518. return {
  519. output,
  520. modelContent: formatWriteModelContent(output),
  521. };
  522. }
  523. function formatWriteModelContent(output: unknown): ModelMessageContent {
  524. const modelContent = writeToolEntry.formatModelContent?.(output);
  525. if (modelContent === undefined) {
  526. throw new Error("Write tool is missing formatModelContent");
  527. }
  528. return modelContent;
  529. }
  530. function asModelText(content: ModelMessageContent | undefined): string {
  531. if (content === undefined) {
  532. throw new Error("Missing model content");
  533. }
  534. return modelMessageContentToText(content);
  535. }
  536. async function executeWrite(input: unknown, fileSystemPort: FileSystemPort) {
  537. const sessionId = createSessionId("write-contract");
  538. const turnId = createTurnId("write-contract");
  539. const traceContext = createRootTraceContext({ sessionId, turnId });
  540. const registry = createToolRegistry();
  541. registry.register(writeToolEntry);
  542. return createToolExecutor({
  543. emitEvent: async () => {},
  544. fileSystemPort,
  545. mode: "edit",
  546. permissionService: new PermissionService(defaultPermissionConfig),
  547. registry,
  548. sessionId,
  549. traceContext,
  550. turnId,
  551. workingDirectory: tmpDir,
  552. workspaceRoot: tmpDir,
  553. }).execute(
  554. {
  555. id: createToolCallId("write-contract"),
  556. input,
  557. name: "Write",
  558. },
  559. { traceContext },
  560. );
  561. }
  562. function contextWith(
  563. fileSystemPort: FileSystemPort,
  564. options: {
  565. readFileState?: ReadFileStateMap;
  566. workingDirectory?: string;
  567. workspaceRoot?: string;
  568. } = {},
  569. ): ToolExecutionContext {
  570. return {
  571. toolCallId: "tool_test",
  572. traceId: "trace_test",
  573. spanId: "span_test",
  574. abortSignal: new AbortController().signal,
  575. fileSystemPort,
  576. readFileState: options.readFileState,
  577. workingDirectory: options.workingDirectory ?? tmpDir,
  578. workspaceRoot: options.workspaceRoot ?? tmpDir,
  579. sessionId: "sess_test",
  580. turnId: "turn_test",
  581. };
  582. }
  583. function createReadFileState(
  584. filePath: string,
  585. content: string,
  586. options: {
  587. isPartialView?: boolean;
  588. limit?: number;
  589. mtimeMs?: number;
  590. offset?: number;
  591. readAt?: Date;
  592. revisionContent?: string;
  593. } = {},
  594. ): ReadFileStateMap {
  595. const revisionContent = options.revisionContent ?? content;
  596. const revision = revisionFor(filePath, revisionContent, options.mtimeMs ?? 1);
  597. return new Map([
  598. [
  599. [
  600. filePath,
  601. String(options.offset ?? 1),
  602. options.limit === undefined ? "" : String(options.limit),
  603. ].join("\0"),
  604. {
  605. path: filePath,
  606. content: normalizeLineEndings(content),
  607. offset: options.offset,
  608. limit: options.limit,
  609. isPartialView: options.isPartialView ?? false,
  610. readAt: options.readAt ?? new Date(),
  611. revisionId: revision.id,
  612. mtimeMs: revision.mtimeMs,
  613. sizeBytes: revision.sizeBytes,
  614. },
  615. ],
  616. ]);
  617. }
  618. interface MemoryFileSystem extends FileSystemPort {
  619. files: Map<string, string>;
  620. lastWrite?: FileSystemWriteTextRequest;
  621. mtimes: Map<string, number>;
  622. readPaths: string[];
  623. setMtime(path: string, mtimeMs: number): void;
  624. }
  625. function createMemoryFileSystem(initial: Record<string, string>): MemoryFileSystem {
  626. const files = new Map(Object.entries(initial));
  627. const mtimes = new Map<string, number>();
  628. const fs: MemoryFileSystem = {
  629. files,
  630. mtimes,
  631. readPaths: [],
  632. setMtime(path, mtimeMs) {
  633. mtimes.set(path, mtimeMs);
  634. },
  635. async stat(request): Promise<FileSystemStatResult> {
  636. const content = files.get(request.path);
  637. if (content === undefined) throw missingFile(request.path);
  638. const mtimeMs = mtimes.get(request.path) ?? 1;
  639. return {
  640. kind: "file",
  641. path: request.path,
  642. mtimeMs,
  643. revision: revisionFor(request.path, content, mtimeMs),
  644. sizeBytes: Buffer.byteLength(content, "utf8"),
  645. };
  646. },
  647. async readTextFile(request): Promise<FileSystemReadTextResult> {
  648. fs.readPaths.push(request.path);
  649. const content = readTextOrThrow(request.path, files);
  650. const normalized = normalizeLineEndings(content);
  651. const mtimeMs = mtimes.get(request.path) ?? 1;
  652. return {
  653. bytesRead: Buffer.byteLength(content, "utf8"),
  654. content: normalized,
  655. encoding: request.encoding ?? "utf8",
  656. lineEndings: detectLineEndings(content),
  657. path: request.path,
  658. revision: revisionFor(request.path, content, mtimeMs),
  659. sizeBytes: Buffer.byteLength(content, "utf8"),
  660. truncated: false,
  661. };
  662. },
  663. async readBinaryFile(request) {
  664. const content = readTextOrThrow(request.path, files);
  665. const buffer = Buffer.from(content, "utf8");
  666. return {
  667. bytesRead: buffer.byteLength,
  668. content: buffer,
  669. path: request.path,
  670. revision: revisionFor(request.path, content, mtimes.get(request.path) ?? 1),
  671. sizeBytes: buffer.byteLength,
  672. };
  673. },
  674. async readTextFileRange(request): Promise<FileSystemReadTextRangeResult> {
  675. const content = readTextOrThrow(request.path, files);
  676. const normalized = normalizeLineEndings(content);
  677. const lines = normalized.length === 0 ? [] : normalized.split("\n");
  678. const offsetLine = Math.max(0, Math.trunc(request.offsetLine ?? 0));
  679. const limitLines =
  680. request.limitLines === undefined ? undefined : Math.max(0, Math.trunc(request.limitLines));
  681. const selected =
  682. limitLines === undefined
  683. ? lines.slice(offsetLine)
  684. : lines.slice(offsetLine, offsetLine + limitLines);
  685. return {
  686. bytesRead: Buffer.byteLength(content, "utf8"),
  687. content: selected.join("\n"),
  688. encoding: request.encoding ?? "utf8",
  689. lineCount: selected.length,
  690. lineEndings: detectLineEndings(content),
  691. path: request.path,
  692. revision: revisionFor(request.path, content, mtimes.get(request.path) ?? 1),
  693. sizeBytes: Buffer.byteLength(content, "utf8"),
  694. startLine: offsetLine + 1,
  695. totalLines: lines.length,
  696. truncated: false,
  697. };
  698. },
  699. async writeTextFile(request) {
  700. const content = applyLineEndings(request.content, request.lineEndings);
  701. fs.lastWrite = request;
  702. files.set(request.path, content);
  703. mtimes.set(request.path, (mtimes.get(request.path) ?? 1) + 1);
  704. return {
  705. bytesWritten: Buffer.byteLength(content, "utf8"),
  706. path: request.path,
  707. revision: revisionFor(request.path, content, mtimes.get(request.path) ?? 1),
  708. };
  709. },
  710. async removeFile(request) {
  711. const removed = files.delete(request.path);
  712. if (!removed && request.missingOk !== true) throw missingFile(request.path);
  713. return {
  714. path: request.path,
  715. removed,
  716. };
  717. },
  718. async listDirectory(request) {
  719. const prefix = `${request.path.replace(/\/+$/u, "")}/`;
  720. const entries = Array.from(files.keys())
  721. .filter((path) => path.startsWith(prefix))
  722. .map((path) => ({
  723. kind: "file" as const,
  724. name: path.slice(prefix.length),
  725. path,
  726. }));
  727. return {
  728. durationMs: 0,
  729. entries,
  730. numEntries: entries.length,
  731. path: request.path,
  732. };
  733. },
  734. async searchFiles(request): Promise<FileSystemSearchFilesResult> {
  735. return {
  736. durationMs: 0,
  737. files: [],
  738. numFiles: 0,
  739. path: request.path,
  740. pattern: request.pattern,
  741. truncated: false,
  742. };
  743. },
  744. async searchText(request): Promise<FileSystemSearchTextResult> {
  745. return {
  746. durationMs: 0,
  747. entries: [],
  748. files: [],
  749. mode: request.outputMode ?? "files_with_matches",
  750. numMatches: 0,
  751. path: request.path,
  752. pattern: request.pattern,
  753. truncated: false,
  754. };
  755. },
  756. };
  757. return fs;
  758. }
  759. function readTextOrThrow(path: string, files: Map<string, string>): string {
  760. const content = files.get(path);
  761. if (content === undefined) throw missingFile(path);
  762. return content;
  763. }
  764. function missingFile(path: string): Error {
  765. return createFileSystemError({
  766. code: "not_found",
  767. message: `missing: ${path}`,
  768. path,
  769. });
  770. }
  771. function normalizeLineEndings(content: string): string {
  772. return content.replaceAll("\r\n", "\n");
  773. }
  774. function applyLineEndings(content: string, lineEndings: FileSystemLineEndings | undefined): string {
  775. if (lineEndings !== "CRLF") return content;
  776. return content.replaceAll("\r\n", "\n").split("\n").join("\r\n");
  777. }
  778. function detectLineEndings(content: string): "LF" | "CRLF" {
  779. let crlfCount = 0;
  780. let lfCount = 0;
  781. for (let index = 0; index < content.length; index += 1) {
  782. if (content[index] !== "\n") continue;
  783. if (index > 0 && content[index - 1] === "\r") crlfCount += 1;
  784. else lfCount += 1;
  785. }
  786. return crlfCount > lfCount ? "CRLF" : "LF";
  787. }
  788. function revisionFor(path: string, content: string, mtimeMs = 1): FileSystemRevision {
  789. return {
  790. id: `rev:${path}:${content.length}:${mtimeMs}`,
  791. mtimeMs,
  792. sizeBytes: Buffer.byteLength(content, "utf8"),
  793. };
  794. }