UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

105 lines (104 loc) • 8.23 kB
import { Type } from "typebox"; import { defineTool } from "../core/tools.js"; import { mountRuleFace, toolFace } from "../core/tool-catalog-entries.js"; import { egressValue } from "../core/untrusted-egress.js"; import { inlineUntrusted } from "../core/untrusted-text.js"; import { PATH_TARGET_ELEMENTS_MAX } from "../core/tool-registry.js"; import { imageMimeForRead } from "../tools/fs/safety.js"; export const SEND_USER_MESSAGE_TOOL_NAME = "SendUserMessage"; const DELIVERED = "Message delivered to user."; const CLAIM = Type.Object({ about: Type.String({ description: "The task id of the member this conclusion is about, as the ledger lists it." }), text: Type.String({ description: "The conclusion, in one or two sentences." }), basis: Type.Union([Type.Literal("verified"), Type.Literal("relayed"), Type.Literal("inferred")], { description: '"verified": you checked it yourself after that member reported (cite the check) — "relayed": it is what the member said, unchecked — "inferred": your own judgment.', }), verdict: Type.Optional(Type.Union([Type.Literal("confirms"), Type.Literal("refutes"), Type.Literal("partial")], { description: 'For "verified": whether your check confirms, refutes or partly confirms what the member reported.' })), evidence: Type.Optional(Type.Array(Type.String(), { maxItems: 8, description: 'For "verified": the id of each check — a tool call you made after the member reported, or another member\'s task id (a verification worker).' })), }, { additionalProperties: false }); const PARAMETERS = Type.Object({ message: Type.String({ description: "What the person reads. Markdown is fine." }), status: Type.Union([Type.Literal("normal"), Type.Literal("proactive")], { description: "'normal' when replying to what they just asked; 'proactive' when you are initiating — a phase finished, a blocker surfaced, a result was overturned, you need a decision. Set it honestly; downstream routing uses it.", }), attachments: Type.Optional(Type.Array(Type.String(), { description: "Optional file paths (absolute or relative to the working directory) to show beside the message — a screenshot, a log, a diff." })), report: Type.Optional(Type.Object({ kind: Type.Optional(Type.Union([Type.Literal("start"), Type.Literal("interim"), Type.Literal("final")])), claims: Type.Optional(Type.Array(CLAIM, { maxItems: 32 })), decisions: Type.Optional(Type.Array(Type.Object({ question: Type.String(), options: Type.Array(Type.String(), { maxItems: 8 }), recommend: Type.Optional(Type.String()) }, { additionalProperties: false }), { maxItems: 8 })), next: Type.Optional(Type.String()), }, { additionalProperties: false })), }, { additionalProperties: false }); const namesFiles = (args) => { const v = typeof args === "object" && args !== null ? args.attachments : undefined; return v !== undefined && !(Array.isArray(v) && v.length === 0); }; const NO_LEGS = Object.freeze([]); const ENV_LEG = Object.freeze(["env"]); const REMEDY = "A file is shown only where the rules let Read reach it without asking anyone: inside the task's directories (or one added to them), and on no deny or ask rule."; const closedSentence = (why) => (/[.!?]\)?$/.test(why) ? why : `${why}.`); async function attachmentsOf(show, paths, signal) { const list = Array.isArray(paths) && paths.every((p) => typeof p === "string") ? paths : undefined; if (list === undefined) return { ok: false, why: "`attachments` is a list of file paths." }; if (list.length > PATH_TARGET_ELEMENTS_MAX) return { ok: false, why: `this report names ${list.length} files; one report may name at most ${PATH_TARGET_ELEMENTS_MAX}.` }; if (show === undefined) return { ok: false, why: "this run has no workspace to read files from." }; const shown = await show(list, signal); if (!shown.ok) return { ok: false, why: `attachment "${inlineUntrusted(shown.path, 200)}" is not shown: ${closedSentence(shown.why)} ${REMEDY}` }; return { ok: true, value: shown.files.map((f) => ({ path: f.key, size: f.size, isImage: imageMimeForRead(f.key) !== undefined, pathValidated: true })) }; } export function createSendUserMessageTool(seats) { return defineTool({ name: SEND_USER_MESSAGE_TOOL_NAME, ...toolFace("send-user-message"), ruleFace: mountRuleFace("send-user-message"), description: "Send a message the person you work for will read. Use it to report — when you start, when a result is overturned, when you are blocked or need a decision, and at the end.\n\n" + "`status` labels intent: 'normal' when replying to what they just asked; 'proactive' when you are initiating. Set it honestly; downstream routing uses it.\n\n" + "`attachments` is optional: files to show beside the message (a screenshot, a log, a diff). Only each file's path and size are shown, and only where the rules let Read reach it without asking anyone — inside the task's directories and on no deny or ask rule; if any one is not shown the message is not sent and the reason comes back — drop it or name another, and send again.\n\n" + "`report.claims` is optional: one entry per conclusion about a member you dispatched (`about` = its task id), each saying what it rests on. " + 'A "verified" claim must cite evidence made AFTER that member reported — a tool call of your own, or another member that checked it — and state a verdict; ' + "a report whose checks do not hold is not delivered and the reason comes back, so check again or mark the claim \"relayed\". " + "Beside every message the engine delivers its own ledger of the members — how each ended, what each did, which ones nobody checked — whatever the message says.", parameters: PARAMETERS, boundaryLegsFor: (args) => ({ legs: namesFiles(args) ? ENV_LEG : NO_LEGS }), execute: async (args, ctx) => { let attachments; if (namesFiles(args)) { const read = await attachmentsOf(seats.show, args.attachments, ctx?.signal); if (!read.ok) return { content: `Report not sent: ${read.why.slice(0, 1200)}`, details: { type: "send-user-message", status: args.status, delivered: false }, isError: true }; attachments = read.value; } const { attachments: _named, ...said } = args; const a = egressValue("same-principal", { ...said, ...(attachments !== undefined ? { attachments } : {}) }); const verdict = seats.book.acceptReport({ status: a.status, message: a.message, ...(a.report !== undefined ? { report: { ...(a.report.kind !== undefined ? { kind: a.report.kind } : {}), ...(a.report.claims !== undefined ? { claims: a.report.claims } : {}) } } : {}), ...(ctx?.toolCallId !== undefined ? { toolCallId: ctx.toolCallId } : {}), }); if (!verdict.ok) { return { content: `Report not sent: ${verdict.why.slice(0, 1200)}`, details: { type: "send-user-message", status: a.status, delivered: false }, isError: true }; } const ledger = seats.book.snapshot({ kind: "report", ...(ctx?.toolCallId !== undefined ? { toolCallId: ctx.toolCallId } : {}) }); await seats.record(ledger).catch(() => undefined); const n = a.attachments?.length ?? 0; return { content: `${DELIVERED}${n === 0 ? "" : ` (${n} ${n === 1 ? "attachment" : "attachments"} included)`}\nLedger: ${ledger.headline}`, details: { type: "send-user-message", status: a.status, delivered: true, message: a.message, ...(a.report?.kind !== undefined ? { kind: a.report.kind } : {}), ...(a.report !== undefined ? { report: a.report } : {}), ...(a.attachments !== undefined ? { attachments: a.attachments } : {}), ledger, }, }; }, }); }