UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

122 lines (121 loc) • 6.69 kB
import { AsyncLocalStorage } from "node:async_hooks"; import { types } from "node:util"; import { isPlainRecord } from "./mods/kernel/receive.js"; import { callerText, dataKind } from "./caller-text.js"; export const MCP_TOOL_USE_ID_META_KEY = "sema/toolUseId"; export const MCP_REQUEST_META_KEY = "sema/requestMeta"; export const MCP_REQUEST_META_MAX_BYTES = 262_144; const kindOf = (v) => v === null ? "null" : Array.isArray(v) ? "a list" : typeof v === "object" ? (types.isProxy(v) ? "a Proxy" : "an object that is not a plain record") : `a ${typeof v}`; export function judgeRequestMeta(value) { if (value === undefined) return { meta: undefined }; if (typeof value === "object" && value !== null && types.isProxy(value)) return { problem: "requestMeta is a Proxy; it takes a plain record of strings" }; if (!isPlainRecord(value)) return { problem: `requestMeta is ${kindOf(value)}; it takes a plain record of strings` }; const descriptors = Object.getOwnPropertyDescriptors(value); if (Object.getOwnPropertySymbols(descriptors).length > 0) return { problem: "requestMeta has a symbol-keyed member; its members are string keys holding strings" }; const copy = Object.create(null); let bytes = 0; let members = 0; for (const key of Object.getOwnPropertyNames(descriptors)) { const d = descriptors[key]; if (!Object.hasOwn(d, "value") || d.enumerable !== true) return { problem: `requestMeta's member ${callerText(key)} is not an enumerable data property (a getter is never run)` }; const v = d.value; if (typeof v !== "string") return { problem: `requestMeta's member ${callerText(key)} is ${kindOf(v)}, not a string` }; bytes += Buffer.byteLength(key, "utf8") + Buffer.byteLength(v, "utf8"); Object.defineProperty(copy, key, { value: v, enumerable: true, writable: false, configurable: false }); members += 1; } if (bytes > MCP_REQUEST_META_MAX_BYTES) return { problem: `requestMeta is ${bytes} bytes of keys and values; the most is ${MCP_REQUEST_META_MAX_BYTES}` }; return { meta: members === 0 ? undefined : Object.freeze(copy) }; } export function readHandedRequestMeta(payload) { const d = Object.getOwnPropertyDescriptor(payload, "requestMeta"); if (d === undefined) return { meta: undefined }; if (!Object.hasOwn(d, "value")) return { problem: "requestMeta is an accessor (a getter is never run); it takes a plain record of strings" }; return judgeRequestMeta(d.value); } const SDK_PROGRESS_TOKEN_KEY = "progressToken"; const ENGINE_META_NAMESPACE = "sema/"; export const MCP_SESSION_META_KEY_MAX_CHARS = 128; const MCP_RESERVED_LABELS = ["modelcontextprotocol", "mcp"]; const META_LABEL = /^[A-Za-z](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/; const META_NAME = /^(?:[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?)?$/; export function judgeSessionMetaKey(value) { if (value === undefined) return { key: undefined }; if (typeof value !== "string") return { problem: `sessionMetaKey is ${dataKind(value)}; it takes a non-empty string` }; if (value === "") return { problem: "sessionMetaKey is the empty string; it takes a non-empty string" }; if (value.length > MCP_SESSION_META_KEY_MAX_CHARS) return { problem: `sessionMetaKey is ${value.length} characters; the most is ${MCP_SESSION_META_KEY_MAX_CHARS}` }; const slash = value.indexOf("/"); const labels = slash === -1 ? [] : value.slice(0, slash).split("."); if (!labels.every((label) => META_LABEL.test(label))) return { problem: `sessionMetaKey ${callerText(value)} has a prefix that is not dot-separated labels (a label starts with a letter, ends with a letter or digit, and holds letters, digits and hyphens) followed by a slash` }; if (!META_NAME.test(value.slice(slash + 1))) return { problem: `sessionMetaKey ${callerText(value)} has a name that does not begin and end with a letter or digit, or holds a character other than letters, digits, hyphen, underscore and dot` }; if (value === SDK_PROGRESS_TOKEN_KEY) return { problem: `sessionMetaKey ${callerText(value)} is the key the MCP SDK writes for its own progress token` }; if (value.startsWith(ENGINE_META_NAMESPACE)) return { problem: `sessionMetaKey ${callerText(value)} is under the engine's own "${ENGINE_META_NAMESPACE}" namespace` }; const second = labels[1]?.toLowerCase(); if (second !== undefined && MCP_RESERVED_LABELS.includes(second)) return { problem: `sessionMetaKey ${callerText(value)} is under a prefix MCP reserves (second label "${second}")` }; return { key: value }; } export const MCP_CALLER_META_KEY = "sema/caller"; export function mcpCaller(facts) { const caller = Object.create(null); caller["taskId"] = facts.taskId; caller["runId"] = facts.runId; caller["rootSessionId"] = facts.rootSessionId; if (typeof facts.parentTaskId === "string" && facts.parentTaskId !== "") caller["parentTaskId"] = facts.parentTaskId; return Object.freeze(caller); } export function judgeCallerMeta(value) { if (value === undefined || value === false) return { send: false }; if (value === true) return { send: true }; return { problem: `callerMeta is ${dataKind(value)}; it takes true or false` }; } export function mcpCallMeta(toolUseId, requestMeta, sessionMetaKey, sessionId, caller) { const meta = { ...(typeof toolUseId === "string" && toolUseId !== "" ? { [MCP_TOOL_USE_ID_META_KEY]: toolUseId } : {}), ...(requestMeta !== undefined ? { [MCP_REQUEST_META_KEY]: requestMeta } : {}), ...(caller !== undefined ? { [MCP_CALLER_META_KEY]: caller } : {}), ...(sessionMetaKey !== undefined && typeof sessionId === "string" && sessionId !== "" ? { [sessionMetaKey]: sessionId } : {}), }; return Object.keys(meta).length === 0 ? undefined : meta; } const store = new AsyncLocalStorage(); export function createMcpRequestMetaSeat(sessionId, caller) { const seat = {}; return { sessionId, ...(caller !== undefined ? { caller } : {}), async hold(toolCallId, meta, body) { const held = { seat, toolCallId, meta, live: true }; try { return await store.run(held, body); } finally { held.live = false; } }, of(toolCallId) { const held = store.getStore(); return held !== undefined && held.live && held.seat === seat && held.toolCallId === toolCallId ? held.meta : undefined; }, }; }