Buckets:
| ; | |
| /** | |
| * opencode.ts — OpenCode support: plugin install and transcript reads. | |
| * | |
| * OpenCode has no Claude-style hooks; it loads JS plugins that run inside its | |
| * process. `crew install-hook` writes a small generated plugin into the global | |
| * plugins directory. The plugin is a thin adapter: it shells back out to | |
| * `crew --hook` with the same hook payloads Claude and Codex send, injects the | |
| * returned additionalContext through OpenCode's mutable hook outputs, and tags | |
| * shell commands with CREW_SESSION_ID so `crew send` attributes correctly even | |
| * though one OpenCode process hosts many sessions. All behavior stays in the | |
| * crew CLI, so upgrading crew upgrades live plugins without a reinstall. | |
| * | |
| * Transcripts live in OpenCode's SQLite store (message/part tables). Like the | |
| * Codex rollout, the schema is a convenience input, not a stable API: reads go | |
| * through the `sqlite3` CLI (ships with macOS, common elsewhere) and degrade | |
| * to an empty transcript when the binary or tables are missing. | |
| */ | |
| Object.defineProperty(exports, "__esModule", { value: true }); | |
| exports.OPENCODE_PLUGIN_MARKER = void 0; | |
| exports.opencodePluginVersion = opencodePluginVersion; | |
| exports.opencodePluginPath = opencodePluginPath; | |
| exports.opencodeDbPath = opencodeDbPath; | |
| exports.parseOpencodeTranscript = parseOpencodeTranscript; | |
| exports.opencodePluginSource = opencodePluginSource; | |
| const node_child_process_1 = require("node:child_process"); | |
| const node_path_1 = require("node:path"); | |
| const node_os_1 = require("node:os"); | |
| const home_1 = require("./home"); | |
| const transcript_1 = require("./transcript"); | |
| exports.OPENCODE_PLUGIN_MARKER = "generated by @0xmmo/crew"; | |
| /** The crew version stamped into a generated plugin, or null if unstamped. */ | |
| function opencodePluginVersion(source) { | |
| const m = /^\/\/ crew (\S+) — generated by @0xmmo\/crew/m.exec(source); | |
| return m ? m[1] : null; | |
| } | |
| function xdgConfigHome() { | |
| return process.env.XDG_CONFIG_HOME || (0, node_path_1.join)((0, node_os_1.homedir)(), ".config"); | |
| } | |
| function xdgDataHome() { | |
| return process.env.XDG_DATA_HOME || (0, node_path_1.join)((0, node_os_1.homedir)(), ".local", "share"); | |
| } | |
| /** The generated plugin's location in OpenCode's global plugins directory. */ | |
| function opencodePluginPath() { | |
| return (0, node_path_1.join)(xdgConfigHome(), "opencode", "plugins", "crew.js"); | |
| } | |
| function opencodeDbPath() { | |
| return (0, node_path_1.join)(xdgDataHome(), "opencode", "opencode.db"); | |
| } | |
| function queryDb(sessionId) { | |
| // No parameter binding through the sqlite3 CLI; ids are validated instead. | |
| if (!/^[a-zA-Z0-9_-]+$/.test(sessionId)) | |
| return []; | |
| const sql = "SELECT m.time_created AS t, m.data AS message, " + | |
| "(SELECT json_group_array(json(data)) FROM " + | |
| "(SELECT data FROM part WHERE message_id = m.id ORDER BY id)) AS parts " + | |
| `FROM message m WHERE m.session_id = '${sessionId}' ` + | |
| "ORDER BY m.time_created, m.id"; | |
| try { | |
| const out = (0, node_child_process_1.execFileSync)("sqlite3", ["-readonly", "-json", opencodeDbPath(), sql], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }); | |
| const rows = out.trim() ? JSON.parse(out) : []; | |
| return Array.isArray(rows) ? rows : []; | |
| } | |
| catch { | |
| return []; // sqlite3 missing, db locked/absent, or schema drift | |
| } | |
| } | |
| /** Parse an OpenCode session's history out of its SQLite store. */ | |
| function parseOpencodeTranscript(sessionId) { | |
| const out = { recap: null, total: 0, entries: [] }; | |
| if (!sessionId) | |
| return out; | |
| for (const row of queryDb(sessionId)) { | |
| let role = "assistant"; | |
| try { | |
| role = JSON.parse(row.message)?.role ?? "assistant"; | |
| } | |
| catch { | |
| continue; | |
| } | |
| const ts = Number.isFinite(row.t) ? new Date(row.t).toISOString() : null; | |
| let parts; | |
| try { | |
| parts = JSON.parse(row.parts); | |
| } | |
| catch { | |
| continue; | |
| } | |
| if (!Array.isArray(parts)) | |
| continue; | |
| for (const p of parts) { | |
| if (!p || typeof p !== "object") | |
| continue; | |
| if (p.type === "text") { | |
| if (p.synthetic || p.ignored) | |
| continue; // crew's own injections etc. | |
| const text = (0, transcript_1.clean)(String(p.text ?? "")); | |
| if (!text) | |
| continue; | |
| out.entries.push({ ts, role, kind: "text", text }); | |
| out.total++; | |
| } | |
| else if (p.type === "tool") { | |
| const state = p.state ?? {}; | |
| out.entries.push({ | |
| ts, | |
| role: "assistant", | |
| kind: "tool_use", | |
| name: String(p.tool ?? "?"), | |
| summary: (0, transcript_1.toolInputSummary)(state.input), | |
| }); | |
| out.total++; | |
| const result = (0, transcript_1.clean)(String(state.output ?? state.error ?? "")); | |
| if (result) { | |
| out.entries.push({ ts, role: "tool", kind: "tool_result", text: result }); | |
| out.total++; | |
| } | |
| } | |
| // reasoning / step-start / step-finish / file / patch: not user-visible | |
| } | |
| } | |
| return out; | |
| } | |
| // ---------- generated plugin ---------- | |
| /** | |
| * The plugin source written to opencodePluginPath(). `nodeBin`/`crewScript` | |
| * are resolved at install time so the plugin works regardless of PATH inside | |
| * OpenCode. Every failure path is swallowed: a broken crew must never break | |
| * an OpenCode session. | |
| */ | |
| function opencodePluginSource(nodeBin, crewScript) { | |
| return `// crew ${(0, home_1.crewVersion)()} — ${exports.OPENCODE_PLUGIN_MARKER}; \`crew uninstall-hook\` removes it. | |
| // Bridges OpenCode to \`crew --hook\`: shared session context, mail delivery, | |
| // and kickstart wake-ups. Regenerate with \`crew install-hook\` after moving | |
| // node or crew. Do not edit by hand. | |
| import { spawn } from "node:child_process" | |
| import { existsSync, readdirSync } from "node:fs" | |
| import { join } from "node:path" | |
| // Baked at install time, but neither path is guaranteed to survive: a node | |
| // upgrade removes a version-pinned bin, and the crew script moves if it was | |
| // installed from a checkout. Both fall back to PATH lookups. | |
| const BAKED_NODE = ${JSON.stringify(nodeBin)} | |
| const BAKED_CREW = ${JSON.stringify(crewScript)} | |
| const NODE = existsSync(BAKED_NODE) ? BAKED_NODE : "node" | |
| const CREW = existsSync(BAKED_CREW) ? BAKED_CREW : null | |
| // Mailbox roots as crew itself resolved them, rather than a second guess at | |
| // /tmp/crew-<uid> that could drift from the CLI's. \`crew install-hook\` | |
| // re-bakes them; a runtime CREW_INBOX_ROOT is added ahead of them. | |
| const BAKED_INBOX_ROOTS = ${JSON.stringify((0, home_1.inboxRoots)())} | |
| const INBOX_ROOTS = (process.env.CREW_INBOX_ROOT ? [process.env.CREW_INBOX_ROOT] : []) | |
| .concat(BAKED_INBOX_ROOTS) | |
| const POLL_MS = 15000 | |
| function crewHook(event, sessionID, cwd) { | |
| return new Promise((resolve) => { | |
| try { | |
| const cmd = CREW ? NODE : "crew" | |
| const args = CREW ? [CREW, "--hook"] : ["--hook"] | |
| const child = spawn(cmd, args, { | |
| env: { ...process.env, CREW_AGENT: "opencode", CREW_PID: String(process.pid) }, | |
| stdio: ["pipe", "pipe", "ignore"], | |
| }) | |
| const timer = setTimeout(() => child.kill(), 5000) | |
| let out = "" | |
| child.stdout.on("data", (chunk) => (out += chunk)) | |
| child.on("error", () => { clearTimeout(timer); resolve(null) }) | |
| child.on("close", () => { | |
| clearTimeout(timer) | |
| try { resolve(out.trim() ? JSON.parse(out) : null) } catch { resolve(null) } | |
| }) | |
| child.stdin.end(JSON.stringify({ | |
| session_id: sessionID, | |
| hook_event_name: event, | |
| transcript_path: null, | |
| cwd, | |
| })) | |
| } catch { resolve(null) } | |
| }) | |
| } | |
| export const CrewPlugin = async ({ client, directory }) => { | |
| const tops = new Map() // sessionID -> is this a top-level (non-subagent) session? | |
| const idle = new Set() // top-level sessions currently between turns | |
| const polled = new Map() // sessionID -> inbox signature at last poll | |
| async function topLevel(sessionID) { | |
| if (tops.has(sessionID)) return tops.get(sessionID) | |
| let top = true | |
| try { | |
| const res = await client.session.get({ path: { id: sessionID } }) | |
| const info = res && (res.data ?? res) | |
| top = !(info && info.parentID) | |
| } catch { /* assume top-level */ } | |
| tops.set(sessionID, top) | |
| return top | |
| } | |
| function inboxSignature(sessionID) { | |
| const names = [] | |
| for (const root of INBOX_ROOTS) { | |
| try { | |
| names.push(...readdirSync(join(root, sessionID)).filter((f) => f.endsWith(".json"))) | |
| } catch { /* no inbox for this session in this root */ } | |
| } | |
| return names.sort().join(",") | |
| } | |
| // The Stop hook returns a forced continuation only for kickstart mail; a | |
| // plain message stays queued for the session's next turn. | |
| async function deliverIdle(sessionID) { | |
| const res = await crewHook("Stop", sessionID, directory) | |
| if (res && res.decision === "block" && res.reason) { | |
| idle.delete(sessionID) | |
| try { | |
| await client.session.promptAsync({ | |
| path: { id: sessionID }, | |
| body: { parts: [{ type: "text", text: res.reason }] }, | |
| }) | |
| } catch { idle.add(sessionID) } | |
| } | |
| } | |
| // Unlike Claude/Codex, an idle OpenCode session can be woken from outside: | |
| // poll the inbox and prompt the session when kickstart mail arrives. | |
| const timer = setInterval(() => { | |
| for (const sessionID of [...idle]) { | |
| const sig = inboxSignature(sessionID) | |
| if (!sig || sig === polled.get(sessionID)) continue | |
| polled.set(sessionID, sig) | |
| deliverIdle(sessionID) | |
| } | |
| }, POLL_MS) | |
| if (timer.unref) timer.unref() | |
| return { | |
| dispose: async () => clearInterval(timer), | |
| "chat.message": async (input, output) => { | |
| const sessionID = input.sessionID || (output.message && output.message.sessionID) | |
| if (!sessionID || !(await topLevel(sessionID))) return | |
| idle.delete(sessionID) | |
| const res = await crewHook("UserPromptSubmit", sessionID, directory) | |
| const context = res && res.hookSpecificOutput && res.hookSpecificOutput.additionalContext | |
| if (context && Array.isArray(output.parts)) { | |
| output.parts.push({ | |
| id: "prt_crew" + Math.random().toString(36).slice(2, 14), | |
| sessionID, | |
| messageID: output.message && output.message.id, | |
| type: "text", | |
| text: context, | |
| synthetic: true, | |
| }) | |
| } | |
| }, | |
| "tool.execute.after": async (input, output) => { | |
| if (!input.sessionID || !(await topLevel(input.sessionID))) return | |
| const res = await crewHook("PostToolUse", input.sessionID, directory) | |
| const context = res && res.hookSpecificOutput && res.hookSpecificOutput.additionalContext | |
| if (context && typeof output.output === "string") { | |
| output.output += "\\n\\n<crew-messages>\\n" + context + "\\n</crew-messages>" | |
| } | |
| }, | |
| // Tag shell commands with the session id so \`crew send\` run inside an | |
| // OpenCode session attributes to it (one process hosts many sessions). | |
| "shell.env": async (input, output) => { | |
| if (input.sessionID && output.env) output.env.CREW_SESSION_ID = input.sessionID | |
| }, | |
| event: async ({ event }) => { | |
| if (event.type === "session.idle") { | |
| const sessionID = event.properties && event.properties.sessionID | |
| if (!sessionID || !(await topLevel(sessionID))) return | |
| idle.add(sessionID) | |
| polled.delete(sessionID) | |
| await deliverIdle(sessionID) | |
| } else if (event.type === "session.deleted") { | |
| const info = event.properties && event.properties.info | |
| if (info && info.id) { | |
| idle.delete(info.id) | |
| tops.delete(info.id) | |
| await crewHook("SessionEnd", info.id, directory) | |
| } | |
| } | |
| }, | |
| } | |
| } | |
| `; | |
| } | |
Xet Storage Details
- Size:
- 12 kB
- Xet hash:
- 7450035e9b81e5b3fbd7c230d31aa3f9132416b0d4caa283db050f1933c0e4d2
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.