The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { |
| 2 | ANTIGRAVITY_DEFAULT_MODEL, |
| 3 | type AntigravityAuthMethod, |
| 4 | PROVIDER_SEND_TURN_MAX_FILE_BYTES, |
| 5 | PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, |
| 6 | type ProviderSendTurnInput, |
| 7 | type RuntimeMode, |
| 8 | } from "@t3tools/contracts"; |
| 9 | import * as SecureRandom from "effect/crypto/SecureRandom"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as FileSystem from "effect/FileSystem"; |
| 12 | import * as Layer from "effect/Layer"; |
| 13 | import * as Path from "effect/Path"; |
| 14 | import * as Predicate from "effect/Predicate"; |
| 15 | import * as Scope from "effect/Scope"; |
| 16 | import * as Stream from "effect/Stream"; |
| 17 | import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; |
| 18 | import * as EffectAcpErrors from "effect-acp/errors"; |
| 19 | import type * as EffectAcpSchema from "effect-acp/compat"; |
| 20 | |
| 21 | import { |
| 22 | makeAntigravityStderrHandler, |
| 23 | makeAntigravityStdoutTransform, |
| 24 | } from "../antigravityAuthSupport.ts"; |
| 25 | import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; |
| 26 | import { |
| 27 | acpPermissionDisposition, |
| 28 | type AcpRuntimePolicy, |
| 29 | } from "@t3tools/provider-acp/server/clientPolicy"; |
| 30 | import type { AcpSessionModeState } from "@t3tools/provider-acp/server/runtimeModel"; |
| 31 | import packageJson from "../../../package.json" with { type: "json" }; |
| 32 | import { normalizeAntigravitySessionUpdate } from "./AntigravityProtocol.ts"; |
| 33 | |
| 34 | export interface AntigravityAcpRuntimeInput extends Omit< |
| 35 | AcpSessionRuntime.AcpSessionRuntimeOptions, |
| 36 | | "authMethodId" |
| 37 | | "authenticateEagerly" |
| 38 | | "cancelBehavior" |
| 39 | | "clientCapabilities" |
| 40 | | "clientInfo" |
| 41 | | "onStderr" |
| 42 | | "resumeMethod" |
| 43 | | "sessionMeta" |
| 44 | | "transformSessionUpdate" |
| 45 | | "transformStdout" |
| 46 | > { |
| 47 | readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"]; |
| 48 | readonly onAuthorizationUrl?: (url: string) => Effect.Effect<void, EffectAcpErrors.AcpError>; |
| 49 | /** Serve `fs/read_text_file` from T3 instead of the agent's native reader. */ |
| 50 | readonly clientFileReads?: boolean; |
| 51 | readonly clientCapabilities?: AcpSessionRuntime.AcpSessionRuntimeOptions["clientCapabilities"]; |
| 52 | /** The installed version, known before `initialize`; it picks the client name. */ |
| 53 | readonly runtimeVersion?: string | null; |
| 54 | /** Conversational sessions only; helpers and probes leave the system prompt untouched. */ |
| 55 | readonly sessionSystemPromptAppend?: string; |
| 56 | readonly authMethod?: AntigravityAuthMethod; |
| 57 | } |
| 58 | |
| 59 | function parseAntigravityVersion(version: string | null | undefined) { |
| 60 | const match = /^(\d+)\.(\d+)\.(\d+)/.exec(version?.trim() ?? ""); |
| 61 | return match === null ? undefined : [Number(match[1]), Number(match[2]), Number(match[3])]; |
| 62 | } |
| 63 | |
| 64 | function compareVersions(left: ReadonlyArray<number>, right: ReadonlyArray<number>) { |
| 65 | for (let index = 0; index < 3; index++) { |
| 66 | const difference = (left[index] ?? 0) - (right[index] ?? 0); |
| 67 | if (difference !== 0) return difference; |
| 68 | } |
| 69 | return 0; |
| 70 | } |
| 71 | |
| 72 | // `agy acp` 1.5.1 offers every model to every ACP client; older runtimes allowlist editors. |
| 73 | const OPEN_MODEL_ACCESS_RELEASE = [1, 5, 1] as const; |
| 74 | // `agy acp` 1.5.0 steers a running turn with the next prompt; the 1.4 harness queues it. |
| 75 | const PROMPT_STEERING_RELEASE = [1, 5, 0] as const; |
| 76 | |
| 77 | export const antigravitySteersWithPrompt = ( |
| 78 | initializeResult: EffectAcpSchema.InitializeResponse, |
| 79 | ) => { |
| 80 | const parsed = parseAntigravityVersion(initializeResult.agentInfo?.version); |
| 81 | return parsed !== undefined && compareVersions(parsed, PROMPT_STEERING_RELEASE) >= 0; |
| 82 | }; |
| 83 | |
| 84 | export const antigravityAppendsSystemPrompt = ( |
| 85 | initializeResult: EffectAcpSchema.InitializeResponse, |
| 86 | ) => { |
| 87 | const extension = initializeResult.agentCapabilities?._meta?.antigravity; |
| 88 | return ( |
| 89 | Predicate.isObject(extension) && |
| 90 | Predicate.isObject(extension.systemPrompt) && |
| 91 | extension.systemPrompt.append === true |
| 92 | ); |
| 93 | }; |
| 94 | |
| 95 | export function antigravitySessionMeta( |
| 96 | initializeResult: EffectAcpSchema.InitializeResponse, |
| 97 | systemPromptAppend?: string, |
| 98 | ): EffectAcpSchema.NewSessionRequest["_meta"] | undefined { |
| 99 | return systemPromptAppend !== undefined && antigravityAppendsSystemPrompt(initializeResult) |
| 100 | ? { antigravity: { systemPrompt: { append: systemPromptAppend } } } |
| 101 | : undefined; |
| 102 | } |
| 103 | |
| 104 | /** Older releases offer non-Gemini models only to allowlisted clients such as Zed. */ |
| 105 | export function antigravityClientInfo(version: string | null | undefined) { |
| 106 | const parsed = parseAntigravityVersion(version); |
| 107 | return parsed !== undefined && compareVersions(parsed, OPEN_MODEL_ACCESS_RELEASE) >= 0 |
| 108 | ? { name: "t3-code", title: "T3 Code", version: packageJson.version } |
| 109 | : { name: "zed", version: "0.0.0" }; |
| 110 | } |
| 111 | |
| 112 | export const makeAntigravityAcpRuntime = Effect.fn("makeAntigravityAcpRuntime")(function* ( |
| 113 | input: AntigravityAcpRuntimeInput, |
| 114 | ): Effect.fn.Return< |
| 115 | AcpSessionRuntime.AcpSessionRuntime["Service"], |
| 116 | EffectAcpErrors.AcpError, |
| 117 | SecureRandom.SecureRandom | Scope.Scope |
| 118 | > { |
| 119 | const context = yield* Layer.build( |
| 120 | AcpSessionRuntime.layer({ |
| 121 | ...input, |
| 122 | authMethodId: input.authMethod ?? "oauth-personal", |
| 123 | authenticateEagerly: true, |
| 124 | resumeMethod: "resume", |
| 125 | cancelBehavior: "wait-for-prompt", |
| 126 | clientInfo: antigravityClientInfo(input.runtimeVersion), |
| 127 | sessionMeta: (initializeResult) => |
| 128 | antigravitySessionMeta(initializeResult, input.sessionSystemPromptAppend), |
| 129 | clientCapabilities: { |
| 130 | ...input.clientCapabilities, |
| 131 | // Advertising writes swaps the agent's diff edits for whole-file client_edit_file. |
| 132 | fs: { |
| 133 | readTextFile: input.clientFileReads === true, |
| 134 | writeTextFile: false, |
| 135 | }, |
| 136 | terminal: false, |
| 137 | }, |
| 138 | transformStdout: makeAntigravityStdoutTransform( |
| 139 | input.onAuthorizationUrl ? { onAuthorizationUrl: input.onAuthorizationUrl } : {}, |
| 140 | ), |
| 141 | onStderr: makeAntigravityStderrHandler( |
| 142 | input.onAuthorizationUrl ? { onAuthorizationUrl: input.onAuthorizationUrl } : {}, |
| 143 | ), |
| 144 | transformSessionUpdate: normalizeAntigravitySessionUpdate, |
| 145 | }).pipe( |
| 146 | Layer.provide( |
| 147 | Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner), |
| 148 | ), |
| 149 | ), |
| 150 | ); |
| 151 | return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(Effect.provide(context)); |
| 152 | }); |
| 153 | |
| 154 | export function antigravityPermissionMode(runtimeMode: RuntimeMode): string { |
| 155 | switch (runtimeMode) { |
| 156 | case "full-access": |
| 157 | return "yolo"; |
| 158 | case "auto-accept-edits": |
| 159 | return "auto_edit"; |
| 160 | case "auto": |
| 161 | return "auto"; |
| 162 | case "approval-required": |
| 163 | return "default"; |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | /** |
| 168 | * The agy CLI rejects `yolo` and `auto_edit`, and sessions without native Auto reject `auto`. |
| 169 | * Those stay in `default`, where it asks before acting and T3 answers from the live runtime |
| 170 | * policy, so permission changes apply on the next turn without a restart. |
| 171 | */ |
| 172 | export function antigravitySessionMode( |
| 173 | modeId: string, |
| 174 | modeState: AcpSessionModeState | undefined, |
| 175 | ): string { |
| 176 | if (modeId === "auto") { |
| 177 | return modeState?.availableModes.some((mode) => mode.id === "auto") === true |
| 178 | ? "auto" |
| 179 | : "default"; |
| 180 | } |
| 181 | return modeId === "yolo" || modeId === "auto_edit" ? "default" : modeId; |
| 182 | } |
| 183 | |
| 184 | export function antigravityPermissionDisposition( |
| 185 | policy: AcpRuntimePolicy, |
| 186 | request: EffectAcpSchema.RequestPermissionRequest, |
| 187 | ) { |
| 188 | const disposition = acpPermissionDisposition(policy, request); |
| 189 | // agy's Auto has already reviewed what it sends; the user decides unless the sandbox forbids it. |
| 190 | return policy.runtimeMode === "auto" && disposition !== "deny" ? "ask" : disposition; |
| 191 | } |
| 192 | |
| 193 | /** The runtime mode an Antigravity session mode grants; the inverse of `antigravityPermissionMode`. */ |
| 194 | export function antigravityRuntimeModeForSessionMode(modeId: string): RuntimeMode | undefined { |
| 195 | switch (modeId) { |
| 196 | case "yolo": |
| 197 | return "full-access"; |
| 198 | case "auto_edit": |
| 199 | return "auto-accept-edits"; |
| 200 | case "auto": |
| 201 | return "auto"; |
| 202 | case "default": |
| 203 | return "approval-required"; |
| 204 | default: |
| 205 | return undefined; |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | export function antigravityModelOptions( |
| 210 | configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>, |
| 211 | ) { |
| 212 | const model = configOptions.find((option) => option.id === "model"); |
| 213 | if (model?.type !== "select") return []; |
| 214 | return model.options.flatMap((entry) => ("value" in entry ? [entry] : entry.options)); |
| 215 | } |
| 216 | |
| 217 | /** Runtime 1.4 reports thinking as its own option; 1.3 encoded it in the model ID. */ |
| 218 | export function antigravityThinkingConfig( |
| 219 | configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined, |
| 220 | ) { |
| 221 | const option = configOptions?.find((candidate) => candidate.category === "thought_level"); |
| 222 | return option?.type === "select" ? option : undefined; |
| 223 | } |
| 224 | |
| 225 | /** |
| 226 | * Runtime 1.4 lists `gemini-3.8-flash` where 1.3 listed `gemini-3.8-flash-high`. The agent |
| 227 | * still accepts the old IDs, so pass them through; the current model may have no thinking option. |
| 228 | */ |
| 229 | function legacyAntigravityFamily( |
| 230 | configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>, |
| 231 | model: string, |
| 232 | ) { |
| 233 | return antigravityModelOptions(configOptions) |
| 234 | .map((option) => option.value) |
| 235 | .filter((family) => model.startsWith(`${family}-`)) |
| 236 | .toSorted((left, right) => right.length - left.length)[0]; |
| 237 | } |
| 238 | |
| 239 | function resolveAntigravityModel(input: { |
| 240 | readonly configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>; |
| 241 | readonly model: string | null | undefined; |
| 242 | readonly defaultModel?: string | undefined; |
| 243 | }): string | undefined { |
| 244 | const modelConfig = input.configOptions.find((option) => option.id === "model"); |
| 245 | const current = modelConfig?.type === "select" ? modelConfig.currentValue : undefined; |
| 246 | if (input.model && input.model !== ANTIGRAVITY_DEFAULT_MODEL) return input.model; |
| 247 | const options = antigravityModelOptions(input.configOptions); |
| 248 | return input.defaultModel && |
| 249 | (options.some((option) => option.value === input.defaultModel) || |
| 250 | legacyAntigravityFamily(input.configOptions, input.defaultModel) !== undefined) |
| 251 | ? input.defaultModel |
| 252 | : current; |
| 253 | } |
| 254 | |
| 255 | /** Never replace a saved selection with the default returned by a cold resume. */ |
| 256 | export const applyAntigravityAcpModelSelection = Effect.fn("applyAntigravityAcpModelSelection")( |
| 257 | function* <E>(input: { |
| 258 | readonly runtime: Pick< |
| 259 | AcpSessionRuntime.AcpSessionRuntime["Service"], |
| 260 | "getConfigOptions" | "setModel" | "setConfigOption" |
| 261 | >; |
| 262 | readonly model: string | null | undefined; |
| 263 | readonly defaultModel?: string | undefined; |
| 264 | readonly mapError: (cause: EffectAcpErrors.AcpError) => E; |
| 265 | }): Effect.fn.Return<string | undefined, E> { |
| 266 | const configOptions = yield* input.runtime.getConfigOptions; |
| 267 | const modelConfig = configOptions.find((option) => option.id === "model"); |
| 268 | const current = modelConfig?.type === "select" ? modelConfig.currentValue : undefined; |
| 269 | const resolved = resolveAntigravityModel({ |
| 270 | configOptions, |
| 271 | model: input.model, |
| 272 | defaultModel: input.defaultModel, |
| 273 | }); |
| 274 | const explicit = Boolean(input.model) && input.model !== ANTIGRAVITY_DEFAULT_MODEL; |
| 275 | if (resolved === undefined || (!explicit && resolved === current)) return current; |
| 276 | const options = antigravityModelOptions(configOptions); |
| 277 | const legacyFamily = options.some((option) => option.value === resolved) |
| 278 | ? undefined |
| 279 | : legacyAntigravityFamily(configOptions, resolved); |
| 280 | if (legacyFamily !== undefined) { |
| 281 | yield* input.runtime |
| 282 | .setConfigOption("model", resolved, { allowUnlistedValue: true }) |
| 283 | .pipe(Effect.mapError(input.mapError)); |
| 284 | return legacyFamily; |
| 285 | } |
| 286 | if (!options.some((option) => option.value === resolved)) { |
| 287 | return yield* Effect.fail( |
| 288 | input.mapError( |
| 289 | EffectAcpErrors.AcpRequestError.invalidParams( |
| 290 | `Antigravity model '${resolved}' is unavailable for this Google account. Select an available model.`, |
| 291 | ), |
| 292 | ), |
| 293 | ); |
| 294 | } |
| 295 | yield* input.runtime.setModel(resolved).pipe(Effect.mapError(input.mapError)); |
| 296 | return resolved; |
| 297 | }, |
| 298 | ); |
| 299 | |
| 300 | const IMAGE_MIME_TYPES = new Set(["image/bmp", "image/jpeg", "image/png", "image/webp"]); |
| 301 | const AUDIO_MIME_TYPES = new Set([ |
| 302 | "audio/aac", |
| 303 | "audio/flac", |
| 304 | "audio/mp3", |
| 305 | "audio/mpeg", |
| 306 | "audio/mp4", |
| 307 | "audio/m4a", |
| 308 | "audio/x-m4a", |
| 309 | "audio/ogg", |
| 310 | "audio/wav", |
| 311 | "audio/x-wav", |
| 312 | "audio/webm", |
| 313 | ]); |
| 314 | const ANTIGRAVITY_MAX_AUDIO_ATTACHMENT_BYTES = 20 * 1024 * 1024; |
| 315 | const TEXT_MIME_TYPES = new Set([ |
| 316 | "application/json", |
| 317 | "application/ld+json", |
| 318 | "application/javascript", |
| 319 | "application/typescript", |
| 320 | "application/xml", |
| 321 | "application/yaml", |
| 322 | "application/x-yaml", |
| 323 | "application/x-sh", |
| 324 | ]); |
| 325 | const TEXT_FILE_EXTENSIONS = new Set([ |
| 326 | ".txt", |
| 327 | ".md", |
| 328 | ".mdx", |
| 329 | ".json", |
| 330 | ".jsonl", |
| 331 | ".yaml", |
| 332 | ".yml", |
| 333 | ".toml", |
| 334 | ".xml", |
| 335 | ".csv", |
| 336 | ".tsv", |
| 337 | ".js", |
| 338 | ".jsx", |
| 339 | ".mjs", |
| 340 | ".cjs", |
| 341 | ".ts", |
| 342 | ".tsx", |
| 343 | ".html", |
| 344 | ".css", |
| 345 | ".scss", |
| 346 | ".less", |
| 347 | ".py", |
| 348 | ".rs", |
| 349 | ".go", |
| 350 | ".java", |
| 351 | ".kt", |
| 352 | ".swift", |
| 353 | ".c", |
| 354 | ".h", |
| 355 | ".cc", |
| 356 | ".cpp", |
| 357 | ".hpp", |
| 358 | ".cs", |
| 359 | ".rb", |
| 360 | ".php", |
| 361 | ".sh", |
| 362 | ".bash", |
| 363 | ".zsh", |
| 364 | ".sql", |
| 365 | ".graphql", |
| 366 | ".svelte", |
| 367 | ".vue", |
| 368 | ".log", |
| 369 | ".diff", |
| 370 | ".patch", |
| 371 | ".ini", |
| 372 | ".conf", |
| 373 | ]); |
| 374 | const ANTIGRAVITY_MAX_TEXT_ATTACHMENT_BYTES = 1024 * 1024; |
| 375 | const MAX_TOTAL_ATTACHMENT_BYTES = PROVIDER_SEND_TURN_MAX_FILE_BYTES; |
| 376 | |
| 377 | export const buildAntigravityPrompt = Effect.fn("buildAntigravityPrompt")(function* (input: { |
| 378 | readonly input: ProviderSendTurnInput["input"]; |
| 379 | readonly attachments: ProviderSendTurnInput["attachments"]; |
| 380 | readonly resolveAttachmentPath: ( |
| 381 | attachment: NonNullable<ProviderSendTurnInput["attachments"]>[number], |
| 382 | ) => string | null; |
| 383 | readonly promptCapabilities: EffectAcpSchema.AgentCapabilities["promptCapabilities"]; |
| 384 | }): Effect.fn.Return< |
| 385 | ReadonlyArray<EffectAcpSchema.ContentBlock>, |
| 386 | EffectAcpErrors.AcpError, |
| 387 | FileSystem.FileSystem | Path.Path |
| 388 | > { |
| 389 | const fileSystem = yield* FileSystem.FileSystem; |
| 390 | const path = yield* Path.Path; |
| 391 | const blocks: Array<EffectAcpSchema.ContentBlock> = []; |
| 392 | const text = input.input?.trim(); |
| 393 | if (text) blocks.push({ type: "text", text }); |
| 394 | let totalBytes = 0; |
| 395 | |
| 396 | for (const attachment of input.attachments ?? []) { |
| 397 | const isPastedText = |
| 398 | attachment.type === "file" && |
| 399 | "source" in attachment && |
| 400 | attachment.source?._tag === "pasted-text"; |
| 401 | // The text already carries the path; keep folded pastes lazy so agents can search without embedding the whole file. |
| 402 | const mimeType = attachment.mimeType.toLowerCase().split(";", 1)[0] ?? ""; |
| 403 | const image = attachment.type === "image" && IMAGE_MIME_TYPES.has(mimeType); |
| 404 | const audio = attachment.type === "file" && AUDIO_MIME_TYPES.has(mimeType); |
| 405 | const pdf = attachment.type === "file" && mimeType === "application/pdf"; |
| 406 | const textFile = |
| 407 | attachment.type === "file" && |
| 408 | (mimeType.startsWith("text/") || |
| 409 | TEXT_MIME_TYPES.has(mimeType) || |
| 410 | TEXT_FILE_EXTENSIONS.has(path.extname(attachment.name).toLowerCase())); |
| 411 | const isPathOnly = |
| 412 | (attachment.type === "image" && (!image || input.promptCapabilities?.image !== true)) || |
| 413 | (attachment.type === "file" && |
| 414 | (isPastedText || |
| 415 | (audio |
| 416 | ? input.promptCapabilities?.audio !== true |
| 417 | : !(pdf || textFile) || input.promptCapabilities?.embeddedContext !== true))); |
| 418 | const attachmentPath = input.resolveAttachmentPath(attachment); |
| 419 | if (!attachmentPath) { |
| 420 | return yield* EffectAcpErrors.AcpRequestError.invalidParams( |
| 421 | `Invalid attachment '${attachment.name}'.`, |
| 422 | ); |
| 423 | } |
| 424 | const info = yield* fileSystem |
| 425 | .stat(attachmentPath) |
| 426 | .pipe( |
| 427 | Effect.mapError(() => |
| 428 | EffectAcpErrors.AcpRequestError.invalidParams( |
| 429 | `Could not read attachment '${attachment.name}'.`, |
| 430 | ), |
| 431 | ), |
| 432 | ); |
| 433 | if (info.type !== "File") { |
| 434 | return yield* EffectAcpErrors.AcpRequestError.invalidParams( |
| 435 | `Could not read attachment '${attachment.name}'.`, |
| 436 | ); |
| 437 | } |
| 438 | if (isPathOnly) continue; |
| 439 | const size = Number(info.size); |
| 440 | const limit = image |
| 441 | ? PROVIDER_SEND_TURN_MAX_IMAGE_BYTES |
| 442 | : audio |
| 443 | ? ANTIGRAVITY_MAX_AUDIO_ATTACHMENT_BYTES |
| 444 | |
| 445 | ? MAX_TOTAL_ATTACHMENT_BYTES |
| 446 | : ANTIGRAVITY_MAX_TEXT_ATTACHMENT_BYTES; |
| 447 | if ( |
| 448 | attachment.type === "file" && |
| 449 | (size > limit || totalBytes + size > MAX_TOTAL_ATTACHMENT_BYTES) |
| 450 | ) { |
| 451 | continue; |
| 452 | } |
| 453 | totalBytes += size; |
| 454 | if (size > limit || totalBytes > MAX_TOTAL_ATTACHMENT_BYTES) { |
| 455 | return yield* EffectAcpErrors.AcpRequestError.invalidParams( |
| 456 | `Image '${attachment.name}' is too large. Antigravity accepts images up to 10 MiB and 50 MiB of native attachments per message.`, |
| 457 | ); |
| 458 | } |
| 459 | const uri = yield* path.toFileUrl(attachmentPath).pipe( |
| 460 | Effect.map((url) => url.href), |
| 461 | Effect.mapError(() => |
| 462 | EffectAcpErrors.AcpRequestError.invalidParams(`Invalid attachment '${attachment.name}'.`), |
| 463 | ), |
| 464 | ); |
| 465 | if (pdf) { |
| 466 | blocks.push({ type: "resource_link", uri, name: attachment.name, mimeType, size }); |
| 467 | continue; |
| 468 | } |
| 469 | const bytes = yield* fileSystem.stream(attachmentPath, { bytesToRead: limit + 1 }).pipe( |
| 470 | Stream.runCollect, |
| 471 | Effect.map((chunks) => Buffer.concat(chunks)), |
| 472 | Effect.mapError(() => |
| 473 | EffectAcpErrors.AcpRequestError.invalidParams( |
| 474 | `Could not read attachment '${attachment.name}'.`, |
| 475 | ), |
| 476 | ), |
| 477 | ); |
| 478 | totalBytes += bytes.length - size; |
| 479 | if (bytes.length > limit || totalBytes > MAX_TOTAL_ATTACHMENT_BYTES) { |
| 480 | return yield* EffectAcpErrors.AcpRequestError.invalidParams( |
| 481 | `Attachment '${attachment.name}' changed while being read and is too large.`, |
| 482 | ); |
| 483 | } |
| 484 | if (image) { |
| 485 | blocks.push({ type: "image", data: Buffer.from(bytes).toString("base64"), mimeType }); |
| 486 | } else if (audio) { |
| 487 | blocks.push({ type: "audio", data: Buffer.from(bytes).toString("base64"), mimeType }); |
| 488 | } else { |
| 489 | const encoding = |
| 490 | bytes[0] === 0xff && bytes[1] === 0xfe |
| 491 | ? "UTF-16LE" |
| 492 | : bytes[0] === 0xfe && bytes[1] === 0xff |
| 493 | ? "UTF-16BE" |
| 494 | : "UTF-8"; |
| 495 | const decoded = yield* Effect.try({ |
| 496 | try: () => new TextDecoder(encoding, { fatal: true }).decode(bytes), |
| 497 | catch: () => |
| 498 | EffectAcpErrors.AcpRequestError.invalidParams( |
| 499 | `Attachment '${attachment.name}' is not a ${encoding} text file.`, |
| 500 | ), |
| 501 | }); |
| 502 | if (decoded.includes("\0")) { |
| 503 | return yield* EffectAcpErrors.AcpRequestError.invalidParams( |
| 504 | `Attachment '${attachment.name}' contains binary data.`, |
| 505 | ); |
| 506 | } |
| 507 | blocks.push({ type: "resource", resource: { uri, mimeType, text: decoded } }); |
| 508 | } |
| 509 | } |
| 510 | if (blocks.length === 0) { |
| 511 | return yield* EffectAcpErrors.AcpRequestError.invalidParams( |
| 512 | "A turn requires text or supported attachments.", |
| 513 | ); |
| 514 | } |
| 515 | return blocks; |
| 516 | }); |