455 455
456 456
457 457
458
459
460
461Use Go 1.26 or later and `playwright-go` v0.5200.1 from the [Go sample module](https://github.com/openai/developers-website/tree/main/src/content/platform/go-examples). Start at the repository root to install the driver and Chromium.
462
463```bash
464cd src/content/platform/go-examples
465go run github.com/playwright-community/playwright-go/cmd/playwright@v0.5200.1 install chromium
466```
467
468If Linux system libraries are missing, run the same versioned command with `install --with-deps chromium`. You need permission to install operating-system packages.
469
470Browser actions and screenshots belong inside the callback passed to `withBrowserPage`, before its cleanup.
471
472**Runtime helper requirement**
473
474The runtime helper requires a preinstalled matching driver and browser. It does not download them.
475
476
477
478
458Then launch a browser instance. Keep the browser and page alive while you run the remaining steps.479Then launch a browser instance. Keep the browser and page alive while you run the remaining steps.
459 480
460 481
510 page = browser.new_page(viewport={"width": 1280, "height": 720})531 page = browser.new_page(viewport={"width": 1280, "height": 720})
511```532```
512 533
534```go
535import (
536 "errors"
537 "fmt"
538 "time"
539
540 "github.com/playwright-community/playwright-go"
541)
542
543// withBrowserPage owns the browser lifecycle around your application's page operations.
544// For example, the callback can call page.SetContent with application-owned HTML.
545func withBrowserPage(visit func(playwright.Page) error) (err error) {
546 // Runtime prerequisites must be installed separately; this sample never downloads browsers.
547 pw, err := playwright.Run()
548 if err != nil {
549 return err
550 }
551 defer func() { err = errors.Join(err, pw.Stop()) }()
552 browser, err := pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
553 Headless: playwright.Bool(true), ChromiumSandbox: playwright.Bool(true),
554 Env: map[string]string{}, Timeout: playwright.Float(30000),
555 Args: []string{"--disable-extensions", "--disable-file-system"},
556 })
557 if err != nil {
558 return err
559 }
560 defer func() { err = errors.Join(err, browser.Close()) }()
561 deadlineResult := make(chan error, 1)
562 deadline := time.AfterFunc(5*time.Minute, func() {
563 deadlineResult <- errors.Join(fmt.Errorf("browser page lifetime exceeded five minutes"), browser.Close())
564 })
565 defer func() {
566 if !deadline.Stop() {
567 err = errors.Join(err, <-deadlineResult)
568 }
569 }()
570
571 context, err := browser.NewContext(playwright.BrowserNewContextOptions{
572 Viewport: &playwright.Size{
573 Width: 1280,
574 Height: 720,
575 },
576 })
577 if err != nil {
578 return err
579 }
580 defer func() { err = errors.Join(err, context.Close()) }()
581 page, err := context.NewPage()
582 if err != nil {
583 return err
584 }
585 page.SetDefaultTimeout(10000)
586 return visit(page)
587}
588```
589
513```java590```java
514import com.microsoft.playwright.*;591import com.microsoft.playwright.*;
515import com.microsoft.playwright.options.*;592import com.microsoft.playwright.options.*;
534 611
535```612```
536 613
614```csharp
615using System;
616using System.Collections.Generic;
617using System.IO;
618using System.Text.Json;
619using System.Threading;
620using System.Threading.Tasks;
621using Microsoft.Playwright;
622// Microsoft.Playwright 1.52.0 and its matching Chromium installation.
623
624static async Task CloseAtDeadlineAsync(IBrowser browser, CancellationToken cancellationToken)
625{
626 try { await Task.Delay(TimeSpan.FromMinutes(5), cancellationToken); }
627 catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { return; }
628 await browser.CloseAsync();
629 throw new TimeoutException("Browser page lifetime exceeded five minutes.");
630}
631
632static BrowserTypeLaunchOptions CreateLaunchOptions() => new()
633{
634 Headless = true,
635 ChromiumSandbox = true,
636 Env = new Dictionary<string, string>(),
637 Timeout = 30_000,
638 Args = ["--disable-extensions", "--disable-file-system"],
639};
640
641static BrowserNewContextOptions CreateContextOptions() => new()
642{
643 ViewportSize = new() { Width = 1280, Height = 720 },
644};
645
646using IPlaywright playwright = await Playwright.CreateAsync();
647await using IBrowser browser = await playwright.Chromium.LaunchAsync(CreateLaunchOptions());
648await using IBrowserContext context = await browser.NewContextAsync(CreateContextOptions());
649using CancellationTokenSource lifetime = new();
650Task deadline = CloseAtDeadlineAsync(browser, lifetime.Token);
651try
652{
653 IPage page = await context.NewPageAsync();
654 page.SetDefaultTimeout(10_000);
655 // Subsequent browser actions and screenshots before cleanup.
656
657}
658finally
659{
660 await lifetime.CancelAsync();
661 await deadline;
662}
663```
664
537```ruby665```ruby
538require "playwright"666require "playwright"
539 667
706vm = VM(display=":99", container_name="cua-image")834vm = VM(display=":99", container_name="cua-image")
707```835```
708 836
837```go
838import (
839 "bytes"
840 "context"
841 "fmt"
842 "os/exec"
843 "sort"
844 "time"
845)
846
847type VM struct {
848 Display string
849 ContainerName string
850 Executions int
851}
852
853// dockerExec preserves argument boundaries and returns stdout as bytes, including PNGs.
854func (vm *VM) dockerExec(executable string, arguments []string, environment map[string]string) ([]byte, error) {
855 args := []string{"exec"}
856 names := make([]string, 0, len(environment))
857 for name := range environment {
858 names = append(names, name)
859 }
860 sort.Strings(names)
861 for _, name := range names {
862 args = append(args, "--env", name+"="+environment[name])
863 }
864 args = append(args, vm.ContainerName, executable)
865 args = append(args, arguments...)
866 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
867 defer cancel()
868 command := exec.CommandContext(ctx, "docker", args...)
869 var stderr bytes.Buffer
870 command.Stderr = &stderr
871 vm.Executions++
872 output, err := command.Output()
873 if err != nil {
874 return nil, fmt.Errorf("docker exec %s: %w: %s", executable, err, stderr.String())
875 }
876 return output, nil
877}
878
879func (vm *VM) xdotool(arguments ...string) error {
880 _, err := vm.dockerExec("xdotool", arguments, map[string]string{"DISPLAY": vm.Display})
881 return err
882}
883```
884
709```java885```java
710import com.openai.core.ObjectMappers;886import com.openai.core.ObjectMappers;
711import java.nio.charset.StandardCharsets;887import java.nio.charset.StandardCharsets;
749}925}
750```926```
751 927
928```csharp
929using System;
930using System.Collections.Generic;
931using System.Diagnostics;
932using System.IO;
933using System.Linq;
934using System.Text;
935using System.Text.Json;
936using System.Threading;
937using System.Threading.Tasks;
938
939internal sealed record VM(string Display, string ContainerName)
940{
941 internal int Executions { get; set; }
942}
943
944internal static ProcessStartInfo CreateDockerStartInfo(
945 VM vm, string executable, IReadOnlyList<string> arguments,
946 IReadOnlyDictionary<string, string>? environment = null)
947{
948 ProcessStartInfo start = new("docker")
949 {
950 UseShellExecute = false,
951 RedirectStandardInput = true,
952 RedirectStandardOutput = true,
953 RedirectStandardError = true,
954 StandardErrorEncoding = Encoding.UTF8,
955 };
956 start.ArgumentList.Add("exec");
957 if (environment is not null)
958 {
959 foreach ((string name, string value) in environment)
960 {
961 start.ArgumentList.Add("--env");
962 start.ArgumentList.Add($"{name}={value}");
963 }
964 }
965 start.ArgumentList.Add(vm.ContainerName);
966 start.ArgumentList.Add(executable);
967 foreach (string argument in arguments)
968 {
969 start.ArgumentList.Add(argument);
970 }
971 return start;
972}
973
974// ArgumentList avoids shell expansion; stdout remains binary throughout.
975internal static async Task<byte[]> DockerExecAsync(
976 VM vm, string executable, IReadOnlyList<string> arguments,
977 IReadOnlyDictionary<string, string>? environment = null)
978{
979 ProcessStartInfo start = CreateDockerStartInfo(vm, executable, arguments, environment);
980 using Process process = new() { StartInfo = start };
981 vm.Executions++;
982 if (!process.Start())
983 {
984 throw new InvalidOperationException("Could not start Docker.");
985 }
986 process.StandardInput.Close();
987 using CancellationTokenSource timeout = new(TimeSpan.FromSeconds(30));
988 using MemoryStream stdout = new();
989 try
990 {
991 Task copy = process.StandardOutput.BaseStream.CopyToAsync(stdout, timeout.Token);
992 Task<string> stderr = process.StandardError.ReadToEndAsync(timeout.Token);
993 await Task.WhenAll(copy, stderr, process.WaitForExitAsync(timeout.Token));
994 if (process.ExitCode != 0)
995 {
996 throw new InvalidOperationException($"docker exec {executable} failed ({process.ExitCode}): {await stderr}");
997 }
998 return stdout.ToArray();
999 }
1000 finally
1001 {
1002 if (!process.HasExited)
1003 {
1004 process.Kill(entireProcessTree: true);
1005 }
1006 await process.WaitForExitAsync();
1007 }
1008}
1009
1010internal static async Task XdotoolAsync(VM vm, params string[] arguments)
1011{
1012 await DockerExecAsync(vm, "xdotool", arguments, new Dictionary<string, string> { ["DISPLAY"] = vm.Display });
1013}
1014```
1015
752```ruby1016```ruby
753def docker_exec(container_name, executable, args, decode: true, env: {})1017def docker_exec(container_name, executable, args, decode: true, env: {})
754 environment = env.flat_map { |name, value| ["--env", "#{name}=#{value}"] }1018 environment = env.flat_map { |name, value| ["--env", "#{name}=#{value}"] }
966 return [(point.x, point.y) for point in path]1230 return [(point.x, point.y) for point in path]
967```1231```
968 1232
1233```go
1234import (
1235 "fmt"
1236
1237 "github.com/openai/openai-go/v3/responses"
1238 "github.com/playwright-community/playwright-go"
1239)
1240
1241func normalizeKey(key string) string {
1242 switch key {
1243 case "ENTER", "RETURN":
1244 return "Enter"
1245 case "ESC", "ESCAPE":
1246 return "Escape"
1247 case "TAB":
1248 return "Tab"
1249 case "SPACE":
1250 return "Space"
1251 case "BACKSPACE":
1252 return "Backspace"
1253 case "DELETE", "DEL":
1254 return "Delete"
1255 case "HOME":
1256 return "Home"
1257 case "END":
1258 return "End"
1259 case "PAGEUP":
1260 return "PageUp"
1261 case "PAGEDOWN":
1262 return "PageDown"
1263 case "UP", "ARROWUP":
1264 return "ArrowUp"
1265 case "DOWN", "ARROWDOWN":
1266 return "ArrowDown"
1267 case "LEFT", "ARROWLEFT":
1268 return "ArrowLeft"
1269 case "RIGHT", "ARROWRIGHT":
1270 return "ArrowRight"
1271 case "CTRL", "CONTROL":
1272 return "Control"
1273 case "SHIFT":
1274 return "Shift"
1275 case "ALT", "OPTION":
1276 return "Alt"
1277 case "META", "CMD", "COMMAND":
1278 return "Meta"
1279 default:
1280 return key
1281 }
1282}
1283
1284func normalizeButton(button string) (playwright.MouseButton, error) {
1285 switch button {
1286 case "left":
1287 return playwright.MouseButton("left"), nil
1288 case "wheel":
1289 return playwright.MouseButton("middle"), nil
1290 case "right":
1291 return playwright.MouseButton("right"), nil
1292 default:
1293 return "", fmt.Errorf("unsupported mouse button: %s", button)
1294 }
1295}
1296
1297func normalizeDragPath(path []responses.ComputerActionDragPath) [][2]int64 {
1298 result := make([][2]int64, len(path))
1299 for i, point := range path {
1300 result[i] = [2]int64{point.X, point.Y}
1301 }
1302 return result
1303}
1304```
1305
969```java1306```java
970import com.microsoft.playwright.*;1307import com.microsoft.playwright.*;
971import com.microsoft.playwright.options.*;1308import com.microsoft.playwright.options.*;
1014}1351}
1015```1352```
1016 1353
1354```csharp
1355using System;
1356using System.Collections.Generic;
1357using System.IO;
1358using System.Linq;
1359using System.Text.Json;
1360using System.Threading;
1361using System.Threading.Tasks;
1362using Microsoft.Playwright;
1363
1364internal static string NormalizeKey(string key) => key switch
1365{
1366 "ENTER" or "RETURN" => "Enter",
1367 "ESC" or "ESCAPE" => "Escape",
1368 "TAB" => "Tab",
1369 "SPACE" => "Space",
1370 "BACKSPACE" => "Backspace",
1371 "DELETE" or "DEL" => "Delete",
1372 "HOME" => "Home",
1373 "END" => "End",
1374 "PAGEUP" => "PageUp",
1375 "PAGEDOWN" => "PageDown",
1376 "UP" or "ARROWUP" => "ArrowUp",
1377 "DOWN" or "ARROWDOWN" => "ArrowDown",
1378 "LEFT" or "ARROWLEFT" => "ArrowLeft",
1379 "RIGHT" or "ARROWRIGHT" => "ArrowRight",
1380 "CTRL" or "CONTROL" => "Control",
1381 "SHIFT" => "Shift",
1382 "ALT" or "OPTION" => "Alt",
1383 "META" or "CMD" or "COMMAND" => "Meta",
1384 _ => key,
1385};
1386
1387internal static MouseButton NormalizeButton(string button) => button switch
1388{
1389 "left" => MouseButton.Left,
1390 "wheel" => MouseButton.Middle,
1391 "right" => MouseButton.Right,
1392 _ => throw new ArgumentException($"Unsupported mouse button: {button}", nameof(button)),
1393};
1394
1395internal static double[][] NormalizeDragPath(JsonElement path)
1396{
1397 if (path.ValueKind != JsonValueKind.Array)
1398 {
1399 throw new ArgumentException("A drag path must be an array.", nameof(path));
1400 }
1401 return path.EnumerateArray().Select(point =>
1402 {
1403 double[] coordinates = point.ValueKind switch
1404 {
1405 JsonValueKind.Array when point.GetArrayLength() >= 2 =>
1406 [point[0].GetDouble(), point[1].GetDouble()],
1407 JsonValueKind.Object =>
1408 [point.GetProperty("x").GetDouble(), point.GetProperty("y").GetDouble()],
1409 _ => throw new ArgumentException("Expected coordinate pairs or objects.", nameof(path)),
1410 };
1411 if (!coordinates.All(double.IsFinite))
1412 {
1413 throw new ArgumentException("Coordinates must be finite.", nameof(path));
1414 }
1415 return coordinates;
1416 }).ToArray();
1417}
1418```
1419
1017```ruby1420```ruby
1018def normalize_key(key)1421def normalize_key(key)
1019 names = {1422 names = {
1282 return [(point.x, point.y) for point in path]1685 return [(point.x, point.y) for point in path]
1283```1686```
1284 1687
1688```go
1689import (
1690 "github.com/openai/openai-go/v3/responses"
1691 "math"
1692)
1693
1694type InvalidInputError struct{ Message string }
1695
1696func (e *InvalidInputError) Error() string { return e.Message }
1697
1698func normalizeKey(key string) string {
1699 switch key {
1700 case "ENTER", "RETURN":
1701 return "Return"
1702 case "ESC", "ESCAPE":
1703 return "Escape"
1704 case "TAB":
1705 return "Tab"
1706 case "SPACE":
1707 return "space"
1708 case "BACKSPACE":
1709 return "BackSpace"
1710 case "DELETE", "DEL":
1711 return "Delete"
1712 case "HOME":
1713 return "Home"
1714 case "END":
1715 return "End"
1716 case "PAGEUP":
1717 return "Page_Up"
1718 case "PAGEDOWN":
1719 return "Page_Down"
1720 case "UP", "ARROWUP":
1721 return "Up"
1722 case "DOWN", "ARROWDOWN":
1723 return "Down"
1724 case "LEFT", "ARROWLEFT":
1725 return "Left"
1726 case "RIGHT", "ARROWRIGHT":
1727 return "Right"
1728 case "CTRL", "CONTROL":
1729 return "ctrl"
1730 case "SHIFT":
1731 return "shift"
1732 case "ALT", "OPTION":
1733 return "alt"
1734 case "META", "CMD", "COMMAND":
1735 return "super"
1736 default:
1737 return key
1738 }
1739}
1740
1741func normalizeButton(button string) (int, error) {
1742 switch button {
1743 case "left":
1744 return 1, nil
1745 case "wheel":
1746 return 2, nil
1747 case "right":
1748 return 3, nil
1749 case "back":
1750 return 8, nil
1751 case "forward":
1752 return 9, nil
1753 default:
1754 return 0, &InvalidInputError{"Unsupported mouse button: " + button}
1755 }
1756}
1757
1758func normalizeDragPath(path []responses.ComputerActionDragPath) [][2]int64 {
1759 result := make([][2]int64, 0, len(path))
1760 for _, point := range path {
1761 result = append(result, [2]int64{point.X, point.Y})
1762 }
1763 return result
1764}
1765
1766func scrollButtons(x, y int64) []int {
1767 buttons := []int{}
1768 for _, direction := range [][3]int64{{y, 4, 5}, {x, 6, 7}} {
1769 delta := direction[0]
1770 if delta == 0 {
1771 continue
1772 }
1773 button := direction[2]
1774 if delta < 0 {
1775 button = direction[1]
1776 }
1777 // Python round and Java rint use ties-to-even (Go math.Round does not).
1778 clicks := max(1, int(math.Abs(math.RoundToEven(float64(delta)/100))))
1779 for i := 0; i < clicks; i++ {
1780 buttons = append(buttons, int(button))
1781 }
1782 }
1783 return buttons
1784}
1785```
1786
1285```java1787```java
1286import com.openai.core.ObjectMappers;1788import com.openai.core.ObjectMappers;
1287import com.openai.models.responses.ComputerAction;1789import com.openai.models.responses.ComputerAction;
1341}1843}
1342```1844```
1343 1845
1846```csharp
1847using System;
1848using System.Collections.Generic;
1849using System.Diagnostics;
1850using System.IO;
1851using System.Linq;
1852using System.Text;
1853using System.Text.Json;
1854using System.Text.Json.Serialization;
1855using System.Threading;
1856using System.Threading.Tasks;
1857
1858internal sealed record Point(
1859 [property: JsonPropertyName("x")] long X,
1860 [property: JsonPropertyName("y")] long Y);
1861
1862internal static string NormalizeKey(string key) => key switch
1863{
1864 "ENTER" or "RETURN" => "Return",
1865 "ESC" or "ESCAPE" => "Escape",
1866 "TAB" => "Tab",
1867 "SPACE" => "space",
1868 "BACKSPACE" => "BackSpace",
1869 "DELETE" or "DEL" => "Delete",
1870 "HOME" => "Home",
1871 "END" => "End",
1872 "PAGEUP" => "Page_Up",
1873 "PAGEDOWN" => "Page_Down",
1874 "UP" or "ARROWUP" => "Up",
1875 "DOWN" or "ARROWDOWN" => "Down",
1876 "LEFT" or "ARROWLEFT" => "Left",
1877 "RIGHT" or "ARROWRIGHT" => "Right",
1878 "CTRL" or "CONTROL" => "ctrl",
1879 "SHIFT" => "shift",
1880 "ALT" or "OPTION" => "alt",
1881 "META" or "CMD" or "COMMAND" => "super",
1882 _ => key,
1883};
1884
1885internal static int NormalizeButton(string button) => button switch
1886{
1887 "left" => 1,
1888 "wheel" => 2,
1889 "right" => 3,
1890 "back" => 8,
1891 "forward" => 9,
1892 _ => throw new ArgumentException($"Unsupported mouse button: {button}", nameof(button)),
1893};
1894
1895internal static long[][] NormalizeDragPath(IReadOnlyList<Point> path) =>
1896 path.Select(point => new[] { point.X, point.Y }).ToArray();
1897
1898internal static List<int> ScrollButtons(long x, long y)
1899{
1900 List<int> buttons = [];
1901 foreach ((long delta, int negative, int positive) in new[] { (y, 4, 5), (x, 6, 7) })
1902 {
1903 if (delta == 0)
1904 {
1905 continue;
1906 }
1907 int button = delta < 0 ? negative : positive;
1908 // Match the Python reference's round-to-even behavior, including half steps.
1909 int clicks = Math.Max(1, checked((int)Math.Abs(Math.Round(delta / 100.0, MidpointRounding.ToEven))));
1910 for (int index = 0; index < clicks; index++)
1911 {
1912 buttons.Add(button);
1913 }
1914 }
1915 return buttons;
1916}
1917```
1918
1344```ruby1919```ruby
1345def normalize_xdotool_key(key)1920def normalize_xdotool_key(key)
1346 names = {1921 names = {
1575 raise ValueError(f"Unsupported action: {action.type}")2150 raise ValueError(f"Unsupported action: {action.type}")
1576```2151```
1577 2152
1578```java2153```go
1579import com.microsoft.playwright.*;2154import (
1580import com.microsoft.playwright.options.*;2155 "errors"
1581import com.openai.core.ObjectMappers;2156 "fmt"
1582import com.openai.models.responses.ComputerAction;2157 "strings"
1583import java.nio.file.*;2158 "time"
1584import java.util.*;
1585 2159
2160 "github.com/openai/openai-go/v3/responses"
2161 "github.com/playwright-community/playwright-go"
2162)
1586 2163
2164func normalizeKey(key string) string {
2165 switch key {
2166 case "ENTER", "RETURN":
2167 return "Enter"
2168 case "ESC", "ESCAPE":
2169 return "Escape"
2170 case "TAB":
2171 return "Tab"
2172 case "SPACE":
2173 return "Space"
2174 case "BACKSPACE":
2175 return "Backspace"
2176 case "DELETE", "DEL":
2177 return "Delete"
2178 case "HOME":
2179 return "Home"
2180 case "END":
2181 return "End"
2182 case "PAGEUP":
2183 return "PageUp"
2184 case "PAGEDOWN":
2185 return "PageDown"
2186 case "UP", "ARROWUP":
2187 return "ArrowUp"
2188 case "DOWN", "ARROWDOWN":
2189 return "ArrowDown"
2190 case "LEFT", "ARROWLEFT":
2191 return "ArrowLeft"
2192 case "RIGHT", "ARROWRIGHT":
2193 return "ArrowRight"
2194 case "CTRL", "CONTROL":
2195 return "Control"
2196 case "SHIFT":
2197 return "Shift"
2198 case "ALT", "OPTION":
2199 return "Alt"
2200 case "META", "CMD", "COMMAND":
2201 return "Meta"
2202 default:
2203 return key
2204 }
2205}
1587 2206
1588static void handleComputerActions(Page page, List<ComputerAction> actions) {2207func normalizeButton(button string) (playwright.MouseButton, error) {
1589 for (var action : actions) {2208 switch button {
1590 List<String> keys = List.of();2209 case "left":
1591 Runnable operation;2210 return playwright.MouseButton("left"), nil
1592 if (action.isClick()) {2211 case "wheel":
1593 var click = action.asClick();2212 return playwright.MouseButton("middle"), nil
1594 keys = click.keys().orElse(List.of());2213 case "right":
1595 operation =2214 return playwright.MouseButton("right"), nil
1596 () ->2215 default:
1597 page.mouse()2216 return "", fmt.Errorf("unsupported mouse button: %s", button)
1598 .click(2217 }
1599 click.x(),2218}
2219
2220func normalizeDragPath(path []responses.ComputerActionDragPath) [][2]int64 {
2221 result := make([][2]int64, len(path))
2222 for i, point := range path {
2223 result[i] = [2]int64{point.X, point.Y}
2224 }
2225 return result
2226}
2227
2228func handleComputerActions(page playwright.Page, actions []responses.ComputerActionUnion) error {
2229 for _, action := range actions {
2230 var operation func() error
2231 switch action.Type {
2232 case "click":
2233 button, err := normalizeButton(action.Button)
2234 if err != nil {
2235 return err
2236 }
2237 operation = func() error {
2238 return page.Mouse().Click(float64(action.X), float64(action.Y), playwright.MouseClickOptions{Button: &button})
2239 }
2240 case "double_click":
2241 operation = func() error { return page.Mouse().Dblclick(float64(action.X), float64(action.Y)) }
2242 case "move":
2243 operation = func() error { return page.Mouse().Move(float64(action.X), float64(action.Y)) }
2244 case "drag":
2245 path := normalizeDragPath(action.Path)
2246 if len(path) < 2 {
2247 return fmt.Errorf("drag requires at least two points")
2248 }
2249 operation = func() (err error) {
2250 if err = page.Mouse().Move(float64(path[0][0]), float64(path[0][1])); err != nil {
2251 return err
2252 }
2253 if err = page.Mouse().Down(); err != nil {
2254 return err
2255 }
2256 defer func() { err = errors.Join(err, page.Mouse().Up()) }()
2257 for _, point := range path[1:] {
2258 if err = page.Mouse().Move(float64(point[0]), float64(point[1])); err != nil {
2259 return err
2260 }
2261 }
2262 return nil
2263 }
2264 case "scroll":
2265 operation = func() error {
2266 if err := page.Mouse().Move(float64(action.X), float64(action.Y)); err != nil {
2267 return err
2268 }
2269 return page.Mouse().Wheel(float64(action.ScrollX), float64(action.ScrollY))
2270 }
2271 case "keypress":
2272 keys := make([]string, len(action.Keys))
2273 for i, key := range action.Keys {
2274 keys[i] = normalizeKey(key)
2275 }
2276 if len(keys) == 0 {
2277 return fmt.Errorf("keypress requires at least one key")
2278 }
2279 if err := page.Keyboard().Press(strings.Join(keys, "+")); err != nil {
2280 return err
2281 }
2282 continue
2283 case "type":
2284 if err := page.Keyboard().InsertText(action.Text); err != nil {
2285 return err
2286 }
2287 continue
2288 case "wait":
2289 time.Sleep(2 * time.Second)
2290 continue
2291 case "screenshot":
2292 continue // The caller captures the page after the batch.
2293 default:
2294 return fmt.Errorf("unsupported computer action: %s", action.Type)
2295 }
2296 if len(action.Keys) != 0 {
2297 return fmt.Errorf("use the modifier-aware handler")
2298 }
2299 if err := operation(); err != nil {
2300 return err
2301 }
2302 }
2303 return nil
2304}
2305```
2306
2307```java
2308import com.microsoft.playwright.*;
2309import com.microsoft.playwright.options.*;
2310import com.openai.core.ObjectMappers;
2311import com.openai.models.responses.ComputerAction;
2312import java.nio.file.*;
2313import java.util.*;
2314
2315
2316
2317static void handleComputerActions(Page page, List<ComputerAction> actions) {
2318 for (var action : actions) {
2319 List<String> keys = List.of();
2320 Runnable operation;
2321 if (action.isClick()) {
2322 var click = action.asClick();
2323 keys = click.keys().orElse(List.of());
2324 operation =
2325 () ->
2326 page.mouse()
2327 .click(
2328 click.x(),
1600 click.y(),2329 click.y(),
1601 new Mouse.ClickOptions()2330 new Mouse.ClickOptions()
1602 .setButton(normalizeButton(click.button().toString())));2331 .setButton(normalizeButton(click.button().toString())));
1655}2384}
1656```2385```
1657 2386
2387```csharp
2388using System;
2389using System.Collections.Generic;
2390using System.Diagnostics;
2391using System.IO;
2392using System.Linq;
2393using System.Runtime.ExceptionServices;
2394using System.Text.Json;
2395using System.Threading;
2396using System.Threading.Tasks;
2397using Microsoft.Playwright;
2398
2399internal static string NormalizeKey(string key) => key switch
2400{
2401 "ENTER" or "RETURN" => "Enter",
2402 "ESC" or "ESCAPE" => "Escape",
2403 "TAB" => "Tab",
2404 "SPACE" => "Space",
2405 "BACKSPACE" => "Backspace",
2406 "DELETE" or "DEL" => "Delete",
2407 "HOME" => "Home",
2408 "END" => "End",
2409 "PAGEUP" => "PageUp",
2410 "PAGEDOWN" => "PageDown",
2411 "UP" or "ARROWUP" => "ArrowUp",
2412 "DOWN" or "ARROWDOWN" => "ArrowDown",
2413 "LEFT" or "ARROWLEFT" => "ArrowLeft",
2414 "RIGHT" or "ARROWRIGHT" => "ArrowRight",
2415 "CTRL" or "CONTROL" => "Control",
2416 "SHIFT" => "Shift",
2417 "ALT" or "OPTION" => "Alt",
2418 "META" or "CMD" or "COMMAND" => "Meta",
2419 _ => key,
2420};
2421
2422internal static MouseButton NormalizeButton(string button) => button switch
2423{
2424 "left" => MouseButton.Left,
2425 "wheel" => MouseButton.Middle,
2426 "right" => MouseButton.Right,
2427 _ => throw new ArgumentException($"Unsupported mouse button: {button}", nameof(button)),
2428};
2429
2430internal static long[][] NormalizeDragPath(JsonElement path) => path.EnumerateArray()
2431 .Select(point => new[] { point.GetProperty("x").GetInt64(), point.GetProperty("y").GetInt64() })
2432 .ToArray();
2433
2434// These JSON actions are application inputs, not missing OpenAI SDK types.
2435internal static async Task HandleComputerActionsAsync(IPage page, IEnumerable<JsonElement> actions)
2436{
2437 foreach (JsonElement action in actions)
2438 {
2439 string type = action.GetProperty("type").GetString()
2440 ?? throw new ArgumentException("Action type is required.");
2441 string[] keys = action.TryGetProperty("keys", out JsonElement keyValues)
2442 ? keyValues.EnumerateArray().Select(key => key.GetString()
2443 ?? throw new ArgumentException("Keys must be strings.")).ToArray() : [];
2444 Func<Task> operation;
2445 switch (type)
2446 {
2447 case "click":
2448 MouseButton button = NormalizeButton(action.GetProperty("button").GetString()
2449 ?? throw new ArgumentException("Button is required."));
2450 operation = () => page.Mouse.ClickAsync(action.GetProperty("x").GetInt64(),
2451 action.GetProperty("y").GetInt64(), new() { Button = button });
2452 break;
2453 case "double_click":
2454 operation = () => page.Mouse.DblClickAsync(
2455 action.GetProperty("x").GetInt64(),
2456 action.GetProperty("y").GetInt64());
2457 break;
2458 case "move":
2459 operation = () => page.Mouse.MoveAsync(
2460 action.GetProperty("x").GetInt64(),
2461 action.GetProperty("y").GetInt64());
2462 break;
2463 case "drag":
2464 long[][] path = NormalizeDragPath(action.GetProperty("path"));
2465 if (path.Length < 2) throw new ArgumentException("Drag requires at least two points.");
2466 operation = async () =>
2467 {
2468 await page.Mouse.MoveAsync(path[0][0], path[0][1]);
2469 await page.Mouse.DownAsync();
2470 Exception? operationError = null;
2471 try
2472 {
2473 foreach (long[] point in path.Skip(1)) await page.Mouse.MoveAsync(point[0], point[1]);
2474 }
2475 catch (Exception error)
2476 {
2477 operationError = error;
2478 }
2479 finally
2480 {
2481 try { await page.Mouse.UpAsync(); }
2482 catch (Exception releaseError)
2483 {
2484 operationError = operationError is null
2485 ? releaseError : new AggregateException(operationError, releaseError);
2486 }
2487 }
2488 if (operationError is not null) ExceptionDispatchInfo.Capture(operationError).Throw();
2489 };
2490 break;
2491 case "scroll":
2492 operation = async () =>
2493 {
2494 await page.Mouse.MoveAsync(
2495 action.GetProperty("x").GetInt64(),
2496 action.GetProperty("y").GetInt64());
2497 await page.Mouse.WheelAsync(
2498 action.GetProperty("scroll_x").GetInt64(),
2499 action.GetProperty("scroll_y").GetInt64());
2500 };
2501 break;
2502 case "keypress":
2503 if (keys.Length == 0) throw new ArgumentException("Keypress requires at least one key.");
2504 await page.Keyboard.PressAsync(string.Join("+", keys.Select(NormalizeKey)));
2505 continue;
2506 case "type":
2507 await page.Keyboard.InsertTextAsync(action.GetProperty("text").GetString()
2508 ?? throw new ArgumentException("Text is required."));
2509 continue;
2510 case "wait":
2511 await Task.Delay(TimeSpan.FromSeconds(2));
2512 continue;
2513 case "screenshot":
2514 continue; // The caller captures the page after the batch.
2515 default:
2516 throw new ArgumentException($"Unsupported computer action: {type}");
2517 }
2518 if (keys.Length != 0) throw new ArgumentException("Use the modifier-aware handler.");
2519 await operation();
2520 }
2521}
2522```
2523
1658```ruby2524```ruby
1659def perform_browser_action(page, action)2525def perform_browser_action(page, action)
1660 case action.type2526 case action.type
1945 raise ValueError(f"Unsupported action: {action.type}")2811 raise ValueError(f"Unsupported action: {action.type}")
1946```2812```
1947 2813
2814```go
2815import (
2816 "errors"
2817 "fmt"
2818 "github.com/openai/openai-go/v3/responses"
2819 "time"
2820)
2821
2822func withModifiers(vm *VM, keys []string, operation func() error) (err error) {
2823 pressed := []string{}
2824 defer func() {
2825 // Attempt every release even if one release fails, retaining the original failure.
2826 for i := len(pressed) - 1; i >= 0; i-- {
2827 if releaseErr := vm.xdotool("keyup", pressed[i]); releaseErr != nil {
2828 err = errors.Join(err, releaseErr)
2829 }
2830 }
2831 }()
2832 for _, key := range keys {
2833 normalized := normalizeKey(key)
2834 pressed = append(pressed, normalized)
2835 if err = vm.xdotool("keydown", normalized); err != nil {
2836 return err
2837 }
2838 }
2839 return operation()
2840}
2841
2842func handleComputerActions(vm *VM, actions responses.ComputerActionList) error {
2843 for _, action := range actions {
2844 var operation func() error
2845 switch action.Type {
2846 case "click":
2847 button, err := normalizeButton(action.Button)
2848 if err != nil {
2849 return err
2850 }
2851 operation = func() error {
2852 return vm.xdotool("mousemove", "--sync", fmt.Sprint(action.X), fmt.Sprint(action.Y), "click", fmt.Sprint(button))
2853 }
2854 case "double_click":
2855 operation = func() error {
2856 return vm.xdotool(
2857 "mousemove", "--sync", fmt.Sprint(action.X), fmt.Sprint(action.Y),
2858 "click", "--repeat", "2", "--delay", "100", "1",
2859 )
2860 }
2861 case "move":
2862 operation = func() error { return vm.xdotool("mousemove", "--sync", fmt.Sprint(action.X), fmt.Sprint(action.Y)) }
2863 case "drag":
2864 path := normalizeDragPath(action.Path)
2865 if len(path) < 2 {
2866 return &InvalidInputError{"Drag requires at least two points"}
2867 }
2868 operation = func() (err error) {
2869 if err = vm.xdotool("mousemove", "--sync", fmt.Sprint(path[0][0]), fmt.Sprint(path[0][1])); err != nil {
2870 return err
2871 }
2872 defer func() { err = errors.Join(err, vm.xdotool("mouseup", "1")) }()
2873 if err = vm.xdotool("mousedown", "1"); err != nil {
2874 return err
2875 }
2876 for _, point := range path[1:] {
2877 if err = vm.xdotool("mousemove", "--sync", fmt.Sprint(point[0]), fmt.Sprint(point[1])); err != nil {
2878 return err
2879 }
2880 }
2881 return nil
2882 }
2883 case "scroll":
2884 operation = func() error {
2885 if err := vm.xdotool("mousemove", "--sync", fmt.Sprint(action.X), fmt.Sprint(action.Y)); err != nil {
2886 return err
2887 }
2888 for _, button := range scrollButtons(action.ScrollX, action.ScrollY) {
2889 if err := vm.xdotool("click", fmt.Sprint(button)); err != nil {
2890 return err
2891 }
2892 }
2893 return nil
2894 }
2895 case "keypress":
2896 if len(action.Keys) == 0 {
2897 return &InvalidInputError{"Keypress requires keys"}
2898 }
2899 // Keydown/up provides finally-based release for combinations, too.
2900 if err := withModifiers(vm, action.Keys, func() error { return nil }); err != nil {
2901 return err
2902 }
2903 continue
2904 case "type":
2905 if err := vm.xdotool("type", "--clearmodifiers", "--", action.Text); err != nil {
2906 return err
2907 }
2908 continue
2909 case "wait":
2910 time.Sleep(2 * time.Second)
2911 continue
2912 case "screenshot":
2913 // The caller captures once after the batch, including screenshot-only batches.
2914 continue
2915 default:
2916 return &InvalidInputError{"Unsupported computer action: " + action.Type}
2917 }
2918 if len(action.Keys) != 0 {
2919 return &InvalidInputError{"Use the modifier-aware handler"}
2920 }
2921 if err := operation(); err != nil {
2922 return err
2923 }
2924 }
2925 return nil
2926}
2927```
2928
1948```java2929```java
1949import com.openai.core.ObjectMappers;2930import com.openai.core.ObjectMappers;
1950import com.openai.models.responses.ComputerAction;2931import com.openai.models.responses.ComputerAction;
2055}3036}
2056```3037```
2057 3038
3039```csharp
3040using System;
3041using System.Collections.Generic;
3042using System.Diagnostics;
3043using System.Globalization;
3044using System.IO;
3045using System.Linq;
3046using System.Runtime.ExceptionServices;
3047using System.Text;
3048using System.Text.Json;
3049using System.Text.Json.Serialization;
3050using System.Threading;
3051using System.Threading.Tasks;
3052
3053// Application-owned host messages, independent of the OpenAI SDK computer-tool surface.
3054internal sealed record ComputerAction
3055{
3056 [JsonPropertyName("type")]
3057 public required string Type { get; init; }
3058 [JsonPropertyName("button")]
3059 public string Button { get; init; } = "";
3060 [JsonPropertyName("x")]
3061 public long X { get; init; }
3062 [JsonPropertyName("y")]
3063 public long Y { get; init; }
3064 [JsonPropertyName("keys")]
3065 public string[] Keys { get; init; } = [];
3066 [JsonPropertyName("path")]
3067 public Point[] Path { get; init; } = [];
3068 [JsonPropertyName("scroll_x")]
3069 public long ScrollX { get; init; }
3070 [JsonPropertyName("scroll_y")]
3071 public long ScrollY { get; init; }
3072 [JsonPropertyName("text")]
3073 public string Text { get; init; } = "";
3074}
3075
3076internal static async Task WithModifiersAsync(VM vm, IReadOnlyList<string> keys, Func<Task> operation)
3077{
3078 List<string> pressed = [];
3079 List<Exception> failures = [];
3080 try
3081 {
3082 foreach (string key in keys)
3083 {
3084 string normalized = NormalizeKey(key);
3085 // A failed process may already have sent the keydown; release that key, too.
3086 pressed.Add(normalized);
3087 await XdotoolAsync(vm, "keydown", normalized);
3088 }
3089 await operation();
3090 }
3091 catch (Exception error)
3092 {
3093 failures.Add(error);
3094 }
3095 finally
3096 {
3097 for (int index = pressed.Count - 1; index >= 0; index--)
3098 {
3099 try
3100 {
3101 await XdotoolAsync(vm, "keyup", pressed[index]);
3102 }
3103 catch (Exception error)
3104 {
3105 failures.Add(error);
3106 }
3107 }
3108 }
3109 if (failures.Count == 1)
3110 {
3111 ExceptionDispatchInfo.Capture(failures[0]).Throw();
3112 }
3113 if (failures.Count > 1)
3114 {
3115 throw new AggregateException(failures);
3116 }
3117}
3118
3119internal static async Task HandleComputerActionsAsync(VM vm, IReadOnlyList<ComputerAction> actions)
3120{
3121 foreach (ComputerAction action in actions)
3122 {
3123 Func<Task> operation;
3124 switch (action.Type)
3125 {
3126 case "click":
3127 int button = NormalizeButton(action.Button);
3128 operation = () => XdotoolAsync(
3129 vm,
3130 "mousemove",
3131 "--sync",
3132 Number(action.X),
3133 Number(action.Y),
3134 "click",
3135 Number(button));
3136 break;
3137 case "double_click":
3138 operation = () => XdotoolAsync(
3139 vm,
3140 "mousemove",
3141 "--sync",
3142 Number(action.X),
3143 Number(action.Y),
3144 "click",
3145 "--repeat",
3146 "2",
3147 "--delay",
3148 "100",
3149 "1");
3150 break;
3151 case "move":
3152 operation = () => XdotoolAsync(vm, "mousemove", "--sync", Number(action.X), Number(action.Y));
3153 break;
3154 case "drag":
3155 long[][] path = NormalizeDragPath(action.Path);
3156 if (path.Length < 2)
3157 {
3158 throw new ArgumentException("Drag requires at least two points.", nameof(actions));
3159 }
3160 operation = async () =>
3161 {
3162 await XdotoolAsync(vm, "mousemove", "--sync", Number(path[0][0]), Number(path[0][1]));
3163 Exception? primaryFailure = null;
3164 try
3165 {
3166 await XdotoolAsync(vm, "mousedown", "1");
3167 foreach (long[] point in path.Skip(1))
3168 {
3169 await XdotoolAsync(vm, "mousemove", "--sync", Number(point[0]), Number(point[1]));
3170 }
3171 }
3172 catch (Exception error)
3173 {
3174 primaryFailure = error;
3175 }
3176 finally
3177 {
3178 try
3179 {
3180 await XdotoolAsync(vm, "mouseup", "1");
3181 }
3182 catch (Exception releaseFailure)
3183 {
3184 primaryFailure = primaryFailure is null
3185 ? releaseFailure
3186 : new AggregateException(primaryFailure, releaseFailure);
3187 }
3188 }
3189 if (primaryFailure is not null)
3190 {
3191 ExceptionDispatchInfo.Capture(primaryFailure).Throw();
3192 }
3193 };
3194 break;
3195 case "scroll":
3196 operation = async () =>
3197 {
3198 await XdotoolAsync(vm, "mousemove", "--sync", Number(action.X), Number(action.Y));
3199 foreach (int scrollButton in ScrollButtons(action.ScrollX, action.ScrollY))
3200 {
3201 await XdotoolAsync(vm, "click", Number(scrollButton));
3202 }
3203 };
3204 break;
3205 case "keypress":
3206 if (action.Keys.Length == 0)
3207 {
3208 throw new ArgumentException("Keypress requires keys.", nameof(actions));
3209 }
3210 await WithModifiersAsync(vm, action.Keys, () => Task.CompletedTask);
3211 continue;
3212 case "type":
3213 await XdotoolAsync(vm, "type", "--clearmodifiers", "--", action.Text);
3214 continue;
3215 case "wait":
3216 await Task.Delay(TimeSpan.FromSeconds(2));
3217 continue;
3218 case "screenshot":
3219 // Capture once after the action batch, in the caller.
3220 continue;
3221 default:
3222 throw new ArgumentException($"Unsupported computer action: {action.Type}", nameof(actions));
3223 }
3224 if (action.Keys.Length != 0)
3225 {
3226 throw new ArgumentException("Use the modifier-aware handler.", nameof(actions));
3227 }
3228 await operation();
3229 }
3230}
3231
3232private static string Number(long value) => value.ToString(CultureInfo.InvariantCulture);
3233```
3234
2058```ruby3235```ruby
2059def run_xdotool(vm, *args)3236def run_xdotool(vm, *args)
2060 docker_exec(vm.container_name, "xdotool", args, env: { "DISPLAY" => vm.display })3237 docker_exec(vm.container_name, "xdotool", args, env: { "DISPLAY" => vm.display })
2323 ),3500 ),
2324 )3501 )
2325 case "keypress":3502 case "keypress":
2326 page.keyboard.press("+".join(normalize_key(key) for key in action.keys))3503 page.keyboard.press("+".join(normalize_key(key) for key in action.keys))
3504 case "type":
3505 page.keyboard.type(action.text)
3506 case "wait":
3507 time.sleep(2)
3508 case "screenshot":
3509 # The caller captures a screenshot after every action.
3510 continue
3511 case _:
3512 raise ValueError(f"Unsupported action: {action.type}")
3513```
3514
3515```go
3516import (
3517 "errors"
3518 "fmt"
3519 "strings"
3520 "time"
3521
3522 "github.com/openai/openai-go/v3/responses"
3523 "github.com/playwright-community/playwright-go"
3524)
3525
3526func normalizeKey(key string) string {
3527 switch key {
3528 case "ENTER", "RETURN":
3529 return "Enter"
3530 case "ESC", "ESCAPE":
3531 return "Escape"
3532 case "TAB":
3533 return "Tab"
3534 case "SPACE":
3535 return "Space"
3536 case "BACKSPACE":
3537 return "Backspace"
3538 case "DELETE", "DEL":
3539 return "Delete"
3540 case "HOME":
3541 return "Home"
3542 case "END":
3543 return "End"
3544 case "PAGEUP":
3545 return "PageUp"
3546 case "PAGEDOWN":
3547 return "PageDown"
3548 case "UP", "ARROWUP":
3549 return "ArrowUp"
3550 case "DOWN", "ARROWDOWN":
3551 return "ArrowDown"
3552 case "LEFT", "ARROWLEFT":
3553 return "ArrowLeft"
3554 case "RIGHT", "ARROWRIGHT":
3555 return "ArrowRight"
3556 case "CTRL", "CONTROL":
3557 return "Control"
3558 case "SHIFT":
3559 return "Shift"
3560 case "ALT", "OPTION":
3561 return "Alt"
3562 case "META", "CMD", "COMMAND":
3563 return "Meta"
3564 default:
3565 return key
3566 }
3567}
3568
3569func normalizeButton(button string) (playwright.MouseButton, error) {
3570 switch button {
3571 case "left":
3572 return playwright.MouseButton("left"), nil
3573 case "wheel":
3574 return playwright.MouseButton("middle"), nil
3575 case "right":
3576 return playwright.MouseButton("right"), nil
3577 default:
3578 return "", fmt.Errorf("unsupported mouse button: %s", button)
3579 }
3580}
3581
3582func normalizeDragPath(path []responses.ComputerActionDragPath) [][2]int64 {
3583 result := make([][2]int64, len(path))
3584 for i, point := range path {
3585 result[i] = [2]int64{point.X, point.Y}
3586 }
3587 return result
3588}
3589
3590// withModifiers releases every successfully pressed key, even after an error.
3591func withModifiers(page playwright.Page, keys []string, operation func() error) (err error) {
3592 pressed := make([]string, 0, len(keys))
3593 defer func() {
3594 for i := len(pressed) - 1; i >= 0; i-- {
3595 err = errors.Join(err, page.Keyboard().Up(pressed[i]))
3596 }
3597 }()
3598 for _, key := range keys {
3599 key = normalizeKey(key)
3600 if err = page.Keyboard().Down(key); err != nil {
3601 return err
3602 }
3603 pressed = append(pressed, key)
3604 }
3605 return operation()
3606}
3607
3608func handleComputerActions(page playwright.Page, actions []responses.ComputerActionUnion) error {
3609 for _, action := range actions {
3610 var operation func() error
3611 switch action.Type {
3612 case "click":
3613 button, err := normalizeButton(action.Button)
3614 if err != nil {
3615 return err
3616 }
3617 operation = func() error {
3618 return page.Mouse().Click(
3619 float64(action.X), float64(action.Y),
3620 playwright.MouseClickOptions{Button: &button},
3621 )
3622 }
3623 case "double_click":
3624 operation = func() error {
3625 return page.Mouse().Dblclick(float64(action.X), float64(action.Y))
3626 }
3627 case "move":
3628 operation = func() error {
3629 return page.Mouse().Move(float64(action.X), float64(action.Y))
3630 }
3631 case "drag":
3632 path := normalizeDragPath(action.Path)
3633 if len(path) < 2 {
3634 return fmt.Errorf("drag requires at least two points")
3635 }
3636 operation = func() (err error) {
3637 if err = page.Mouse().Move(float64(path[0][0]), float64(path[0][1])); err != nil {
3638 return err
3639 }
3640 if err = page.Mouse().Down(); err != nil {
3641 return err
3642 }
3643 defer func() { err = errors.Join(err, page.Mouse().Up()) }()
3644 for _, point := range path[1:] {
3645 if err = page.Mouse().Move(float64(point[0]), float64(point[1])); err != nil {
3646 return err
3647 }
3648 }
3649 return nil
3650 }
3651 case "scroll":
3652 operation = func() error {
3653 if err := page.Mouse().Move(float64(action.X), float64(action.Y)); err != nil {
3654 return err
3655 }
3656 return page.Mouse().Wheel(float64(action.ScrollX), float64(action.ScrollY))
3657 }
3658 case "keypress":
3659 keys := make([]string, len(action.Keys))
3660 for i, key := range action.Keys {
3661 keys[i] = normalizeKey(key)
3662 }
3663 if len(keys) == 0 {
3664 return fmt.Errorf("keypress requires at least one key")
3665 }
3666 if err := page.Keyboard().Press(strings.Join(keys, "+")); err != nil {
3667 return err
3668 }
3669 continue
2327 case "type":3670 case "type":
2328 page.keyboard.type(action.text)3671 if err := page.Keyboard().InsertText(action.Text); err != nil {
3672 return err
3673 }
3674 continue
2329 case "wait":3675 case "wait":
2330 time.sleep(2)3676 time.Sleep(2 * time.Second)
2331 case "screenshot":
2332 # The caller captures a screenshot after every action.
2333 continue3677 continue
2334 case _:3678 case "screenshot":
2335 raise ValueError(f"Unsupported action: {action.type}")3679 continue // The caller captures the page after the batch.
3680 default:
3681 return fmt.Errorf("unsupported computer action: %s", action.Type)
3682 }
3683 if err := withModifiers(page, action.Keys, operation); err != nil {
3684 return err
3685 }
3686 }
3687 return nil
3688}
2336```3689```
2337 3690
2338```java3691```java
2429}3782}
2430```3783```
2431 3784
3785```csharp
3786using System;
3787using System.Collections.Generic;
3788using System.Diagnostics;
3789using System.IO;
3790using System.Linq;
3791using System.Runtime.ExceptionServices;
3792using System.Text.Json;
3793using System.Threading;
3794using System.Threading.Tasks;
3795using Microsoft.Playwright;
3796
3797internal static string NormalizeKey(string key) => key switch
3798{
3799 "ENTER" or "RETURN" => "Enter",
3800 "ESC" or "ESCAPE" => "Escape",
3801 "TAB" => "Tab",
3802 "SPACE" => "Space",
3803 "BACKSPACE" => "Backspace",
3804 "DELETE" or "DEL" => "Delete",
3805 "HOME" => "Home",
3806 "END" => "End",
3807 "PAGEUP" => "PageUp",
3808 "PAGEDOWN" => "PageDown",
3809 "UP" or "ARROWUP" => "ArrowUp",
3810 "DOWN" or "ARROWDOWN" => "ArrowDown",
3811 "LEFT" or "ARROWLEFT" => "ArrowLeft",
3812 "RIGHT" or "ARROWRIGHT" => "ArrowRight",
3813 "CTRL" or "CONTROL" => "Control",
3814 "SHIFT" => "Shift",
3815 "ALT" or "OPTION" => "Alt",
3816 "META" or "CMD" or "COMMAND" => "Meta",
3817 _ => key,
3818};
3819
3820internal static MouseButton NormalizeButton(string button) => button switch
3821{
3822 "left" => MouseButton.Left,
3823 "wheel" => MouseButton.Middle,
3824 "right" => MouseButton.Right,
3825 _ => throw new ArgumentException($"Unsupported mouse button: {button}", nameof(button)),
3826};
3827
3828internal static long[][] NormalizeDragPath(JsonElement path) => path.EnumerateArray()
3829 .Select(point => new[] { point.GetProperty("x").GetInt64(), point.GetProperty("y").GetInt64() })
3830 .ToArray();
3831
3832internal static async Task WithModifiersAsync(IPage page, IReadOnlyList<string> keys, Func<Task> operation)
3833{
3834 List<string> pressed = [];
3835 List<Exception> failures = [];
3836 try
3837 {
3838 foreach (string key in keys)
3839 {
3840 string normalized = NormalizeKey(key);
3841 await page.Keyboard.DownAsync(normalized);
3842 pressed.Add(normalized);
3843 }
3844 await operation();
3845 }
3846 catch (Exception error)
3847 {
3848 failures.Add(error);
3849 }
3850 finally
3851 {
3852 // Attempt every release, preserving both operation and cleanup errors.
3853 for (int i = pressed.Count - 1; i >= 0; i--)
3854 {
3855 try { await page.Keyboard.UpAsync(pressed[i]); }
3856 catch (Exception error) { failures.Add(error); }
3857 }
3858 }
3859 if (failures.Count != 0) throw new AggregateException(failures);
3860}
3861
3862// These JSON actions are application inputs, not missing OpenAI SDK types.
3863internal static async Task HandleComputerActionsAsync(IPage page, IEnumerable<JsonElement> actions)
3864{
3865 foreach (JsonElement action in actions)
3866 {
3867 string type = action.GetProperty("type").GetString()
3868 ?? throw new ArgumentException("Action type is required.");
3869 string[] keys = action.TryGetProperty("keys", out JsonElement keyValues)
3870 && keyValues.ValueKind != JsonValueKind.Null
3871 ? keyValues.EnumerateArray().Select(key => key.GetString()
3872 ?? throw new ArgumentException("Keys must be strings.")).ToArray() : [];
3873 Func<Task> operation;
3874 switch (type)
3875 {
3876 case "click":
3877 MouseButton button = NormalizeButton(action.GetProperty("button").GetString()
3878 ?? throw new ArgumentException("Button is required."));
3879 operation = () => page.Mouse.ClickAsync(action.GetProperty("x").GetInt64(),
3880 action.GetProperty("y").GetInt64(), new() { Button = button });
3881 break;
3882 case "double_click":
3883 operation = () => page.Mouse.DblClickAsync(
3884 action.GetProperty("x").GetInt64(),
3885 action.GetProperty("y").GetInt64());
3886 break;
3887 case "move":
3888 operation = () => page.Mouse.MoveAsync(
3889 action.GetProperty("x").GetInt64(),
3890 action.GetProperty("y").GetInt64());
3891 break;
3892 case "drag":
3893 long[][] path = NormalizeDragPath(action.GetProperty("path"));
3894 if (path.Length < 2) throw new ArgumentException("Drag requires at least two points.");
3895 operation = async () =>
3896 {
3897 await page.Mouse.MoveAsync(path[0][0], path[0][1]);
3898 await page.Mouse.DownAsync();
3899 Exception? operationError = null;
3900 try
3901 {
3902 foreach (long[] point in path.Skip(1)) await page.Mouse.MoveAsync(point[0], point[1]);
3903 }
3904 catch (Exception error)
3905 {
3906 operationError = error;
3907 }
3908 finally
3909 {
3910 try { await page.Mouse.UpAsync(); }
3911 catch (Exception releaseError)
3912 {
3913 operationError = operationError is null
3914 ? releaseError : new AggregateException(operationError, releaseError);
3915 }
3916 }
3917 if (operationError is not null) ExceptionDispatchInfo.Capture(operationError).Throw();
3918 };
3919 break;
3920 case "scroll":
3921 operation = async () =>
3922 {
3923 await page.Mouse.MoveAsync(
3924 action.GetProperty("x").GetInt64(),
3925 action.GetProperty("y").GetInt64());
3926 await page.Mouse.WheelAsync(
3927 action.GetProperty("scroll_x").GetInt64(),
3928 action.GetProperty("scroll_y").GetInt64());
3929 };
3930 break;
3931 case "keypress":
3932 if (keys.Length == 0) throw new ArgumentException("Keypress requires at least one key.");
3933 await page.Keyboard.PressAsync(string.Join("+", keys.Select(NormalizeKey)));
3934 continue;
3935 case "type":
3936 await page.Keyboard.InsertTextAsync(action.GetProperty("text").GetString()
3937 ?? throw new ArgumentException("Text is required."));
3938 continue;
3939 case "wait":
3940 await Task.Delay(TimeSpan.FromSeconds(2));
3941 continue;
3942 case "screenshot":
3943 continue; // The caller captures the page after the batch.
3944 default:
3945 throw new ArgumentException($"Unsupported computer action: {type}");
3946 }
3947 await WithModifiersAsync(page, keys, operation);
3948 }
3949}
3950```
3951
2432```ruby3952```ruby
2433def with_modifiers(page, keys)3953def with_modifiers(page, keys)
2434 pressed = []3954 pressed = []
2753 raise ValueError(f"Unsupported action: {action.type}")4273 raise ValueError(f"Unsupported action: {action.type}")
2754```4274```
2755 4275
4276```go
4277import (
4278 "errors"
4279 "fmt"
4280 "github.com/openai/openai-go/v3/responses"
4281 "time"
4282)
4283
4284func withModifiers(vm *VM, keys []string, operation func() error) (err error) {
4285 pressed := []string{}
4286 defer func() {
4287 // Attempt every release even if one release fails, retaining the original failure.
4288 for i := len(pressed) - 1; i >= 0; i-- {
4289 if releaseErr := vm.xdotool("keyup", pressed[i]); releaseErr != nil {
4290 err = errors.Join(err, releaseErr)
4291 }
4292 }
4293 }()
4294 for _, key := range keys {
4295 normalized := normalizeKey(key)
4296 pressed = append(pressed, normalized)
4297 if err = vm.xdotool("keydown", normalized); err != nil {
4298 return err
4299 }
4300 }
4301 return operation()
4302}
4303
4304func handleComputerActions(vm *VM, actions responses.ComputerActionList) error {
4305 for _, action := range actions {
4306 var operation func() error
4307 switch action.Type {
4308 case "click":
4309 button, err := normalizeButton(action.Button)
4310 if err != nil {
4311 return err
4312 }
4313 operation = func() error {
4314 return vm.xdotool("mousemove", "--sync", fmt.Sprint(action.X), fmt.Sprint(action.Y), "click", fmt.Sprint(button))
4315 }
4316 case "double_click":
4317 operation = func() error {
4318 return vm.xdotool(
4319 "mousemove", "--sync", fmt.Sprint(action.X), fmt.Sprint(action.Y),
4320 "click", "--repeat", "2", "--delay", "100", "1",
4321 )
4322 }
4323 case "move":
4324 operation = func() error { return vm.xdotool("mousemove", "--sync", fmt.Sprint(action.X), fmt.Sprint(action.Y)) }
4325 case "drag":
4326 path := normalizeDragPath(action.Path)
4327 if len(path) < 2 {
4328 return &InvalidInputError{"Drag requires at least two points"}
4329 }
4330 operation = func() (err error) {
4331 if err = vm.xdotool("mousemove", "--sync", fmt.Sprint(path[0][0]), fmt.Sprint(path[0][1])); err != nil {
4332 return err
4333 }
4334 defer func() { err = errors.Join(err, vm.xdotool("mouseup", "1")) }()
4335 if err = vm.xdotool("mousedown", "1"); err != nil {
4336 return err
4337 }
4338 for _, point := range path[1:] {
4339 if err = vm.xdotool("mousemove", "--sync", fmt.Sprint(point[0]), fmt.Sprint(point[1])); err != nil {
4340 return err
4341 }
4342 }
4343 return nil
4344 }
4345 case "scroll":
4346 operation = func() error {
4347 if err := vm.xdotool("mousemove", "--sync", fmt.Sprint(action.X), fmt.Sprint(action.Y)); err != nil {
4348 return err
4349 }
4350 for _, button := range scrollButtons(action.ScrollX, action.ScrollY) {
4351 if err := vm.xdotool("click", fmt.Sprint(button)); err != nil {
4352 return err
4353 }
4354 }
4355 return nil
4356 }
4357 case "keypress":
4358 if len(action.Keys) == 0 {
4359 return &InvalidInputError{"Keypress requires keys"}
4360 }
4361 // Keydown/up provides finally-based release for combinations, too.
4362 if err := withModifiers(vm, action.Keys, func() error { return nil }); err != nil {
4363 return err
4364 }
4365 continue
4366 case "type":
4367 if err := vm.xdotool("type", "--clearmodifiers", "--", action.Text); err != nil {
4368 return err
4369 }
4370 continue
4371 case "wait":
4372 time.Sleep(2 * time.Second)
4373 continue
4374 case "screenshot":
4375 // The caller captures once after the batch, including screenshot-only batches.
4376 continue
4377 default:
4378 return &InvalidInputError{"Unsupported computer action: " + action.Type}
4379 }
4380 if err := withModifiers(vm, action.Keys, operation); err != nil {
4381 return err
4382 }
4383 }
4384 return nil
4385}
4386```
4387
2756```java4388```java
2757import com.openai.core.ObjectMappers;4389import com.openai.core.ObjectMappers;
2758import com.openai.models.responses.ComputerAction;4390import com.openai.models.responses.ComputerAction;
2877}4509}
2878```4510```
2879 4511
4512```csharp
4513using System;
4514using System.Collections.Generic;
4515using System.Diagnostics;
4516using System.Globalization;
4517using System.IO;
4518using System.Linq;
4519using System.Runtime.ExceptionServices;
4520using System.Text;
4521using System.Text.Json;
4522using System.Text.Json.Serialization;
4523using System.Threading;
4524using System.Threading.Tasks;
4525
4526// Application-owned host messages, independent of the OpenAI SDK computer-tool surface.
4527internal sealed record ComputerAction
4528{
4529 [JsonPropertyName("type")]
4530 public required string Type { get; init; }
4531 [JsonPropertyName("button")]
4532 public string Button { get; init; } = "";
4533 [JsonPropertyName("x")]
4534 public long X { get; init; }
4535 [JsonPropertyName("y")]
4536 public long Y { get; init; }
4537 [JsonPropertyName("keys")]
4538 public string[] Keys { get; init; } = [];
4539 [JsonPropertyName("path")]
4540 public Point[] Path { get; init; } = [];
4541 [JsonPropertyName("scroll_x")]
4542 public long ScrollX { get; init; }
4543 [JsonPropertyName("scroll_y")]
4544 public long ScrollY { get; init; }
4545 [JsonPropertyName("text")]
4546 public string Text { get; init; } = "";
4547}
4548
4549internal static async Task WithModifiersAsync(VM vm, IReadOnlyList<string> keys, Func<Task> operation)
4550{
4551 List<string> pressed = [];
4552 List<Exception> failures = [];
4553 try
4554 {
4555 foreach (string key in keys)
4556 {
4557 string normalized = NormalizeKey(key);
4558 // A failed process may already have sent the keydown; release that key, too.
4559 pressed.Add(normalized);
4560 await XdotoolAsync(vm, "keydown", normalized);
4561 }
4562 await operation();
4563 }
4564 catch (Exception error)
4565 {
4566 failures.Add(error);
4567 }
4568 finally
4569 {
4570 for (int index = pressed.Count - 1; index >= 0; index--)
4571 {
4572 try
4573 {
4574 await XdotoolAsync(vm, "keyup", pressed[index]);
4575 }
4576 catch (Exception error)
4577 {
4578 failures.Add(error);
4579 }
4580 }
4581 }
4582 if (failures.Count == 1)
4583 {
4584 ExceptionDispatchInfo.Capture(failures[0]).Throw();
4585 }
4586 if (failures.Count > 1)
4587 {
4588 throw new AggregateException(failures);
4589 }
4590}
4591
4592internal static async Task HandleComputerActionsAsync(VM vm, IReadOnlyList<ComputerAction> actions)
4593{
4594 foreach (ComputerAction action in actions)
4595 {
4596 Func<Task> operation;
4597 switch (action.Type)
4598 {
4599 case "click":
4600 int button = NormalizeButton(action.Button);
4601 operation = () => XdotoolAsync(
4602 vm,
4603 "mousemove",
4604 "--sync",
4605 Number(action.X),
4606 Number(action.Y),
4607 "click",
4608 Number(button));
4609 break;
4610 case "double_click":
4611 operation = () => XdotoolAsync(
4612 vm,
4613 "mousemove",
4614 "--sync",
4615 Number(action.X),
4616 Number(action.Y),
4617 "click",
4618 "--repeat",
4619 "2",
4620 "--delay",
4621 "100",
4622 "1");
4623 break;
4624 case "move":
4625 operation = () => XdotoolAsync(vm, "mousemove", "--sync", Number(action.X), Number(action.Y));
4626 break;
4627 case "drag":
4628 long[][] path = NormalizeDragPath(action.Path);
4629 if (path.Length < 2)
4630 {
4631 throw new ArgumentException("Drag requires at least two points.", nameof(actions));
4632 }
4633 operation = async () =>
4634 {
4635 await XdotoolAsync(vm, "mousemove", "--sync", Number(path[0][0]), Number(path[0][1]));
4636 Exception? primaryFailure = null;
4637 try
4638 {
4639 await XdotoolAsync(vm, "mousedown", "1");
4640 foreach (long[] point in path.Skip(1))
4641 {
4642 await XdotoolAsync(vm, "mousemove", "--sync", Number(point[0]), Number(point[1]));
4643 }
4644 }
4645 catch (Exception error)
4646 {
4647 primaryFailure = error;
4648 }
4649 finally
4650 {
4651 try
4652 {
4653 await XdotoolAsync(vm, "mouseup", "1");
4654 }
4655 catch (Exception releaseFailure)
4656 {
4657 primaryFailure = primaryFailure is null
4658 ? releaseFailure
4659 : new AggregateException(primaryFailure, releaseFailure);
4660 }
4661 }
4662 if (primaryFailure is not null)
4663 {
4664 ExceptionDispatchInfo.Capture(primaryFailure).Throw();
4665 }
4666 };
4667 break;
4668 case "scroll":
4669 operation = async () =>
4670 {
4671 await XdotoolAsync(vm, "mousemove", "--sync", Number(action.X), Number(action.Y));
4672 foreach (int scrollButton in ScrollButtons(action.ScrollX, action.ScrollY))
4673 {
4674 await XdotoolAsync(vm, "click", Number(scrollButton));
4675 }
4676 };
4677 break;
4678 case "keypress":
4679 if (action.Keys.Length == 0)
4680 {
4681 throw new ArgumentException("Keypress requires keys.", nameof(actions));
4682 }
4683 await WithModifiersAsync(vm, action.Keys, () => Task.CompletedTask);
4684 continue;
4685 case "type":
4686 await XdotoolAsync(vm, "type", "--clearmodifiers", "--", action.Text);
4687 continue;
4688 case "wait":
4689 await Task.Delay(TimeSpan.FromSeconds(2));
4690 continue;
4691 case "screenshot":
4692 // Capture once after the action batch, in the caller.
4693 continue;
4694 default:
4695 throw new ArgumentException($"Unsupported computer action: {action.Type}", nameof(actions));
4696 }
4697 await WithModifiersAsync(vm, action.Keys, operation);
4698 }
4699}
4700
4701private static string Number(long value) => value.ToString(CultureInfo.InvariantCulture);
4702```
4703
2880```ruby4704```ruby
2881def with_modifiers(vm, keys)4705def with_modifiers(vm, keys)
2882 pressed = []4706 pressed = []
3327 return page.screenshot(type="png")5151 return page.screenshot(type="png")
3328```5152```
3329 5153
5154```go
5155import "github.com/playwright-community/playwright-go"
5156
5157func captureScreenshot(page playwright.Page) ([]byte, error) {
5158 format := playwright.ScreenshotType("png")
5159 return page.Screenshot(playwright.PageScreenshotOptions{Type: &format})
5160}
5161```
5162
3330```java5163```java
3331import com.microsoft.playwright.*;5164import com.microsoft.playwright.*;
3332import com.microsoft.playwright.options.*;5165import com.microsoft.playwright.options.*;
3341}5174}
3342```5175```
3343 5176
5177```csharp
5178using System;
5179using System.Collections.Generic;
5180using System.IO;
5181using System.Text.Json;
5182using System.Threading;
5183using System.Threading.Tasks;
5184using Microsoft.Playwright;
5185
5186internal static Task<byte[]> CaptureScreenshotAsync(IPage page) =>
5187 page.ScreenshotAsync(new() { Type = ScreenshotType.Png });
5188```
5189
3344```ruby5190```ruby
3345def capture_screenshot(page)5191def capture_screenshot(page)
3346 page.screenshot(type: "png")5192 page.screenshot(type: "png")
3381 )5227 )
3382```5228```
3383 5229
5230```go
5231import (
5232 "bytes"
5233 "fmt"
5234 "image/png"
5235)
5236
5237func captureScreenshot(vm *VM) ([]byte, error) {
5238 data, err := vm.dockerExec(
5239 "import",
5240 []string{"-window", "root", "png:-"},
5241 map[string]string{"DISPLAY": vm.Display},
5242 )
5243 if err != nil {
5244 return nil, err
5245 }
5246 if _, err := png.DecodeConfig(bytes.NewReader(data)); err != nil {
5247 return nil, fmt.Errorf("invalid screenshot PNG: %w", err)
5248 }
5249 return data, nil
5250}
5251```
5252
3384```java5253```java
3385import com.openai.core.ObjectMappers;5254import com.openai.core.ObjectMappers;
3386import java.nio.file.*;5255import java.nio.file.*;
3397}5266}
3398```5267```
3399 5268
5269```csharp
5270using System;
5271using System.Collections.Generic;
5272using System.Diagnostics;
5273using System.IO;
5274using System.Text;
5275using System.Text.Json;
5276using System.Threading;
5277using System.Threading.Tasks;
5278
5279internal static Task<byte[]> CaptureScreenshotAsync(VM vm) => DockerExecAsync(
5280 vm, "import", ["-window", "root", "png:-"],
5281 new Dictionary<string, string> { ["DISPLAY"] = vm.Display });
5282```
5283
3400```ruby5284```ruby
3401def capture_screenshot(vm)5285def capture_screenshot(vm)
3402 docker_exec(5286 docker_exec(