diff --git a/.github/workflows/scala.yml b/.github/workflows/scala.yml index f0e9b023..70c5ef2e 100644 --- a/.github/workflows/scala.yml +++ b/.github/workflows/scala.yml @@ -7,12 +7,24 @@ on: branches: [ "main" ] release: types: [ published ] + workflow_dispatch: + inputs: + tag: + description: "Release tag to publish to VS Code Marketplace (e.g. 0.2.4 or v0.2.4)" + required: true + type: string + pre_release: + description: "Publish as a VS Code Marketplace pre-release" + required: false + default: false + type: boolean permissions: contents: read jobs: build: + if: github.event_name != 'workflow_dispatch' name: Build and test (${{ matrix.os }}) strategy: fail-fast: false @@ -102,10 +114,13 @@ jobs: if-no-files-found: error retention-days: 14 - # Publishing a GitHub release (tag vX.Y.Z) builds the distribution jars and - # the compiled VS Code extension (.vsix) in separate, cache-free jobs so npm - # packaging cannot touch the tested CLI jars. Only the upload job, which runs - # no project code, receives `contents: write`. + # Publishing a GitHub release (tag X.Y.Z or vX.Y.Z) builds the distribution jars + # and the compiled VS Code extension (.vsix) in separate, cache-free jobs so npm + # packaging cannot touch the tested CLI jars. Only `publish-release` receives + # `contents: write`, and only `publish-vscode-marketplace` receives + # `id-token: write` (scoped to the `vscode-marketplace` environment for OIDC + # Trusted Publishing); neither runs project code. Manual `workflow_dispatch` + # runs only the VSIX build and Marketplace publish for an existing tag. build-release-jars: if: github.event_name == 'release' needs: build @@ -151,14 +166,27 @@ jobs: if-no-files-found: error build-release-vsix: - if: github.event_name == 'release' + if: ${{ !cancelled() && ((github.event_name == 'release' && needs.build.result == 'success') || github.event_name == 'workflow_dispatch') }} needs: build runs-on: ubuntu-latest timeout-minutes: 15 + outputs: + version: ${{ steps.version.outputs.version }} + pre_release: ${{ steps.version.outputs.pre_release }} steps: + - name: Validate release tag input + if: github.event_name == 'workflow_dispatch' + env: + TAG: ${{ inputs.tag }} + run: | + if [[ ! "$TAG" =~ ^v?[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "::error::tag '$TAG' must match v?MAJOR.MINOR.PATCH (e.g. 0.2.4 or v0.2.4)" + exit 1 + fi - uses: actions/checkout@v7 with: + ref: ${{ github.event_name == 'workflow_dispatch' && format('refs/tags/{0}', inputs.tag) || '' }} persist-credentials: false - name: Set up Node.js 22 uses: actions/setup-node@v4 @@ -167,11 +195,12 @@ jobs: - name: Check that the release tag matches Versions.atc and vscode/package.json id: version env: - TAG: ${{ github.event.release.tag_name }} + TAG: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || github.event.release.tag_name }} + PRE_RELEASE: ${{ (github.event_name == 'workflow_dispatch' && inputs.pre_release) || (github.event_name == 'release' && github.event.release.prerelease) }} run: | version=$(sed -nE 's/^ *val atc = "([^"]+)".*/\1/p' build.mill) vscode_version=$(node -p "require('./vscode/package.json').version") - echo "tag: $TAG, Versions.atc: $version, vscode/package.json: $vscode_version" + echo "tag: $TAG, Versions.atc: $version, vscode/package.json: $vscode_version, pre_release: $PRE_RELEASE" if [ "$TAG" != "v$version" ] && [ "$TAG" != "$version" ]; then echo "::error::release tag '$TAG' does not match Versions.atc = \"$version\" in build.mill; bump the version, move the tag and publish again" exit 1 @@ -181,14 +210,24 @@ jobs: exit 1 fi echo "version=$version" >> "$GITHUB_OUTPUT" + if [ "$PRE_RELEASE" = "true" ]; then + echo "pre_release=true" >> "$GITHUB_OUTPUT" + else + echo "pre_release=false" >> "$GITHUB_OUTPUT" + fi - name: Build, test, and package VS Code extension env: VERSION: ${{ steps.version.outputs.version }} + PRE_RELEASE: ${{ steps.version.outputs.pre_release }} run: | npm --prefix vscode ci npm --prefix vscode run typecheck npm --prefix vscode run test:unit - npm --prefix vscode run package + if [ "$PRE_RELEASE" = "true" ]; then + npm --prefix vscode run package -- --pre-release + else + npm --prefix vscode run package + fi test -f "vscode/atc-vscode-${VERSION}.vsix" - name: Stage release VSIX env: @@ -233,3 +272,36 @@ jobs: fi gh release upload "$TAG" assets/atc.jar assets/atc-lib.jar "${vsix[0]}" gh release view "$TAG" --json assets --jq '.assets[] | "\(.name)\t\(.size) bytes"' + + publish-vscode-marketplace: + if: ${{ !cancelled() && needs.build-release-vsix.result == 'success' && ((github.event_name == 'release' && needs.publish-release.result == 'success') || github.event_name == 'workflow_dispatch') }} + needs: [build-release-vsix, publish-release] + runs-on: ubuntu-latest + timeout-minutes: 10 + environment: vscode-marketplace + permissions: + id-token: write + + steps: + - uses: actions/download-artifact@v4 + with: + name: release-vsix + path: assets + - name: Set up Node.js 22 + uses: actions/setup-node@v4 + with: + node-version: '22' + - name: Publish VS Code extension to Visual Studio Marketplace (OIDC) + env: + PRE_RELEASE: ${{ needs.build-release-vsix.outputs.pre_release }} + run: | + vsix=(assets/atc-vscode-*.vsix) + if [ "${#vsix[@]}" -ne 1 ] || [ ! -f "${vsix[0]}" ]; then + echo "::error::expected exactly one .vsix asset in assets/, found: ${vsix[*]}" + exit 1 + fi + publish_args=(publish --oidc --skip-duplicate --packagePath "${vsix[0]}") + if [ "$PRE_RELEASE" = "true" ]; then + publish_args+=(--pre-release) + fi + npx --yes @vscode/vsce@4.1.1 "${publish_args[@]}" diff --git a/README.md b/README.md index 2a8570f2..b5b0452b 100644 --- a/README.md +++ b/README.md @@ -165,6 +165,8 @@ atc -p 'summarize the README' atc -p 'summarize the README' --output json ``` +To use ATC inside VS Code, see the [VS Code extension](#vs-code-extension). + ## Capabilities and ambient authority In ordinary Scala, any expression can call `Files.readString` or spawn a subprocess; @@ -569,7 +571,13 @@ any retained run in full. Press Ctrl-O to toggle expanded streaming of code, out diffs, and reasoning. While the agent is working, you can type and submit a steering message (using Backspace, Ctrl-W, Ctrl-U, or Esc to edit or discard the draft); it is delivered before the next tool call. Long pastes collapse into placeholders such as -`[Pasted text #1: 120 lines]` in the input buffer while sending the full text. Interactive +`[Pasted text #1: 120 lines]` in the input buffer while sending the full text. You can +attach images to prompts with `/image ` (alias `/attach`), `Ctrl-V` (reads the OS +clipboard), or by dragging and dropping image files onto the terminal; the agent can also +inspect readable, unclassified image files or raw image bytes directly from the REPL via +`viewImage`. Large images are automatically resized and compressed, classified paths are +guarded, and saved sessions replace binary image payloads with compact metadata +placeholders. Interactive sessions auto-save after each turn, and the next interactive start in the same directory offers to resume. ATC notifies you when a turn finishes or awaits input, and emits Program Status Protocol updates for supporting terminals. Background monitor messages trigger a @@ -582,7 +590,9 @@ The terminal tab (and the tmux window when running inside tmux) is titled ` or the agent's `setTitle` renames it for the session. In `-p` non-interactive mode, ATC never prompts: unpermitted operations fail immediately -unless `--approve-all` is passed (intended only for trusted environments). By default, the +unless `--approve-all` is passed (intended only for trusted environments). Pass repeatable +`-i` / `--image ` flags to attach images to a `-p` request (or pre-stage them on +interactive startup). By default, the final answer is written to standard output while notices, tool blocks, and statistics go to standard error; with `--output json`, structured JSONL events (`start`, `tool_start`, `tool_end`, `delta`, `result`, …) are emitted to standard output instead. @@ -591,11 +601,25 @@ standard error; with `--output json`, structured JSONL events (`start`, `tool_st A VS Code extension lives in [vscode/](vscode/README.md) and communicates with a persistent `atc --ide` session over a bidirectional JSONL stdio protocol. It provides a native sidebar -chat panel with streaming Markdown, collapsible Scala 3 REPL tool blocks, clickable inline +chat panel with streaming Markdown, collapsible Scala 3 REPL tool blocks, image attachments +(paste, drag-and-drop, file picker, and inline `viewImage` previews), clickable inline diffs, interactive permission/question/skill/project-trust approval cards, mode and model pickers, editor actions (send/explain selection, fix diagnostics, run Scala selection in the shared REPL), a status bar indicator, and JSON Schema validation for `.atc/config.json`. +After [installing ATC](#setup), install the extension from the +[Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=noti0na1.atc-vscode) +(search for **ATC — Agent with Tracked Capabilities** in the Extensions view) or from the +command line: + +```bash +code --install-extension noti0na1.atc-vscode +``` + +Pre-built `.vsix` packages are also attached to every +[GitHub release](https://github.com/lampepfl/atc/releases). Open the ATC sidebar with +`Cmd+Alt+A` (macOS) or `Ctrl+Alt+A` (Windows/Linux). + ## License Apache-2.0. diff --git a/app/src/atc/App.scala b/app/src/atc/App.scala index b5030d99..0fbd1abf 100644 --- a/app/src/atc/App.scala +++ b/app/src/atc/App.scala @@ -5,7 +5,7 @@ import atc.commands.{Commands, SlashCommand} import atc.config.{Config, Configuration, ProjectConventions, ProjectRules} import atc.host.{FileChange, Host, HostLlm, HostOutput, HostUi} import atc.lib.Todo -import atc.llm.{CancelledException, ChatGPTAuth, ChatModel, TokenUsage} +import atc.llm.{CancelledException, ChatGPTAuth, ChatModel, ImageInput, Images, TokenUsage} import atc.memory.MemoryStore import atc.perms.* import atc.platform.PlatformPath @@ -221,6 +221,8 @@ final class App(args: Cli.Args, val tui: Tui, json: Option[JsonReporter] = None) private val commands = Commands(this) + private[atc] def clearStagedImages(): Unit = commands.imageCommands.clearStaged() + // ── running ─────────────────────────────────────────────────────── private def cleanup(action: => Unit): Unit = @@ -231,9 +233,12 @@ final class App(args: Cli.Args, val tui: Tui, json: Option[JsonReporter] = None) updateStatus() tui.completions = commands.complete tui.commandList = commands.commandTable + tui.onPasteImage = () => commands.imageCommands.pasteForPrompt() + tui.onPastedPaths = text => commands.imageCommands.handlePastedPaths(text) try args.prompt match case Some(p) => + val cliImages = commands.imageCommands.loadCliImages(args.images, nonInteractive = true) json.foreach: reporter => reporter.start(Main.Version, agent.model.ref, policy.mode.label, PlatformPath.display(cwd)) startupWarnings.foreach(reporter.warn) @@ -252,7 +257,7 @@ final class App(args: Cli.Args, val tui: Tui, json: Option[JsonReporter] = None) agentUi.info(s"Using ${models.describe(agent.model)}: no model was named with -m or in a config.") sandbox.warm() // Report a failed turn through the process exit code so scripts can detect it. - runTurn(p).exitCode + runTurn(p, cliImages).exitCode case None => if !policy.effective(ScopeId.Base, PlatformPath.canonical(cwd)).canRead then tui.info( @@ -260,6 +265,7 @@ final class App(args: Cli.Args, val tui: Tui, json: Option[JsonReporter] = None) "Run `atc --init` to give this project a config, or add a rule to ~/.atc/config.json." ) banner() + if args.images.nonEmpty then commands.imageCommands.stageCliImages(args.images) models.catalog.refresh() if tui.menusAvailable then commands.sessionCommands.offerResume() sandbox.warm() // after the resume offer: restoring would only discard it @@ -313,14 +319,14 @@ final class App(args: Cli.Args, val tui: Tui, json: Option[JsonReporter] = None) ) /** Run one turn and retain its outcome for the terminal summary and scripted exit code. */ - private def runTurn(input: String): TurnOutcome = + private def runTurn(input: String, images: List[ImageInput] = Nil): TurnOutcome = predictor.invalidate() tui.beginTurn() val started = System.nanoTime() val (usageBefore, callsBefore) = (agent.usage, agent.toolCalls) var outcome = TurnOutcome.Failed try - outcome = agent.turn(sandbox.ensure(), input, () => tui.isInterrupted) + outcome = agent.turn(sandbox.ensure(), input, () => tui.isInterrupted, images) outcome catch case _: CancelledException | _: InterruptedException => @@ -374,16 +380,22 @@ final class App(args: Cli.Args, val tui: Tui, json: Option[JsonReporter] = None) var running = true while running do // A monitor message ends the read (`tui.wake`), which keeps what the user typed. - val next = if hasPendingInput then Some("") else tui.readLine(prompt) + val next = if hasPendingInput then Some(Tui.UserInput("")) else tui.readInput(prompt) next match - case Some("") if hasPendingInput => afterTurn(runTurn("")) + case Some(Tui.UserInput("", Nil)) if hasPendingInput => afterTurn(runTurn("")) case None => Debug.log("input closed, exiting") running = false - case Some(line) if line.trim.isEmpty => () + case Some(Tui.UserInput(line, Nil)) if line.trim.isEmpty => + val staged = commands.imageCommands.stagedCount + if staged > 0 then + tui.info( + s"${atc.ui.Format.plural(staged, "image")} staged — type a message to send, or /image clear to discard." + ) // Typed out of habit; not listed in /help. - case Some(line) if App.QuitWords.contains(line.trim.toLowerCase(Locale.ROOT)) => running = false - case Some(line) if SlashCommand.isCommandLine(line) => + case Some(Tui.UserInput(line, Nil)) if App.QuitWords.contains(line.trim.toLowerCase(Locale.ROOT)) => + running = false + case Some(Tui.UserInput(line, Nil)) if SlashCommand.isCommandLine(line) => commands.run(line.trim) match case Commands.Action.Continue => tui.commandList = commands.commandTable @@ -391,10 +403,18 @@ final class App(args: Cli.Args, val tui: Tui, json: Option[JsonReporter] = None) running = false case Commands.Action.SendPrompt(expanded) => monitorsHeld = false - afterTurn(runTurn(expanded)) - case Some(line) => - monitorsHeld = false - afterTurn(runTurn(line)) + val staged = commands.imageCommands.takeStaged() + afterTurn(runTurn(expanded, staged)) + case Some(Tui.UserInput(line, inlineImages)) => + val combined = commands.imageCommands.staged ++ inlineImages + if combined.size > Images.MaxImagesPerMessage then + tui.error( + s"Too many images (${combined.size}; at most ${Images.MaxImagesPerMessage} allowed). Use /image rm or /image clear." + ) + else + commands.imageCommands.clearStaged() + monitorsHeld = false + afterTurn(runTurn(line, combined)) /** After Ctrl-C, a correction typed during the turn goes back to the prompt: starting * another turn with it would contact the model right after the user stopped it. Monitor @@ -410,10 +430,13 @@ final class App(args: Cli.Args, val tui: Tui, json: Option[JsonReporter] = None) tui.commandList = commands.commandTable if tui.menusAvailable then commands.sessionCommands.checkpoint() - /** The input prompt names the mode unless it is the full one. */ - def prompt: String = policy.mode match - case Mode.Full => "> " - case m => s"${m.label} > " + /** The input prompt names the mode unless it is the full one, plus any staged image count. */ + def prompt: String = + val count = commands.imageCommands.stagedCount + val tag = if count == 0 then "" else s"[${atc.ui.Format.plural(count, "image")}] " + policy.mode match + case Mode.Full => s"$tag> " + case m => s"${m.label} $tag> " object App: /** Thrown to end the program from setup, before there is anything to run. */ diff --git a/app/src/atc/Cli.scala b/app/src/atc/Cli.scala index 10170d64..274ade84 100644 --- a/app/src/atc/Cli.scala +++ b/app/src/atc/Cli.scala @@ -1,5 +1,6 @@ package atc +import atc.llm.Images import atc.perms.Mode import atc.platform.PlatformPath @@ -24,6 +25,7 @@ private[atc] object Cli: model: Option[String] = None, mode: Option[Mode] = None, prompt: Option[String] = None, + images: List[Path] = Nil, output: OutputFormat = OutputFormat.Text, ide: Boolean = false, approveAll: Boolean = false, @@ -35,7 +37,7 @@ private[atc] object Cli: def outputJson: Boolean = output == OutputFormat.Json private val FlagsWithValues = - Set("-c", "--config", "-C", "--cwd", "-m", "--model", "-p", "--prompt", "--mode", "--output") + Set("-c", "--config", "-C", "--cwd", "-m", "--model", "-p", "--prompt", "-i", "--image", "--mode", "--output") /** Parse first, then resolve paths once. In particular, `-c extra.json -C * project` and `-C project -c extra.json` have identical meaning. */ @@ -48,7 +50,7 @@ private[atc] object Cli: val raw = parseRaw(expanded, initial) val base = initial.cwd.toAbsolutePath.nn.normalize.nn val cwd = resolve(base, raw.cwd) - raw.copy(cwd = cwd, config = raw.config.map(resolve(cwd, _))) + raw.copy(cwd = cwd, config = raw.config.map(resolve(cwd, _)), images = raw.images.map(resolve(cwd, _))) @tailrec private def parseRaw(arguments: List[String], current: Args): Args = arguments match case Nil => current @@ -58,6 +60,8 @@ private[atc] object Cli: parseRaw(rest, current.copy(cwd = PlatformPath.parse(value))) case ("-m" | "--model") :: value :: rest => parseRaw(rest, current.copy(model = Some(value))) case ("-p" | "--prompt") :: value :: rest => parseRaw(rest, current.copy(prompt = Some(value))) + case ("-i" | "--image") :: value :: rest => + parseRaw(rest, current.copy(images = current.images :+ PlatformPath.parse(value))) case "--mode" :: value :: rest => parseRaw(rest, current.copy(mode = Some(Mode.parse(value)))) case "--output" :: value :: rest => parseRaw(rest, current.copy(output = OutputFormat.parse(value))) case "--ide" :: rest => parseRaw(rest, current.copy(ide = true)) @@ -91,6 +95,19 @@ private[atc] object Cli: throw IllegalArgumentException("--ide cannot be used with --init or --init-global (try --help)") if args.outputJson && args.prompt.isEmpty then throw IllegalArgumentException("--output json requires -p / --prompt (try --help)") + if args.images.nonEmpty then + if args.ide then + throw IllegalArgumentException("-i / --image cannot be used with --ide (try --help)") + if args.init || args.initGlobal then + throw IllegalArgumentException("-i / --image cannot be used with --init or --init-global (try --help)") + if args.images.size > Images.MaxImagesPerMessage then + throw IllegalArgumentException( + s"Too many images (${args.images.size}); at most ${Images.MaxImagesPerMessage} allowed" + ) + args.images.foreach: image => + if !Files.exists(image) then throw IllegalArgumentException(s"Image file does not exist: $image") + if !Files.isRegularFile(image) then + throw IllegalArgumentException(s"Image path is not a regular file: $image") if !args.init && !args.initGlobal then args.config.foreach: config => if !Files.exists(config) then throw IllegalArgumentException(s"Config file does not exist: $config") diff --git a/app/src/atc/Main.scala b/app/src/atc/Main.scala index 6d7f21ae..56748a43 100644 --- a/app/src/atc/Main.scala +++ b/app/src/atc/Main.scala @@ -22,6 +22,7 @@ object Main: | -C, --cwd working directory (default: current) | -m, --model model to use: an alias from the config, or provider/alias | -p, --prompt run one turn non-interactively and exit + | -i, --image attach an image file (repeatable; use with -p or interactive start) | --output output format for -p: text (default) | json (JSONL events on stdout) | --ide run interactive JSONL protocol over stdin/stdout (for IDE plugins) | --mode sandbox mode: readonly | local | full (default: the config's "mode", else full) diff --git a/app/src/atc/agent/Agent.scala b/app/src/atc/agent/Agent.scala index 9e4612ed..918a10f8 100644 --- a/app/src/atc/agent/Agent.scala +++ b/app/src/atc/agent/Agent.scala @@ -42,7 +42,7 @@ final class Agent( private val conversation = Conversation() private val context = ContextManager() private val request = ModelRequest() - private val queuedInput = ConcurrentLinkedQueue[String]() + private val queuedInput = ConcurrentLinkedQueue[Agent.QueuedInput]() /** Monitor messages for the model, in the form it reads them. */ private val monitorMessages = ConcurrentLinkedQueue[String]() private val monitorLock = new AnyRef @@ -102,9 +102,10 @@ final class Agent( /** Queue input typed while a turn runs. A model request in progress is cancelled so * that the next round sees the input; a running tool call finishes first. */ - def submit(input: String): Unit = - if input.trim.nonEmpty then - queuedInput.add(input.trim) + def submit(input: String, images: List[ImageInput] = Nil): Unit = + val trimmed = input.trim + if trimmed.nonEmpty || images.nonEmpty then + queuedInput.add(Agent.QueuedInput(trimmed, images)) request.recheck() /** The user interrupted: a model request in progress re-evaluates its cancellation @@ -113,15 +114,19 @@ final class Agent( def queuedInputCount: Int = queuedInput.size() - /** Remove and return the input queued during a turn, in the order it was typed. */ + /** Remove and return the text of input queued during a turn, in the order it was typed. */ def takeQueuedInput(): List[String] = + takeQueuedSteering().map(_.text).filter(_.nonEmpty) + + /** Remove and return queued steering inputs (text and images), in the order they were sent. */ + def takeQueuedSteering(): List[Agent.QueuedInput] = Iterator.continually(queuedInput.poll()).takeWhile(_ != null).map(_.nn).toList private def acceptQueuedInput(): Unit = var input = queuedInput.poll() while input != null do - conversation.steer(input) - ui.inputAccepted(input) + conversation.steer(input.text, input.images) + ui.inputAccepted(input.text, input.images) input = queuedInput.poll() var message = monitorMessages.poll() while message != null do @@ -306,13 +311,23 @@ final class Agent( Agent.CompactOutcome.Compacted(older.size, recent.size, tokensBefore, tokensAfter) /** Run one user turn; returns when the model gives its final answer or the user interrupts. */ - def turn(session: => ReplSession, input: String, cancelled: () => Boolean): TurnOutcome = - runTurn(ScalaToolRunner(session, policy, ui, config.maxToolOutputChars, cancelled), input, cancelled) + def turn( + session: => ReplSession, + input: String, + cancelled: () => Boolean, + images: List[ImageInput] = Nil, + ): TurnOutcome = + runTurn(ScalaToolRunner(session, policy, ui, config.maxToolOutputChars, cancelled), input, cancelled, images) /** Core entry point, with concrete tool execution supplied by the host adapter. */ - private[atc] def runTurn(runner: ToolRunner, input: String, cancelled: () => Boolean): TurnOutcome = + private[atc] def runTurn( + runner: ToolRunner, + input: String, + cancelled: () => Boolean, + images: List[ImageInput] = Nil, + ): TurnOutcome = tools = runner.tools - conversation.beginTurn(input) + conversation.beginTurn(input, images) context.beginTurn() Turn(runner, cancelled).run() @@ -526,6 +541,9 @@ final class Agent( Done(TurnOutcome.Interrupted) object Agent: + /** Steering input queued by the user while a turn is in progress. */ + final case class QueuedInput(text: String, images: List[ImageInput] = Nil) + /** Monitor messages kept while they wait for the model. */ val MaxMonitorMessages: Int = 50 diff --git a/app/src/atc/agent/AgentUI.scala b/app/src/atc/agent/AgentUI.scala index 803e7e7d..3c0169e3 100644 --- a/app/src/atc/agent/AgentUI.scala +++ b/app/src/atc/agent/AgentUI.scala @@ -1,5 +1,6 @@ package atc.agent +import atc.llm.ImageInput import atc.sandbox.ExecutionResult /** Terminal callbacks for streaming agent turns and tool execution. */ @@ -21,6 +22,12 @@ trait AgentUI: def info(text: String): Unit = warn(text) /** Notify that queued mid-turn steering input entered the conversation at a tool boundary. */ def inputAccepted(text: String): Unit = () + /** Notify that queued mid-turn steering input (possibly with images) entered the conversation. */ + def inputAccepted(text: String, images: List[ImageInput]): Unit = + val display = + if images.isEmpty then text + else List(text, images.map(_.placeholder).mkString(" ")).filter(_.nonEmpty).mkString(" ") + inputAccepted(display) /** Notify that a background monitor message was appended to the conversation. */ def monitorMessage(text: String): Unit = () /** Prompt the user to extend the per-turn tool-call budget by another `budget` calls diff --git a/app/src/atc/agent/ContextManager.scala b/app/src/atc/agent/ContextManager.scala index ab93bbe0..27229b6e 100644 --- a/app/src/atc/agent/ContextManager.scala +++ b/app/src/atc/agent/ContextManager.scala @@ -75,11 +75,11 @@ final class ContextManager: case None => (history, 0) contextDropped += dropped val preparedHistory = fitted match - case Msg.User(text) :: rest if dropped > 0 => + case Msg.User(text, images) :: rest if dropped > 0 => val notes = if retained.isEmpty then "" else s"\n\n[retained task context; current user instructions take precedence]\n$retained" - Msg.User(s"${AgentMessages.contextCutNotice(contextDropped)}$notes\n\n$text") :: rest + Msg.User(s"${AgentMessages.contextCutNotice(contextDropped)}$notes\n\n$text", images) :: rest case other => other // The estimate of what will actually be sent, for the overflow check and calibration. @@ -177,11 +177,12 @@ object ContextManager: estimateTokens(msg, model.providerKey, model.ref) private def estimateTokens(msg: Msg, replayed: NativeTurn => Boolean): Long = msg match - case Msg.User(text) => estimateTokens(text) + 4 + case Msg.User(text, images) => estimateTokens(text) + images.map(_.estimatedTokens).sum + 4 case Msg.Continuation(text) => estimateTokens(text) + 4 case Msg.Monitor(text) => estimateTokens(text) + 4 case Msg.Assistant(text, calls, native) => estimateAssistantTokens(text, calls, native.filter(replayed)) - case Msg.ToolResults(results) => results.map(result => estimateTokens(result.output) + 12).sum + 4 + case Msg.ToolResults(results) => + results.map(result => estimateTokens(result.output) + result.images.map(_.estimatedTokens).sum + 12).sum + 4 private def estimateAssistantTokens( text: String, @@ -204,7 +205,7 @@ object ContextManager: ): (List[Msg], List[Msg]) = val suffixSizes = history.map(estimate).scanRight(0L)(_ + _).toVector val start = history.zipWithIndex.collectFirst { - case (Msg.User(_), index) if suffixSizes(index) <= budget => index + case (Msg.User(_, _), index) if suffixSizes(index) <= budget => index }.getOrElse(history.size) history.splitAt(start) @@ -222,7 +223,7 @@ object ContextManager: fitWithSizes(history, sizes, sizes.sum, budget) private def fitWithSizes(history: List[Msg], sizes: List[Long], total: Long, budget: Long): (List[Msg], Int) = - val users = history.zipWithIndex.collect { case (Msg.User(_), i) => i } + val users = history.zipWithIndex.collect { case (Msg.User(_, _), i) => i } if total <= budget || users.lastOption.forall(_ == 0) then (history, 0) else // The earliest user boundary that sheds enough (`before(i)` is the size of diff --git a/app/src/atc/agent/Conversation.scala b/app/src/atc/agent/Conversation.scala index c6e38c94..2565a1e9 100644 --- a/app/src/atc/agent/Conversation.scala +++ b/app/src/atc/agent/Conversation.scala @@ -1,7 +1,7 @@ package atc.agent import atc.TextFiles -import atc.llm.{Msg, ToolResult} +import atc.llm.{ImageInput, Msg, ToolResult} /** Stores conversation history and pending notes, and repairs incomplete * message sequences after failed or interrupted rounds. */ @@ -19,38 +19,44 @@ private[agent] final class Conversation: def notes: List[String] = synchronized(pendingNotes) - private def remember(input: String): Unit = - if input.nonEmpty then - requests :+= TextFiles.takeChars(input, MaxRequestChars) + private def remember(input: String, images: List[ImageInput]): Unit = + val entry = + if input.nonEmpty then input + else images.map(_.placeholder).mkString(" ") + if entry.nonEmpty then + requests :+= TextFiles.takeChars(entry, MaxRequestChars) if requests.size > RecentRequests + 1 then requests = requests.take(1) ++ requests.takeRight(RecentRequests) def queueNote(note: String): Unit = synchronized: pendingNotes :+= note - def beginTurn(input: String): Unit = synchronized: - remember(input) + def beginTurn(input: String, images: List[ImageInput] = Nil): Unit = synchronized: + remember(input, images) val message = AgentMessages.userMessage(pendingNotes, input) pendingNotes = Nil - if message.nonEmpty then + if message.nonEmpty || images.nonEmpty then messages.lastOption match case Some(_: Msg.ToolResults | _: Msg.Continuation | _: Msg.User | _: Msg.Monitor) => append(Msg.Assistant(AgentMessages.pausedForUpdate, Nil, None)) - append(Msg.User(message)) - case _ => append(Msg.User(message)) + append(Msg.User(message, images)) + case _ => append(Msg.User(message, images)) def append(message: Msg): Unit = synchronized: messages :+= message /** Add a user correction only after pending tool calls have matching results. */ - def steer(input: String): Unit = synchronized: - remember(input) + def steer(input: String, images: List[ImageInput] = Nil): Unit = synchronized: + remember(input, images) messages.lastOption match - case Some(Msg.User(text)) => - messages = messages.init :+ Msg.User(List(text, input).filter(_.nonEmpty).mkString("\n\n")) + case Some(Msg.User(text, prevImages)) => + messages = messages.init :+ Msg.User( + List(text, input).filter(_.nonEmpty).mkString("\n\n"), + prevImages ++ images, + ) case Some(_: Msg.ToolResults | _: Msg.Continuation | _: Msg.Monitor) => append(Msg.Assistant(AgentMessages.pausedForUpdate, Nil, None)) - append(Msg.User(input)) - case _ => append(Msg.User(input)) + append(Msg.User(input, images)) + case _ => append(Msg.User(input, images)) /** Deliver a monitor's message as a distinct [[Msg.Monitor]] turn so untrusted monitor * output never fuses into a real [[Msg.User]] message or feeds next-input prediction. */ @@ -87,7 +93,7 @@ private[agent] final class Conversation: messages.lastOption match case Some(Msg.Assistant(_, calls, _)) if calls.nonEmpty => append(Msg.ToolResults(calls.map(call => ToolResult(call.id, marker, isError = true)))) - case Some(Msg.User(_) | Msg.Continuation(_) | Msg.Monitor(_)) => + case Some(Msg.User(_, _) | Msg.Continuation(_) | Msg.Monitor(_)) => append(Msg.Assistant(marker, Nil, None)) case _ => () diff --git a/app/src/atc/agent/InputPredictor.scala b/app/src/atc/agent/InputPredictor.scala index a32a571d..36e7e414 100644 --- a/app/src/atc/agent/InputPredictor.scala +++ b/app/src/atc/agent/InputPredictor.scala @@ -131,7 +131,11 @@ object InputPredictor: * record instead of letting transcript content reshape the prediction prompt. */ def render(history: List[Msg]): String = val texts = history.reverseIterator.collect { - case Msg.User(t) => ("User", t) + case Msg.User(t, imgs) => + val summary = + if imgs.isEmpty then t + else List(t, imgs.map(_.placeholder).mkString(" ")).filter(_.nonEmpty).mkString(" ") + ("User", summary) case Msg.Assistant(t, _, _) if t.trim.nonEmpty => ("Agent", t) } // Roughly the last N exchanges: an exchange is a user line plus the answers to it. diff --git a/app/src/atc/agent/Prompts.scala b/app/src/atc/agent/Prompts.scala index f03e6b6e..30783721 100644 --- a/app/src/atc/agent/Prompts.scala +++ b/app/src/atc/agent/Prompts.scala @@ -199,7 +199,8 @@ object Prompts: | `pyproject.toml`, `Cargo.toml`, `go.mod`, `Makefile`, etc.) to learn the layout, build tool, tests, and | conventions, subject to the instruction boundaries above. |2. Explore before editing: use `ls`, `walk`, `find`, `grepRecursive`, and `cat(path)` / `cat(path, from, to)` - | for numbered views (`read` and `readLines` return raw text for programmatic use). + | for numbered views (`read` and `readLines` return raw text for programmatic use); use `viewImage(path)` + | (or `viewImage(bytes, label)`) to inspect image files or screenshots visually. |3. Edit safely. Prefer `replaceExact(path, expected, replacement)` for literal edits (validates a unique match | before writing), `sed(path, regex, replacement)` for regex edits (throws on zero matches; verify the | returned count), and `write(path, content)` for new files or full rewrites (read first). Leave unrelated diff --git a/app/src/atc/agent/SessionStore.scala b/app/src/atc/agent/SessionStore.scala index b79c3bb2..1ccc1447 100644 --- a/app/src/atc/agent/SessionStore.scala +++ b/app/src/atc/agent/SessionStore.scala @@ -142,18 +142,29 @@ private[atc] object SessionStore: decode(String(bytes, UTF_8)) /** A neutral message as saved sessions and the compaction transcript write it, without - * native replay payloads or the internal `needsReplan` flag. */ - private[agent] def messageJson(message: Msg): ujson.Obj = message match - case Msg.User(text) => ujson.Obj("role" -> "user", "text" -> text) - case Msg.Continuation(text) => ujson.Obj("role" -> "continuation", "text" -> text) - case Msg.Monitor(text) => ujson.Obj("role" -> "monitor", "text" -> text) - case Msg.Assistant(text, calls, _) => - val entries = calls.map(call => ujson.Obj("id" -> call.id, "name" -> call.name, "arguments" -> call.arguments)) - ujson.Obj("role" -> "assistant", "text" -> text, "calls" -> ujson.Arr.from(entries)) - case Msg.ToolResults(results) => - val entries = - results.map(result => ujson.Obj("id" -> result.callId, "output" -> result.output, "error" -> result.isError)) - ujson.Obj("role" -> "tools", "results" -> ujson.Arr.from(entries)) + * native replay payloads, raw image bytes, or the internal `needsReplan` flag. + * Attached images are replaced by compact metadata placeholders so saved sessions + * remain small and compaction transcripts never serialize base64 blobs. */ + private[agent] def messageJson(message: Msg): ujson.Obj = + def withPlaceholders(text: String, images: List[atc.llm.ImageInput], sep: String): String = + if images.isEmpty then text + else List(text, images.map(_.placeholder).mkString("\n")).filter(_.nonEmpty).mkString(sep) + message match + case Msg.User(text, images) => + ujson.Obj("role" -> "user", "text" -> withPlaceholders(text, images, "\n\n")) + case Msg.Continuation(text) => ujson.Obj("role" -> "continuation", "text" -> text) + case Msg.Monitor(text) => ujson.Obj("role" -> "monitor", "text" -> text) + case Msg.Assistant(text, calls, _) => + val entries = calls.map(call => ujson.Obj("id" -> call.id, "name" -> call.name, "arguments" -> call.arguments)) + ujson.Obj("role" -> "assistant", "text" -> text, "calls" -> ujson.Arr.from(entries)) + case Msg.ToolResults(results) => + val entries = results.map: result => + ujson.Obj( + "id" -> result.callId, + "output" -> withPlaceholders(result.output, result.images, "\n"), + "error" -> result.isError, + ) + ujson.Obj("role" -> "tools", "results" -> ujson.Arr.from(entries)) private[atc] def encode(session: SessionSnapshot): String = def strings(values: List[String]): ujson.Arr = ujson.Arr.from(values) diff --git a/app/src/atc/agent/ToolRunner.scala b/app/src/atc/agent/ToolRunner.scala index 8db83acd..bb33ae9f 100644 --- a/app/src/atc/agent/ToolRunner.scala +++ b/app/src/atc/agent/ToolRunner.scala @@ -48,7 +48,13 @@ private[atc] final class ScalaToolRunner( case (Decision.Revise(_), _) => true case _ => false } - ToolResult(call.id, rendered, isError = !result.success, needsReplan = needsReplan) + ToolResult( + call.id, + rendered, + isError = !result.success, + needsReplan = needsReplan, + images = result.images, + ) private[atc] object ScalaToolRunner: /** The native Scala tool; other operations are library calls. */ diff --git a/app/src/atc/commands/Commands.scala b/app/src/atc/commands/Commands.scala index d012a139..328862d7 100644 --- a/app/src/atc/commands/Commands.scala +++ b/app/src/atc/commands/Commands.scala @@ -22,6 +22,8 @@ final class Commands(app: App): private val configCommands = ConfigCommands(app) private val skillCommands = SkillCommands(app) private val memoryCommands = MemoryCommands(app) + /** Manages staged images, clipboard paste, and dragged image paths. */ + val imageCommands: ImageCommands = ImageCommands(app) /** Also used at the start and end of an interactive run, to resume and save the session. */ val sessionCommands: SessionCommands = SessionCommands(app) @@ -47,6 +49,7 @@ final class Commands(app: App): "last" :: tui.outputHistory.ids.map(_.toString), skillTargets = skillCommands.targetsFor, memoryTargets = memoryCommands.targetsFor, + imageTargets = imageCommands.targetsFor, ) /** Handle a slash command line; returns [[Commands.Action]] indicating whether to continue, @@ -94,6 +97,7 @@ final class Commands(app: App): if ref.startsWith("No API name ") || ref == atc.ApiReference.Unavailable then tui.println(ref) else tui.showScala(ref) case Cmd.Run => sessionCommands.run(arg) + case Cmd.Image => imageCommands.run(arg) case Cmd.New => sessionCommands.newSession() case Cmd.Reset => sessionCommands.reset() case Cmd.Compact => sessionCommands.compact(arg) @@ -150,6 +154,7 @@ object Commands: outputIds: => List[String] = Nil, skillTargets: String => List[String] = _ => Nil, memoryTargets: String => List[String] = _ => Nil, + imageTargets: String => List[String] = _ => Nil, ): List[String] = words match case typed :: Nil => val lower = typed.toLowerCase(Locale.ROOT) @@ -177,6 +182,9 @@ object Commands: case (Cmd.Memory, sub :: _ :: Nil) if Set("list", "show", "delete", "rm", "forget", "clear")(sub.toLowerCase(Locale.ROOT)) => memoryTargets(sub) + case (Cmd.Image, _ :: Nil) => ImageCommands.Subcommands + case (Cmd.Image, sub :: _ :: Nil) if Set("rm", "remove")(sub.toLowerCase(Locale.ROOT)) => + imageTargets(sub) case (Cmd.Kill, _ :: Nil) => processIds case (Cmd.Monitors, _ :: Nil) => List("stop") case (Cmd.Monitors, sub :: _ :: Nil) if sub.toLowerCase(Locale.ROOT) == "stop" => monitorIds diff --git a/app/src/atc/commands/ImageCommands.scala b/app/src/atc/commands/ImageCommands.scala new file mode 100644 index 00000000..5102e4db --- /dev/null +++ b/app/src/atc/commands/ImageCommands.scala @@ -0,0 +1,186 @@ +package atc.commands + +import atc.{App, Debug} +import atc.llm.{ImageInput, Images} +import atc.perms.ScopeId +import atc.platform.{Clipboard, PlatformPath} +import atc.ui.Format + +import java.nio.file.Path +import java.util.Locale +import scala.collection.mutable.ListBuffer +import scala.util.control.NonFatal + +/** Manages staged images for the next interactive turn (`/image`, `/attach`), OS clipboard paste + * (`Ctrl-V`), dragged/pasted image paths, and CLI `-i` / `--image` attachments, enforcing + * ATC's classified-file guard before any local image file is read for the main model. */ +final class ImageCommands(app: App): + import app.{cwd, policy, tui} + + private val stagedImages = ListBuffer[ImageInput]() + + /** Currently staged images waiting for the next prompt. */ + def staged: List[ImageInput] = stagedImages.synchronized(stagedImages.toList) + + def stagedCount: Int = stagedImages.synchronized(stagedImages.size) + + /** Consume and return all staged images (called when a turn begins). */ + def takeStaged(): List[ImageInput] = stagedImages.synchronized: + val out = stagedImages.toList + stagedImages.clear() + out + + def clearStaged(): Unit = stagedImages.synchronized(stagedImages.clear()) + + /** Completion targets for `/image ...`. */ + def targetsFor(sub: String): List[String] = + if sub.equalsIgnoreCase("rm") || sub.equalsIgnoreCase("remove") then + "all" :: (1 to stagedCount).map(_.toString).toList + else Nil + + /** Handle `/image [path|paste|clear|rm ]`. */ + def run(arg: String): Unit = + val trimmed = arg.trim + if trimmed.isEmpty then list() + else + val parts = SlashCommand.words(trimmed) + val head = parts.headOption.map(_.toLowerCase(Locale.ROOT)).getOrElse("") + head match + case "paste" | "clipboard" if parts.size == 1 => pasteCommand() + case "clear" if parts.size == 1 => + val count = stagedCount + clearStaged() + if count == 0 then tui.info("No images staged.") + else tui.info(s"Cleared ${Format.plural(count, "staged image")}.") + case ("rm" | "remove") if parts.size == 2 => remove(parts(1)) + case "rm" | "remove" => tui.println("Usage: /image rm ") + case _ => attachPath(trimmed) + + private def list(): Unit = + val current = staged + if current.isEmpty then + tui.info("No images staged. Use /image , /image paste, Ctrl-V, or drag-and-drop an image file.") + else + tui.println(s"Staged images (${current.size}/${Images.MaxImagesPerMessage}):") + current.zipWithIndex.foreach: (img, idx) => + tui.println(s" ${idx + 1}. ${describe(img)}") + tui.info("Send a message to include them, or use /image rm or /image clear.") + + private def remove(target: String): Unit = + if target.equalsIgnoreCase("all") then + val count = stagedCount + clearStaged() + if count == 0 then tui.info("No images staged.") + else tui.info(s"Cleared ${Format.plural(count, "staged image")}.") + else + target.toIntOption match + case Some(n) if n >= 1 => + val removed = stagedImages.synchronized: + if n <= stagedImages.size then Some(stagedImages.remove(n - 1)) else None + removed match + case Some(img) => tui.info(s"Removed image #$n: ${img.label}") + case None => tui.error(s"No staged image #$n (staged: $stagedCount).") + case _ => tui.error(s"Invalid image number '$target' (use 1..$stagedCount or all).") + + private def attachPath(raw: String): Unit = + val path = Images.parsePathArg(raw, cwd) + loadFile(path, interactiveConfirm = true, approveAll = app.approveAll) match + case Left(err) => tui.error(err) + case Right(img) => stage(img) + + private def pasteCommand(): Unit = + readClipboard(interactiveConfirm = true) match + case Left(err) => tui.info(err) + case Right(img) => stage(img) + + private def stage(img: ImageInput): Unit = + val added = stagedImages.synchronized: + if stagedImages.size >= Images.MaxImagesPerMessage then + Left(s"At most ${Images.MaxImagesPerMessage} images can be attached to one message.") + else + stagedImages += img + Right(stagedImages.size) + added match + case Left(err) => tui.error(err) + case Right(index) => + tui.success(s"Attached #$index: ${describe(img)}") + + /** Stage CLI `-i` / `--image` files at startup (refuses classified paths unless `--approve-all` + * or interactive confirmation succeeds). */ + def loadCliImages(paths: List[Path], nonInteractive: Boolean): List[ImageInput] = + paths.map: path => + loadFile(path, interactiveConfirm = !nonInteractive && tui.menusAvailable, approveAll = app.approveAll) match + case Right(img) => img + case Left(err) => throw IllegalArgumentException(err) + + /** Stage CLI images for interactive start so the first prompt shows them ready. */ + def stageCliImages(paths: List[Path]): Unit = + loadCliImages(paths, nonInteractive = false).foreach(stage) + + /** Callback for `Ctrl-V` inside `PromptReader`: reads an image from the OS clipboard without + * opening a nested interactive confirmation menu while JLine owns the terminal. */ + def pasteForPrompt(): Either[String, ImageInput] = + readClipboard(interactiveConfirm = false) + + /** Callback for bracketed paste inside `PromptReader`: auto-detects dragged/pasted local image + * file paths. Returns `None` when the text is ordinary text, `Some(Right(imgs))` when loaded, + * or `Some(Left(warning))` when an image path was blocked (e.g. classified) or invalid. */ + def handlePastedPaths(text: String): Option[Either[String, List[ImageInput]]] = + Images.parsePastedPaths(text, cwd).map: paths => + val remainingRoom = (Images.MaxImagesPerMessage - stagedCount).max(0) + if paths.size > remainingRoom then + Left(s"Too many images (${paths.size} dropped, ${Images.MaxImagesPerMessage} max per message).") + else + val loaded = List.newBuilder[ImageInput] + var failure: Option[String] = None + val iter = paths.iterator + while iter.hasNext && failure.isEmpty do + loadFile(iter.next(), interactiveConfirm = false, approveAll = app.approveAll) match + case Right(img) => loaded += img + case Left(err) => failure = Some(err) + failure.toLeft(loaded.result()) + + private def readClipboard(interactiveConfirm: Boolean): Either[String, ImageInput] = + Clipboard.readImage().flatMap: + case Clipboard.ClipData.Bytes(bytes, label) => + try Right(Images.prepare(bytes, label)) + catch case NonFatal(e) => Left(Debug.message(e)) + case Clipboard.ClipData.FilePath(path) => + loadFile(path, interactiveConfirm = interactiveConfirm, approveAll = app.approveAll) + + /** Load a local image file while guarding paths marked `classified` by ATC policy. */ + private[atc] def loadFile( + path: Path, + interactiveConfirm: Boolean, + approveAll: Boolean, + ): Either[String, ImageInput] = + try + val canonical = PlatformPath.canonical(path) + val display = displayPath(canonical) + val perm = policy.effective(ScopeId.Base, canonical) + if perm.classified && !approveAll then + if !interactiveConfirm then + return Left( + s"'$display' is marked classified by ATC policy; confirm explicitly with /image $display to send it to the main model." + ) + else + val ok = tui.confirm( + s"'$display' is marked classified by ATC policy. Attach it to send to the main model anyway?" + ) + if !ok then return Left(s"Cancelled attaching classified image '$display'.") + Right(Images.fromFile(canonical, display)) + catch case NonFatal(e) => Left(Debug.message(e)) + + private def displayPath(canonical: Path): String = + val cwdCanonical = PlatformPath.canonical(cwd) + if PlatformPath.within(canonical, cwdCanonical) && canonical.getNameCount > cwdCanonical.getNameCount then + PlatformPath.portable(canonical.subpath(cwdCanonical.getNameCount, canonical.getNameCount).nn) + else PlatformPath.display(canonical) + + private def describe(img: ImageInput): String = + val dims = if img.width > 0 && img.height > 0 then s", ${img.width}x${img.height}" else "" + val size = if img.byteSize > 0 then s", ${Images.formatBytes(img.byteSize.toLong)}" else "" + s"${img.label} (${img.mediaType}$dims$size)" + +object ImageCommands: + val Subcommands: List[String] = List("paste", "clear", "rm") diff --git a/app/src/atc/commands/SessionCommands.scala b/app/src/atc/commands/SessionCommands.scala index cf481fd8..96cdd112 100644 --- a/app/src/atc/commands/SessionCommands.scala +++ b/app/src/atc/commands/SessionCommands.scala @@ -32,6 +32,7 @@ final class SessionCommands(app: App): tui.clearOutputHistory() policy.resetSession() app.resetMonitorsHeld() + app.clearStagedImages() replaced /** Replace the REPL; the conversation is kept. `reason` tells the agent why diff --git a/app/src/atc/commands/SlashCommand.scala b/app/src/atc/commands/SlashCommand.scala index d0917d5e..fbc51f70 100644 --- a/app/src/atc/commands/SlashCommand.scala +++ b/app/src/atc/commands/SlashCommand.scala @@ -22,6 +22,12 @@ enum SlashCommand(val usage: String, val help: String, val aliases: String*): extends SlashCommand("/skills [list|enable|disable|delete ]", "list, enable, disable, or delete skills") case Interface extends SlashCommand("/interface [name]", "show the sandbox API reference", "/api") case Run extends SlashCommand("/run [code]", "run Scala; omit code for multiline input", "/scala") + case Image + extends SlashCommand( + "/image [path|paste|clear|rm ]", + "attach, paste, list, or clear images for the next message", + "/attach", + ) case New extends SlashCommand("/new", "clear conversation, task state, REPL and session grants") case Reset extends SlashCommand("/reset", "restart the REPL; keep the conversation") case Compact extends SlashCommand("/compact [focus]", "summarize conversation context; keep the REPL") @@ -53,7 +59,7 @@ enum SlashCommand(val usage: String, val help: String, val aliases: String*): SlashCommand.Section.ModelsConfig case New | Reset | Compact | Save | Resume | Task | Memory | Cost | Quit => SlashCommand.Section.SessionContext case Mode | Perms | Interface => SlashCommand.Section.SandboxPerms - case Run | Output | Todos | Ps | Kill | Monitors | Help => SlashCommand.Section.ToolsBackground + case Run | Image | Output | Todos | Ps | Kill | Monitors | Help => SlashCommand.Section.ToolsBackground private def answersTo(typed: String): Boolean = typed == name || aliases.contains(typed) diff --git a/app/src/atc/host/Host.scala b/app/src/atc/host/Host.scala index 8d845149..10c2a50c 100644 --- a/app/src/atc/host/Host.scala +++ b/app/src/atc/host/Host.scala @@ -2,6 +2,7 @@ package atc.host import atc.config.Config import atc.lib.* +import atc.llm.{ImageInput, Images} import atc.memory.MemoryStore import atc.perms.{GitIgnore, Policy, ScopeId} import atc.skills.Skill @@ -86,6 +87,52 @@ final class Host( try body finally callTexts = Map.empty + /** Images attached by agent code via `viewImage` during the active tool evaluation. */ + private val attachedImagesLock = new AnyRef + private var attachedImages = List.newBuilder[ImageInput] + private var attachedImageCount = 0 + private var collectingImages = false + + /** Begin collecting images for a new evaluation, discarding any leftovers. */ + private[atc] def beginImageCollection(): Unit = attachedImagesLock.synchronized: + attachedImages = List.newBuilder[ImageInput] + attachedImageCount = 0 + collectingImages = true + + /** End image collection for the active evaluation and return the attached images in order. */ + private[atc] def finishImageCollection(): List[ImageInput] = attachedImagesLock.synchronized: + val result = attachedImages.result() + attachedImages = List.newBuilder[ImageInput] + attachedImageCount = 0 + collectingImages = false + result + + /** Run `body` collecting any images attached via `viewImage`. */ + private[atc] def collectImages[T](body: => T): (T, List[ImageInput]) = + beginImageCollection() + var result: Option[T] = None + try + val value = body + result = Some(value) + (value, finishImageCollection()) + finally if result.isEmpty then finishImageCollection() + + /** Validate evaluation context and record an image produced by `viewImage`. */ + private[host] def attachImage(image: ImageInput): Unit = + if Host.inMonitor then + throw UnsupportedOperationException("viewImage cannot be called from a background monitor") + if ClassifiedImpl.running then + throw SecurityException("viewImage cannot be called inside a classified computation") + attachedImagesLock.synchronized: + if !collectingImages then + throw UnsupportedOperationException("viewImage is only available during a tool evaluation") + if attachedImageCount >= Images.MaxImagesPerMessage then + throw IllegalStateException( + s"viewImage: at most ${Images.MaxImagesPerMessage} images may be attached in one tool call" + ) + attachedImages += image + attachedImageCount += 1 + // Read-only and full access use the same runtime objects; their Scala types // expose different operations to agent code. def fileSystem(using IOCap): FileSystem = FileSystemImpl(ScopeId.Base, this) diff --git a/app/src/atc/host/HostFiles.scala b/app/src/atc/host/HostFiles.scala index 2fe53649..8ae09b7b 100644 --- a/app/src/atc/host/HostFiles.scala +++ b/app/src/atc/host/HostFiles.scala @@ -2,6 +2,7 @@ package atc.host import atc.{ScalaSource, TextFiles} import atc.lib.* +import atc.llm.Images import atc.platform.{Interruptible, PathGlob, Platform, PlatformPath} import java.io.IOException @@ -136,6 +137,29 @@ private[host] trait HostFiles: def readBytes(path: String)(using fs: FileSystem): Array[Byte] = fs.access(path).readBytes() + def viewImage(path: String)(using fs: FileSystem, user: UserIO): Unit = + if Host.inMonitor then + throw UnsupportedOperationException("viewImage cannot be called from a background monitor") + if ClassifiedImpl.running then + throw SecurityException("viewImage cannot be called inside a classified computation") + val p = canonical(path) + requireReadable(scopeOf(fs), p, "viewImage", "readClassified") + val label = fromCwd(PlatformPath.portable(p)) + val image = Images.fromFile(p, label) + attachImage(image) + val note = s"[attached image: ${image.placeholder}]\n" + output.print(note, note) + + def viewImage(bytes: Array[Byte], label: String)(using user: UserIO): Unit = + if Host.inMonitor then + throw UnsupportedOperationException("viewImage cannot be called from a background monitor") + if ClassifiedImpl.running then + throw SecurityException("viewImage cannot be called inside a classified computation") + val image = Images.prepare(bytes, label) + attachImage(image) + val note = s"[attached image: ${image.placeholder}]\n" + output.print(note, note) + def write(path: String, content: String)(using fs: FileSystem): Unit = fs.access(path).write(content) def writeBytes(path: String, content: Array[Byte])(using fs: FileSystem): Unit = diff --git a/app/src/atc/ide/IdeProtocol.scala b/app/src/atc/ide/IdeProtocol.scala index dd12b999..6c770a18 100644 --- a/app/src/atc/ide/IdeProtocol.scala +++ b/app/src/atc/ide/IdeProtocol.scala @@ -14,7 +14,7 @@ import atc.config.{ } import atc.host.FileChange import atc.lib.{TaskNotes, Todo} -import atc.llm.{Msg, SdkJson, TokenUsage} +import atc.llm.{ImageInput, Images, Msg, SdkJson, TokenUsage} import atc.perms.{ Decision, ExecRequest, FileRequest, MemoryRequest, NetRequest, PermissionRequest, Policy, SessionGrant } @@ -119,8 +119,23 @@ private[atc] object IdeProtocol: def openPanel(panel: String): ujson.Obj = ujson.Obj("type" -> "open_panel", "panel" -> panel) - def turnStart(input: String, source: String): ujson.Obj = - ujson.Obj("type" -> "turn_start", "input" -> input, "source" -> source) + def imageJson(img: ImageInput): ujson.Obj = + ujson.Obj( + "label" -> img.label, + "mediaType" -> img.mediaType, + "width" -> img.width, + "height" -> img.height, + "byteSize" -> img.byteSize, + "dataUri" -> img.dataUri, + ) + + def imagesJson(images: List[ImageInput]): ujson.Arr = + ujson.Arr.from(images.map(imageJson)) + + def turnStart(input: String, source: String, images: List[ImageInput] = Nil): ujson.Obj = + val obj = ujson.Obj("type" -> "turn_start", "input" -> input, "source" -> source) + if images.nonEmpty then obj("images") = imagesJson(images) + obj def status(text: String): ujson.Obj = ujson.Obj("type" -> "status", "text" -> text) @@ -172,10 +187,13 @@ private[atc] object IdeProtocol: "output" -> result.output, ) result.error.foreach(err => obj("error") = err) + if result.images.nonEmpty then obj("images") = imagesJson(result.images) obj - def inputAccepted(text: String): ujson.Obj = - ujson.Obj("type" -> "input_accepted", "text" -> text) + def inputAccepted(text: String, images: List[ImageInput] = Nil): ujson.Obj = + val obj = ujson.Obj("type" -> "input_accepted", "text" -> text) + if images.nonEmpty then obj("images") = imagesJson(images) + obj def monitorMessage(text: String): ujson.Obj = ujson.Obj("type" -> "monitor_message", "text" -> text) @@ -250,7 +268,7 @@ private[atc] object IdeProtocol: /** Serialize restored conversation messages for display in the IDE after `/resume`. */ def historyRestored(snapshot: SessionSnapshot): ujson.Obj = val entries = snapshot.history.map: - case Msg.User(text) => ujson.Obj("role" -> "user", "text" -> text) + case Msg.User(text, _) => ujson.Obj("role" -> "user", "text" -> text) case Msg.Continuation(text) => ujson.Obj("role" -> "continuation", "text" -> text) case Msg.Monitor(text) => ujson.Obj("role" -> "monitor", "text" -> text) case Msg.Assistant(text, calls, _) => @@ -651,6 +669,30 @@ private[atc] object IdeProtocol: // ── client -> server decoding ───────────────────────────────────── + /** Decode an optional `"images"` attachment array from a client `prompt` or `steer` message. */ + def parseImages(obj: ujson.Obj): Either[String, List[ImageInput]] = + obj.value.get("images") match + case None | Some(ujson.Null) => Right(Nil) + case Some(ujson.Arr(items)) => + if items.size > Images.MaxImagesPerMessage then + Left(s"Too many images (${items.size}); at most ${Images.MaxImagesPerMessage} allowed per message.") + else + val out = List.newBuilder[ImageInput] + var failure: Option[String] = None + val iter = items.iterator + while iter.hasNext && failure.isEmpty do + iter.next() match + case item: ujson.Obj => + val data = item.value.get("data").flatMap(_.strOpt).getOrElse("") + val label = item.value.get("label").flatMap(_.strOpt).getOrElse("") + try out += Images.fromBase64(data, label) + catch + case e: IllegalArgumentException => + failure = Some(Option(e.getMessage).filter(_.nonEmpty).getOrElse("Invalid image attachment")) + case _ => failure = Some("Each entry in 'images' must be a JSON object with a 'data' string.") + failure.toLeft(out.result()) + case Some(_) => Left("'images' must be a JSON array.") + /** Decode a permission response; unrecognized decisions fail closed to [[Decision.Deny]]. */ def parsePermissionDecision(obj: ujson.Obj, allowAlwaysPermitted: Boolean): Decision = val raw = obj.value.get("decision").flatMap(_.strOpt).getOrElse("deny").trim.toLowerCase(Locale.ROOT) diff --git a/app/src/atc/ide/IdeServer.scala b/app/src/atc/ide/IdeServer.scala index 7e3321cd..afe4aa19 100644 --- a/app/src/atc/ide/IdeServer.scala +++ b/app/src/atc/ide/IdeServer.scala @@ -33,7 +33,7 @@ import atc.config.{ } import atc.host.{FileChange, Host, HostLlm, HostOutput, HostUi} import atc.lib.{MemoryOptions, TaskNotes, Todo} -import atc.llm.{CancelledException, ChatGPTAuth, ChatModel, TokenUsage} +import atc.llm.{CancelledException, ChatGPTAuth, ChatModel, ImageInput, TokenUsage} import atc.memory.MemoryStore import atc.perms.{Decision, GitIgnore, MemoryKey, MemoryScope, Mode, PermissionRequest, Policy, ScopeId, SessionGrant} import atc.platform.PlatformPath @@ -87,7 +87,7 @@ private[atc] final class IdeServer( else SessionStore.autoSavePath(home, cwd) private enum Action: - case Prompt(text: String, generation: Long) + case Prompt(text: String, images: List[ImageInput], generation: Long) case RunScala(code: String, generation: Long) case Command(line: String, generation: Long) case SetMode(mode: String) @@ -156,7 +156,7 @@ private[atc] final class IdeServer( private final case class PendingRequest(expectedResponseType: String, future: CompletableFuture[ujson.Obj]) - private val MaxIncomingLineChars = 4 * 1024 * 1024 + private val MaxIncomingLineChars = 64 * 1024 * 1024 private val sessionToken: String = val bytes = new Array[Byte](4) SecureRandom().nextBytes(bytes) @@ -360,13 +360,16 @@ private[atc] final class IdeServer( activeSession.foreach(_.interruptActive()) case "steer" | "prompt" => val text = str("text") - turnStateLock.synchronized: - activeSession match - case Some(session) if busy => - session.steer(text) - actions.offer(Action.WakeMonitor) - case _ => - actions.offer(Action.Prompt(text, cancelGeneration.get())) + IdeProtocol.parseImages(obj) match + case Left(err) => emit(IdeProtocol.error(err)) + case Right(images) => + turnStateLock.synchronized: + activeSession match + case Some(session) if busy => + session.steer(text, images) + actions.offer(Action.WakeMonitor) + case _ => + actions.offer(Action.Prompt(text, images, cancelGeneration.get())) case "run_scala" => actions.offer(Action.RunScala(str("code"), cancelGeneration.get())) case "command" => actions.offer(Action.Command(str("line"), cancelGeneration.get())) case "set_mode" => actions.offer(Action.SetMode(str("mode"))) @@ -1268,12 +1271,12 @@ private[atc] final class IdeServer( agent.interrupt() sandbox.interrupt() - def steer(line: String): Unit = - if SlashCommand.isCommandLine(line) then + def steer(line: String, images: List[ImageInput] = Nil): Unit = + if images.isEmpty && SlashCommand.isCommandLine(line) then val cmd = line.trim.takeWhile(!_.isWhitespace) emit(IdeProtocol.info(s"$cmd was not run: commands run between turns. Cancel the turn first.")) else - agent.submit(line) + agent.submit(line, images) scheduleStateEmit() private def scheduleStateEmit(): Unit = @@ -1323,14 +1326,15 @@ private[atc] final class IdeServer( try action match case Action.Quit => running = false - case Action.Prompt(text, gen) => + case Action.Prompt(text, images, gen) => if !isCancelled(gen) then val trimmed = text.trim - if trimmed.nonEmpty then - if SlashCommand.isCommandLine(trimmed) then running = runSlashCommand(trimmed, gen) + if trimmed.nonEmpty || images.nonEmpty then + if images.isEmpty && SlashCommand.isCommandLine(trimmed) then + running = runSlashCommand(trimmed, gen) else monitorsHeld = false - afterTurn(runTurn(text, "user", gen)) + afterTurn(runTurn(text, "user", gen, images = images)) case Action.RunScala(code, gen) => if !isCancelled(gen) then runUserScala(code, gen) case Action.Command(line, gen) => @@ -1531,19 +1535,20 @@ private[atc] final class IdeServer( source: String, generation: Long, displayInput: Option[String] = None, + images: List[ImageInput] = Nil, ): TurnOutcome = if isCancelled(generation) then return TurnOutcome.Interrupted predictor.invalidate() turnStateLock.synchronized: activeGeneration = generation busy = true - emit(IdeProtocol.turnStart(displayInput.getOrElse(input), source)) + emit(IdeProtocol.turnStart(displayInput.getOrElse(input), source, images)) emitState() val started = System.nanoTime() val (usageBefore, callsBefore) = (agent.usage, agent.toolCalls) var outcome = TurnOutcome.Failed try - outcome = agent.turn(sandbox.ensure(), input, () => isCancelled(generation)) + outcome = agent.turn(sandbox.ensure(), input, () => isCancelled(generation), images) outcome catch case _: CancelledException | _: InterruptedException => @@ -1667,6 +1672,12 @@ private[atc] final class IdeServer( case Cmd.Run => if arg.trim.isEmpty then emit(IdeProtocol.info("Usage: /run ")) else runUserScala(arg, generation) + case Cmd.Image => + emit( + IdeProtocol.info( + "Attach images directly in the composer by pasting (Ctrl+V / Cmd+V), dragging and dropping image files, or choosing + → Attach image." + ) + ) case Cmd.New => newSession() case Cmd.Reset => resetRepl() case Cmd.Compact => compact(arg, generation) @@ -2634,6 +2645,8 @@ private final class IdeAgentUi( emit(IdeProtocol.info(text)) override def inputAccepted(text: String): Unit = emit(IdeProtocol.inputAccepted(text)) + override def inputAccepted(text: String, images: List[ImageInput]): Unit = + emit(IdeProtocol.inputAccepted(text, images)) override def monitorMessage(text: String): Unit = emit(IdeProtocol.monitorMessage(text)) override def confirmMoreToolCalls(used: Int, budget: Int): Boolean = diff --git a/app/src/atc/llm/AnthropicModel.scala b/app/src/atc/llm/AnthropicModel.scala index 480bd0a6..e7c66d9c 100644 --- a/app/src/atc/llm/AnthropicModel.scala +++ b/app/src/atc/llm/AnthropicModel.scala @@ -97,10 +97,33 @@ final class AnthropicModel(spec: ModelSpec) extends SpecModel(spec, AnthropicMod settings.webSearchVersion.getOrElse("20260209") match case "20250305" => b.addTool(ToolUnion.ofWebSearchTool20250305(WebSearchTool20250305.builder().build())) case _ => b.addTool(ToolUnion.ofWebSearchTool20260209(WebSearchTool20260209.builder().build())) - def addUserText(text: String, mark: Boolean): Unit = - val block = TextBlockParam.builder().text(text) - if mark then block.cacheControl(cache) - b.addUserMessageOfContentBlockParams(List(ContentBlockParam.ofText(block.build())).asJava) + def imageBlock(img: ImageInput, mark: Boolean): ImageBlockParam = + val mediaType = img.mediaType match + case "image/png" => Base64ImageSource.MediaType.IMAGE_PNG + case "image/jpeg" => Base64ImageSource.MediaType.IMAGE_JPEG + case "image/gif" => Base64ImageSource.MediaType.IMAGE_GIF + case "image/webp" => Base64ImageSource.MediaType.IMAGE_WEBP + case other => Base64ImageSource.MediaType.of(other) + val source = Base64ImageSource.builder().mediaType(mediaType).data(img.data).build() + val ib = ImageBlockParam.builder().source(source) + if mark then ib.cacheControl(cache) + ib.build() + def addUserContent(text: String, images: List[ImageInput], mark: Boolean): Unit = + if images.isEmpty then + val block = TextBlockParam.builder().text(text) + if mark then block.cacheControl(cache) + b.addUserMessageOfContentBlockParams(List(ContentBlockParam.ofText(block.build())).asJava) + else + val blocks = List.newBuilder[ContentBlockParam] + val hasText = text.nonEmpty + images.zipWithIndex.foreach: (img, idx) => + val markHere = mark && !hasText && idx == images.length - 1 + blocks += ContentBlockParam.ofImage(imageBlock(img, markHere)) + if hasText then + val tb = TextBlockParam.builder().text(text) + if mark then tb.cacheControl(cache) + blocks += ContentBlockParam.ofText(tb.build()) + b.addUserMessageOfContentBlockParams(blocks.result().asJava) // Only a user-role block can carry the breakpoint, and a round resumed after a // server-side pause re-sends a history that ends with an assistant message. val last = AnthropicModel.cacheBreakpoint(history) @@ -119,13 +142,22 @@ final class AnthropicModel(spec: ModelSpec) extends SpecModel(spec, AnthropicMod @tailrec def append(remaining: List[(Msg, Int)]): Unit = remaining match case Nil => () - case (msg: (Msg.User | Msg.Continuation | Msg.Monitor), i) :: rest => - msg.userText.foreach(addUserText(_, i == last)) + case (Msg.User(text, images), i) :: rest => + addUserContent(text, images, i == last) + append(rest) + case (msg: (Msg.Continuation | Msg.Monitor), i) :: rest => + msg.userText.foreach(addUserContent(_, Nil, i == last)) append(rest) case (Msg.ToolResults(results), i) :: rest => val mark = i == last val blocks = results.zipWithIndex.map: (r, j) => - val block = ToolResultBlockParam.builder().toolUseId(r.callId).content(r.output).isError(r.isError) + val block = ToolResultBlockParam.builder().toolUseId(r.callId).isError(r.isError) + if r.images.isEmpty then block.content(r.output) + else + val parts = List.newBuilder[ToolResultBlockParam.Content.Block] + if r.output.nonEmpty then parts += ToolResultBlockParam.Content.Block.ofText(r.output) + r.images.foreach(img => parts += ToolResultBlockParam.Content.Block.ofImage(imageBlock(img, mark = false))) + block.contentOfBlocks(parts.result().asJava) if mark && j == results.length - 1 then block.cacheControl(cache) ContentBlockParam.ofToolResult(block.build()) b.addUserMessageOfContentBlockParams(blocks.asJava) diff --git a/app/src/atc/llm/AntigravityCli.scala b/app/src/atc/llm/AntigravityCli.scala index cee1cf3e..d0d9c120 100644 --- a/app/src/atc/llm/AntigravityCli.scala +++ b/app/src/atc/llm/AntigravityCli.scala @@ -108,18 +108,26 @@ private[atc] final class AntigravityCli private ( () /** Start a model turn (`session/prompt`). Its updates and final result arrive via [[next]]. */ - def prompt(sessionId: String, text: String): Unit = + def prompt(sessionId: String, text: String, images: List[ImageInput] = Nil): Unit = val id = nextId.incrementAndGet() synchronized: if ended || gone then throw exited() promptRequest = Some(id) + val blocks = + if images.isEmpty then ujson.Arr(ujson.Obj("type" -> "text", "text" -> text)) + else + val out = List.newBuilder[ujson.Value] + if text.nonEmpty then out += ujson.Obj("type" -> "text", "text" -> text) + images.foreach: img => + out += ujson.Obj("type" -> "image", "data" -> img.data, "mimeType" -> img.mediaType) + ujson.Arr.from(out.result()) val message = ujson.Obj( "jsonrpc" -> "2.0", "id" -> id, "method" -> "session/prompt", "params" -> ujson.Obj( "sessionId" -> sessionId, - "prompt" -> ujson.Arr(ujson.Obj("type" -> "text", "text" -> text)), + "prompt" -> blocks, ), ) try send(message) diff --git a/app/src/atc/llm/AntigravityMcp.scala b/app/src/atc/llm/AntigravityMcp.scala index a0493b63..afeb2bb6 100644 --- a/app/src/atc/llm/AntigravityMcp.scala +++ b/app/src/atc/llm/AntigravityMcp.scala @@ -168,8 +168,16 @@ private[atc] object AntigravityMcp: Thread.currentThread().interrupt() ToolResult(callId, "Cancelled.", isError = true) case NonFatal(e) => ToolResult(callId, Debug.message(e), isError = true) + val content = + if toolResult.images.isEmpty then ujson.Arr(ujson.Obj("type" -> "text", "text" -> toolResult.output)) + else + val blocks = List.newBuilder[ujson.Value] + if toolResult.output.nonEmpty then blocks += ujson.Obj("type" -> "text", "text" -> toolResult.output) + toolResult.images.foreach: img => + blocks += ujson.Obj("type" -> "image", "data" -> img.data, "mimeType" -> img.mediaType) + ujson.Arr.from(blocks.result()) Right(ujson.Obj( - "content" -> ujson.Arr(ujson.Obj("type" -> "text", "text" -> toolResult.output)), + "content" -> content, "isError" -> toolResult.isError, )) case other => diff --git a/app/src/atc/llm/AntigravityModel.scala b/app/src/atc/llm/AntigravityModel.scala index ca34f4d2..35e6e43f 100644 --- a/app/src/atc/llm/AntigravityModel.scala +++ b/app/src/atc/llm/AntigravityModel.scala @@ -45,7 +45,7 @@ final class AntigravityModel( /** What a request sends to its session. */ private enum Input: - case Prompt(text: String) + case Prompt(text: String, images: List[ImageInput]) case Results(results: List[ToolResult]) private var session: Option[Session] = None @@ -89,13 +89,14 @@ final class AntigravityModel( if reject then cli.close() throw IllegalStateException("AntigravityModel has been closed") - started -> Input.Prompt(Providers.transcript(history)) + val (text, images) = Providers.transcriptWithImages(history) + started -> Input.Prompt(text, images) val guard = Providers.CancelGuard(() => end(Some(active))) var completed = false try val completion = ModelRequest.withResource(guard): _ => input match - case Input.Prompt(text) => active.cli.prompt(active.sessionId, text) + case Input.Prompt(text, images) => active.cli.prompt(active.sessionId, text, images) case Input.Results(results) => results.foreach(active.cli.answer) val turn = Turn(Turns.incrementAndGet()) val cumulativeUsage = input.isInstanceOf[Input.Results] @@ -124,7 +125,10 @@ final class AntigravityModel( results.map(_.callId).toSet == s.pending.toSet && s.cli.canAnswer(s.pending) => Some(Input.Results(results)) case added if s.pending.isEmpty && added.forall(_.userText.isDefined) => - Some(Input.Prompt(added.flatMap(_.userText).mkString("\n\n"))) + Some(Input.Prompt( + added.flatMap(_.userText).filter(_.nonEmpty).mkString("\n\n"), + added.flatMap(_.userImages) + )) case _ => None case _ => None diff --git a/app/src/atc/llm/ClaudeCli.scala b/app/src/atc/llm/ClaudeCli.scala index c0d2db42..03a019e1 100644 --- a/app/src/atc/llm/ClaudeCli.scala +++ b/app/src/atc/llm/ClaudeCli.scala @@ -53,13 +53,28 @@ private[atc] final class ClaudeCli private (process: ClaudeCli.Process, tools: L request(ujson.Obj("subtype" -> "set_model", "model" -> model)) () - /** Start a model turn with `text` as the user's message. */ - def prompt(text: String): Unit = + /** Start a model turn with `text` and optional `images` as the user's message. */ + def prompt(text: String, images: List[ImageInput] = Nil): Unit = + val content: ujson.Value = + if images.isEmpty then ujson.Str(text) + else + val blocks = List.newBuilder[ujson.Value] + images.foreach: img => + blocks += ujson.Obj( + "type" -> "image", + "source" -> ujson.Obj( + "type" -> "base64", + "media_type" -> img.mediaType, + "data" -> img.data, + ), + ) + if text.nonEmpty then blocks += ujson.Obj("type" -> "text", "text" -> text) + ujson.Arr.from(blocks.result()) send(ujson.Obj( "type" -> "user", "session_id" -> "", "parent_tool_use_id" -> ujson.Null, - "message" -> ujson.Obj("role" -> "user", "content" -> text), + "message" -> ujson.Obj("role" -> "user", "content" -> content), )) /** The result of a tool call the CLI made or will make. */ @@ -300,8 +315,16 @@ private[atc] object ClaudeCli: Process(handle.input, handle.output, handle.stop, handle.diagnostics) private def toolResult(result: ToolResult): ujson.Value = + val content = + if result.images.isEmpty then ujson.Arr(ujson.Obj("type" -> "text", "text" -> result.output)) + else + val blocks = List.newBuilder[ujson.Value] + if result.output.nonEmpty then blocks += ujson.Obj("type" -> "text", "text" -> result.output) + result.images.foreach: img => + blocks += ujson.Obj("type" -> "image", "data" -> img.data, "mimeType" -> img.mediaType) + ujson.Arr.from(blocks.result()) ujson.Obj( - "content" -> ujson.Arr(ujson.Obj("type" -> "text", "text" -> result.output)), + "content" -> content, "isError" -> result.isError, ) diff --git a/app/src/atc/llm/ClaudeCodeModel.scala b/app/src/atc/llm/ClaudeCodeModel.scala index 6bcb6dd2..b3acbc86 100644 --- a/app/src/atc/llm/ClaudeCodeModel.scala +++ b/app/src/atc/llm/ClaudeCodeModel.scala @@ -43,7 +43,7 @@ final class ClaudeCodeModel(spec: ModelSpec, launch: List[String] => ClaudeCli.P /** What a request sends to its session. */ private enum Input: - case Prompt(text: String) + case Prompt(text: String, images: List[ImageInput]) case Results(results: List[ToolResult]) private var session: Option[Session] = None @@ -94,7 +94,8 @@ final class ClaudeCodeModel(spec: ModelSpec, launch: List[String] => ClaudeCli.P if reject then started.cli.close() throw IllegalStateException("ClaudeCodeModel has been closed") - (started, Input.Prompt(transcript(history)), true) + val (text, images) = Providers.transcriptWithImages(history) + (started, Input.Prompt(text, images), true) val guard = Providers.CancelGuard(() => end(Some(active))) var completed = false try @@ -102,7 +103,7 @@ final class ClaudeCodeModel(spec: ModelSpec, launch: List[String] => ClaudeCli.P if fresh && settings.contextWindow.isEmpty && reported.isEmpty then reported = windowOf(_ => active.cli.contextWindow(), modelId).map(_.toInt) input match - case Input.Prompt(text) => active.cli.prompt(text) + case Input.Prompt(text, images) => active.cli.prompt(text, images) case Input.Results(results) => results.foreach(active.cli.answer) val turn = Turn(Turns.incrementAndGet()) val result = read(active.cli, sink, cancelled, Some(NativeTurn(providerKey, ref, turn))) @@ -130,7 +131,10 @@ final class ClaudeCodeModel(spec: ModelSpec, launch: List[String] => ClaudeCli.P results.map(_.callId).toSet == s.pending.toSet => Some(Input.Results(results)) case added if s.pending.isEmpty && added.forall(userText(_).isDefined) => - Some(Input.Prompt(added.flatMap(userText).mkString("\n\n"))) + Some(Input.Prompt( + added.flatMap(userText).filter(_.nonEmpty).mkString("\n\n"), + added.flatMap(_.userImages) + )) case _ => None case _ => None diff --git a/app/src/atc/llm/EchoModel.scala b/app/src/atc/llm/EchoModel.scala index 795b4fda..5b482c98 100644 --- a/app/src/atc/llm/EchoModel.scala +++ b/app/src/atc/llm/EchoModel.scala @@ -34,7 +34,7 @@ final class EchoModel(val alias: String, override val ref: String, override val CompletionStop.Complete, ) history.lastOption match - case Some(Msg.User(text)) => + case Some(Msg.User(text, images)) => runPayload(text) match case Some(code) => val id = counter.incrementAndGet() @@ -42,10 +42,20 @@ final class EchoModel(val alias: String, override val ref: String, override val "Running that in the sandbox.", List(ToolCall(s"echo-$id", "run_scala", ujson.write(ujson.Obj("code" -> code)))) ) - case None => reply(s"echo: $text") + case None => + val imgSummary = images.map(_.placeholder).mkString(", ") + val echoed = + if images.isEmpty then s"echo: $text" + else if text.isEmpty then s"echo: $imgSummary" + else s"echo: $text ($imgSummary)" + reply(echoed) case Some(Msg.Continuation(text)) => reply(s"echo: $text") case Some(Msg.Monitor(text)) => reply(s"echo: $text") - case Some(Msg.ToolResults(results)) => reply("Result:\n" + results.map(_.output).mkString("\n")) + case Some(Msg.ToolResults(results)) => + val rendered = results.map: r => + if r.images.isEmpty then r.output + else List(r.output, r.images.map(_.placeholder).mkString("\n")).filter(_.nonEmpty).mkString("\n") + reply("Result:\n" + rendered.mkString("\n")) case _ => Completion("", Nil, None, TokenUsage(), "end_turn", CompletionStop.Complete) /** The `run: ` payload of a user message, if it has one. Agent notes diff --git a/app/src/atc/llm/Images.scala b/app/src/atc/llm/Images.scala new file mode 100644 index 00000000..d54c5aea --- /dev/null +++ b/app/src/atc/llm/Images.scala @@ -0,0 +1,419 @@ +package atc.llm + +import atc.platform.{Platform, PlatformPath} + +import java.awt.{Color, RenderingHints} +import java.awt.image.BufferedImage +import java.io.{ByteArrayInputStream, ByteArrayOutputStream} +import java.net.{URI, URLDecoder} +import java.nio.charset.StandardCharsets.UTF_8 +import java.nio.file.{Files, Path} +import java.nio.file.attribute.BasicFileAttributes +import java.util.{Base64, Locale} +import javax.imageio.{IIOImage, ImageIO, ImageWriteParam} +import javax.imageio.stream.ImageInputStream +import scala.util.Using +import scala.util.control.NonFatal + +/** Validates, inspects, auto-resizes, and base64-encodes images for vision-capable LLM providers. + * + * Always detects image formats from magic bytes rather than trusting file extensions or declared + * MIME types, checks pixel dimensions before decoding to defend against decompression bombs, and + * keeps encoded payloads safely below every provider's per-image size and dimension limits. */ +private[atc] object Images: + /** Largest raw image file or payload read into memory before resizing (25 MiB). */ + val MaxRawInputBytes: Int = 25 * 1024 * 1024 + + /** Largest encoded binary image kept in an [[ImageInput]] (~3.57 MiB -> <= 5 MB base64, + * staying below Anthropic's 5 MB base64 image limit as well as OpenAI/Gemini limits). */ + val MaxBinaryBytes: Int = 3_750_000 + + /** Maximum long-edge pixel dimension before proportional downscaling. */ + val MaxDimension: Int = 1568 + + /** Maximum decoded pixel count (8000x8000) before refusing as a decompression bomb. */ + val MaxPixels: Long = 64_000_000L + + /** Maximum number of images attached to one user message or tool evaluation. */ + val MaxImagesPerMessage: Int = 10 + + /** MIME types universally accepted on the wire by all supported vision providers. */ + val SupportedWireMediaTypes: Set[String] = Set("image/png", "image/jpeg", "image/gif", "image/webp") + + /** File extensions recognized for drag-and-drop path auto-detection. */ + val ImageExtensions: Set[String] = Set("png", "jpg", "jpeg", "gif", "webp", "bmp", "tif", "tiff") + + private val JpegQualities: List[Float] = List(0.85f, 0.75f, 0.60f) + + private def ensureHeadless(): Unit = + if System.getProperty("java.awt.headless") == null then + System.setProperty("java.awt.headless", "true") + () + + /** Detect image MIME type from magic bytes; `None` if unrecognized. */ + def detectMediaType(bytes: Array[Byte]): Option[String] = + if bytes.length >= 8 && + bytes(0) == 0x89.toByte && bytes(1) == 0x50 && bytes(2) == 0x4e && bytes(3) == 0x47 && + bytes(4) == 0x0d && bytes(5) == 0x0a && bytes(6) == 0x1a && bytes(7) == 0x0a + then Some("image/png") + else if bytes.length >= 3 && bytes(0) == 0xff.toByte && bytes(1) == 0xd8.toByte && bytes(2) == 0xff.toByte then + Some("image/jpeg") + else if bytes.length >= 6 && + bytes(0) == 'G' && bytes(1) == 'I' && bytes(2) == 'F' && bytes(3) == '8' && + (bytes(4) == '7' || bytes(4) == '9') && bytes(5) == 'a' + then Some("image/gif") + else if bytes.length >= 12 && + bytes(0) == 'R' && bytes(1) == 'I' && bytes(2) == 'F' && bytes(3) == 'F' && + bytes(8) == 'W' && bytes(9) == 'E' && bytes(10) == 'B' && bytes(11) == 'P' + then Some("image/webp") + else if bytes.length >= 2 && bytes(0) == 'B' && bytes(1) == 'M' then Some("image/bmp") + else if bytes.length >= 4 && + ((bytes(0) == 'I' && bytes(1) == 'I' && bytes(2) == 42 && bytes(3) == 0) || + (bytes(0) == 'M' && bytes(1) == 'M' && bytes(2) == 0 && bytes(3) == 42)) + then Some("image/tiff") + else None + + /** Read and prepare an image file from disk. Refuses non-regular files (directories, FIFOs, + * devices) and files larger than [[MaxRawInputBytes]]. */ + def fromFile(path: Path, label: String = ""): ImageInput = + val attrs = Files.readAttributes(path, classOf[BasicFileAttributes]).nn + if !attrs.isRegularFile then + throw IllegalArgumentException(s"Image path is not a regular file: ${PlatformPath.display(path)}") + if attrs.size() > MaxRawInputBytes then + throw IllegalArgumentException( + s"Image '${effectiveLabel(path, label)}' is too large (${formatBytes(attrs.size())}; limit is ${formatBytes(MaxRawInputBytes.toLong)})" + ) + val bytes = Using.resource(Files.newInputStream(path).nn)(_.readNBytes(MaxRawInputBytes + 1).nn) + if bytes.length > MaxRawInputBytes then + throw IllegalArgumentException( + s"Image '${effectiveLabel(path, label)}' exceeds the ${formatBytes(MaxRawInputBytes.toLong)} raw input limit" + ) + prepare(bytes, effectiveLabel(path, label)) + + private def effectiveLabel(path: Path, label: String): String = + val trimmed = label.trim + if trimmed.nonEmpty then trimmed + else Option(path.getFileName).map(_.toString).getOrElse(PlatformPath.display(path)) + + /** Decode a base64 string or `data:;base64,` URI and prepare the image. + * Rejects oversized payloads before decoding and validates actual magic bytes. */ + def fromBase64(data: String, label: String = ""): ImageInput = + val raw = data.trim + val payload = + if raw.regionMatches(true, 0, "data:", 0, 5) then + val comma = raw.indexOf(',') + if comma < 0 then throw IllegalArgumentException("Invalid data URI: missing ',' separator") + val header = raw.substring(5, comma).nn + if !header.toLowerCase(Locale.ROOT).endsWith(";base64") then + throw IllegalArgumentException("Image data URI must be base64-encoded") + raw.substring(comma + 1).nn + else raw + val maxBase64Chars = (MaxRawInputBytes.toLong * 4L / 3L) + 256L + if payload.length.toLong > maxBase64Chars then + throw IllegalArgumentException( + s"Image payload exceeds the ${formatBytes(MaxRawInputBytes.toLong)} raw input limit" + ) + val bytes = + try Base64.getMimeDecoder.nn.decode(payload).nn + catch + case e: IllegalArgumentException => + throw IllegalArgumentException(s"Invalid base64 image data: ${Option(e.getMessage).getOrElse("malformed")}") + if bytes.length > MaxRawInputBytes then + throw IllegalArgumentException( + s"Image exceeds the ${formatBytes(MaxRawInputBytes.toLong)} raw input limit" + ) + prepare(bytes, label) + + /** Validate, auto-resize/compress if necessary, and encode raw image bytes into an [[ImageInput]]. */ + def prepare(bytes: Array[Byte], label: String = ""): ImageInput = + if bytes.isEmpty then throw IllegalArgumentException("Image data is empty") + if bytes.length > MaxRawInputBytes then + throw IllegalArgumentException( + s"Image exceeds the ${formatBytes(MaxRawInputBytes.toLong)} raw input limit" + ) + val cleanLabel = sanitizeLabel(label) + val detected = detectMediaType(bytes).getOrElse( + throw IllegalArgumentException( + "Unsupported image format (expected PNG, JPEG, GIF, WebP, BMP, or TIFF)" + ) + ) + if detected == "image/webp" then prepareWebp(bytes, cleanLabel) + else prepareWithImageIO(bytes, detected, cleanLabel) + + private def prepareWebp(bytes: Array[Byte], label: String): ImageInput = + val (w, h) = webpDimensions(bytes).getOrElse((0, 0)) + if w > 0 && h > 0 && w.toLong * h.toLong > MaxPixels then + throw IllegalArgumentException(s"Image dimensions (${w}x${h}) exceed the maximum pixel limit") + if bytes.length > MaxBinaryBytes then + throw IllegalArgumentException( + s"WebP image (${formatBytes(bytes.length.toLong)}) exceeds the ${formatBytes(MaxBinaryBytes.toLong)} limit and cannot be re-encoded automatically; convert to PNG or JPEG first" + ) + ImageInput( + mediaType = "image/webp", + data = Base64.getEncoder.nn.encodeToString(bytes).nn, + label = label, + width = w, + height = h, + byteSize = bytes.length, + ) + + private def prepareWithImageIO(bytes: Array[Byte], detected: String, label: String): ImageInput = + ensureHeadless() + val (w, h, decodedOpt) = probeAndMaybeDecode(bytes, detected) + decodedOpt match + case None => + // Already a supported wire format within dimension and byte limits: keep original bytes verbatim. + ImageInput( + mediaType = detected, + data = Base64.getEncoder.nn.encodeToString(bytes).nn, + label = label, + width = w, + height = h, + byteSize = bytes.length, + ) + case Some(original) => + val scaled = scaleToFit(original, MaxDimension) + val (outMedia, outBytes, outW, outH) = compress(scaled, preferPng = detected != "image/jpeg") + ImageInput( + mediaType = outMedia, + data = Base64.getEncoder.nn.encodeToString(outBytes).nn, + label = label, + width = outW, + height = outH, + byteSize = outBytes.length, + ) + + /** Inspect dimensions before allocating pixel buffers. Returns `(w, h, None)` when the original + * bytes can be sent verbatim without re-encoding, or `(w, h, Some(img))` when transcoding, + * resizing, or compression is required. */ + private def probeAndMaybeDecode(bytes: Array[Byte], detected: String): (Int, Int, Option[BufferedImage]) = + val iis: ImageInputStream | Null = ImageIO.createImageInputStream(ByteArrayInputStream(bytes)) + if iis == null then throw IllegalArgumentException(s"Could not decode $detected image") + Using.resource(iis): stream => + val readers = ImageIO.getImageReaders(stream).nn + if !readers.hasNext then throw IllegalArgumentException(s"No decoder available for $detected image") + val reader = readers.next().nn + try + reader.setInput(stream, true, true) + val w = reader.getWidth(0) + val h = reader.getHeight(0) + if w <= 0 || h <= 0 then throw IllegalArgumentException("Image has invalid dimensions") + if w.toLong * h.toLong > MaxPixels then + throw IllegalArgumentException(s"Image dimensions (${w}x${h}) exceed the maximum pixel limit") + val keepVerbatim = + SupportedWireMediaTypes.contains(detected) && + w <= MaxDimension && h <= MaxDimension && + bytes.length <= MaxBinaryBytes + if keepVerbatim then (w, h, None) + else + val img: BufferedImage | Null = reader.read(0) + if img == null then throw IllegalArgumentException(s"Could not decode $detected image") + (w, h, Some(img)) + finally reader.dispose() + + private def scaleToFit(img: BufferedImage, maxEdge: Int): BufferedImage = + val w = img.getWidth + val h = img.getHeight + val longest = w.max(h) + if longest <= maxEdge then img + else + val scale = maxEdge.toDouble / longest.toDouble + val newW = (w * scale).round.toInt.max(1) + val newH = (h * scale).round.toInt.max(1) + val imageType = + if img.getColorModel.nn.hasAlpha then BufferedImage.TYPE_INT_ARGB else BufferedImage.TYPE_INT_RGB + val out = BufferedImage(newW, newH, imageType) + val g = out.createGraphics().nn + try + g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC) + g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY) + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) + g.drawImage(img, 0, 0, newW, newH, null) + finally g.dispose() + out + + private def flattenAlpha(img: BufferedImage): BufferedImage = + if !img.getColorModel.nn.hasAlpha && img.getType == BufferedImage.TYPE_INT_RGB then img + else + val out = BufferedImage(img.getWidth, img.getHeight, BufferedImage.TYPE_INT_RGB) + val g = out.createGraphics().nn + try + g.setColor(Color.WHITE) + g.fillRect(0, 0, img.getWidth, img.getHeight) + g.drawImage(img, 0, 0, null) + finally g.dispose() + out + + private def encodePng(img: BufferedImage): Array[Byte] = + val baos = ByteArrayOutputStream() + if !ImageIO.write(img, "png", baos) then throw IllegalStateException("PNG image encoder unavailable") + baos.toByteArray.nn + + private def encodeJpeg(img: BufferedImage, quality: Float): Array[Byte] = + val rgb = flattenAlpha(img) + val baos = ByteArrayOutputStream() + val writers = ImageIO.getImageWritersByFormatName("jpeg").nn + if !writers.hasNext then throw IllegalStateException("JPEG image encoder unavailable") + val writer = writers.next().nn + try + val ios = ImageIO.createImageOutputStream(baos).nn + Using.resource(ios): out => + writer.setOutput(out) + val param = writer.getDefaultWriteParam.nn + if param.canWriteCompressed then + param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT) + param.setCompressionQuality(quality) + writer.write(null, IIOImage(rgb, null, null), param) + baos.toByteArray.nn + finally writer.dispose() + + /** Encode `img` within [[MaxBinaryBytes]], preferring PNG for lossless sources when small enough + * and falling back to JPEG compression and progressive downscaling when needed. */ + private def compress(img: BufferedImage, preferPng: Boolean): (String, Array[Byte], Int, Int) = + val pngAttempt = Option.when(preferPng)(encodePng(img)).filter(_.length <= MaxBinaryBytes) + .map(bytes => ("image/png", bytes, img.getWidth, img.getHeight)) + pngAttempt.getOrElse: + var current = img + var attempts = 0 + var encoded: Option[(String, Array[Byte], Int, Int)] = None + while attempts < 5 && encoded.isEmpty do + encoded = JpegQualities.iterator + .map(q => encodeJpeg(current, q)) + .find(_.length <= MaxBinaryBytes) + .map(bytes => ("image/jpeg", bytes, current.getWidth, current.getHeight)) + if encoded.isEmpty then + val nextEdge = (current.getWidth.max(current.getHeight) * 3 / 4).max(256) + if nextEdge >= current.getWidth.max(current.getHeight) then attempts = 5 + else + current = scaleToFit(current, nextEdge) + attempts += 1 + encoded.getOrElse( + throw IllegalArgumentException( + s"Could not compress image under the ${formatBytes(MaxBinaryBytes.toLong)} limit" + ) + ) + + /** Parse width and height from a WebP container (`VP8 `, `VP8L`, or `VP8X` chunk). */ + private[llm] def webpDimensions(bytes: Array[Byte]): Option[(Int, Int)] = + def u8(i: Int): Int = bytes(i) & 0xff + def u16le(i: Int): Int = u8(i) | (u8(i + 1) << 8) + def u24le(i: Int): Int = u8(i) | (u8(i + 1) << 8) | (u8(i + 2) << 16) + if bytes.length < 25 then None + else + val chunk = String(bytes, 12, 4, UTF_8) + chunk match + case "VP8X" if bytes.length >= 30 => + val w = u24le(24) + 1 + val h = u24le(27) + 1 + Option.when(w > 0 && h > 0)((w, h)) + case "VP8L" if bytes.length >= 25 && u8(20) == 0x2f => + val b0 = u8(21) + val b1 = u8(22) + val b2 = u8(23) + val b3 = u8(24) + val bits = b0 | (b1 << 8) | (b2 << 16) | (b3 << 24) + val w = (bits & 0x3fff) + 1 + val h = ((bits >>> 14) & 0x3fff) + 1 + Option.when(w > 0 && h > 0)((w, h)) + case "VP8 " if bytes.length >= 30 && u8(23) == 0x9d && u8(24) == 0x01 && u8(25) == 0x2a => + val w = u16le(26) & 0x3fff + val h = u16le(28) & 0x3fff + Option.when(w > 0 && h > 0)((w, h)) + case _ => None + + /** Strip control characters and clamp label length for display and placeholders. */ + def sanitizeLabel(label: String): String = + val clean = label.filter(c => c >= ' ' && c != 0x7f).trim + if clean.length <= 120 then clean else clean.take(119) + "…" + + /** Human-readable byte size (`842 B`, `142 KB`, `1.4 MB`). */ + def formatBytes(bytes: Long): String = + if bytes < 1024L then s"$bytes B" + else if bytes < 1024L * 1024L then f"${bytes / 1024.0}%.0f KB" + else f"${bytes / (1024.0 * 1024.0)}%.1f MB" + + /** Whether a filename or path has a recognized image extension. */ + def hasImageExtension(path: Path): Boolean = + val name = Option(path.getFileName).map(_.toString).getOrElse("") + val dot = name.lastIndexOf('.') + dot > 0 && dot < name.length - 1 && ImageExtensions.contains(name.substring(dot + 1).nn.toLowerCase(Locale.ROOT)) + + /** Parse a single path argument as typed or dragged into `/image ` (handling surrounding + * quotes, `file://` URIs, and POSIX backslash-escaped spaces). */ + def parsePathArg(raw: String, cwd: Path): Path = + val tokens = tokenizePaths(raw) + val token = if tokens.size == 1 then tokens.head else unquoteSingle(raw) + resolveToken(token, cwd) + + /** Detect whether a pasted terminal string consists solely of one or more existing local image + * file paths (as terminals deliver on drag-and-drop). Returns `None` for normal prose or + * non-image files so ordinary pastes are never misclassified. */ + def parsePastedPaths(text: String, cwd: Path): Option[List[Path]] = + val trimmed = text.trim + if trimmed.isEmpty || trimmed.length > 4096 || trimmed.linesIterator.size > MaxImagesPerMessage then None + else + val tokens = tokenizePaths(trimmed) + if tokens.isEmpty || tokens.size > MaxImagesPerMessage then None + else + val resolved = tokens.flatMap: tok => + try + val p = resolveToken(tok, cwd) + if hasImageExtension(p) && Files.isRegularFile(p) then Some(p) else None + catch case NonFatal(_) => None + Option.when(resolved.size == tokens.size)(resolved) + + private def unquoteSingle(raw: String): String = + val s = raw.trim + if s.length >= 2 && ((s.head == '\'' && s.last == '\'') || (s.head == '"' && s.last == '"')) then + s.drop(1).dropRight(1) + else s + + private def resolveToken(token: String, cwd: Path): Path = + val cleaned = + if token.regionMatches(true, 0, "file://", 0, 7) then + val uri = URI(token) + if Option(uri.getScheme).exists(_.equalsIgnoreCase("file")) then Path.of(uri).nn.toString + else URLDecoder.decode(token.drop(7), UTF_8).nn + else token + val parsed = PlatformPath.parse(cleaned) + val abs = if parsed.isAbsolute then parsed else cwd.resolve(parsed).nn + abs.toAbsolutePath.nn.normalize.nn + + /** Split whitespace-separated path tokens, respecting `'...'`, `"..."`, and POSIX `\ ` escapes. */ + private[llm] def tokenizePaths(text: String): List[String] = + val out = List.newBuilder[String] + val cur = StringBuilder() + var i = 0 + var quote: Char = 0 + var hasToken = false + while i < text.length do + val c = text.charAt(i) + if quote != 0 then + if c == quote then quote = 0 + else if quote == '"' && c == '\\' && !Platform.isWindows && i + 1 < text.length then + val next = text.charAt(i + 1) + if next == '"' || next == '\\' || next == '$' || next == '`' then + cur.append(next) + i += 1 + else cur.append(c) + else cur.append(c) + else if c == '\'' || c == '"' then + quote = c + hasToken = true + else if c == '\\' && !Platform.isWindows && i + 1 < text.length then + cur.append(text.charAt(i + 1)) + hasToken = true + i += 1 + else if Character.isWhitespace(c) then + if hasToken then + out += cur.toString + cur.clear() + hasToken = false + else + cur.append(c) + hasToken = true + i += 1 + if quote != 0 then Nil // unclosed quote -> not a clean path paste + else + if hasToken then out += cur.toString + out.result().filter(_.nonEmpty) diff --git a/app/src/atc/llm/Model.scala b/app/src/atc/llm/Model.scala index 3fe87c00..b37aeb1b 100644 --- a/app/src/atc/llm/Model.scala +++ b/app/src/atc/llm/Model.scala @@ -11,12 +11,44 @@ final case class ToolSpec(name: String, description: String, parametersJson: Str final case class ToolCall(id: String, name: String, arguments: String) +/** An image attached to a user message or returned by a tool call. + * `data` is raw base64 (without a `data:` URI prefix); `mediaType` is one of + * `image/png`, `image/jpeg`, `image/gif`, or `image/webp`. */ +final case class ImageInput( + mediaType: String, + data: String, + label: String = "", + width: Int = 0, + height: Int = 0, + byteSize: Int = 0, +): + /** `data:;base64,` URI for OpenAI APIs and webview previews. */ + def dataUri: String = s"data:$mediaType;base64,$data" + + /** Compact metadata description used in saved sessions, compaction transcripts, and notices + * (never embeds raw base64 bytes). */ + def placeholder: String = + val parts = List( + Option(label).map(_.trim).filter(_.nonEmpty), + Some(mediaType), + Option.when(width > 0 && height > 0)(s"${width}x${height}"), + ).flatten + s"[image: ${parts.mkString(", ")}]" + + /** Rough vision token estimate for context window accounting (~`(w * h) / 750`, bounded to + * `[85, 1600]`, or `1000` when dimensions are unknown). */ + def estimatedTokens: Long = + if width > 0 && height > 0 then ((width.toLong * height.toLong + 749L) / 750L).max(85L).min(1600L) + else 1000L + final case class ToolResult( callId: String, output: String, isError: Boolean, /** Local scheduling flag: return to the model before executing more calls from this batch. */ needsReplan: Boolean = false, + /** Images inspected by the tool (e.g. via `viewImage`), sent alongside `output`. */ + images: List[ImageInput] = Nil, ) /** Provider-native replay data for an assistant turn (e.g. Anthropic content @@ -35,7 +67,7 @@ final case class NativeTurn(providerKey: String, modelRef: String, payload: Any) /** Provider-neutral conversation history. */ enum Msg: - case User(text: String) + case User(text: String, images: List[ImageInput] = Nil) case Assistant(text: String, toolCalls: List[ToolCall], native: Option[NativeTurn]) case ToolResults(results: List[ToolResult]) /** Internal user-role message asking a provider to continue a response that @@ -49,11 +81,16 @@ enum Msg: /** The text of a user-role message (`User`, `Continuation`, or `Monitor`), or `None` for assistant/tool messages. */ def userText: Option[String] = this match - case Msg.User(text) => Some(text) + case Msg.User(text, _) => Some(text) case Msg.Continuation(text) => Some(text) case Msg.Monitor(text) => Some(text) case _ => None + /** Images attached to a [[User]] message, or empty for all other message kinds. */ + def userImages: List[ImageInput] = this match + case Msg.User(_, images) => images + case _ => Nil + final case class TokenUsage(input: Long = 0, output: Long = 0, cacheRead: Long = 0): def +(o: TokenUsage): TokenUsage = TokenUsage(input + o.input, output + o.output, cacheRead + o.cacheRead) diff --git a/app/src/atc/llm/OpenAIChatModel.scala b/app/src/atc/llm/OpenAIChatModel.scala index f1cd236e..d578b9cb 100644 --- a/app/src/atc/llm/OpenAIChatModel.scala +++ b/app/src/atc/llm/OpenAIChatModel.scala @@ -61,16 +61,51 @@ final class OpenAIChatModel(spec: ModelSpec) extends OpenAIShapedModel(spec): configure(b, thinking = true, fragment, effort) tools.foreach(t => b.addTool(functionTool(t))) if searches(tools) then b.webSearchOptions(ChatCompletionCreateParams.WebSearchOptions.builder().build()) + def addUserContent(text: String, images: List[ImageInput]): Unit = + if images.isEmpty then b.addUserMessage(text) + else + val parts = List.newBuilder[ChatCompletionContentPart] + if text.nonEmpty then + parts += ChatCompletionContentPart.ofText(ChatCompletionContentPartText.builder().text(text).build()) + images.foreach: img => + parts += ChatCompletionContentPart.ofImageUrl( + ChatCompletionContentPartImage.builder() + .imageUrl(ChatCompletionContentPartImage.ImageUrl.builder().url(img.dataUri).build()) + .build() + ) + b.addMessage( + ChatCompletionUserMessageParam.builder().contentOfArrayOfContentParts(parts.result().asJava).build() + ) @tailrec def append(remaining: List[Msg]): Unit = remaining match case Nil => () - case (msg: (Msg.User | Msg.Continuation | Msg.Monitor)) :: rest => + case Msg.User(text, images) :: rest => + addUserContent(text, images) + append(rest) + case (msg: (Msg.Continuation | Msg.Monitor)) :: rest => msg.userText.foreach(b.addUserMessage) append(rest) case Msg.ToolResults(results) :: rest => results.foreach: r => b.addMessage(ChatCompletionToolMessageParam.builder().toolCallId(r.callId).content(r.output).build()) - append(rest) + val toolImages = results.flatMap(_.images) + if toolImages.isEmpty then append(rest) + else + // Chat Completions `tool` messages accept text only; follow the tool batch with a + // user message carrying the inspected images (coalescing with an immediately following + // user-role message when present to keep role alternation clean on strict gateways). + val header = "[Attached image(s) from the tool call above]" + rest match + case Msg.User(nextText, nextImages) :: after => + addUserContent(List(header, nextText).filter(_.nonEmpty).mkString("\n\n"), toolImages ++ nextImages) + append(after) + case (next: (Msg.Continuation | Msg.Monitor)) :: after => + val nextText = next.userText.getOrElse("") + addUserContent(List(header, nextText).filter(_.nonEmpty).mkString("\n\n"), toolImages) + append(after) + case _ => + addUserContent(header, toolImages) + append(rest) case (first: Msg.Assistant) :: rest => replay[ChatCompletionAssistantMessageParam](first.native) match case Some(turn) => diff --git a/app/src/atc/llm/OpenAIResponsesModel.scala b/app/src/atc/llm/OpenAIResponsesModel.scala index fb623f63..659ebbb6 100644 --- a/app/src/atc/llm/OpenAIResponsesModel.scala +++ b/app/src/atc/llm/OpenAIResponsesModel.scala @@ -49,6 +49,26 @@ class OpenAIResponsesModel(spec: ModelSpec) extends OpenAIShapedModel(spec): private def message(role: EasyInputMessage.Role, text: String): ResponseInputItem = ResponseInputItem.ofEasyInputMessage(EasyInputMessage.builder().role(role).content(text).build()) + private def userMessage(text: String, images: List[ImageInput]): ResponseInputItem = + if images.isEmpty then message(EasyInputMessage.Role.USER, text) + else + val parts = List.newBuilder[ResponseInputContent] + if text.nonEmpty then + parts += ResponseInputContent.ofInputText(ResponseInputText.builder().text(text).build()) + images.foreach: img => + parts += ResponseInputContent.ofInputImage( + ResponseInputImage.builder() + .detail(ResponseInputImage.Detail.AUTO) + .imageUrl(img.dataUri) + .build() + ) + ResponseInputItem.ofEasyInputMessage( + EasyInputMessage.builder() + .role(EasyInputMessage.Role.USER) + .contentOfResponseInputMessageContentList(parts.result().asJava) + .build() + ) + private def params(system: SystemPrompt, history: List[Msg], tools: List[ToolSpec]): ResponseCreateParams = val b = ResponseCreateParams.builder().model(modelId).instructions(system).store(false) // Stateless (store(false)) replay must carry the reasoning between calls: ask @@ -61,7 +81,7 @@ class OpenAIResponsesModel(spec: ModelSpec) extends OpenAIShapedModel(spec): b.addTool(Tool.ofWebSearch(WebSearchTool.builder().`type`(WebSearchTool.Type.WEB_SEARCH).build())) val input = List.newBuilder[ResponseInputItem] history.foreach: - case Msg.User(text) => input += message(EasyInputMessage.Role.USER, text) + case Msg.User(text, images) => input += userMessage(text, images) case Msg.Continuation(text) => input += message(EasyInputMessage.Role.USER, text) case Msg.Monitor(text) => input += message(EasyInputMessage.Role.USER, text) case Msg.Assistant(text, calls, native) => @@ -75,9 +95,23 @@ class OpenAIResponsesModel(spec: ModelSpec) extends OpenAIShapedModel(spec): ) case Msg.ToolResults(results) => results.foreach: r => - input += ResponseInputItem.ofFunctionCallOutput( - ResponseInputItem.FunctionCallOutput.builder().callId(r.callId).output(r.output).build() - ) + val fb = ResponseInputItem.FunctionCallOutput.builder().callId(r.callId) + if r.images.isEmpty then fb.output(r.output) + else + val items = List.newBuilder[ResponseFunctionCallOutputItem] + if r.output.nonEmpty then + items += ResponseFunctionCallOutputItem.ofInputText( + ResponseInputTextContent.builder().text(r.output).build() + ) + r.images.foreach: img => + items += ResponseFunctionCallOutputItem.ofInputImage( + ResponseInputImageContent.builder() + .detail(ResponseInputImageContent.Detail.AUTO) + .imageUrl(img.dataUri) + .build() + ) + fb.outputOfResponseFunctionCallOutputItemList(items.result().asJava) + input += ResponseInputItem.ofFunctionCallOutput(fb.build()) b.inputOfResponse(input.result().asJava) b.build() diff --git a/app/src/atc/llm/Providers.scala b/app/src/atc/llm/Providers.scala index 05087d0b..657b6d56 100644 --- a/app/src/atc/llm/Providers.scala +++ b/app/src/atc/llm/Providers.scala @@ -81,23 +81,46 @@ private[atc] object Providers: /** The first message of a new CLI session: the request itself, or the history as a transcript * followed by the latest user message. */ - private[atc] def transcript(history: List[Msg]): String = history match - case List(message) => message.userText.getOrElse(formatTranscript(history)) - case _ => formatTranscript(history) - - private def formatTranscript(history: List[Msg]): String = + private[atc] def transcript(history: List[Msg]): String = transcriptWithImages(history)._1 + + /** As [[transcript]], also returning any live images from the latest user message (or trailing + * tool results) so a freshly started CLI session still sees them visually, while older images + * remain in the transcript as compact metadata placeholders. */ + private[atc] def transcriptWithImages(history: List[Msg]): (String, List[ImageInput]) = history match + case List(Msg.User(text, images)) => (text, images) + case List(message) => (message.userText.getOrElse(formatTranscript(history)), Nil) + case _ => + val liveImages = history.lastOption match + case Some(Msg.User(_, images)) => images + case Some(Msg.ToolResults(results)) => results.flatMap(_.images) + case _ => Nil + (formatTranscript(history, omitLastToolImagePlaceholders = liveImages.nonEmpty), liveImages) + + private def withImagePlaceholders(text: String, images: List[ImageInput]): String = + if images.isEmpty then text + else List(text, images.map(_.placeholder).mkString("\n")).filter(_.nonEmpty).mkString("\n\n") + + private def formatTranscript(history: List[Msg], omitLastToolImagePlaceholders: Boolean = false): String = val latest = history.lastOption.flatMap(_.userText) val earlier = if latest.isDefined then history.init else history - val entries = earlier.flatMap: - case Msg.User(text) => List(s"[user]\n$text") - case Msg.Continuation(text) => List(s"[user]\n$text") - case Msg.Monitor(text) => List(s"[monitor]\n$text") - case Msg.Assistant(text, calls, _) => - Option.when(text.nonEmpty)(s"[assistant]\n$text").toList ++ - calls.map(c => s"[tool call ${c.name}, id ${c.id}]\n${c.arguments}") - case Msg.ToolResults(results) => - results.map(r => s"[tool result, id ${r.callId}${if r.isError then ", error" else ""}]\n${r.output}") - val ending = latest.fold("Continue from where the transcript ends.")(text => s"[user, the latest message]\n$text") + val lastIdx = earlier.length - 1 + val entries = earlier.zipWithIndex.flatMap: (msg, idx) => + msg match + case Msg.User(text, images) => List(s"[user]\n${withImagePlaceholders(text, images)}") + case Msg.Continuation(text) => List(s"[user]\n$text") + case Msg.Monitor(text) => List(s"[monitor]\n$text") + case Msg.Assistant(text, calls, _) => + Option.when(text.nonEmpty)(s"[assistant]\n$text").toList ++ + calls.map(c => s"[tool call ${c.name}, id ${c.id}]\n${c.arguments}") + case Msg.ToolResults(results) => + val includePlaceholders = !(omitLastToolImagePlaceholders && idx == lastIdx) + results.map: r => + val body = if includePlaceholders then withImagePlaceholders(r.output, r.images) else r.output + s"[tool result, id ${r.callId}${if r.isError then ", error" else ""}]\n$body" + val ending = latest match + case Some(text) if text.nonEmpty => s"[user, the latest message]\n$text" + case Some(_) => "[user, the latest message]\n[See attached image(s)]" + case None => "Continue from where the transcript ends." (TranscriptIntro :: (entries :+ ending)).mkString("\n\n") private val TranscriptIntro = diff --git a/app/src/atc/platform/Clipboard.scala b/app/src/atc/platform/Clipboard.scala new file mode 100644 index 00000000..241868b0 --- /dev/null +++ b/app/src/atc/platform/Clipboard.scala @@ -0,0 +1,199 @@ +package atc.platform + +import atc.{Debug, ProcessEnvironment} +import atc.llm.Images + +import java.nio.charset.StandardCharsets.{UTF_16LE, UTF_8} +import java.nio.file.{Files, Path} +import java.util.{Base64, Locale} +import java.util.concurrent.TimeUnit +import scala.util.Using +import scala.util.control.NonFatal + +/** Reads image data (or a copied image file path) from the OS clipboard using native platform + * tools so headless terminals never initialize AWT or spawn a macOS Dock icon. */ +private[atc] object Clipboard: + private val TimeoutSeconds = 5L + private val PreferredLinuxMimes = List("image/png", "image/jpeg", "image/webp", "image/gif", "image/bmp") + + enum ClipData: + /** Raw image bytes copied directly (e.g. a screenshot). */ + case Bytes(data: Array[Byte], label: String) + /** A local file path copied from Finder / Explorer / file manager. */ + case FilePath(path: Path) + + /** Attempt to read an image from the system clipboard. + * Returns `Right(ClipData)` on success or `Left(message)` explaining why none was available. */ + def readImage(env: String => Option[String] = ProcessEnvironment.get): Either[String, ClipData] = + if Platform.isMac then readMac() + else if Platform.isWindows then readWindows() + else readLinux(env) + + private def readMac(): Either[String, ClipData] = + val tmp = Files.createTempFile("atc-clip-", ".img").nn + try + // Keep the temp file owner-only when possible since clipboard screenshots may be sensitive. + try OwnerOnlyFiles.replace(tmp, Array.emptyByteArray, keepPermissions = false) + catch case NonFatal(_) => () + val script = + """on run argv + | set outPath to POSIX file (item 1 of argv) + | set clipInfo to (clipboard info) as text + | if clipInfo contains "PNGf" then + | set imgData to the clipboard as «class PNGf» + | set f to open for access outPath with write permission + | set eof f to 0 + | write imgData to f + | close access f + | return "bytes:png" + | else if clipInfo contains "JPEG" then + | set imgData to the clipboard as JPEG picture + | set f to open for access outPath with write permission + | set eof f to 0 + | write imgData to f + | close access f + | return "bytes:jpeg" + | else if clipInfo contains "TIFF" then + | set imgData to the clipboard as TIFF picture + | set f to open for access outPath with write permission + | set eof f to 0 + | write imgData to f + | close access f + | return "bytes:tiff" + | else + | try + | set filePath to POSIX path of (the clipboard as «class furl») + | return "file:" & filePath + | on error + | return "none" + | end try + | end if + |end run""".stripMargin + runCommand(List("osascript", "-e", script, "--", tmp.toAbsolutePath.nn.toString)) match + case Left(err) => Left(err) + case Right(out) => + val result = String(out, UTF_8).trim + if result.startsWith("bytes:") then + val ext = result.stripPrefix("bytes:").trim + val bytes = Using.resource(Files.newInputStream(tmp).nn)(_.readNBytes(Images.MaxRawInputBytes + 1).nn) + if bytes.isEmpty then Left("No image in clipboard.") + else if bytes.length > Images.MaxRawInputBytes then + Left(s"Clipboard image exceeds the ${Images.formatBytes(Images.MaxRawInputBytes.toLong)} limit.") + else Right(ClipData.Bytes(bytes, s"clipboard.$ext")) + else if result.startsWith("file:") then + val p = PlatformPath.parse(result.stripPrefix("file:").trim) + if Images.hasImageExtension(p) && Files.isRegularFile(p) then Right(ClipData.FilePath(p)) + else Left("No image in clipboard.") + else Left("No image in clipboard.") + finally + try Files.deleteIfExists(tmp) + catch case NonFatal(_) => () + + private def readWindows(): Either[String, ClipData] = + val tmp = Files.createTempFile("atc-clip-", ".png").nn + try + val escaped = tmp.toAbsolutePath.nn.toString.replace("'", "''") + val script = + s"""Add-Type -AssemblyName System.Windows.Forms + |Add-Type -AssemblyName System.Drawing + |if ([System.Windows.Forms.Clipboard]::ContainsImage()) { + | $$img = [System.Windows.Forms.Clipboard]::GetImage() + | $$img.Save('$escaped', [System.Drawing.Imaging.ImageFormat]::Png) + | $$img.Dispose() + | Write-Output 'bytes:png' + |} elseif ([System.Windows.Forms.Clipboard]::ContainsFileDropList()) { + | $$files = [System.Windows.Forms.Clipboard]::GetFileDropList() + | if ($$files.Count -eq 1) { + | Write-Output ('file:' + $$files[0]) + | } else { + | Write-Output 'none' + | } + |} else { + | Write-Output 'none' + |}""".stripMargin + val encoded = Base64.getEncoder.nn.encodeToString(script.getBytes(UTF_16LE)).nn + runCommand(List("powershell.exe", "-NoProfile", "-NonInteractive", "-STA", "-EncodedCommand", encoded)) match + case Left(err) => Left(err) + case Right(out) => + val result = String(out, UTF_8).trim + if result == "bytes:png" then + val bytes = Using.resource(Files.newInputStream(tmp).nn)(_.readNBytes(Images.MaxRawInputBytes + 1).nn) + if bytes.isEmpty then Left("No image in clipboard.") + else if bytes.length > Images.MaxRawInputBytes then + Left(s"Clipboard image exceeds the ${Images.formatBytes(Images.MaxRawInputBytes.toLong)} limit.") + else Right(ClipData.Bytes(bytes, "clipboard.png")) + else if result.startsWith("file:") then + val p = PlatformPath.parse(result.stripPrefix("file:").trim) + if Images.hasImageExtension(p) && Files.isRegularFile(p) then Right(ClipData.FilePath(p)) + else Left("No image in clipboard.") + else Left("No image in clipboard.") + finally + try Files.deleteIfExists(tmp) + catch case NonFatal(_) => () + + private def readLinux(env: String => Option[String]): Either[String, ClipData] = + val isWayland = env("WAYLAND_DISPLAY").exists(_.nonEmpty) + val isX11 = env("DISPLAY").exists(_.nonEmpty) + if !isWayland && !isX11 then + Left("No graphical clipboard available (no DISPLAY or WAYLAND_DISPLAY); attach a file with /image .") + else if isWayland then + readWayland().orElse(if isX11 then readX11() + else Left("Install wl-paste to paste clipboard images, or use /image .")) + else readX11() + + private def readWayland(): Either[String, ClipData] = + runCommand(List("wl-paste", "--list-types")).flatMap: out => + val types = String(out, UTF_8).linesIterator.map(_.trim.toLowerCase(Locale.ROOT)).filter(_.nonEmpty).toSet + PreferredLinuxMimes.find(types.contains) match + case Some(mime) => + runCommand(List("wl-paste", "--no-newline", "--type", mime)).flatMap: bytes => + if bytes.isEmpty then Left("No image in clipboard.") + else if bytes.length > Images.MaxRawInputBytes then + Left(s"Clipboard image exceeds the ${Images.formatBytes(Images.MaxRawInputBytes.toLong)} limit.") + else Right(ClipData.Bytes(bytes, s"clipboard.${mime.stripPrefix("image/")}")) + case None if types.contains("text/uri-list") => + runCommand(List("wl-paste", "--no-newline", "--type", "text/uri-list")).flatMap(parseUriList) + case None => Left("No image in clipboard.") + + private def readX11(): Either[String, ClipData] = + runCommand(List("xclip", "-selection", "clipboard", "-t", "TARGETS", "-o")).flatMap: out => + val types = String(out, UTF_8).linesIterator.map(_.trim.toLowerCase(Locale.ROOT)).filter(_.nonEmpty).toSet + PreferredLinuxMimes.find(types.contains) match + case Some(mime) => + runCommand(List("xclip", "-selection", "clipboard", "-t", mime, "-o")).flatMap: bytes => + if bytes.isEmpty then Left("No image in clipboard.") + else if bytes.length > Images.MaxRawInputBytes then + Left(s"Clipboard image exceeds the ${Images.formatBytes(Images.MaxRawInputBytes.toLong)} limit.") + else Right(ClipData.Bytes(bytes, s"clipboard.${mime.stripPrefix("image/")}")) + case None if types.contains("text/uri-list") => + runCommand(List("xclip", "-selection", "clipboard", "-t", "text/uri-list", "-o")).flatMap(parseUriList) + case None => Left("No image in clipboard.") + + private def parseUriList(raw: Array[Byte]): Either[String, ClipData] = + val lines = String(raw, UTF_8).linesIterator.map(_.trim).filter(l => l.nonEmpty && !l.startsWith("#")).toList + lines match + case single :: Nil => + Images.parsePastedPaths(single, PlatformPath.userHome) match + case Some(path :: Nil) => Right(ClipData.FilePath(path)) + case _ => Left("No image in clipboard.") + case _ => Left("No image in clipboard.") + + private def runCommand(command: List[String]): Either[String, Array[Byte]] = + try + val home = PlatformPath.userHome + val resolved = WindowsExecutable.resolve(command, home) + val proc = ProcessBuilder(resolved*) + .directory(home.toFile) + .redirectInput(ProcessBuilder.Redirect.from(Platform.nullDevice)) + .redirectError(ProcessBuilder.Redirect.DISCARD) + .start().nn + val bytes = Using.resource(proc.getInputStream.nn)(_.readNBytes(Images.MaxRawInputBytes + 1).nn) + if !proc.waitFor(TimeoutSeconds, TimeUnit.SECONDS) then + proc.destroyForcibly() + Left("Reading the clipboard timed out.") + else if proc.exitValue() != 0 then Left("No image in clipboard.") + else Right(bytes) + catch + case NonFatal(e) => + Debug.log(s"clipboard command ${command.head} failed: ${Debug.message(e)}") + Left(s"Could not read clipboard (${command.head} unavailable); attach a file with /image .") diff --git a/app/src/atc/sandbox/Execution.scala b/app/src/atc/sandbox/Execution.scala index 98997acc..52e0c550 100644 --- a/app/src/atc/sandbox/Execution.scala +++ b/app/src/atc/sandbox/Execution.scala @@ -1,9 +1,15 @@ package atc.sandbox +import atc.llm.ImageInput import atc.perms.Mode /** What one evaluation of agent code produced. */ -final case class ExecutionResult(success: Boolean, output: String, error: Option[String] = None): +final case class ExecutionResult( + success: Boolean, + output: String, + error: Option[String] = None, + images: List[ImageInput] = Nil, +): /** What the agent gets to see. */ def render: String = val parts = List( diff --git a/app/src/atc/sandbox/ReplSession.scala b/app/src/atc/sandbox/ReplSession.scala index 28fef76e..5813ec3d 100644 --- a/app/src/atc/sandbox/ReplSession.scala +++ b/app/src/atc/sandbox/ReplSession.scala @@ -2,6 +2,7 @@ package atc.sandbox import atc.Threads import atc.host.{ClassifiedImpl, Host, MonitorRepl} +import atc.llm.ImageInput import atc.perms.Mode import atc.platform.Platform @@ -233,8 +234,15 @@ object ReplSession: /** What one evaluation produced, before it is adopted into the session: * the new state, the captured output, the message of what escaped the driver (`thrown`), - * and whether agent code threw an exception the REPL rendered (`failed`). */ - private final case class Evaluated(state: State, output: String, thrown: Option[String], failed: Boolean) + * whether agent code threw an exception the REPL rendered (`failed`), and any images + * attached via `viewImage`. */ + private final case class Evaluated( + state: State, + output: String, + thrown: Option[String], + failed: Boolean, + images: List[ImageInput] = Nil, + ) private val InterruptedMessage = "Execution interrupted by the user (completed effects are not rolled back)" private val NoResultMessage = "Execution failed (no result; possible fatal error)" @@ -367,6 +375,7 @@ final class ReplSession(config: SandboxConfig, host: Host, preambleOverride: Opt private def evaluate(res: ParseResult, started: CountDownLatch): Evaluated = var newState = state var threw = false + var images: List[ImageInput] = Nil val (output, thrown) = withOutputCapture(onEnter = started.countDown()) { // An interrupt may have landed while we waited for the output lock. `run` // cleared `stopRequested` at the top, so it is true only if `interrupt()` @@ -383,8 +392,11 @@ final class ReplSession(config: SandboxConfig, host: Host, preambleOverride: Opt Sandbox.installHost(host) host.repl = this // a monitor this code adds runs code of this REPL driver.resetEvaluationThrew() - newState = driver.runParseResult(res)(using state) - threw = driver.evaluationThrew + host.beginImageCollection() + try + newState = driver.runParseResult(res)(using state) + threw = driver.evaluationThrew + finally images = host.finishImageCollection() } // What escapes the driver may be the agent's own exception, thrown by a `toString` the // REPL called to show a value. Its message is agent code and is read here, on the @@ -392,11 +404,11 @@ final class ReplSession(config: SandboxConfig, host: Host, preambleOverride: Opt val problem = thrown.map: e => try Option(e.getMessage).filter(_.nonEmpty).getOrElse(e.toString) catch case NonFatal(_) => e.getClass.getName.nn - Evaluated(newState, output, problem, threw) + Evaluated(newState, output, problem, threw, images) /** Take over the new state and turn the evaluation into the agent-visible result. */ private def adopt(res: ParseResult, evaluated: Evaluated): ExecutionResult = - val Evaluated(newState, output, thrown, failed) = evaluated + val Evaluated(newState, output, thrown, failed, images) = evaluated val previousIndex = state.objectIndex state = newState if stopRequested then @@ -412,12 +424,12 @@ final class ReplSession(config: SandboxConfig, host: Host, preambleOverride: Opt // The driver did not return a state, but it had compiled and loaded this line's // wrapper: the next line must not take the same index and find that class. skipInvalidWrapper(previousIndex) - ExecutionResult(false, output, Some(problem)) + ExecutionResult(false, output, Some(problem), images) case None => val compileFailed = res match case p: Parsed => p.reporter.hasErrors case _ => false - ExecutionResult(!compileFailed && !failed, output) + ExecutionResult(!compileFailed && !failed, output, None, images) /** Exclude the stopped wrapper while preserving every earlier definition. The driver may * already have advanced its index; advancing again would leave an unregistered valid index. */ diff --git a/app/src/atc/ui/PastedImages.scala b/app/src/atc/ui/PastedImages.scala new file mode 100644 index 00000000..9e5a1af7 --- /dev/null +++ b/app/src/atc/ui/PastedImages.scala @@ -0,0 +1,77 @@ +package atc.ui + +import atc.llm.ImageInput + +import java.util.regex.Pattern +import scala.collection.mutable + +/** Tracks inline image placeholders inserted into the active prompt read via clipboard paste + * (`Ctrl-V`) or dragged/pasted image file paths. Behaves like [[PastedText]]: each image is + * shown as a styled chip (e.g. `[Image #1: shot.png 1280x720]`), Backspace removes it as a + * unit, and deleting a placeholder before pressing Enter drops that attachment from the turn. */ +private[ui] final class PastedImages: + /** Placeholder text -> prepared image, in insertion order. */ + private val held = mutable.LinkedHashMap[String, ImageInput]() + private var nextNumber = 0 + private var cachedPattern: Option[Pattern] = None + + /** Forget all inline image placeholders for a fresh read. */ + def clear(): Unit = + held.clear() + nextNumber = 0 + cachedPattern = None + + /** Number of placeholders currently tracked in this read. */ + def size: Int = held.size + + /** Record `image` and return its unique numbered placeholder chip for the buffer. */ + def add(image: ImageInput): String = + nextNumber += 1 + val placeholder = PastedImages.placeholder(nextNumber, image) + held(placeholder) = image + cachedPattern = None + placeholder + + /** The placeholder that ends `prefix`, which Backspace removes whole. */ + def endingWith(prefix: String): Option[String] = + held.keysIterator.find(prefix.endsWith) + + /** Regex matching all tracked image placeholders for Cyan highlighting; `None` when empty. */ + def pattern: Option[Pattern] = + if held.isEmpty then None + else + if cachedPattern.isEmpty then + cachedPattern = Some(Pattern.compile(held.keysIterator.map(Pattern.quote).mkString("|")).nn) + cachedPattern + + /** Extract surviving images in order of appearance in `line` and return `(cleanedText, images)`. + * If the line consists solely of image placeholders and whitespace, `cleanedText` is empty; + * otherwise surrounding user text is preserved with placeholders kept as concise references. */ + def extract(line: String): (String, List[ImageInput]) = + pattern match + case None => (line, Nil) + case Some(pat) => + val matcher = pat.matcher(line).nn + val images = List.newBuilder[ImageInput] + val remaining = StringBuilder() + var lastEnd = 0 + while matcher.find() do + remaining.append(line.substring(lastEnd, matcher.start())) + held.get(matcher.group().nn).foreach(images += _) + lastEnd = matcher.end() + remaining.append(line.substring(lastEnd)) + val attached = images.result() + if attached.isEmpty then (line, Nil) + else if remaining.toString.trim.isEmpty then ("", attached) + else (line, attached) + +private[ui] object PastedImages: + /** Build a concise chip such as `[Image #1: shot.png 1280x720]` or `[Image #2: clipboard]`. */ + def placeholder(number: Int, image: ImageInput): String = + val name = + val clean = Ansi.sanitize(image.label).trim + val short = if clean.length <= 32 then clean else clean.take(31) + "…" + if short.isEmpty then image.mediaType.stripPrefix("image/") else short + val dims = Option.when(image.width > 0 && image.height > 0)(s"${image.width}x${image.height}") + val detail = (name :: dims.toList).mkString(" ") + s"[Image #$number: $detail]" diff --git a/app/src/atc/ui/PromptReader.scala b/app/src/atc/ui/PromptReader.scala index 4281b9c2..3007b11f 100644 --- a/app/src/atc/ui/PromptReader.scala +++ b/app/src/atc/ui/PromptReader.scala @@ -1,5 +1,6 @@ package atc.ui +import atc.llm.{ImageInput, Images} import atc.platform.OwnerOnlyFiles import org.jline.keymap.KeyMap @@ -41,6 +42,10 @@ private[ui] final class PromptReader(screen: Screen, historyPath: Path, alerts: /** Ctrl-O in a read: `Tui` switches between the compact and the expanded view. */ @volatile var onToggle: () => Unit = () => () + /** Ctrl-V at the main prompt: attempt to read an image from the OS clipboard. */ + @volatile var onPasteImage: () => Either[String, ImageInput] = () => Left("No image in clipboard.") + /** Bracketed paste at the main prompt: detect dragged/pasted local image file paths. */ + @volatile var onPastedPaths: String => Option[Either[String, List[ImageInput]]] = _ => None /** What [[whileReading]] hands its widget; set and cleared under `actionLock`. */ private var action: () => Unit = () => () private val actionLock = Object() @@ -66,7 +71,13 @@ private[ui] final class PromptReader(screen: Screen, historyPath: Path, alerts: seen = buffer alerts.touch() val text = super.highlight(r, buffer).nn - val base = pasted.pattern.filter(_ => !plain).fold(text)(text.styleMatches(_, PromptReader.PlaceholderStyle).nn) + val withText = + pasted.pattern.filter(_ => !plain).fold(text)(text.styleMatches(_, PromptReader.PlaceholderStyle).nn) + val base = + pastedImages.pattern.filter(_ => !plain).fold(withText)(withText.styleMatches( + _, + PromptReader.PlaceholderStyle + ).nn) ghost(buffer) match case Some(rest) if !plain && !closing => AttributedStringBuilder().append(base).styled(AttributedStyle.DEFAULT.faint(), rest).toAttributedString.nn @@ -89,6 +100,8 @@ private[ui] final class PromptReader(screen: Screen, historyPath: Path, alerts: /** The long pastes of the current read, which the buffer shows as placeholders. */ private val pasted = PastedText() + /** Inline image attachments inserted via clipboard paste or dragged file paths during this read. */ + private val pastedImages = PastedImages() /** Whether a long paste gets a placeholder: not in a code block, which is there to be * read and edited, nor in a secret, whose every character shows as `*`. */ private var collapsePastes = false @@ -204,20 +217,44 @@ private[ui] final class PromptReader(screen: Screen, historyPath: Path, alerts: try super.doCleanup(nl) finally closing = false - /** A bracketed paste: JLine writes it into the buffer, and a long one is then replaced by - * its placeholder, which stays marked as the pasted region until the next key. */ + /** A bracketed paste: JLine writes it into the buffer. At the main prompt, dragged or pasted + * local image paths become numbered image chips; otherwise a long text paste becomes a + * text placeholder. */ override def beginPaste(): Boolean = val start = buf.cursor val read = super.beginPaste() if read && collapsePastes && buf.cursor > start then - pasted.collapse(buf.substring(start, buf.cursor).nn).foreach: placeholder => - buf.backspace(buf.cursor - start) - buf.write(placeholder) + val chunk = buf.substring(start, buf.cursor).nn + val before = buf.substring(0, start).nn.trim + val imageResult = + if mainPrompt && !plain && !before.startsWith("/") then onPastedPaths(chunk) else None + imageResult match + case Some(Right(images)) if images.nonEmpty => + val room = (Images.MaxImagesPerMessage - pastedImages.size).max(0) + if images.size > room then + reader.printAbove( + screen.styled( + s"${screen.g.warn} At most ${Images.MaxImagesPerMessage} images may be attached to one message.", + Ansi.Yellow, + ) + ) + else + val chips = images.map(pastedImages.add).mkString(" ") + buf.backspace(buf.cursor - start) + if start > 0 && !Character.isWhitespace(buf.atChar(start - 1)) then buf.write(" ") + buf.write(chips) + case Some(Left(warning)) => + reader.printAbove(screen.styled(s"${screen.g.warn} ${Ansi.sanitize(warning)}", Ansi.Yellow)) + case _ => + pasted.collapse(chunk).foreach: placeholder => + buf.backspace(buf.cursor - start) + buf.write(placeholder) read /** Backspace after a placeholder removes all of it: a part would stand for nothing. */ override protected def backwardDeleteChar(): Boolean = - pasted.endingWith(buf.substring(0, buf.cursor).nn) match + val prefix = buf.substring(0, buf.cursor).nn + pasted.endingWith(prefix).orElse(pastedImages.endingWith(prefix)) match case Some(placeholder) => buf.backspace(placeholder.length); true case None => super.backwardDeleteChar() @@ -259,6 +296,29 @@ private[ui] final class PromptReader(screen: Screen, historyPath: Path, alerts: // request; here it switches the view, as it does during a turn. reader.getWidgets.put("atc-toggle-view", (() => { onToggle(); true }): Widget) keyMap.bind(Reference("atc-toggle-view"), "\u000f") + // Ctrl-V (and Alt-V, helpful on Windows Terminal where Ctrl-V pastes text) reads an + // image from the OS clipboard at the main prompt and inserts an inline placeholder chip. + val pasteImage: Widget = () => + if mainPrompt then + if pastedImages.size >= Images.MaxImagesPerMessage then + reader.printAbove( + screen.styled( + s"${screen.g.warn} At most ${Images.MaxImagesPerMessage} images may be attached to one message.", + Ansi.Yellow, + ) + ) + else + onPasteImage() match + case Right(img) => + val chip = pastedImages.add(img) + val buf = reader.getBuffer + if buf.cursor > 0 && !Character.isWhitespace(buf.atChar(buf.cursor - 1)) then buf.write(" ") + buf.write(chip) + case Left(msg) => + reader.printAbove(screen.styled(Ansi.sanitize(msg), Ansi.Dim)) + true + reader.getWidgets.put("atc-paste-image", pasteImage) + keyMap.bind(Reference("atc-paste-image"), "\u0016", "\u001bv") /** What `capability` sends according to the terminfo, when it says, then the usual `fallbacks`. */ def key(capability: InfoCmp.Capability, fallbacks: String*): List[String] = (Option(KeyMap.key(terminal, capability)).toList ++ fallbacks).distinct.filter(_.nonEmpty) @@ -375,6 +435,7 @@ private[ui] final class PromptReader(screen: Screen, historyPath: Path, alerts: ghostHighlighter.seen = typed mainPrompt = commands && !plain pasted.clear() + pastedImages.clear() resetCommandPopup() collapsePastes = !blockMode try reader.readLine(prompt, null: String | Null, null: MaskingCallback | Null, typed) @@ -394,6 +455,7 @@ private[ui] final class PromptReader(screen: Screen, historyPath: Path, alerts: collapsePastes = false secretMode = true pasted.clear() + pastedImages.clear() resetCommandPopup() try withoutHistory(PromptReader.answerOf(reader.readLine(prompt, Character.valueOf('*')))) finally @@ -430,6 +492,9 @@ private[ui] final class PromptReader(screen: Screen, historyPath: Path, alerts: /** `line` with the text its paste placeholders stand for, as a read that ended returns it. */ def expandPastes(line: String): String = pasted.expand(line) + /** Extract surviving inline image attachments from a finished read line. */ + def extractPastedImages(line: String): (String, List[ImageInput]) = pastedImages.extract(line) + /** Write `line` above the prompt while it reads, keeping the user's input; false when it is not reading. */ def printAbove(line: String): Boolean = whileReading(reader.printAbove(line)) diff --git a/app/src/atc/ui/Tui.scala b/app/src/atc/ui/Tui.scala index ece5bb35..51b0713c 100644 --- a/app/src/atc/ui/Tui.scala +++ b/app/src/atc/ui/Tui.scala @@ -3,7 +3,7 @@ package atc.ui import atc.{Debug, ProcessEnvironment, TextFiles} import atc.agent.{AgentUI, ContextManager, TurnOutcome} import atc.lib.{Todo, TodoStatus} -import atc.llm.TokenUsage +import atc.llm.{ImageInput, TokenUsage} import atc.perms.* import atc.host.FileChange import atc.sandbox.ExecutionResult @@ -72,6 +72,14 @@ final class Tui private ( def commandList: List[Tui.CommandEntry] = prompt.commandList def commandList_=(value: List[Tui.CommandEntry]): Unit = prompt.commandList = value + /** Ctrl-V at the main prompt: read an image from the OS clipboard. */ + def onPasteImage: () => Either[String, ImageInput] = prompt.onPasteImage + def onPasteImage_=(value: () => Either[String, ImageInput]): Unit = prompt.onPasteImage = value + + /** Bracketed paste at the main prompt: detect dragged/pasted local image file paths. */ + def onPastedPaths: String => Option[Either[String, List[ImageInput]]] = prompt.onPastedPaths + def onPastedPaths_=(value: String => Option[Either[String, List[ImageInput]]]): Unit = prompt.onPastedPaths = value + // ── state ───────────────────────────────────────────────────────── /** Set by Ctrl-C during a turn; `beginTurn` clears it. */ @@ -319,6 +327,7 @@ final class Tui private ( s"Tab / $rightKey" -> "Complete a command or accept a suggestion", "1..9" -> "Pick a menu item directly (in short single-choice pop-ups)", "Ctrl-O" -> "Toggle expanded tool output and reasoning", + "Ctrl-V" -> "Paste an image from the clipboard (or drag-and-drop image files)", "Ctrl-C" -> "Interrupt the current turn, or clear the prompt", "Ctrl-U / Ctrl-W / Esc" -> "Clear draft or delete a word while steering mid-turn", "Ctrl-L" -> "Clear the screen", @@ -723,13 +732,17 @@ final class Tui private ( * during the previous turn are pre-filled. The input may span lines (a * pasted block, Shift+Enter or `\`+Enter, a `/run` with brackets still * open: [[Continuation]]); the trailing empty line that submits is removed. */ - def readLine(promptText: String): Option[String] = readBuffer(promptText).map(_.stripTrailing) + def readLine(promptText: String): Option[String] = readInput(promptText).map(_.text) + + /** Read one input together with any inline images pasted (`Ctrl-V`) or dragged into the prompt. */ + def readInput(promptText: String): Option[Tui.UserInput] = + readBufferWithImages(promptText).map(in => in.copy(text = in.text.stripTrailing)) /** Read a block of code: Enter adds a line until one is left empty, which * submits the block (without that line); `None` on EOF. */ def readBlock(promptText: String): Option[String] = prompt.blockMode = true - try readBuffer(promptText).map(_.stripTrailing) + try readBufferWithImages(promptText).map(_.text.stripTrailing) finally prompt.blockMode = false /** Text the next prompt starts with, before any keys typed ahead. */ @@ -785,8 +798,8 @@ final class Tui private ( /** Start the next prompt with `text`, for the user to edit or send. */ def draft(text: String): Unit = nextDraft = text - private def readBuffer(promptText: String): Option[String] = - var result: Option[String] = None + private def readBufferWithImages(promptText: String): Option[Tui.UserInput] = + var result: Option[Tui.UserInput] = None var again = true while again do try @@ -795,10 +808,12 @@ final class Tui private ( nextDraft = "" frame { statusLine.draft = ""; statusLine.refresh() } result = readWakeable(styled(promptText, Cyan, Bold), typed) match - case Right(line) => Some(line) + case Right(line) => + val (text, images) = prompt.extractPastedImages(line) + Some(Tui.UserInput(text, images)) case Left(partial) => nextDraft = prompt.expandPastes(partial) - Some("") + Some(Tui.UserInput("")) again = false catch case _: UserInterruptException => @@ -847,6 +862,9 @@ final class Tui private ( terminal.handle(Terminal.Signal.WINCH, _ => resized()) object Tui: + /** One user submission read from the prompt: text plus any inline pasted/dropped images. */ + final case class UserInput(text: String, images: List[ImageInput] = Nil) + /** How much of a monitor's message the window shows; the model reads all of it. */ private val MonitorShownChars = 500 diff --git a/app/test/src/atc/MainSuite.scala b/app/test/src/atc/MainSuite.scala index d8b7bc34..b947a89e 100644 --- a/app/test/src/atc/MainSuite.scala +++ b/app/test/src/atc/MainSuite.scala @@ -187,3 +187,35 @@ class MainSuite extends munit.FunSuite: Cli.validate(Cli.Args(cwd = cwd, ide = true, init = true)) ) assert(withInit.getMessage.nn.contains("--ide cannot be used with --init"), withInit.getMessage) + + test("parses and validates repeatable -i / --image flags"): + val cwd = TestEnv.tempDir("atc-main-images") + val img1 = Files.writeString(cwd.resolve("a.png"), "placeholder").nn + val img2 = Files.writeString(cwd.resolve("b.png"), "placeholder").nn + val parsed = parse("-C", cwd.toString, "-i", "a.png", "--image=b.png", "-p", "describe") + assertEquals(parsed.images, List(img1, img2)) + Cli.validate(parsed) + + val missing = intercept[IllegalArgumentException]( + Cli.validate(Cli.Args(cwd = cwd, prompt = Some("hi"), images = List(cwd.resolve("missing.png").nn))) + ) + assert(missing.getMessage.nn.contains("does not exist"), missing.getMessage) + + val dir = intercept[IllegalArgumentException]( + Cli.validate(Cli.Args(cwd = cwd, prompt = Some("hi"), images = List(cwd))) + ) + assert(dir.getMessage.nn.contains("not a regular file"), dir.getMessage) + + val withIde = intercept[IllegalArgumentException]( + Cli.validate(Cli.Args(cwd = cwd, ide = true, images = List(img1))) + ) + assert(withIde.getMessage.nn.contains("-i / --image cannot be used with --ide"), withIde.getMessage) + + val tooMany = intercept[IllegalArgumentException]( + Cli.validate(Cli.Args( + cwd = cwd, + prompt = Some("hi"), + images = List.fill(atc.llm.Images.MaxImagesPerMessage + 1)(img1) + )) + ) + assert(tooMany.getMessage.nn.contains("Too many images"), tooMany.getMessage) diff --git a/app/test/src/atc/agent/AgentLoopSuite.scala b/app/test/src/atc/agent/AgentLoopSuite.scala index 4343aae3..93a2a410 100644 --- a/app/test/src/atc/agent/AgentLoopSuite.scala +++ b/app/test/src/atc/agent/AgentLoopSuite.scala @@ -340,7 +340,7 @@ class AgentLoopSuite extends munit.FunSuite: import loop.* turn("look it up") assert(!agent.history.exists { - case Msg.User(t) => t != "look it up"; case _ => false + case Msg.User(t, _) => t != "look it up"; case _ => false }) // no injected user messages assertEquals(assistants.map(_.text), List("searching the web…", "Here is what I found.")) assert(ui.statuses.exists(_.contains("resuming"))) @@ -451,7 +451,7 @@ class AgentLoopSuite extends munit.FunSuite: assert(model.seenHistories.last.head.asInstanceOf[Msg.User].text.contains("keep the answer")) assert(session.run("answer + 1").success) turn("continue") - assert(agent.history.collect { case Msg.User(t) => t }.last.contains("test pending notice")) + assert(agent.history.collect { case Msg.User(t, _) => t }.last.contains("test pending notice")) test("failed, incomplete, empty and larger summaries leave history unchanged"): val steps = List( @@ -958,3 +958,33 @@ class AgentLoopSuite extends munit.FunSuite: assertEquals(agent.compact("", () => false), Agent.CompactOutcome.NothingToCompact) assertEquals(agent.snapshot, before) assertEquals(model.i, steps.size) + + test("agent turn delivers user images and tool-returned images to the model, and strips them on compaction"): + val userImg = ImageInput("image/png", "U" * 512, label = "bug.png", width = 640, height = 480, byteSize = 384) + val toolImg = ImageInput("image/png", "T" * 512, label = "plot.png", width = 400, height = 300, byteSize = 384) + val model = ScriptedModel( + "m", + Seq( + ScriptedModel.Comp(completion("", List(ToolCall("c1", "inspect", "{}")))), + ScriptedModel.Reply("checked both images"), + ), + ) + val loop = Loop(model) + val runner = new ToolRunner: + val tools: List[ToolSpec] = Nil + def run(call: ToolCall): ToolResult = ToolResult(call.id, "loaded plot", isError = false, images = List(toolImg)) + + val outcome = loop.agent.runTurn(runner, "compare", () => false, images = List(userImg)) + assertEquals(outcome, TurnOutcome.Finished) + assertEquals(model.seenHistories(0), List(Msg.User("compare", List(userImg)))) + assertEquals( + model.seenHistories(1).last, + Msg.ToolResults(List(ToolResult("c1", "loaded plot", isError = false, images = List(toolImg)))), + ) + + // Compaction transcript strips base64 data into metadata placeholders. + val transcript = ContextCompaction.transcript(loop.agent.history, "").head.asInstanceOf[Msg.User].text + assert(transcript.contains("[image: bug.png, image/png, 640x480]"), transcript) + assert(transcript.contains("[image: plot.png, image/png, 400x300]"), transcript) + assert(!transcript.contains("U" * 100), "user image base64 must not appear in compaction transcript") + assert(!transcript.contains("T" * 100), "tool image base64 must not appear in compaction transcript") diff --git a/app/test/src/atc/agent/ContextManagerSuite.scala b/app/test/src/atc/agent/ContextManagerSuite.scala index 22686606..1418574a 100644 --- a/app/test/src/atc/agent/ContextManagerSuite.scala +++ b/app/test/src/atc/agent/ContextManagerSuite.scala @@ -182,3 +182,28 @@ class ContextManagerSuite extends munit.FunSuite: val largerOutput = model.copy(maxOutputTokens = Some(20000)) assertEquals(manager.contextBreakdown(500, history, largerOutput).outputReserve, Some(20000L)) assertEquals(ContextManager.estimateTokens(Msg.Monitor("abcdefgh")), 6L) + + test("context estimation accounts for images and context cuts preserve images on retained head messages"): + val img = atc.llm.ImageInput("image/png", "AAAA", label = "ui.png", width = 1500, height = 1000, byteSize = 3) + assertEquals(img.estimatedTokens, 1600L) // (1500*1000)/750 = 2000 -> clamped to 1600 + val msgWithImg = Msg.User("look", List(img)) + assertEquals(ContextManager.estimateTokens(msgWithImg), ContextManager.estimateTokens(Msg.User("look")) + 1600L) + val toolWithImg = Msg.ToolResults(List(ToolResult("c1", "ok", isError = false, images = List(img)))) + assertEquals( + ContextManager.estimateTokens(toolWithImg), + ContextManager.estimateTokens(Msg.ToolResults(List(ToolResult("c1", "ok", isError = false)))) + 1600L, + ) + + val manager = ContextManager() + val model = ModelContext("m", "p", "p/m", contextWindow = Some(3000)) + val history = List( + Msg.User("old"), + assistant("x" * 12000), + msgWithImg, + ) + val prepared = manager.prepare(fixedTokens = 100, history = history, model = model, retained = "") + prepared.history.head match + case Msg.User(text, images) => + assert(text.contains("dropped"), text) + assertEquals(images, List(img)) + case other => fail(s"expected Msg.User, got $other") diff --git a/app/test/src/atc/agent/SessionStoreSuite.scala b/app/test/src/atc/agent/SessionStoreSuite.scala index fcc8e5f6..ae4cd5b7 100644 --- a/app/test/src/atc/agent/SessionStoreSuite.scala +++ b/app/test/src/atc/agent/SessionStoreSuite.scala @@ -140,3 +140,25 @@ class SessionStoreSuite extends munit.FunSuite: assertEquals(summaries.head.cwd, Some("~/work/proj")) assertEquals(summaries.head.messages, 3) assertEquals(summaries.head.preview, "implement") + + test("saving a session strips image binary payloads to compact placeholders"): + val img = + atc.llm.ImageInput("image/png", "A" * 10000, label = "screen.png", width = 800, height = 600, byteSize = 7500) + val imageHistory = List( + Msg.User("check this", List(img)), + Msg.Assistant("", List(ToolCall("c1", "run_scala", """{"code":"viewImage(\"screen.png\")"}""")), None), + Msg.ToolResults(List(ToolResult("c1", "ok", isError = false, images = List(img)))), + Msg.Assistant("looks good", Nil, None), + ) + val encoded = SessionStore.encode(snapshot.copy(history = imageHistory)) + assert(!encoded.contains("A" * 100), "raw base64 payload must not be stored in saved sessions") + assert(encoded.contains("[image: screen.png, image/png, 800x600]"), encoded) + val decoded = SessionStore.decode(encoded) + assertEquals( + decoded.history.head, + Msg.User("check this\n\n[image: screen.png, image/png, 800x600]", Nil), + ) + assertEquals( + decoded.history(2), + Msg.ToolResults(List(ToolResult("c1", "ok\n[image: screen.png, image/png, 800x600]", isError = false))), + ) diff --git a/app/test/src/atc/commands/SlashCommandSuite.scala b/app/test/src/atc/commands/SlashCommandSuite.scala index 16cbf88c..5a123def 100644 --- a/app/test/src/atc/commands/SlashCommandSuite.scala +++ b/app/test/src/atc/commands/SlashCommandSuite.scala @@ -137,3 +137,20 @@ class SlashCommandSuite extends munit.FunSuite: SessionCommands.formatEntry(summary, isCurrentDirectory = false, now = now), "[atc] 2m ago · 6 msgs · openai/gpt-5 · Polish UX and add JSON output", ) + + test("/image and /attach parse and complete subcommands and staged image targets"): + assertEquals(parse("/image"), Right((Image, ""))) + assertEquals(parse("/attach shot.png"), Right((Image, "shot.png"))) + assertEquals(parse("/image paste"), Right((Image, "paste"))) + def complete(words: String*) = Commands.complete( + words.toList, + labels = Nil, + efforts = Nil, + classifiedLabels = Nil, + scopes = Nil, + imageTargets = sub => if sub.equalsIgnoreCase("rm") then List("all", "1", "2") else Nil, + ) + assertEquals(complete("/image", ""), List("paste", "clear", "rm")) + assertEquals(complete("/attach", ""), List("paste", "clear", "rm")) + assertEquals(complete("/image", "rm", ""), List("all", "1", "2")) + assertEquals(complete("/image", "clear", ""), Nil) diff --git a/app/test/src/atc/host/HostSuite.scala b/app/test/src/atc/host/HostSuite.scala index 0aa0daef..ab0cdc93 100644 --- a/app/test/src/atc/host/HostSuite.scala +++ b/app/test/src/atc/host/HostSuite.scala @@ -1000,3 +1000,45 @@ class HostSuite extends munit.FunSuite: tiny.host.search(".", "abc", "*.txt", atc.lib.SearchOptions(maxMatches = 10, maxCharsPerFile = 10))(using tiny.fs) assert(found.limited, "file exceeding maxCharsPerFile should report limited") assertEquals(found.matches, Nil, "truncated partial line must not be emitted as a complete match") + + test("viewImage enforces read permissions, refuses classified files, and respects the per-call cap"): + System.setProperty("java.awt.headless", "true") + val imgBuf = java.awt.image.BufferedImage(12, 8, java.awt.image.BufferedImage.TYPE_INT_RGB) + val baos = java.io.ByteArrayOutputStream() + javax.imageio.ImageIO.write(imgBuf, "png", baos) + val pngBytes = baos.toByteArray.nn + + val envWithSecrets = TestEnv(TestEnv.withSecrets) + import envWithSecrets.given + Files.write(envWithSecrets.root.resolve("shot.png"), pngBytes) + Files.createDirectories(envWithSecrets.root.resolve("secrets")) + Files.write(envWithSecrets.root.resolve("secrets/private.png"), pngBytes) + + // Path overload attaches prepared image and prints a note. + val (_, attached) = envWithSecrets.host.collectImages: + envWithSecrets.host.viewImage("shot.png") + assertEquals(attached.size, 1) + assertEquals(attached.head.mediaType, "image/png") + assertEquals(attached.head.width, 12) + assertEquals(attached.head.height, 8) + assertEquals(attached.head.label, "shot.png") + assert( + envWithSecrets.agentOut.toString.contains("[attached image: [image: shot.png"), + envWithSecrets.agentOut.toString + ) + + // Classified image path is refused. + val (_, classifiedImgs) = envWithSecrets.host.collectImages: + val err = intercept[SecurityException](envWithSecrets.host.viewImage("secrets/private.png")) + assert(err.getMessage.nn.contains("classified"), err.getMessage) + assertEquals(classifiedImgs, Nil) + + // Bytes overload works and enforces MaxImagesPerMessage. + val (_, many) = envWithSecrets.host.collectImages: + for i <- 1 to atc.llm.Images.MaxImagesPerMessage do + envWithSecrets.host.viewImage(pngBytes, s"frame-$i.png") + intercept[IllegalStateException](envWithSecrets.host.viewImage(pngBytes, "too-many.png")) + assertEquals(many.size, atc.llm.Images.MaxImagesPerMessage) + + // Calling outside an active evaluation is rejected. + intercept[UnsupportedOperationException](envWithSecrets.host.viewImage("shot.png")) diff --git a/app/test/src/atc/ide/IdeServerSuite.scala b/app/test/src/atc/ide/IdeServerSuite.scala index 51911be9..1e959b5c 100644 --- a/app/test/src/atc/ide/IdeServerSuite.scala +++ b/app/test/src/atc/ide/IdeServerSuite.scala @@ -774,3 +774,83 @@ class IdeServerSuite extends munit.FunSuite: assert(!Files.exists(bumpDir)) assertEquals(afterDirectDelete("skills").arr.size, 0) finally harness.close() + + test( + "IDE protocol accepts user image attachments, rejects invalid image data, and emits tool_end images from viewImage" + ): + System.setProperty("java.awt.headless", "true") + val imgBuf = java.awt.image.BufferedImage(10, 12, java.awt.image.BufferedImage.TYPE_INT_RGB) + val baos = ByteArrayOutputStream() + javax.imageio.ImageIO.write(imgBuf, "png", baos) + val pngBytes = baos.toByteArray.nn + val pngB64 = java.util.Base64.getEncoder.nn.encodeToString(pngBytes).nn + + val globalDir = TestEnv.tempDir("atc-ide-img-global") + val project = TestEnv.tempDir("atc-ide-img-proj") + Files.write(project.resolve("sample.png"), pngBytes) + Files.writeString( + globalDir.resolve("config.json"), + """{ + | "providers": { "echo": { "api": "echo", "models": { "echo": {} } } }, + | "model": "echo/echo", + | "files": [{ "path": ".", "access": "write" }] + |} + |""".stripMargin, + ) + val harness = IdeHarness(Cli.Args(cwd = project, ide = true), globalDir) + try + harness.collectUntil(_("type").str == "ready") + + // 1. Prompt with an image attachment emits turn_start.images and echoes the image placeholder. + harness.send(ujson.Obj( + "type" -> "prompt", + "text" -> "check layout", + "images" -> ujson.Arr(ujson.Obj("mediaType" -> "image/png", "data" -> pngB64, "label" -> "mock.png")), + )) + val events1 = harness.collectUntil(_("type").str == "turn_end") + val turnStart1 = events1.find(_("type").str == "turn_start").get + val startImages = turnStart1("images").arr + assertEquals(startImages.size, 1) + assertEquals(startImages(0)("label").str, "mock.png") + assertEquals(startImages(0)("width").num.toInt, 10) + assertEquals(startImages(0)("height").num.toInt, 12) + val deltaText1 = events1.filter(_("type").str == "delta").map(_("text").str).mkString + assert(deltaText1.contains("[image: mock.png, image/png, 10x12]"), deltaText1) + + // 2. Image-only prompt (empty text) succeeds. + harness.send(ujson.Obj( + "type" -> "prompt", + "text" -> "", + "images" -> ujson.Arr(ujson.Obj( + "mediaType" -> "image/png", + "data" -> s"data:image/png;base64,$pngB64", + "label" -> "only.png" + )), + )) + val events2 = harness.collectUntil(_("type").str == "turn_end") + val deltaText2 = events2.filter(_("type").str == "delta").map(_("text").str).mkString + assert(deltaText2.contains("[image: only.png, image/png, 10x12]"), deltaText2) + + // 3. Invalid image data emits an error without crashing the server. + harness.send(ujson.Obj( + "type" -> "prompt", + "text" -> "bad", + "images" -> + ujson.Arr(ujson.Obj("mediaType" -> "image/png", "data" -> "bm90IGFuIGltYWdl", "label" -> "bad.png")), + )) + val errEv = harness.collectUntil(_("type").str == "error").last + assert(errEv("message").str.contains("Unsupported image format"), errEv("message").str) + + // 4. Agent calling viewImage in run_scala emits tool_end.images and passes the image back to the model. + harness.send(ujson.Obj("type" -> "prompt", "text" -> """run: viewImage("sample.png")""")) + val events4 = harness.collectUntil(_("type").str == "turn_end") + val toolEnd4 = events4.find(_("type").str == "tool_end").get + assert(toolEnd4("success").bool, toolEnd4.toString) + val toolImages = toolEnd4("images").arr + assertEquals(toolImages.size, 1) + assertEquals(toolImages(0)("label").str, "sample.png") + assertEquals(toolImages(0)("width").num.toInt, 10) + assertEquals(toolImages(0)("height").num.toInt, 12) + val deltaText4 = events4.filter(_("type").str == "delta").map(_("text").str).mkString + assert(deltaText4.contains("[image: sample.png, image/png, 10x12]"), deltaText4) + finally harness.close() diff --git a/app/test/src/atc/llm/AntigravitySuite.scala b/app/test/src/atc/llm/AntigravitySuite.scala index 9d0f92e8..8cc6f3ca 100644 --- a/app/test/src/atc/llm/AntigravitySuite.scala +++ b/app/test/src/atc/llm/AntigravitySuite.scala @@ -120,8 +120,8 @@ class AntigravitySuite extends munit.FunSuite: assertEquals(listed("result")("tools").arr.map(_("name").str).toList, List("run_scala")) /** Handle `session/set_config_option` and `session/set_model` until the next `session/prompt` - * arrives; returns the prompt text. */ - def nextPrompt(): String = + * arrives; returns all prompt content blocks. */ + def nextPromptBlocks(): ujson.Arr = var msg = read() while msg("method").str != "session/prompt" do msg("method").str match @@ -140,7 +140,11 @@ class AntigravitySuite extends munit.FunSuite: case other => fail(s"unexpected method while waiting for prompt: $other") msg = read() lastPromptId = msg("id") - msg("params")("prompt")(0)("text").str + msg("params")("prompt").arr + + /** Handle `session/set_config_option` and `session/set_model` until the next `session/prompt` + * arrives; returns the prompt text. */ + def nextPrompt(): String = nextPromptBlocks()(0)("text").str /** Answer config option queries until the host closes stdin (used by `listModels`). */ def serveConfigUntilClose(): Unit = @@ -1153,3 +1157,37 @@ class AntigravitySuite extends munit.FunSuite: finally Providers.closeOkHttp(client) server.close() + + test("ACP session/prompt and MCP tools/call carry image content blocks"): + val sample = ImageInput("image/png", "iVBORw0KGgo=", label = "ui.png", width = 10, height = 10, byteSize = 8) + val receivedPrompt = AtomicReference[ujson.Value]() + val receivedMcp = AtomicReference[ujson.Value]() + val h = Harness( + spec, + cli => + cli.handshake() + receivedPrompt.set(cli.nextPromptBlocks()) + val mcpRes = cli.mcpPost( + "tools/call", + ujson.Obj("name" -> "run_scala", "arguments" -> ujson.Obj("code" -> "viewImage(\"ui.png\")")), + ) + receivedMcp.set(mcpRes("result")("content")) + cli.answer("saw it") + , + ) + val start = List(Msg.User("describe", List(sample))) + val first = completion(h, start) + assertEquals(first.toolCalls.size, 1) + val promptBlocks = receivedPrompt.get().nn.arr + assertEquals(promptBlocks.map(_("type").str).toList, List("text", "image")) + assertEquals(promptBlocks(1)("mimeType").str, "image/png") + assertEquals(promptBlocks(1)("data").str, "iVBORw0KGgo=") + + val next = start :+ assistant(first) :+ Msg.ToolResults( + List(ToolResult(first.toolCalls.head.id, "attached", isError = false, images = List(sample))) + ) + assertEquals(completion(h, next).text, "saw it") + val mcpBlocks = receivedMcp.get().nn.arr + assertEquals(mcpBlocks.map(_("type").str).toList, List("text", "image")) + assertEquals(mcpBlocks(1)("mimeType").str, "image/png") + assertEquals(mcpBlocks(1)("data").str, "iVBORw0KGgo=") diff --git a/app/test/src/atc/llm/ClaudeCodeSuite.scala b/app/test/src/atc/llm/ClaudeCodeSuite.scala index cdc33e7f..feb844b7 100644 --- a/app/test/src/atc/llm/ClaudeCodeSuite.scala +++ b/app/test/src/atc/llm/ClaudeCodeSuite.scala @@ -616,3 +616,67 @@ class ClaudeCodeSuite extends munit.FunSuite: val next = start :+ assistant(first) :+ Msg.ToolResults(List(ToolResult("tu-1", "2", isError = false))) assertEquals(completion(h, next).text, "recovered") assertEquals(h.launches.size, 2) + + test("user images and MCP tool-result images travel as base64 content blocks"): + val sample = ImageInput("image/png", "iVBORw0KGgo=", label = "ui.png", width = 10, height = 10, byteSize = 8) + val receivedUser = AtomicReference[ujson.Value]() + val receivedTool = AtomicReference[ujson.Value]() + val h = Harness(cli => + cli.handshake() + val msg = cli.receive(m => m("type").str == "user") + receivedUser.set(msg("message")("content")) + cli.send(ujson.Obj( + "type" -> "assistant", + "parent_tool_use_id" -> ujson.Null, + "message" -> ujson.Obj( + "role" -> "assistant", + "content" -> ujson.Arr(ujson.Obj( + "type" -> "tool_use", + "id" -> "tu-img", + "name" -> "mcp__atc__run_scala", + "input" -> ujson.Obj("code" -> "viewImage(\"ui.png\")"), + )), + ), + )) + cli.send(ujson.Obj( + "type" -> "stream_event", + "parent_tool_use_id" -> ujson.Null, + "event" -> ujson.Obj( + "type" -> "message_delta", + "delta" -> ujson.Obj("stop_reason" -> "tool_use"), + "usage" -> ujson.Obj("input_tokens" -> 10, "output_tokens" -> 3), + ), + )) + cli.send(ujson.Obj( + "type" -> "stream_event", + "parent_tool_use_id" -> ujson.Null, + "event" -> ujson.Obj("type" -> "message_stop"), + )) + val mcpRes = cli.mcp( + "tools/call", + ujson.Obj( + "name" -> "run_scala", + "arguments" -> ujson.Obj("code" -> "viewImage(\"ui.png\")"), + "_meta" -> ujson.Obj("claudecode/toolUseId" -> "tu-img"), + ), + ) + receivedTool.set(mcpRes("content")) + cli.answer("looks good") + , + ) + val start = List(Msg.User("inspect", List(sample))) + val first = completion(h, start) + assertEquals(first.toolCalls.map(_.id), List("tu-img")) + val userBlocks = receivedUser.get().nn.arr + assertEquals(userBlocks.map(_("type").str).toList, List("image", "text")) + assertEquals(userBlocks(0)("source")("media_type").str, "image/png") + assertEquals(userBlocks(0)("source")("data").str, "iVBORw0KGgo=") + + val next = start :+ assistant(first) :+ Msg.ToolResults( + List(ToolResult("tu-img", "attached", isError = false, images = List(sample))) + ) + assertEquals(completion(h, next).text, "looks good") + val toolBlocks = receivedTool.get().nn.arr + assertEquals(toolBlocks.map(_("type").str).toList, List("text", "image")) + assertEquals(toolBlocks(1)("mimeType").str, "image/png") + assertEquals(toolBlocks(1)("data").str, "iVBORw0KGgo=") diff --git a/app/test/src/atc/llm/ImagesSuite.scala b/app/test/src/atc/llm/ImagesSuite.scala new file mode 100644 index 00000000..c9a6d6bc --- /dev/null +++ b/app/test/src/atc/llm/ImagesSuite.scala @@ -0,0 +1,155 @@ +package atc.llm + +import atc.TestEnv + +import java.awt.Color +import java.awt.image.BufferedImage +import java.io.ByteArrayOutputStream +import java.nio.ByteBuffer +import java.nio.file.Files +import java.util.Base64 +import javax.imageio.ImageIO + +/** Tests for [[Images]] format detection, auto-resizing, compression, validation, and path parsing. */ +class ImagesSuite extends munit.FunSuite: + private def makeImage(width: Int, height: Int, format: String, withAlpha: Boolean = false): Array[Byte] = + System.setProperty("java.awt.headless", "true") + val imgType = if withAlpha then BufferedImage.TYPE_INT_ARGB else BufferedImage.TYPE_INT_RGB + val img = BufferedImage(width, height, imgType) + val g = img.createGraphics().nn + try + g.setColor(if withAlpha then Color(20, 120, 220, 180) else Color(40, 140, 200)) + g.fillRect(0, 0, width, height) + g.setColor(Color.WHITE) + g.drawLine(0, 0, width - 1, height - 1) + finally g.dispose() + val out = ByteArrayOutputStream() + assert(ImageIO.write(img, format, out), s"failed to encode $format") + out.toByteArray.nn + + /** Minimal valid lossless WebP (VP8L) carrying exact `width` x `height` header fields. */ + private def makeVp8lWebp(width: Int, height: Int): Array[Byte] = + val bits = ((width - 1) & 0x3fff) | (((height - 1) & 0x3fff) << 14) + val out = new Array[Byte](28) + System.arraycopy("RIFF".getBytes, 0, out, 0, 4) + out(4) = 20 // RIFF payload size + System.arraycopy("WEBP".getBytes, 0, out, 8, 4) + System.arraycopy("VP8L".getBytes, 0, out, 12, 4) + out(16) = 8 // chunk size + out(20) = 0x2f // VP8L signature + out(21) = (bits & 0xff).toByte + out(22) = ((bits >>> 8) & 0xff).toByte + out(23) = ((bits >>> 16) & 0xff).toByte + out(24) = ((bits >>> 24) & 0xff).toByte + out + + test("detects supported image formats from magic bytes and rejects non-images"): + assertEquals(Images.detectMediaType(makeImage(4, 4, "png")), Some("image/png")) + assertEquals(Images.detectMediaType(makeImage(4, 4, "jpeg")), Some("image/jpeg")) + assertEquals(Images.detectMediaType(makeImage(4, 4, "gif")), Some("image/gif")) + assertEquals(Images.detectMediaType(makeImage(4, 4, "bmp")), Some("image/bmp")) + assertEquals(Images.detectMediaType(makeVp8lWebp(32, 24)), Some("image/webp")) + assertEquals(Images.detectMediaType(Array[Byte]('I', 'I', 42, 0, 8, 0, 0, 0)), Some("image/tiff")) + assertEquals(Images.detectMediaType("hello world".getBytes), None) + assertEquals(Images.detectMediaType(Array.emptyByteArray), None) + + test("preserves small PNG/JPEG/WebP verbatim and records accurate dimensions and token estimates"): + val png = makeImage(300, 150, "png", withAlpha = true) + val prepared = Images.prepare(png, "ui.png") + assertEquals(prepared.mediaType, "image/png") + assertEquals(prepared.width, 300) + assertEquals(prepared.height, 150) + assertEquals(prepared.byteSize, png.length) + assertEquals(prepared.data, Base64.getEncoder.nn.encodeToString(png)) + assertEquals(prepared.dataUri, s"data:image/png;base64,${prepared.data}") + assertEquals(prepared.placeholder, "[image: ui.png, image/png, 300x150]") + assertEquals(prepared.estimatedTokens, 85L) // (300*150)/750 = 60 -> clamped to 85 + + val webp = makeVp8lWebp(1200, 900) + val prepWebp = Images.prepare(webp, "hero.webp") + assertEquals(prepWebp.mediaType, "image/webp") + assertEquals(prepWebp.width, 1200) + assertEquals(prepWebp.height, 900) + assertEquals(prepWebp.estimatedTokens, 1440L) + + test("auto-resizes oversized images proportionally to MaxDimension and transcodes BMP to PNG"): + val big = makeImage(3136, 1568, "png") + val resized = Images.prepare(big, "wide.png") + assertEquals(resized.mediaType, "image/png") + assertEquals(resized.width, Images.MaxDimension) + assertEquals(resized.height, Images.MaxDimension / 2) + assert(resized.byteSize <= Images.MaxBinaryBytes) + + val bmp = makeImage(64, 48, "bmp") + val transcoded = Images.prepare(bmp, "clip.bmp") + assertEquals(transcoded.mediaType, "image/png") + assertEquals(transcoded.width, 64) + assertEquals(transcoded.height, 48) + + test("rejects decompression-bomb headers before allocating full pixel buffers"): + // Take a valid small PNG and patch IHDR width/height to 100000 x 100000. + val png = makeImage(4, 4, "png").clone() + val buf = ByteBuffer.wrap(png).nn + buf.putInt(16, 100000) + buf.putInt(20, 100000) + val err = intercept[IllegalArgumentException](Images.prepare(png, "bomb.png")) + assert(err.getMessage.nn.contains("maximum pixel limit"), err.getMessage) + + test("fromBase64 accepts raw base64 and data URIs while validating real magic bytes"): + val png = makeImage(16, 16, "png") + val b64 = Base64.getEncoder.nn.encodeToString(png).nn + val raw = Images.fromBase64(b64, "raw.png") + val uri = Images.fromBase64(s"data:image/png;base64,$b64", "uri.png") + assertEquals(raw.data, b64) + assertEquals(uri.data, b64) + assertEquals(uri.width, 16) + + // Spoofed MIME header carrying plain text must be rejected by magic-byte check. + val spoofed = s"data:image/png;base64,${Base64.getEncoder.nn.encodeToString("not an image".getBytes)}" + val err = intercept[IllegalArgumentException](Images.fromBase64(spoofed, "fake.png")) + assert(err.getMessage.nn.contains("Unsupported image format"), err.getMessage) + + test("fromFile validates regular files and parsePastedPaths detects dragged image paths safely"): + val dir = TestEnv.tempDir("atc-images") + val img1 = dir.resolve("my shot.png").nn + val img2 = dir.resolve("second.jpg").nn + val code = dir.resolve("Main.scala").nn + Files.write(img1, makeImage(20, 10, "png")) + Files.write(img2, makeImage(10, 20, "jpeg")) + Files.writeString(code, "object Main") + + val loaded = Images.fromFile(img1) + assertEquals(loaded.label, "my shot.png") + assertEquals(loaded.width, 20) + assertEquals(loaded.height, 10) + + intercept[IllegalArgumentException](Images.fromFile(dir)) + + // Single quoted path, file:// URI, and multi-file drag-and-drop all resolve cleanly. + assertEquals(Images.parsePastedPaths(s"'${img1.toString}' ", dir), Some(List(img1.toAbsolutePath.nn.normalize.nn))) + assertEquals(Images.parsePastedPaths(img1.toUri.toString, dir), Some(List(img1.toAbsolutePath.nn.normalize.nn))) + assertEquals( + Images.parsePastedPaths(s"'${img1.toString}' '${img2.toString}'", dir), + Some(List(img1.toAbsolutePath.nn.normalize.nn, img2.toAbsolutePath.nn.normalize.nn)), + ) + // Non-image files, missing files, and normal prose are never mistaken for image drops. + assertEquals(Images.parsePastedPaths(code.toString, dir), None) + assertEquals(Images.parsePastedPaths(s"'${img1.toString}' '${code.toString}'", dir), None) + assertEquals(Images.parsePastedPaths("please check my shot.png for bugs", dir), None) + assertEquals(Images.parsePastedPaths(dir.resolve("missing.png").toString, dir), None) + + test("EchoModel includes user and tool-result image placeholders in replies"): + val img = Images.prepare(makeImage(8, 8, "png"), "icon.png") + val echo = EchoModel("echo") + val userReply = echo.complete("sys", List(Msg.User("check", List(img))), Nil, StreamSink(_ => ()), () => false) + assertEquals(userReply.text, "echo: check ([image: icon.png, image/png, 8x8])") + val imageOnly = echo.complete("sys", List(Msg.User("", List(img))), Nil, StreamSink(_ => ()), () => false) + assertEquals(imageOnly.text, "echo: [image: icon.png, image/png, 8x8]") + val toolReply = echo.complete( + "sys", + List(Msg.ToolResults(List(ToolResult("c1", "ok", isError = false, images = List(img))))), + Nil, + StreamSink(_ => ()), + () => false, + ) + assert(toolReply.text.contains("[image: icon.png, image/png, 8x8]"), toolReply.text) diff --git a/app/test/src/atc/llm/ProviderRequestSuite.scala b/app/test/src/atc/llm/ProviderRequestSuite.scala index 8da0b668..4967c09b 100644 --- a/app/test/src/atc/llm/ProviderRequestSuite.scala +++ b/app/test/src/atc/llm/ProviderRequestSuite.scala @@ -513,3 +513,89 @@ class ProviderRequestSuite extends munit.FunSuite: assertEquals(merged("content").str, "searching...\n\ncalling tool") assertEquals(merged("tool_calls").arr.size, 1) finally model.close() + + test("Anthropic, OpenAI Responses, and OpenAI Chat serialize user and tool-result images"): + val sample = ImageInput("image/png", "iVBORw0KGgo=", label = "ui.png", width = 10, height = 10, byteSize = 8) + val history = List( + Msg.User("describe this", List(sample)), + Msg.Assistant("", List(ToolCall("c1", "run_scala", """{"code":"viewImage(\"ui.png\")"}""")), None), + Msg.ToolResults(List(ToolResult("c1", "attached", isError = false, images = List(sample)))), + ) + + val anthropicReply = ujson.write(ujson.Obj( + "id" -> "m1", + "type" -> "message", + "role" -> "assistant", + "model" -> "m", + "content" -> ujson.Arr(ujson.Obj("type" -> "text", "text" -> "ok")), + "stop_reason" -> "end_turn", + "stop_sequence" -> ujson.Null, + "usage" -> ujson.Obj("input_tokens" -> 5, "output_tokens" -> 2), + )) + val anthropicStream = List( + s"event: message_start\ndata: {\"type\":\"message_start\",\"message\":$anthropicReply}\n\n", + "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n", + ).mkString + withServer(_ => (200, "text/event-stream", anthropicStream)): (url, requests) => + val model = ChatModel.create(endpoint("anthropic", url).copy(alias = "m", modelId = "m")) + try + model.complete("sys", history, someTool, StreamSink(_ => ()), () => false) + val msgs = requests().last.json("messages").arr + val userBlocks = msgs(0)("content").arr + assertEquals(userBlocks.map(_("type").str).toList, List("image", "text")) + assertEquals(userBlocks(0)("source")("media_type").str, "image/png") + assertEquals(userBlocks(0)("source")("data").str, "iVBORw0KGgo=") + val toolResultContent = msgs(2)("content")(0)("content").arr + assertEquals(toolResultContent.map(_("type").str).toList, List("text", "image")) + assertEquals(toolResultContent(1)("source")("data").str, "iVBORw0KGgo=") + finally model.close() + + val responsesReply = ujson.write(ujson.Obj( + "id" -> "r1", + "object" -> "response", + "created_at" -> 1, + "status" -> "completed", + "model" -> "m", + "output" -> ujson.Arr(ujson.Obj( + "id" -> "msg1", + "type" -> "message", + "role" -> "assistant", + "status" -> "completed", + "content" -> ujson.Arr(ujson.Obj("type" -> "output_text", "text" -> "ok", "annotations" -> ujson.Arr())), + )), + "usage" -> ujson.Obj( + "input_tokens" -> 10, + "output_tokens" -> 2, + "total_tokens" -> 12, + "input_tokens_details" -> ujson.Obj("cached_tokens" -> 0), + "output_tokens_details" -> ujson.Obj("reasoning_tokens" -> 0), + ), + )) + val responsesStream = + s"event: response.completed\ndata: {\"type\":\"response.completed\",\"sequence_number\":0,\"response\":$responsesReply}\n\n" + withServer(_ => (200, "text/event-stream", responsesStream)): (url, requests) => + val model = ChatModel.create(endpoint("openai-responses", url).copy(alias = "m", modelId = "m")) + try + model.complete("sys", history, someTool, StreamSink(_ => ()), () => false) + val input = requests().last.json("input").arr + val userParts = input(0)("content").arr + assertEquals(userParts.map(_("type").str).toList, List("input_text", "input_image")) + assertEquals(userParts(1)("image_url").str, sample.dataUri) + val toolOut = input(2)("output").arr + assertEquals(toolOut.map(_("type").str).toList, List("input_text", "input_image")) + assertEquals(toolOut(1)("image_url").str, sample.dataUri) + finally model.close() + + withServer(_ => (200, "text/event-stream", streamedDone)): (url, requests) => + val model = ChatModel.create(endpoint("openai", url).copy(alias = "m", modelId = "m")) + try + model.complete("sys", history, someTool, StreamSink(_ => ()), () => false) + val msgs = requests().last.json("messages").arr + assertEquals(msgs.map(_("role").str).toList, List("system", "user", "assistant", "tool", "user")) + val userParts = msgs(1)("content").arr + assertEquals(userParts.map(_("type").str).toList, List("text", "image_url")) + assertEquals(userParts(1)("image_url")("url").str, sample.dataUri) + val toolImgParts = msgs(4)("content").arr + assertEquals(toolImgParts.map(_("type").str).toList, List("text", "image_url")) + assertEquals(toolImgParts(1)("image_url")("url").str, sample.dataUri) + finally model.close() diff --git a/app/test/src/atc/sandbox/CapabilitySuite.scala b/app/test/src/atc/sandbox/CapabilitySuite.scala index 9016d3fb..3f471b90 100644 --- a/app/test/src/atc/sandbox/CapabilitySuite.scala +++ b/app/test/src/atc/sandbox/CapabilitySuite.scala @@ -525,3 +525,12 @@ class CapabilitySuite extends munit.FunSuite, ReplAssertions: s"""requestMemory("global/cap") { addMonitor("scoped-mem", $later) { () => send => { recall("global/cap/a"); () } } }""" )) finally env.host.stopMonitors() + + test("viewImage requires full UserIO^ and cannot run inside Classified.map"): + // Read-only FileSystem view suffices for viewImage(path), so it works in read-only mode too. + assertOk(run("""def checkView(using fs: FileSystem, u: UserIO^): Unit = viewImage("x.png")""")) + // Both overloads require full UserIO^: read-only UserIO and Classified.map are rejected statically. + assertFails(run("""val ru: UserIO^{user.rd} = user; viewImage("x.png")(using fs, ru)"""), "read-only") + assertFails(run("""val ru: UserIO^{user.rd} = user; viewImage(Array[Byte](1), "x")(using ru)"""), "read-only") + assertFails(run("""classify("x.png").map(p => { viewImage(p); p })""")) + assertFails(run("""classify("x").map(s => { viewImage(s.getBytes, "leak"); s })""")) diff --git a/app/test/src/atc/sandbox/ReplSessionSuite.scala b/app/test/src/atc/sandbox/ReplSessionSuite.scala index b8253e54..ce6f4984 100644 --- a/app/test/src/atc/sandbox/ReplSessionSuite.scala +++ b/app/test/src/atc/sandbox/ReplSessionSuite.scala @@ -528,3 +528,25 @@ class ReplSessionSuite extends munit.FunSuite, ReplAssertions: assertEquals(clock.paused, closed) clock.reset() assertEquals(clock.paused, 0L) + + test("viewImage in REPL attaches images to ExecutionResult and resets between runs"): + System.setProperty("java.awt.headless", "true") + val imgBuf = java.awt.image.BufferedImage(16, 12, java.awt.image.BufferedImage.TYPE_INT_RGB) + val baos = java.io.ByteArrayOutputStream() + javax.imageio.ImageIO.write(imgBuf, "png", baos) + val pngBytes = baos.toByteArray.nn + val imgEnv = TestEnv() + java.nio.file.Files.write(imgEnv.root.resolve("diagram.png"), pngBytes) + val repl = ReplSession(SandboxConfig(mode = atc.perms.Mode.ReadOnly), imgEnv.host).init() + try + val res = assertOk(repl.run("""viewImage("diagram.png")""")) + assertEquals(res.images.size, 1) + assertEquals(res.images.head.label, "diagram.png") + assertEquals(res.images.head.width, 16) + assertEquals(res.images.head.height, 12) + assert(imgEnv.agentOut.toString.contains("[attached image:"), imgEnv.agentOut.toString) + + // Next evaluation starts with no stale images. + val next = assertOk(repl.run("1 + 1")) + assertEquals(next.images, Nil) + finally repl.close() diff --git a/app/test/src/atc/ui/PromptReaderSuite.scala b/app/test/src/atc/ui/PromptReaderSuite.scala index aaab0152..a515966c 100644 --- a/app/test/src/atc/ui/PromptReaderSuite.scala +++ b/app/test/src/atc/ui/PromptReaderSuite.scala @@ -277,3 +277,56 @@ class PromptReaderSuite extends munit.FunSuite: val untrusted = List("/evil" -> "desc \u001b]52;c;aGk=\u0007\u202ehidden\nnext") val sanitized = PromptReader.renderCommands(untrusted, 0, ">", 80, 5).toString assert(!sanitized.contains("\u001b]52") && !sanitized.contains("\u202e") && !sanitized.contains("\n"), sanitized) + + test("Ctrl-V pastes an inline image chip, Backspace deletes it whole, and dragged image paths auto-attach"): + val img1 = atc.llm.ImageInput("image/png", "AAAA", label = "clip.png", width = 640, height = 480, byteSize = 3) + val img2 = atc.llm.ImageInput("image/png", "BBBB", label = "drop.png", width = 320, height = 240, byteSize = 3) + + // 1. Ctrl-V inserts an inline placeholder chip and extracts the image on submit. + val (p1, t1, _) = promptOn("check \u0016 please\r") + p1.onPasteImage = () => Right(img1) + try + val line = p1.read("> ", "") + val (text, images) = p1.extractPastedImages(line) + assertEquals(text, "check [Image #1: clip.png 640x480] please") + assertEquals(images, List(img1)) + finally t1.close() + + // 2. Image-only Ctrl-V submission yields empty text + the attached image. + val (p2, t2, _) = promptOn("\u0016\r") + p2.onPasteImage = () => Right(img1) + try + val line = p2.read("> ", "") + val (text, images) = p2.extractPastedImages(line) + assertEquals(text, "") + assertEquals(images, List(img1)) + finally t2.close() + + // 3. Backspace immediately after an image chip removes the whole chip and drops the attachment. + val (p3, t3, _) = promptOn("hi \u0016\u007fthere\r") + p3.onPasteImage = () => Right(img1) + try + val line = p3.read("> ", "") + val (text, images) = p3.extractPastedImages(line) + assertEquals(text, "hi there") + assertEquals(images, Nil) + finally t3.close() + + // 4. Dragged/pasted image file path becomes an image chip; pasting after `/image ` stays literal. + val (p4, t4, _) = promptOn(s"look at ${paste("/tmp/drop.png")}\r") + p4.onPastedPaths = chunk => Option.when(chunk.trim == "/tmp/drop.png")(Right(List(img2))) + try + val line = p4.read("> ", "") + val (text, images) = p4.extractPastedImages(line) + assertEquals(text, "look at [Image #1: drop.png 320x240]") + assertEquals(images, List(img2)) + finally t4.close() + + val (p5, t5, _) = promptOn(s"/image ${paste("/tmp/drop.png")}\r") + p5.onPastedPaths = chunk => Option.when(chunk.trim == "/tmp/drop.png")(Right(List(img2))) + try + val line = p5.read("> ", "") + val (text, images) = p5.extractPastedImages(line) + assertEquals(text, "/image /tmp/drop.png") + assertEquals(images, Nil) + finally t5.close() diff --git a/atc b/atc index 7e664dbe..90af86e3 100755 --- a/atc +++ b/atc @@ -477,7 +477,7 @@ should_check_update() { while [[ $# -gt 0 ]]; do case "$1" in -p|--prompt|--prompt=*|--ide|-h|--help|-v|--version|--init|--init-global) return 1 ;; - -c|--config|-C|--cwd|-m|--model|--mode|--output) + -c|--config|-C|--cwd|-m|--model|-i|--image|--mode|--output) [[ $# -ge 2 ]] || return 1 shift ;; @@ -908,7 +908,7 @@ extract_jvm_options() { RUN_ARGS=() while [[ $# -gt 0 ]]; do case "$1" in - -c|--config|-C|--cwd|-m|--model|-p|--prompt|--mode|--output) + -c|--config|-C|--cwd|-m|--model|-p|--prompt|-i|--image|--mode|--output) RUN_ARGS+=("$1"); shift [[ $# -eq 0 ]] || { RUN_ARGS+=("$1"); shift; } ;; -Xmx*|-Xms*) diff --git a/atc.ps1 b/atc.ps1 index 90dbbd67..3dd9ef72 100644 --- a/atc.ps1 +++ b/atc.ps1 @@ -215,7 +215,7 @@ function Test-StartupCheck([string[]]$Arguments) { for ($i = 0; $i -lt $Arguments.Count; $i++) { $arg = $Arguments[$i] if ($arg -cin '-p', '--prompt', '--ide', '-h', '--help', '-v', '--version', '--init', '--init-global' -or $arg.StartsWith('--prompt=')) { return $false } - if ($arg -cin '-c', '--config', '-C', '--cwd', '-m', '--model', '--mode', '--output') { + if ($arg -cin '-c', '--config', '-C', '--cwd', '-m', '--model', '-i', '--image', '--mode', '--output') { if ($i + 1 -ge $Arguments.Count) { return $false } $i++ } @@ -350,7 +350,7 @@ function Split-HeapOptions([string[]]$Arguments) { if ($expectValue) { $expectValue = $false $atc.Add($arg) - } elseif ($arg -cin '-c', '--config', '-C', '--cwd', '-m', '--model', '-p', '--prompt', '--mode', '--output') { + } elseif ($arg -cin '-c', '--config', '-C', '--cwd', '-m', '--model', '-p', '--prompt', '-i', '--image', '--mode', '--output') { $expectValue = $true $atc.Add($arg) } elseif ($arg -cmatch '^-Xm[sx]') { diff --git a/doc/development.md b/doc/development.md index 60e1f375..8b6fec36 100644 --- a/doc/development.md +++ b/doc/development.md @@ -1213,11 +1213,35 @@ one-shot `simple` operations. Provider adapters normalize stop reasons into `Com `model_context_window_exceeded` (Anthropic, Claude Code) counts as truncation, as an output limit does, so the calls of a response cut by the context window are not run. -`Msg` carries neutral text and tool calls. Assistant messages may also carry a `NativeTurn` +`Msg` carries neutral text, tool calls, and optional `ImageInput` attachments (on `Msg.User` +and `ToolResult`). Assistant messages may also carry a `NativeTurn` for replay to the exact provider/model reference that produced it. Switching models uses neutral fields and excludes model-bound reasoning data. `TokenUsage.input` includes cache reads and writes; adapters normalize provider-specific accounting. +`Images` validates image inputs from magic bytes (PNG, JPEG, GIF, WebP, BMP, TIFF) rather +than trusting file extensions or declared MIME types, checks pixel dimensions before decoding +(guarding against decompression bombs above 64 megapixels), downscales long edges above +`1568` px, transcodes BMP/TIFF to PNG, and compresses payloads below `3.75 MB` raw (`<= 5 MB` +base64). At most `10` images may be attached per user message or tool evaluation. All seven +providers (`anthropic`, `openai-responses`, `chatgpt`, `openai`, `claude-code`, +`antigravity`, and `echo`) carry user and tool-result images: `AnthropicModel` uses +`ImageBlockParam` / `ToolResultBlockParam` content blocks, `OpenAIResponsesModel` (and +`ChatGPTModel`) uses `ResponseInputImage` / `ResponseFunctionCallOutputItem`, `OpenAIChatModel` +sends `ChatCompletionContentPartImage` parts and follows tool batches containing images with a +user message (coalescing with an immediately following user-role message), and both CLI +adapters carry base64 image blocks in prompts (`stream-json` / ACP `session/prompt`) and MCP +`tools/call` results. `ContextManager` estimates image tokens from dimensions (`(w * h) / 750`, +clamped to `[85, 1600]`), and `SessionStore.messageJson` strips binary image data to compact +`[image: ...]` metadata placeholders for both saved sessions and compaction transcripts. + +In the sandbox, `FilesApi.viewImage` provides two overloads (`viewImage(path)(using FileSystem, UserIO^)` +and `viewImage(bytes, label)(using UserIO^)`) that attach prepared images to the active +evaluation's `ExecutionResult` and `ToolResult`. Requiring full `UserIO^` keeps both overloads +out of `Classified.map` at compile time, while runtime host checks enforce `FileSystem` read +access, reject classified paths, reject calls inside classified threads or background monitors, +and clear the per-evaluation image collector in `finally`. + Anthropic requests set two cache breakpoints: the system prompt and the last user-role message (user text, a continuation or tool results), so each round reads the previous round's prefix from the cache. Responses requests use stateless replay with encrypted @@ -1693,6 +1717,16 @@ against the expanded text rather than the placeholder. Code blocks and masked se prompts display pasted text directly. `PastedTextSuite` tests placeholder handling and `PromptReaderSuite` tests prompt integration. +`PastedImages` uses the same inline chip model (`[Image #1: shot.png 1280x720]`) for terminal +image input: `Ctrl-V` (and `Alt-V`) reads clipboard images via `Clipboard` (`osascript` on +macOS, `wl-paste`/`xclip` on Linux, and `powershell.exe -STA` on Windows, avoiding AWT +initialization and macOS Dock icons), and bracketed paste in `PromptReader.beginPaste` +auto-detects dragged or pasted local image paths (`Images.parsePastedPaths`, skipped inside +slash commands). Backspace removes an image chip atomically and drops its attachment. +`/image` (alias `/attach`, implemented by `ImageCommands`) manages staged images for the next +turn, and `-i`/`--image` attaches images from the CLI; all local file entry points guard paths +marked `classified` by policy before reading. + During a turn, Enter submits a steering message while unsent text previews in the status line. Bracketed pastes preserve newlines without submitting individual lines, and the footer refreshes when the paste finishes or pauses rather than on every byte. The footer @@ -1894,8 +1928,8 @@ Extend the suite responsible for the behavior: configuration files, layers and project trust, key bindings, `/providers` edits, and auto-loaded conventions. - `llm/`: `ModelSuite`, `ModelRequestSuite`, `ProviderRequestSuite`, `ProviderCancellationSuite`, - `ChatGPTSuite`, `ClaudeCodeSuite`, `AntigravitySuite`, `LlmJsonSuite`: the model catalog, - provider requests and cancellation, SDK JSON conversion, and each provider's adapter. + `ChatGPTSuite`, `ClaudeCodeSuite`, `AntigravitySuite`, `LlmJsonSuite`, `ImagesSuite`: the model catalog, + provider requests and cancellation, SDK JSON conversion, image processing, and each provider's adapter. - `agent/`: `AgentCoreLoopSuite`, `AgentLoopSuite`, `AgentSuite`, `CompletionPolicySuite`, `ContextManagerSuite`, `AgentMessagesSuite`, `ToolOutputSuite`, `PromptsSuite`, `InputPredictorSuite`, `SessionStoreSuite`: loop decisions, transcript repair, context fitting @@ -2001,10 +2035,17 @@ Scala formatting, verifies that `vscode/package.json` matches `Versions.atc`, an `.vsix` artifact (`atc-vscode-vsix`) for non-release builds; Unix jobs run the Bash wrapper tests, and the Windows job runs the PowerShell wrapper tests under Windows PowerShell and PowerShell 7. Published release tags must match `Versions.atc` and `vscode/package.json` (with an optional `v` -prefix). After the platform jobs succeed, `build-release` builds the two JARs and the `.vsix` -package with read-only access, and `publish-release`, the only job with write access, uploads all -three without running project code. A release is public before its JARs are attached; both -wrappers then say to try again. +prefix). After the platform jobs succeed, `build-release-jars` and `build-release-vsix` build the +two JARs and the `.vsix` package in separate cache-free jobs with read-only access. `publish-release`, +the only job with `contents: write`, uploads all three assets to the GitHub release without running +project code. Once `publish-release` succeeds, `publish-vscode-marketplace` (scoped to the +`vscode-marketplace` GitHub environment with `id-token: write` only, and running no project code) +publishes the exact packaged `.vsix` to the Visual Studio Marketplace via OIDC Trusted Publishing +(`vsce publish --oidc --skip-duplicate --packagePath ...`, adding `--pre-release` for pre-releases). +The workflow also supports manual `workflow_dispatch` with a release `tag` (and optional +`pre_release` flag) to build the tagged `.vsix` and publish it to the Marketplace without re-running +the full release pipeline. A release is public before its JARs are attached; both wrappers then say +to try again. ## IDE protocol and VS Code extension diff --git a/lib/src/atc/lib/Files.scala b/lib/src/atc/lib/Files.scala index f3af0522..ec804c01 100644 --- a/lib/src/atc/lib/Files.scala +++ b/lib/src/atc/lib/Files.scala @@ -98,6 +98,18 @@ trait FilesApi: def readBytes(path: String)(using FileSystem): Array[Byte] // @end + // @api viewImage + // @short Attach an image file (or raw image bytes with a label) to this tool result so you can inspect it visually. + // @full Attach an image (PNG, JPEG, GIF, WebP, BMP, or TIFF) to this `run_scala` tool result so + // you can inspect it visually on the next model turn. Large images are automatically resized + // and compressed. The path overload requires read access and refuses classified files; both + // overloads require `UserIO^` (so neither can run inside `Classified.map` or a monitor). + // At most 10 images may be attached per tool call. + // @show + def viewImage(path: String)(using FileSystem, UserIO^): Unit + def viewImage(bytes: Array[Byte], label: String)(using UserIO^): Unit + // @end + // @api exists // @show def exists(path: String)(using FileSystem): Boolean diff --git a/vscode/CHANGELOG.md b/vscode/CHANGELOG.md new file mode 100644 index 00000000..c940ce4b --- /dev/null +++ b/vscode/CHANGELOG.md @@ -0,0 +1,11 @@ +# Changelog + +All notable changes to the **ATC — Agent with Tracked Capabilities** VS Code extension are documented here. + +## [0.2.4] + +- Initial Visual Studio Marketplace release. +- Sidebar chat view driving a persistent `atc --ide` Scala 3 REPL session with capture-checked capabilities, classified data isolation, and inline interactive permission approvals. +- First-use onboarding and tabbed configuration sheet for managing LLM providers, models, reasoning effort, and `/config` settings. +- Vision and image input support: paste from clipboard, drag-and-drop image files, `+ → Attach image…` picker with classified-path guard, and inline thumbnails for user prompts and `viewImage` tool results. +- Native editor context menu actions, QuickPick commands (`/skills`, `/perms`, `/bg`, `/resume`, `/mode`, `/model`, `/effort`, `/classifiedmodel`), status bar integration, and JSON schema validation for `.atc/config.json`. diff --git a/vscode/README.md b/vscode/README.md index 549c14b3..5ea3914f 100644 --- a/vscode/README.md +++ b/vscode/README.md @@ -1,77 +1,71 @@ # ATC for Visual Studio Code -VS Code extension for [ATC (Agent with Tracked Capabilities)](../README.md). Runs a persistent `atc --ide` session with an in-process Scala 3 REPL, capture-checked capabilities, classified data isolation, and scoped interactive permission approvals directly inside VS Code. +VS Code extension for [ATC (Agent with Tracked Capabilities)](https://lampepfl.github.io/atc/). -## Features +ATC is a coding agent that operates through an in-process Scala 3 REPL and a capability-typed API for files, commands, HTTP requests, and user interaction. Every snippet is type-checked and compiled before execution: capture checking restricts which capabilities code can retain, `Classified` values stay isolated from unauthorized channels, and runtime access is deny-by-default unless granted by policy or approved in a scoped permission prompt. -- **Sidebar Chat View (`ATC` in the Activity Bar):** - - Space-efficient vertical step timeline with full-width user prompt cards, collapsible single-line `Thought for Ns` reasoning steps, streaming Markdown with authentic Scala 3 syntax highlighting, neutral inline code chips, and clickable workspace file links (`path/to/file.scala:42`). - - Collapsible **Run** execution steps (folded by default after completion, `Ctrl+O` to expand all) with full-width syntax-highlighted Scala source (**Run** / **Copy**), named `texts` payloads, live `println` and command output (**Copy** + distinct **🔒 Classified** strip), and inline colored file diffs. - - Click any modified file in a tool diff to open it at the exact changed line, or click **Diff** to open VS Code's side-by-side Git diff. - - Inline interactive approval cards for `requestFiles` / `requestExec` / `requestNetwork` (**Allow Once**, **Allow Session**, **Always Allow** to `.atc/config.json`, **Deny**, or **Revise…**), `ask(...)` user prompts, `createSkill` unified diff approvals, tool-call budget continuation, and untrusted project config confirmations. - - **First-Use Onboarding:** Guides brand-new users seamlessly inside the sidebar — detects missing `atc` binaries (with file browser & install command), walks through connecting any built-in provider (Anthropic, OpenAI, ChatGPT browser OAuth, Claude Code, Gemini, Antigravity, DeepSeek, OpenRouter, OpenCode Go) or custom OpenAI/Anthropic-compatible server (Ollama, LM Studio, vLLM), validates credentials & fetches live models, picks a starter model + reasoning effort, and optionally initializes `.atc/config.json`. - - **Floating Bottom Composer Dock:** Zero redundant topbar; inline italic ghost predictions (`Tab` to accept), `+` quick-actions menu (`@` attach/files, `/` commands, `Ctrl+O` expanded view, `/cost`, `/perms`), inline searchable **Model** picker & **Reasoning Effort** popover (with `Session` / `Project` / `Global` persistence), circular **Context %** ring, **Mode** selector (`Shift+Tab`), `⚙` **Configuration** sheet, and smart **Send (`↑`) / Stop (`■`)** button. - - **Ephemeral Live Tray:** Surfaces active **Tasks** (`◐ 1/3 · current step`), **Background** processes & monitors (`● 1p · 1m` with floating **Kill** / **Stop** sheet), session grants, and queued steers only when active. - - **Tabbed Configuration Sheet (`⚙` — `General` · `Providers` · `Models`):** Manage providers (add presets or custom servers, update API keys stored owner-only in `~/.atc/keys.properties`, sign in with ChatGPT OAuth, toggle providers, shortlist discovered models, add/edit custom models with per-model default effort, context window, and web search), switch & persist default models and effort, adjust live `/config` settings across `Session`/`Project`/`Global` scopes, or open `config.json`. - - Hover tooltips explaining all composer, code-block, background, approval, and configuration controls, plus one-click **Resume last session** on startup and folded `Usage & Context` rail disclosures. -- **Native Editor & Workbench Integration:** - - Status bar item showing sandbox mode (`read-only`, `local`, `full`), active model, context window usage, and live background processes/monitors. - - Editor context menu commands: **Send Selection to Chat**, **Explain Selection**, **Fix Diagnostics in File**, and **Run Selection in ATC Scala REPL** (for Scala selections). - - QuickPick commands for switching sandbox mode, model, reasoning effort, classified model (`/classifiedmodel`), session/project settings (`/config`), resuming saved sessions, revoking session grants, managing background processes/monitors, initializing `.atc/config.json`, and launching ATC in an integrated terminal. -- **JSON Schema Validation:** IntelliSense and validation for `.atc/config.json` (catching unknown keys and invalid values as you edit). +This extension runs a persistent `atc --ide` session directly inside VS Code with a sidebar chat view, inline file diffs, interactive permission approval cards, image attachments, and editor commands. -## Prerequisites +## Quick Start -- JDK 17+ and ATC installed (`atc` on `PATH` or `~/.local/bin/atc`), or a local ATC source checkout built with `./mill dist`. -- Node.js 22+ to build and package the extension from source. +### 1. Install ATC -## Installing from GitHub Releases +JDK 17 or newer is required. -Every GitHub release attaches a pre-built `atc-vscode-.vsix` alongside `atc.jar` and `atc-lib.jar`: +**macOS and Linux:** ```bash -code --install-extension atc-vscode-.vsix +curl -fsSL https://raw.githubusercontent.com/lampepfl/atc/refs/heads/main/atc -o atc +chmod +x atc +./atc setup ``` -Or open the Command Palette in VS Code (`Cmd+Shift+P` / `Ctrl+Shift+P`), run **Extensions: Install from VSIX…**, and select the downloaded `.vsix` file. +This installs `atc` to `~/.local/bin/atc`, adds it to your `PATH`, and downloads the latest verified release JARs. -## Building & Testing +**Windows (PowerShell):** -```bash -cd vscode -npm install -npm run typecheck -npm run build -npm test +```powershell +irm https://raw.githubusercontent.com/lampepfl/atc/refs/heads/main/atc.ps1 -OutFile atc.ps1 +powershell -ExecutionPolicy Bypass -File .\atc.ps1 setup ``` -`npm test` runs both unit tests and a live end-to-end integration test against `../out/dist.dest/atc.jar --ide` (when built via `./mill dist` at the repo root). - -## Running in VS Code (Development) +This installs `atc` to `%USERPROFILE%\.atc\bin` and adds it to your user `Path`. -1. From the repository root, build the ATC distribution JARs (if not already installed on `PATH`): - ```bash - ./mill dist - ``` -2. Open the `vscode/` folder in VS Code and press **F5** (Run Extension). -3. In the Extension Development Host window, open any project folder and click the **ATC** tower icon in the Activity Bar (or press `Cmd+Alt+A` / `Ctrl+Alt+A`). +### 2. Open ATC in VS Code -## Packaging & Installing Locally (`.vsix`) - -```bash -cd vscode -npm run package -code --install-extension atc-vscode-*.vsix -``` +1. Open a trusted project folder in VS Code. +2. Click the **ATC** tower icon in the Activity Bar (or press `Cmd+Alt+A` on macOS / `Ctrl+Alt+A` on Windows and Linux). +3. On first launch, follow the built-in onboarding in the sidebar to connect an LLM provider (or sign in via ChatGPT OAuth, Claude Code, or Antigravity) and optionally generate a starter `.atc/config.json`. ## Settings | Setting | Default | Description | |---|---|---| -| `atc.executablePath` | `""` | Path to `atc`, `start.sh` / `start.ps1`, or `atc.jar`. Auto-detects checkout `start.sh`, `atc` on `PATH`, `~/.local/bin/atc`, or `~/.atc/jars/atc.jar` when empty. | +| `atc.executablePath` | `""` | Path to `atc`, `start.sh` / `start.ps1`, or `atc.jar`. Auto-detects `atc` on `PATH` or `~/.local/bin/atc` (`~/.atc/bin` on Windows) when empty. | | `atc.model` | `""` | Initial model override (`-m `). | | `atc.mode` | `""` | Initial sandbox mode override (`readonly`, `local`, `full`). | | `atc.configPath` | `""` | Extra config file merged over `~/.atc/config.json` and `.atc/config.json` (`-c`). | | `atc.jvmMaxHeap` | `""` | JVM max heap size passed to the launcher (e.g. `4g`). | | `atc.extraArgs` | `[]` | Extra CLI arguments passed to ATC. | | `atc.autoStart` | `true` | Automatically start `atc --ide` when the ATC Chat view is opened. | + +## Building, Packaging & Installing + +Requires Node.js 22+ (and `./mill dist` at the repository root if running the live integration test). + +```bash +cd vscode +npm install +npm run typecheck +npm run build +npm test +npm run package # creates atc-vscode-.vsix +code --install-extension atc-vscode-*.vsix +``` + +You can also install a pre-built `.vsix` attached to any [GitHub release](https://github.com/lampepfl/atc/releases) via `code --install-extension atc-vscode-.vsix` or **Extensions: Install from VSIX…** in the Command Palette. + +## Documentation & Source + +- Documentation: [lampepfl.github.io/atc](https://lampepfl.github.io/atc/) +- Source & issues: [github.com/lampepfl/atc](https://github.com/lampepfl/atc) diff --git a/vscode/media/atc-icon.png b/vscode/media/atc-icon.png new file mode 100644 index 00000000..4ad7b8b8 Binary files /dev/null and b/vscode/media/atc-icon.png differ diff --git a/vscode/package.json b/vscode/package.json index 9806020c..5e77cc74 100644 --- a/vscode/package.json +++ b/vscode/package.json @@ -3,19 +3,28 @@ "displayName": "ATC — Agent with Tracked Capabilities", "description": "VS Code extension for ATC: interactive Scala 3 REPL coding agent with capability tracking, confidential data isolation, and scoped permission approvals.", "version": "0.2.4", - "publisher": "lampepfl", + "publisher": "noti0na1", "license": "Apache-2.0", + "icon": "media/atc-icon.png", + "galleryBanner": { + "color": "#0f172a", + "theme": "dark" + }, + "homepage": "https://lampepfl.github.io/atc/", "repository": { "type": "git", "url": "https://github.com/lampepfl/atc" }, + "bugs": { + "url": "https://github.com/lampepfl/atc/issues" + }, "engines": { "vscode": "^1.85.0" }, "categories": [ "AI", - "Programming Languages", - "Other" + "Chat", + "Programming Languages" ], "keywords": [ "atc", diff --git a/vscode/src/chatViewProvider.ts b/vscode/src/chatViewProvider.ts index 82ecbdf8..0de9caec 100644 --- a/vscode/src/chatViewProvider.ts +++ b/vscode/src/chatViewProvider.ts @@ -1,4 +1,5 @@ import * as crypto from 'node:crypto'; +import * as fs from 'node:fs/promises'; import * as path from 'node:path'; import * as vscode from 'vscode'; import { AtcClient } from './atcClient'; @@ -15,6 +16,7 @@ import { ConnectionStatus, ContinueRequestEvent, HostToWebviewMessage, + ImageAttachmentInput, PermissionRequestEvent, SavedSessionSummary, ServerEvent, @@ -356,6 +358,16 @@ export class AtcChatViewProvider implements vscode.WebviewViewProvider, vscode.D await this.attachActiveEditorContext(); break; } + case 'pick_images': { + await this.pickAndAttachImages(); + break; + } + case 'attach_image_uris': { + if (Array.isArray(msg.uris)) { + await this.attachImageUris(msg.uris); + } + break; + } case 'run_vscode_command': { if (isAllowedWebviewCommand(msg.command)) { await vscode.commands.executeCommand(msg.command); @@ -534,6 +546,97 @@ export class AtcChatViewProvider implements vscode.WebviewViewProvider, vscode.D } } + private async pickAndAttachImages(): Promise { + const root = this.starter.getWorkspaceRoot(); + const defaultUri = root ? vscode.Uri.file(root) : undefined; + const picked = await vscode.window.showOpenDialog({ + canSelectMany: true, + openLabel: 'Attach Image', + defaultUri, + filters: { + Images: ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'tif', 'tiff'], + }, + }); + if (!picked || picked.length === 0) { + return; + } + await this.loadAndPostImages(picked); + } + + private async attachImageUris(rawUris: string[]): Promise { + const uris: vscode.Uri[] = []; + for (const raw of rawUris.slice(0, 10)) { + if (typeof raw !== 'string' || !raw.trim()) { + continue; + } + try { + const uri = vscode.Uri.parse(raw.trim()); + if (uri.scheme === 'file') { + uris.push(uri); + } + } catch { + // Ignore malformed drop URIs. + } + } + if (uris.length > 0) { + await this.loadAndPostImages(uris); + } + } + + private async loadAndPostImages(uris: vscode.Uri[]): Promise { + const MAX_RAW_BYTES = 25 * 1024 * 1024; + const EXT_MIME: Record = { + '.png': 'image/png', + '.jpg': 'image/jpeg', + '.jpeg': 'image/jpeg', + '.gif': 'image/gif', + '.webp': 'image/webp', + '.bmp': 'image/bmp', + '.tif': 'image/tiff', + '.tiff': 'image/tiff', + }; + const root = this.starter.getWorkspaceRoot(); + const attached: ImageAttachmentInput[] = []; + for (const uri of uris.slice(0, 10)) { + const ext = path.extname(uri.fsPath).toLowerCase(); + const mediaType = EXT_MIME[ext]; + if (!mediaType) { + continue; + } + const allowed = await confirmEditorContentAccess(this.client, root, uri, 'Attach Image'); + if (!allowed) { + continue; + } + try { + const st = await fs.stat(uri.fsPath); + if (!st.isFile()) { + continue; + } + if (st.size > MAX_RAW_BYTES) { + void vscode.window.showWarningMessage( + `Skipped "${sanitizeUiText(path.basename(uri.fsPath), 80)}": image exceeds the 25 MB limit.` + ); + continue; + } + const buf = await fs.readFile(uri.fsPath); + const rel = root ? path.relative(root, uri.fsPath).replace(/\\/g, '/') : path.basename(uri.fsPath); + const label = rel && !rel.startsWith('..') && !path.isAbsolute(rel) ? rel : path.basename(uri.fsPath); + attached.push({ + mediaType, + data: buf.toString('base64'), + label, + }); + } catch (err) { + void vscode.window.showWarningMessage( + `Could not read image "${sanitizeUiText(path.basename(uri.fsPath), 80)}": ${err instanceof Error ? err.message : String(err)}` + ); + } + } + if (attached.length > 0) { + this.postToWebview({ type: 'attached_images', images: attached }); + } + } + private buildHtml(webview: vscode.Webview): string { const nonce = crypto.randomBytes(16).toString('base64'); const scriptUri = webview.asWebviewUri(vscode.Uri.joinPath(this.extensionUri, 'dist', 'webview', 'main.js')); @@ -740,13 +843,14 @@ export class AtcChatViewProvider implements vscode.WebviewViewProvider, vscode.D -
+
+