-- ============================================================ -- OpenCode -> ComputerCraft agent -- Polls your Cloudflare Worker for commands, executes them here, -- and posts the result back so OpenCode (via the MCP server) sees it. -- ============================================================ local CONFIG = { DOMAIN = "https://opencode.katermering.com", TOKEN = "CC-9f4c21ab7e5d8b3046c1f7a2e5b8d904", POLL_INTERVAL = 30, -- SAFETY-NET poll only; commands arrive over the -- persistent WebSocket instantly. Kept slow to stay -- well under the free 100k req/day account cap. REGISTER_EVERY = 30, -- (legacy) polls between /register heartbeats MAX_OUTPUT = 4000, -- truncate results LABEL = nil, -- optional friendly name } if not http then error("HTTP API is disabled. Enable it in the server config (http.enabled=true) and reboot.", 0) end local COMPUTER_ID = tostring(os.getComputerID()) local CURRENT_ID = nil local headers = { ["X-CC-Token"] = CONFIG.TOKEN, ["Content-Type"] = "application/json" } local function jsonEncode(t) return textutils.serialiseJSON(t) end local function jsonDecode(s) local ok, t = pcall(textutils.unserialiseJSON, s) return ok and t or nil end local function trim(s) return (tostring(s):gsub("^%s+", ""):gsub("%s+$", "")) end local function httpGet(path, timeout) local ok, resp = pcall(http.get, CONFIG.DOMAIN .. path, headers, false, false, timeout or 8000) if not ok or not resp then return nil end local body = resp.readAll(); resp.close() return jsonDecode(body) end local function httpPost(path, tbl, timeout) local ok, resp = pcall(http.post, CONFIG.DOMAIN .. path, jsonEncode(tbl), headers, false, false, timeout or 10000) if not ok or not resp then return nil end local body = resp.readAll(); resp.close() return jsonDecode(body) end -- ---------- output capture ---------- local function capture(fn, ...) local out = {} local cap = setmetatable({}, { __index = term }) function cap.write(s) out[#out + 1] = tostring(s or "") end function cap.setTextColor() end function cap.setBackgroundColor() end function cap.setCursorPos() end function cap.setCursorBlink() end function cap.clear() end function cap.clearLine() end function cap.scroll() end function cap.getSize() return 51, 19 end local prev = term.current() term.redirect(cap) local ok, res = pcall(fn, ...) term.redirect(prev) return ok, table.concat(out), res end local function tokenize(line) local args = {} for word in tostring(line):gmatch("[^%s]+") do args[#args + 1] = word end return args end local function truncate(s) s = tostring(s or "") if #s > CONFIG.MAX_OUTPUT then return s:sub(1, CONFIG.MAX_OUTPUT) .. "\n...[truncated " .. (#s - CONFIG.MAX_OUTPUT) .. " chars]" end return s end -- ---------- actions ---------- local actions = {} function actions.say(args) print(tostring(args.text or "")) return true, tostring(args.text or "") end function actions.run(args) local argv = args.argv if not argv then argv = tokenize(args.command or "") end if #argv == 0 then return false, "no command" end if not shell then return false, "shell unavailable in agent env" end local unpackFn = table.unpack or unpack pcall(sleep, 0) local ok, output, res = capture(function() return shell.run(unpackFn(argv)) end) if not ok then return false, "run error: " .. tostring(res) end return true, tostring(output) end actions.shell = actions.run function actions.lua(args) local code = args.code or args.text or "" local chunk, err = load(code, "=opencode", "t") if not chunk then return false, "compile error: " .. tostring(err) end local printed = {} local cap = setmetatable({}, { __index = term }) function cap.write(s) printed[#printed + 1] = tostring(s or "") end function cap.setTextColor() end function cap.setBackgroundColor() end function cap.setCursorPos() end function cap.scroll() end function cap.clearLine() end function cap.getSize() return 51, 19 end local prev = term.current() term.redirect(cap) local packed = table.pack(pcall(chunk)) term.redirect(prev) if not packed[1] then return false, "runtime error: " .. tostring(packed[2]) end local returns = {} for i = 2, packed.n do returns[#returns + 1] = tostring(packed[i]) end local body = table.concat(printed) if #returns > 0 then body = body .. (body ~= "" and "\n" or "") .. "return: " .. table.concat(returns, ", ") end return true, body end actions.eval = actions.lua function actions.read(args) local path = args.path if not path then return false, "path required" end if not fs.exists(path) then return false, "no such file: " .. path end local fh = fs.open(path, "r") if not fh then return false, "cannot open " .. path end local data = fh.readAll(); fh.close() return true, data end function actions.write(args) local path = args.path if not path then return false, "path required" end local dir = fs.getDir(path) if dir and dir ~= "" and not fs.exists(dir) then fs.makeDir(dir) end local fh = fs.open(path, args.append and "a" or "w") if not fh then return false, "cannot write " .. path end fh.write(tostring(args.content or "")); fh.close() return true, "wrote " .. path end function actions.ls(args) local path = args.path or "/" local ok, entries = pcall(fs.list, path) if not ok then return false, "cannot list " .. path end table.sort(entries) return true, table.concat(entries, "\n") end function actions.redstone(args) local side = args.side or "top" local value = args.value if value == nil then return false, "value required (on/off/toggle/pulse/number)" end if value == "toggle" then local cur = redstone.getOutput(side) redstone.setOutput(side, not cur) return true, side .. "=" .. tostring(not cur) elseif value == "pulse" then redstone.setOutput(side, true); sleep(0.5); redstone.setOutput(side, false) return true, "pulsed " .. side elseif value == "on" or value == true then redstone.setOutput(side, true); return true, side .. "=true" elseif value == "off" or value == false then redstone.setOutput(side, false); return true, side .. "=false" elseif tonumber(value) then redstone.setAnalogOutput(side, tonumber(value)); return true, side .. "=" .. tostring(value) end return false, "bad value" end function actions.peripherals() local names = peripheral.getNames() table.sort(names) return true, table.concat(names, "\n") end function actions.info() local info = { id = COMPUTER_ID, label = os.getComputerLabel() or "", day = os.day(), time = textutils.formatTime(os.time(), true), } return true, jsonEncode(info) end function actions.sleep(args) sleep(tonumber(args.seconds) or 1) return true, "slept" end function actions.command(args) if not commands then return false, "command computer required" end local ok, err = pcall(commands.exec, tostring(args.command or "")) return ok, ok and "executed" or tostring(err) end function actions.reboot() pcall(function() httpPost("/result", { id = CURRENT_ID, ok = true, output = "rebooting" }) end) sleep(0.5) os.reboot() end -- ---------- reporting ---------- local function report(id, ok, output) if id == nil then return end output = truncate(output) httpPost("/result", { id = id, ok = ok and true or false, output = output }) end local function register() httpPost("/register", { computer = COMPUTER_ID, info = { label = CONFIG.LABEL or os.getComputerLabel() or "", id = tonumber(COMPUTER_ID) }, }) end local function execute(action, args) local fn = actions[action] if not fn then return false, "unknown action: " .. tostring(action) end local packed = table.pack(pcall(fn, args or {})) if not packed[1] then return false, "error: " .. tostring(packed[2]) end return packed[2], packed[3] end -- ---------- transports ---------- -- Primary: a persistent WebSocket (instant push, ~no HTTP requests). -- Fallback: slow HTTP polling in case the socket is down. local WS_URL = (CONFIG.DOMAIN:gsub("^http", "ws")) .. "/ws?id=" .. COMPUTER_ID local wsUp = false local wsRef = nil local function sendWS(tbl) if wsRef then pcall(function() wsRef.send(jsonEncode(tbl)) end) end end local function reportResult(id, ok, output) if id == nil then return end if wsUp and wsRef then sendWS({ type = "result", id = id, ok = ok and true or false, output = truncate(output), computer = COMPUTER_ID }) else report(id, ok, output) end end local function handleCmd(data) if not (data and data.id) then return end CURRENT_ID = data.id pcall(print, "> " .. tostring(data.action)) local ok, output = execute(data.action, data.args) reportResult(data.id, ok, output) CURRENT_ID = nil end -- One bad command must never take the agent down. local function safeHandle(data) local ok, err = pcall(handleCmd, data) if not ok then pcall(reportResult, data and data.id, false, "agent error: " .. tostring(err)) end end local function wsLoop() while true do local conn = nil pcall(function() local okc, ws = pcall(http.websocket, WS_URL, headers) if okc and ws then conn = ws wsRef = ws wsUp = true sendWS({ type = "register", computer = COMPUTER_ID, info = { label = CONFIG.LABEL or os.getComputerLabel() or "", id = tonumber(COMPUTER_ID) } }) while true do local msg = ws.receive() if msg == nil then break end local data = jsonDecode(msg) if data and data.type == "command" then safeHandle(data) end end end end) wsUp = false wsRef = nil if conn then pcall(function() conn.close() end) end sleep(3) end end local function pollLoop() while true do pcall(function() local cmd = httpGet("/poll?id=" .. COMPUTER_ID) if cmd and cmd.id then safeHandle(cmd) end end) sleep(CONFIG.POLL_INTERVAL) end end -- ---------- main ---------- local function main() term.clear(); term.setCursorPos(1, 1) print("OpenCode CC agent") print("Computer #" .. COMPUTER_ID) print("Endpoint: " .. CONFIG.DOMAIN) register() if type(http.websocket) == "function" then print("Listening (wss + slow poll)...") parallel.waitForAny(wsLoop, pollLoop) else print("Listening (poll only)...") pollLoop() end end local ok, err = pcall(main) if not ok then term.setTextColor(colors.red) print("agent crashed: " .. tostring(err)) term.setTextColor(colors.white) end