UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

100 lines (99 loc) • 4.73 kB
import { createHash, randomUUID } from "node:crypto"; import { join, resolve as resolvePath } from "node:path"; import { encodeCcPeerFrame, encodePeerAddress } from "./cross-session-envelope.js"; import { semaMailboxFeature } from "./peer-directory.js"; export const CC_PEER_LINE_MAX_CHARS = 1_048_576; export const CC_PEER_FIRST_LINE_DEADLINE_MS = 30_000; export const CC_PEER_SEND_TIMEOUT_MS = 5_000; export const CC_PEER_SOCKET_PATH_MAX_BYTES = 103; export const CC_PEER_KEY_FILE_MAX_BYTES = 4_096; export const CC_PEER_PROTOCOL = 1; export const CC_PEER_MESSAGE_VERSION = 1; export const CC_PEER_TOKEN_RE = /^[0-9a-f]{32}$/; export const CC_PEER_KEY_FILE_RE = /^(\d+)\.([0-9a-f]{64})\.key$/; export const CC_PEER_ROW_FILE_RE = /^(\d+)\.json$/; export const CC_PEER_NUDGE_ACTION = "mailbox_nudge"; export function ccPeerSocketDigest(socketPath) { return createHash("sha256").update(resolvePath(socketPath)).digest("hex"); } export function ccPeerKeyFileName(pid, socketPath) { return `${pid}.${ccPeerSocketDigest(socketPath)}.key`; } export function ccPeerAddress(socketPath) { return encodePeerAddress(`uds:${socketPath}`); } export function ccPeerDefaultLocations(args) { const base = args.env["XDG_RUNTIME_DIR"] || args.env["CLAUDE_CODE_TMPDIR"] || "/tmp"; const primary = resolvePath(base, "cc-socks", `${args.pid}.sock`); const socketPath = Buffer.byteLength(primary) <= CC_PEER_SOCKET_PATH_MAX_BYTES ? primary : join("/tmp", `cc-socks-${args.uid ?? 0}`, `${args.pid}.sock`); const registryDir = resolvePath(args.env["CLAUDE_CONFIG_DIR"] || join(args.homedir, ".claude"), "sessions"); return { socketPath, registryDir }; } export function encodeCcAuthLine(token) { return `${JSON.stringify({ type: "auth", token })}\n`; } export function encodeCcUserLine(args) { const content = encodeCcPeerFrame(args.fields, args.body); return `${JSON.stringify({ msgV: CC_PEER_MESSAGE_VERSION, msg_id: args.msgId ?? randomUUID(), type: "user", message: { role: "user", content }, priority: "next", ...(args.from !== undefined ? { from: args.from } : {}) })}\n`; } export function encodeCcNudgeLine(args = {}) { return `${JSON.stringify({ type: "control", action: CC_PEER_NUDGE_ACTION, msgV: CC_PEER_MESSAGE_VERSION, msg_id: args.msgId ?? randomUUID() })}\n`; } export function readCcPeerLine(value) { if (value === null || typeof value !== "object" || Array.isArray(value)) return { kind: "malformed", why: "not an object" }; const v = value; const type = v["type"]; if (typeof type !== "string") return { kind: "malformed", why: "no type" }; if (type === "auth") return { kind: "auth", token: typeof v["token"] === "string" ? v["token"] : undefined }; if (type === "user") { const message = v["message"]; const content = message !== null && typeof message === "object" && !Array.isArray(message) ? message["content"] : undefined; if (typeof content !== "string" || content.length === 0) return { kind: "malformed", why: "user frame without text content" }; const rawTo = v["session_id"]; return { kind: "user", content, ...(typeof v["from"] === "string" ? { from: v["from"] } : {}), ...(rawTo !== undefined ? { toSession: typeof rawTo === "string" ? rawTo : null } : {}), attachments: v["file_attachments"] !== undefined, }; } if (type === "control") { const action = v["action"]; if (action === CC_PEER_NUDGE_ACTION) return { kind: "nudge" }; return { kind: "unhandled", type, ...(typeof action === "string" ? { action } : {}) }; } return { kind: "unhandled", type }; } export function parseCcPeerLine(line) { let value; try { value = JSON.parse(line); } catch { return { kind: "malformed", why: "not JSON" }; } return readCcPeerLine(value); } export function ccRegistrationRow(facts) { return { pid: facts.pid, sessionId: facts.sessionId, ...(facts.cwd !== undefined ? { cwd: facts.cwd } : {}), startedAt: facts.startedAt, ...(facts.procStart !== undefined ? { procStart: facts.procStart } : {}), kind: "interactive", ...(facts.entrypoint !== undefined ? { entrypoint: facts.entrypoint } : {}), peerProtocol: CC_PEER_PROTOCOL, peerFeatures: facts.storeIdentity !== undefined && facts.storeIdentity !== "" ? [semaMailboxFeature(facts.storeIdentity)] : [], messagingSocketPath: facts.socketPath, ...(facts.name !== undefined ? { name: facts.name } : {}), updatedAt: facts.updatedAt, occupant: facts.occupant, }; }