Dashboard › opencode › Distillation
9abdb58e-824a-47cd-b12b-888b6138fd1b["lore_tm_v1_16K-DBWCd5QLShZG_AH8lXdhMv_BbyH_FS_da5lj2aQ","lore_tm_v1_2cBR9krmqc8u_tyoFUFWrlPRMtSnFgiq-M8cDDmGHzw","lore_tm_v1_400cIEEDLC6rRmAXI1-xOfBuNKJ0zVaryBCpkHZjhJI","lore_tm_v1_cw89LpHDu-MaJUuz0qd0N_KhCYnHQb5-S1OcQ3yNcv4","lore_tm_v1_pzmEafMF2ajG1HHy2D2txIRKI85ASSxcZhE8q5xRbHg","lore_tm_v1_vp2999cvp_tEK6JN1fGDRXcuac0r0H8dhnbObRAMKIM"]
Date: Sep 8, 2026
cmd/launcher/main.go defines encodedArgumentsEnvironment = "OPENCODE_PTY_ARGV" and launcherFD = 3. run(values) supports an internal exact --exec mode; otherwise it validates encoded arguments, changes directory with syscall.Fchdir(2), duplicates stdout fd 1 onto fd 2, installs a fixed environment, stores encoded argv joined by "." in OPENCODE_PTY_ARGV, binds the launcher executable to fd 3, and execs /usr/bin/script (cmd/launcher/main.go:16-50).cmd/launcher/main.go uses fd 2 initially as the approved cwd descriptor rather than stderr: after Fchdir(2), Dup2(1, 2) restores stderr to the PTY stream. Failure messages are "fchdir approved cwd: %w" and "replace cwd descriptor: %w" (cmd/launcher/main.go:34-39).execCommand() in cmd/launcher/main.go requires nonempty OPENCODE_PTY_ARGV, splits it on ".", validates/decodes argv again, reapplies the fixed environment, closes launcherFD 3, and calls syscall.Exec(command[0], command, os.Environ()) (cmd/launcher/main.go:52-68).bindLauncher() opens /proc/self/exe with unix.O_RDONLY|unix.O_CLOEXEC; if the returned fd is not 3, it uses unix.Dup3(fd, launcherFD, 0), and if it is already 3, it clears close-on-exec using unix.FcntlInt(uintptr(fd), unix.F_SETFD, 0) (cmd/launcher/main.go:70-86).1 and protocol.MaxArgs+1 values, each prefixed by literal "a" and containing only canonical unpadded base64url characters [A-Za-z0-9_-]. The command uses protocol.MaxCommandSize; later values use protocol.MaxArgSize; aggregate argument bytes must not exceed protocol.MaxArgsSize; decoded NUL bytes and an empty command are rejected (cmd/launcher/main.go:88-123).setFixedEnvironment() in cmd/launcher/main.go calls os.Clearenv() and sets exactly: HOME=/home/byk, LANG=C.UTF-8, LOGNAME=byk, PATH=/usr/local/bin:/usr/bin:/bin, SHELL=/bin/sh, TERM=xterm-256color, and USER=byk (cmd/launcher/main.go:125-141).scriptArguments() returns exactly {"script", "-q", "-e", "-f", "-c", "/bin/sh -i -c 'exec /proc/self/fd/3 --exec'", "/dev/null"}, causing /usr/bin/script to provide the interactive PTY and re-enter the bound launcher through /proc/self/fd/3 (cmd/launcher/main.go:143-145).cmd/client/main.go assigns inherited socketFD = 3 and cwdFD = 4. sendStart() marks both close-on-exec, validates fd 3 as a connected socket via unix.Getpeername, validates fd 4 as a directory via unix.Fstat and unix.S_IFDIR, and includes the directory’s exact stat.Dev and stat.Ino in the decoded protocol.Start (cmd/client/main.go:17-45).TypeStart protocol frame and initially sends it with the cwd descriptor via unix.SendmsgN(socket, packet, unix.UnixRights(cwd), nil, unix.MSG_NOSIGNAL). If only part of the frame is sent, it completes the write with repeated unix.Write; a zero-byte write returns syscall.EIO (cmd/client/main.go:46-69).decodeStart() requires metadata count from 2 through protocol.MaxArgs+2, parses runtime as unsigned base-10 32-bit data, and rejects values above protocol.MaxRuntimeSec. Command/argument encoding uses the same "a"-prefixed canonical unpadded base64url grammar and byte limits as the launcher, returning protocol.Start{Device: device, Inode: inode, RuntimeSec: uint32(runtime), Command: decoded[0], Args: decoded[1:]} (cmd/client/main.go:71-107).internal/protocol/frame.go defines HeaderSize = 12, MaxFrameSize = 70 * 1024, MaxIOPayloadSize = 32 * 1024, Version = 1, frame types in exact order TypeStart=1, TypeInput=2, TypeOutput=3, TypeExit=4, TypeError=5, TypeStarted=6, TypeStop=7, and TypeStopped=8; argument limits are MaxArgs=128, MaxCommandSize=4096, MaxArgSize=16384, MaxArgsSize=65536, and MaxRuntimeSec=3600 (internal/protocol/frame.go:12-32).OPTY, version byte at offset 4, type byte at offset 5, reserved zero bytes at offsets 6-7, and a big-endian uint32 payload length at offsets 8-11. parseHeader() rejects malformed magic/version/reserved bytes, payloads above MaxFrameSize, and types outside TypeStart through TypeStopped (internal/protocol/frame.go:34-38,199-210).ReadFrame() uses io.ReadFull for both the 12-byte header and declared payload. WriteFrame() and MarshalFrame() enforce MaxFrameSize; writeAll() retries partial writes and returns io.ErrShortWrite on a zero-byte write. ParsePacket() additionally requires packet length to equal exactly HeaderSize+length (internal/protocol/frame.go:53-82,172-225).Start payload layout is: bytes 0:8 device uint64, 8:16 inode uint64, 16:20 runtime uint32, 20:22 command-length uint16, 22:24 argument-count uint16, command bytes, then each argument as a uint16 length followed by bytes. All integer fields are big-endian (internal/protocol/frame.go:84-118).EncodeStart() and DecodeStart() require a nonempty valid UTF-8 command without NUL, a command length of at most 4096, at most 128 arguments, each argument valid UTF-8 without NUL and at most 16384 bytes, aggregate argument data at most 65536 bytes, runtime at most 3600, and no trailing payload bytes. Oversized total payload returns ErrFrameTooLarge; structural/content violations return ErrInvalidFrame (internal/protocol/frame.go:84-169).cmd/supervisor/main.go creates a root context canceled by SIGINT or SIGTERM, initializes supervisor.NewSystemdManager(ctx), defers manager.Close(), constructs supervisor.NewServer(manager), and runs server.Serve(ctx); initialization or serving errors are printed to stderr and exit status 1 (cmd/supervisor/main.go:13-31).config/opencode/plugins/pty-transport.ts mirrors protocol constants MAGIC="OPTY", VERSION=1, HEADER_SIZE=12, MAX_FRAME_SIZE=70*1024, MAX_IO_PAYLOAD_SIZE=32*1024, and frame types 2 through 8. Defaults are socket /run/opencode-pty/supervisor.sock, helper /usr/local/libexec/opencode-pty-client, HELPER_TIMEOUT_MS=5_000, STOP_TIMEOUT_MS=25_000, and MAX_HELPER_ERROR_BYTES=2_000; unit names must match /^opencode-pty-[0-9a-f]{32}\.service$/ (config/opencode/plugins/pty-transport.ts:10-27).SupervisorTransport exposes unitName, async write(data), async close(), exited: Promise<SupervisorExit>, and onOutput(listener); SupervisorExit contains result, execMainCode, and execMainStatus. SupervisorOptions permits overriding socketPath, helperPath, and verifyRootHelper (config/opencode/plugins/pty-transport.ts:29-47).assertSupervisorAvailable() skips helper verification only when verifyRootHelper === false; otherwise the helper must be a root-owned regular file, have no group/world write bits (mode & 0o022 must be zero), and have at least one executable bit (mode & 0o111). It then verifies connectivity to the supervisor socket and validates access to its fd (config/opencode/plugins/pty-transport.ts:49-58).openSupervisorTransport() buffers output frames until onOutput() installs a listener. Incoming frame parsing validates magic, version, reserved bytes, and payload size; TYPE_OUTPUT requires 1..32*1024 bytes, TYPE_STARTED requires one nonempty valid UTF-8 unit name matching UNIT_NAME, and TYPE_ERROR requires nonempty valid UTF-8 payload no larger than MAX_IO_PAYLOAD_SIZE (config/opencode/plugins/pty-transport.ts:60-128,179-188).TYPE_EXIT payload requires at least 9 bytes: byte 0 is execMainCode, bytes 1:5 are big-endian execMainStatus, bytes 5:9 are big-endian result-string length, and bytes from 9 are valid UTF-8 result text. TYPE_STOPPED requires empty payload and a locally initiated stop, and resolves as {execMainCode: 2, execMainStatus: 15, result: "stopped"} (config/opencode/plugins/pty-transport.ts:129-146).[String(runtimeSeconds), "a"+base64url(command), ...encoded args] and stdio ["pipe","pipe","pipe",connectedSocketFD(socket),binding.fd]. Helper completion and the subsequent TYPE_STARTED acknowledgment each have a 5_000 ms timeout; helper stderr capture is limited to 2_000 bytes and a timeout sends SIGKILL (config/opencode/plugins/pty-transport.ts:153-178,274-295).MAX_IO_PAYLOAD_SIZE = 32*1024, wrap each in TYPE_INPUT, and apply HELPER_TIMEOUT_MS = 5_000. close() sends one empty TYPE_STOP if needed, waits up to STOP_TIMEOUT_MS = 25_000 for structured exit, destroys the socket on failure, and waits for socket closure (config/opencode/plugins/pty-transport.ts:189-208).connectedSocketFD() intentionally accesses Node’s private socket._handle.fd using Reflect.get, requires a nonnegative integer fd, and verifies it with fstatSync(fd).isSocket(). Missing runtime exposure raises "Node runtime does not expose the connected Unix socket descriptor."; invalid values raise "Node runtime returned an invalid connected Unix socket descriptor." (config/opencode/plugins/pty-transport.ts:211-223).config/opencode/plugins/pty.ts limits are: MAX_BUFFER_SIZE=1_000_000, MAX_SESSIONS=16, MAX_SESSIONS_PER_OWNER=5, DEFAULT_READ_LIMIT=500, MAX_READ_LIMIT=2_000, MAX_READ_OFFSET=10_000, MAX_LINE_LENGTH=2_000, MAX_PATTERN_LENGTH=500, MAX_WRITE_SIZE=65_536, MAX_TIMEOUT_SECONDS=3_600, CLOSE_TIMEOUT_MS=27_000, NOTIFICATION_TIMEOUT_MS=5_000, MAX_COMMAND_LENGTH=4_096, MAX_ARGUMENTS=128, MAX_ARGUMENT_LENGTH=16_384, MAX_ARGUMENT_BYTES=65_536, MAX_PATH_LENGTH=4_096, MAX_TITLE_LENGTH=500, MAX_DESCRIPTION_LENGTH=2_000, and MAX_REGEX_WORKERS=4 (config/opencode/plugins/pty.ts:17-36).local-pty plugin installs 5 tools in exact order: 1. pty_spawn—starts a background interactive command, permission "shell"; 2. pty_write—writes decoded input/control characters, permission "shell"; 3. pty_read—reads by line range or extended-regex match; 4. pty_list—lists the caller’s sessions; 5. pty_kill—stops and optionally removes a session, permission "shell" (config/opencode/plugins/pty.ts:120-381).pty_spawn inputs are command, args, optional workdir, optional title, required nonempty description, optional notifyOnExit, and optional positive timeoutSeconds <= 3_600. Its description states: "Start an interactive command in a background PTY. When notifyOnExit is true, a synthetic Session input reports the process exit." (config/opencode/plugins/pty.ts:37-56)."running" | "killing" | "killed" | "exited". Stored session data includes ownership via parentSessionID, systemd unitName, command/args/workdir, timeout and notification settings, exit code/signal, creation timestamp, transport, close/termination promises, timer, and a rolling output buffer (config/opencode/plugins/pty.ts:90-118).16, and one parent Session cannot exceed 5. At the owner limit, one inactive "exited" or "killed" session may be evicted; if none exists, spawning fails. Pending spawns are tracked globally and per owner to coordinate deletion and plugin shutdown (config/opencode/plugins/pty.ts:125-135,198-285).pty_${crypto.randomUUID().replaceAll("-", "").slice(0, 8)}; default title is the command and space-joined arguments; output is appended then truncated to the last 1_000_000 characters. Exit result "timeout" sets timedOut=true; execMainCode===1 maps status to exitCode, while codes 2 or 3 map status to exitSignal (config/opencode/plugins/pty.ts:217-269).notifyOnExit is true, the plugin is not closing, and the parent Session has not been deleted. The synthetic event uses description PTY exited: ${truncate(description, 100)}, delivery "steer", and JSON fields type:"pty.exit", id, description truncated to 100, exitCode, exitSignal, timeoutSeconds, timedOut, outputLines, and last nonblank line truncated to 200; timeout is 5_000 ms (config/opencode/plugins/pty.ts:154-189).pty_write decodes only \\n, \\r, \\t, \\xNN, \\uNNNN, and \\\\, then enforces a post-decoding UTF-8 byte limit of 65_536. It performs shell permission approval before re-fetching the owned session and writing, preventing use if session state changed during approval (config/opencode/plugins/pty.ts:58-63,289-307,468-477).pty_read defaults to offset 0 and limit 500, permits limits through 2_000, offsets through 10_000, and patterns through 500 characters. It allows at most 4 concurrent regex workers, requests offset+limit+1 matches to determine pagination, truncates each returned line to 2_000 characters, and returns totalLines, hasMore, and optional nextOffset (config/opencode/plugins/pty.ts:65-79,309-345)./usr/bin/grep with ["-a","-m",String(limit),"-nE",...(ignoreCase?["-i"]:[]),"--",pattern], kills it after 250 ms, caps stdout retention at MAX_BUFFER_SIZE*2 and stderr at MAX_LINE_LENGTH, treats exit code 1 as no matches, and parses output as lineNumber:text (config/opencode/plugins/pty.ts:593-631).pty_kill rechecks ownership after shell permission approval. With cleanup=true, it terminates, deletes the session, and clears its buffer; otherwise it clears a timer, terminates only "running" or "killing" sessions, and retains metadata/output. terminate() is idempotent, changes status to "killing", closes transport, and requires session.closed within CLOSE_TIMEOUT_MS=27_000 (config/opencode/plugins/pty.ts:360-380,483-503).session.deleted, the plugin marks the parent ID deleted, waits for that owner’s pending spawns, then removes all owned sessions. Plugin teardown sets closing=true, aborts event subscription, and awaits all pending spawns, session removals, and pending notifications using Promise.allSettled, logging rejected cleanup operations (config/opencode/plugins/pty.ts:383-415).authorize() canonicalizes both requested workdir and project directory with realpath; workdirs outside the project require external_directory permission. It separately requests shell permission for a single-quoted escaped command line, re-resolves workdir after approval to detect changes, opens it with O_RDONLY|O_DIRECTORY|O_NOFOLLOW, verifies the handle is a directory, and checks /proc/self/fd/${handle.fd} still resolves to the approved directory (config/opencode/plugins/pty.ts:479-481,505-545).validateCommand() enforces nonempty command, at most 128 arguments, command UTF-8 byte length at most 4_096, each argument at most 16_384 UTF-8 bytes, and aggregate argument bytes at most 65_536; its oversized-argument error identifies the zero-based argument index (config/opencode/plugins/pty.ts:547-561).requireSession() enforces parent-Session ownership and otherwise returns "PTY session not found: <id>". assertShell() represents stdin writes as <quoted command> <stdin> <quoted input> in the shell permission resource, while kill approval uses only the quoted command (config/opencode/plugins/pty.ts:426-430,563-574).