From 1685e70c4b810161d604222e910529eed242dbcb Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Thu, 17 Sep 2026 20:17:14 +1000 Subject: [PATCH] feat(server): add fs.write endpoint (#49466) --- packages/cli/test/service.test.ts | 3 +- .../client/src/promise/generated/client.ts | 27 ++++++++++++-- .../client/src/promise/generated/types.ts | 16 +++++++++ packages/core/src/filesystem.ts | 22 ++++++++++-- packages/httpapi-codegen/src/index.ts | 36 ++++++++++++++----- packages/protocol/src/client.ts | 2 +- packages/protocol/src/groups/fs.ts | 23 ++++++++++++ packages/schema/src/filesystem.ts | 7 +++- packages/server/src/handlers/fs.ts | 8 +++++ packages/server/src/workerd.ts | 1 + 10 files changed, 129 insertions(+), 16 deletions(-) diff --git a/packages/cli/test/service.test.ts b/packages/cli/test/service.test.ts index 9a014136715..b5bcd821794 100644 --- a/packages/cli/test/service.test.ts +++ b/packages/cli/test/service.test.ts @@ -263,7 +263,8 @@ test("concurrent service processes elect one server", async () => { version: info.version, pid: info.pid, urls: [info.url], - paths: { tmp: path.join(os.tmpdir(), "opencode") }, + // The server reports the canonical tmp directory; Windows os.tmpdir() can be an 8.3 short name. + paths: { tmp: await fs.realpath(path.join(os.tmpdir(), "opencode")) }, }) const contender = Bun.spawn(command, { env, stderr: "pipe", stdout: "ignore" }) try { diff --git a/packages/client/src/promise/generated/client.ts b/packages/client/src/promise/generated/client.ts index 8c7eab44afb..f2c271e286c 100644 --- a/packages/client/src/promise/generated/client.ts +++ b/packages/client/src/promise/generated/client.ts @@ -175,6 +175,8 @@ import type { FileListOutput, FileFindInput, FileFindOutput, + FileWriteInput, + FileWriteOutput, CommandListInput, CommandListOutput, SkillListInput, @@ -277,6 +279,7 @@ interface RequestDescriptor { readonly query?: Record readonly headers?: Record readonly body?: unknown + readonly binaryBody?: true readonly successStatus: number readonly declaredStatuses: ReadonlyArray readonly empty: boolean @@ -296,14 +299,20 @@ export function make(options: ClientOptions) { if (value !== undefined && value !== null) headers.set(key, String(value)) } for (const [key, value] of new Headers(requestOptions?.headers)) headers.set(key, value) - if (descriptor.body !== undefined && !headers.has("content-type")) headers.set("content-type", "application/json") + if (descriptor.body !== undefined && !headers.has("content-type")) + headers.set("content-type", descriptor.binaryBody ? "application/octet-stream" : "application/json") return { url, init: { method: descriptor.method, signal: requestOptions?.signal, headers, - body: descriptor.body === undefined ? undefined : JSON.stringify(descriptor.body), + body: + descriptor.body === undefined + ? undefined + : descriptor.binaryBody + ? (descriptor.body as RequestInit["body"]) + : JSON.stringify(descriptor.body), } satisfies RequestInit, } } @@ -1566,6 +1575,20 @@ export function make(options: ClientOptions) { }, requestOptions, ), + write: (input: FileWriteInput, requestOptions?: RequestOptions) => + request( + { + method: "POST", + path: `/api/experimental/fs/write`, + query: { location: input["location"], path: input["path"] }, + body: input["payload"], + successStatus: 200, + declaredStatuses: [400, 401], + empty: false, + binaryBody: true, + }, + requestOptions, + ), }, command: { list: (input?: CommandListInput, requestOptions?: RequestOptions) => diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index 0cc2152133c..61531f3d9ce 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -319,6 +319,8 @@ export type PermissionSavedInfo = { export type FileSystemEntry = { path: string; type: "file" | "directory" } +export type FileSystemWrite = { path: string } + export type CommandInfo = { name: string; description?: string } export type SkillInfo = { @@ -5793,6 +5795,20 @@ export type FileFindInput = { export type FileFindOutput = { location: LocationPublicRef; data: Array } +export type FileWriteInput = { + readonly location?: { + readonly location?: { readonly directory?: string | undefined } | undefined + readonly path: string + }["location"] + readonly path: { + readonly location?: { readonly directory?: string | undefined } | undefined + readonly path: string + }["path"] + readonly payload: globalThis.Uint8Array +} + +export type FileWriteOutput = { location: LocationPublicRef; data: FileSystemWrite } + export type CommandListInput = { readonly location?: { readonly location?: { readonly directory?: string | undefined } | undefined }["location"] } diff --git a/packages/core/src/filesystem.ts b/packages/core/src/filesystem.ts index d3e1e56e7db..b6b1bb3402f 100644 --- a/packages/core/src/filesystem.ts +++ b/packages/core/src/filesystem.ts @@ -5,9 +5,9 @@ import path from "path" import { Context, Effect, Layer, Schema } from "effect" import { FSUtil } from "@opencode/util/fs-util" import { Location } from "./location.js" -import { PositiveInt, RelativePath } from "./schema.js" +import { AbsolutePath, PositiveInt, RelativePath } from "./schema.js" import { FileSystemSearch } from "./filesystem/search.js" -import { Entry, FileSystem, FindInput } from "@opencode/schema/filesystem" +import { Entry, FileSystem, FindInput, Write } from "@opencode/schema/filesystem" export { Entry, Match, Submatch } from "@opencode/schema/filesystem" export const ReadInput = Schema.Struct({ @@ -15,6 +15,13 @@ export const ReadInput = Schema.Struct({ }) export type ReadInput = typeof ReadInput.Type +export const WriteInput = Schema.Struct({ + /** Absolute, or relative to the location directory. */ + path: Schema.String, + data: Schema.Uint8Array, +}) +export type WriteInput = typeof WriteInput.Type + export class NotFoundError extends Schema.TaggedError()("FileSystem.NotFoundError", { path: RelativePath, }) {} @@ -33,7 +40,7 @@ export const ListInput = Schema.Struct({ }) export type ListInput = typeof ListInput.Type -export { FindInput } +export { FindInput, Write } export const DEFAULT_SEARCH_LIMIT = 100 export const DEFAULT_SEARCH_TIMEOUT_MS = 30_000 @@ -62,6 +69,8 @@ export interface Interface { ) => Effect.Effect<{ readonly content: Uint8Array; readonly mime: string }, NotFoundError> readonly list: (input?: ListInput) => Effect.Effect readonly find: (input: FindInput) => Effect.Effect + /** Writes a file at an absolute path or one relative to the location; not confined to it. */ + readonly write: (input: WriteInput) => Effect.Effect } export class Service extends Context.Service()("@opencode/FileSystem") {} @@ -143,6 +152,13 @@ const baseLayer = Layer.effect( ), ) }), + // Unlike read, write reaches outside the location so clients can stage files in the + // server tmp directory, which the model is already told to prefer and permitted to access. + write: Effect.fn("FileSystem.write")(function* (input) { + const target = path.resolve(location.directory, input.path) + yield* fs.writeWithDirs(target, input.data).pipe(Effect.orDie) + return Write.make({ path: AbsolutePath.make(target) }) + }), }) }), ) diff --git a/packages/httpapi-codegen/src/index.ts b/packages/httpapi-codegen/src/index.ts index 84a4c78662b..66807ac73db 100644 --- a/packages/httpapi-codegen/src/index.ts +++ b/packages/httpapi-codegen/src/index.ts @@ -585,11 +585,11 @@ function groupShapeTypeName(group: Group, endpoint: Endpoint) { function assertPromiseEndpoint(endpoint: Endpoint) { const name = `${endpoint.group}.${endpoint.endpoint.identifier}` const payload = endpoint.payloads[0] - const payloadEncoding = payload === undefined ? undefined : resolveHttpApiEncoding(payload.ast) - if ( - payload !== undefined && - (payloadEncoding?._tag ?? (HttpMethod.hasBody(endpoint.endpoint.method) ? "Json" : "FormUrlEncoded")) !== "Json" - ) { + const payloadEncoding = + payload === undefined + ? undefined + : (resolveHttpApiEncoding(payload.ast)?._tag ?? (HttpMethod.hasBody(endpoint.endpoint.method) ? "Json" : "FormUrlEncoded")) + if (payloadEncoding !== undefined && payloadEncoding !== "Json" && payloadEncoding !== "Uint8Array") { throw new GenerationError({ reason: `Unsupported Promise payload encoding: ${name}` }) } const success = endpoint.successes[0] @@ -945,7 +945,7 @@ function renderPromiseClient(groups: ReadonlyArray) { endpoint.payloads.length === 0 ? undefined : `body: ${part("payload")}`, ].filter((value): value is string => value !== undefined) const declaredStatuses = [...new Set(endpoint.errors.map((error) => error.status))] - const descriptor = `{ method: ${JSON.stringify(endpoint.endpoint.method)}, path: ${path}${parts.length === 0 ? "" : `, ${parts.join(", ")}`}, successStatus: ${resolveHttpApiStatus(endpoint.successes[0].ast) ?? 200}, declaredStatuses: [${declaredStatuses.join(", ")}], empty: ${endpoint.operation.success === "void"}${isBinarySchema(endpoint.successes[0]) ? ", binary: true" : ""} }` + const descriptor = `{ method: ${JSON.stringify(endpoint.endpoint.method)}, path: ${path}${parts.length === 0 ? "" : `, ${parts.join(", ")}`}, successStatus: ${resolveHttpApiStatus(endpoint.successes[0].ast) ?? 200}, declaredStatuses: [${declaredStatuses.join(", ")}], empty: ${endpoint.operation.success === "void"}${isBinarySchema(endpoint.successes[0]) ? ", binary: true" : ""}${isBinaryPayload(endpoint) ? ", binaryBody: true" : ""} }` if (endpoint.operation.success === "stream") { const success = endpoint.successes[0] if (!isStreamSchema(success) || success._tag !== "StreamSse" || success.sseMode !== "data") { @@ -1241,13 +1241,33 @@ function normalizePromiseClientContent(content: string, groups: ReadonlyArray("FileSystem.FindInput")({ type: Schema.Literals(["file", "directory"]).pipe(optional), limit: PositiveInt.pipe(optional), }) {} + +export interface Write extends Schema.Schema.Type {} +export const Write = Schema.Struct({ + path: AbsolutePath, +}).annotate({ identifier: "FileSystem.Write" }) diff --git a/packages/server/src/handlers/fs.ts b/packages/server/src/handlers/fs.ts index 27af4b4d352..27d3fbc3476 100644 --- a/packages/server/src/handlers/fs.ts +++ b/packages/server/src/handlers/fs.ts @@ -43,5 +43,13 @@ export const FileSystemHandler = HttpApiBuilder.group(Api, "server.fs", (handler }), ), ) + .handle("fs.write", (ctx) => + response( + Effect.gen(function* () { + const fs = yield* FileSystem.Service + return yield* fs.write({ path: ctx.query.path, data: ctx.payload }) + }), + ), + ) }), ) diff --git a/packages/server/src/workerd.ts b/packages/server/src/workerd.ts index 77fc1daef03..949ee3fd4d0 100644 --- a/packages/server/src/workerd.ts +++ b/packages/server/src/workerd.ts @@ -113,6 +113,7 @@ const fileSystemLayer = Layer.succeed( read: () => unavailable("FileSystem.read"), list: () => unavailable("FileSystem.list"), find: () => unavailable("FileSystem.find"), + write: () => unavailable("FileSystem.write"), }), )