@sema-agent/core
Version:
Stateless, task-oriented AI agent core
120 lines (119 loc) • 6.78 kB
JavaScript
import { deliverEngineNotice } from "../types.js";
import { legNoticeTaskId } from "../mods/stations.js";
import { resolveOwnerStore } from "../permission-rule-provider.js";
import { landRuleAdd, writerOf } from "../permission-rule-store.js";
import { cardRuleFormOf, COMMAND_RULE_TOOL } from "../permission-rule-model.js";
import { wireOf } from "../tool-name-readings.js";
import { thrownText } from "../thrown-value.js";
import { DEFAULT_GATE_AWAIT_TIMEOUT_MS } from "../gate-bounded-await.js";
import { bindCall, CALL_GRANT_MATCH, callGrantCommandOf, callGrantRuleTextOf, offerOfBinding } from "../session-call-grant.js";
export function createCallGrantDoorOf(offersOf) {
return (call, args, ask) => {
if (ask === undefined || ask.classes?.some((c) => c === "sandbox_override" || c === "a2a_inside") === true)
return false;
if (cardRuleFormOf(wireOf("offer.callGrantTool", call), call) !== "command")
return false;
const offered = offersOf(call, args, ask);
return Object.keys(offered).length > 0 && (offered.ruleOffersAbsence === undefined || offered.ruleOffersAbsence === "lane_cannot_speak");
};
}
const WHY = {
not_a_string: "the grant is not a string",
no_offer: "this approval card offered no session grant",
mismatch: "the grant is not the one the card offered (it must be sent back exactly as offered)",
edited: "the approval changed the call's input, and the grant names the call the card showed",
};
function announceRejected(at, reason, why, offered, requested) {
deliverEngineNotice(at.onNotice, {
code: "approval.session_call_grant_rejected",
message: `the approval for "${at.toolName}" asked to allow this call for the rest of the session, and nothing was kept: ${why}. The approval's own verdict is unchanged.`,
detail: { reason, ...(offered !== undefined ? { offered } : {}), ...(requested !== undefined ? { requested } : {}), toolName: at.toolName, toolCallId: at.toolCallId, checkpointId: at.checkpointId, sessionId: at.sessionId, runId: at.runId, ...legNoticeTaskId(at) },
});
}
export function settleUnofferedSessionCallGrant(screen, at) {
if (screen === undefined)
return undefined;
const reason = screen.verdict === "rejected" ? screen.reason : "no_offer";
announceRejected(at, reason, WHY[reason], undefined, screen.verdict === "rejected" ? screen.requested : screen.grant.slice(0, 200));
return undefined;
}
export function sessionCallGrantStation(cfg) {
const bounded = (signal) => AbortSignal.any([...(signal !== undefined ? [signal] : []), AbortSignal.timeout(DEFAULT_GATE_AWAIT_TIMEOUT_MS)]);
const write = async (binding, toolCallId, signal) => {
const owner = cfg.sessionRowOwner();
if (owner === undefined)
return { landed: false, reason: "the run no longer keeps session rules (the rule store's writer is not this engine's)" };
let writer;
let store;
try {
store = resolveOwnerStore({ provider: cfg.provider, owner });
writer = writerOf(store);
}
catch (err) {
return { landed: false, reason: `the rule store could not be resolved (${thrownText(err)})` };
}
if (writer === undefined)
return { landed: false, reason: "the resolved permission-rule store has no write face" };
if (signal.aborted)
return { landed: false, reason: "the call ended before the session row was written" };
const command = callGrantCommandOf(binding);
try {
const dot = await writer.nextDot();
const landing = await landRuleAdd({
store,
writer,
delta: {
kind: "redemption-add",
behavior: "allow",
rule: callGrantRuleTextOf(command),
scope: { kind: "session", sessionId: cfg.sessionId },
tool: COMMAND_RULE_TOOL,
match: CALL_GRANT_MATCH,
command,
add: { dot, origin: "user", createdAt: new Date(cfg.now?.() ?? Date.now()).toISOString() },
redemption: { recordId: `card:${toolCallId}`, ...(owner.kind === "principal" ? { principal: owner.principal } : { owner }) },
},
});
return landing.landed ? { landed: true } : { landed: false, reason: landing.committed === "unknown" ? `${landing.reason} — if it landed, the call stays allowed for the session` : landing.reason };
}
catch (err) {
return { landed: false, reason: `the session row could not be written (${thrownText(err)}) — if it landed, the call stays allowed for the session` };
}
};
return {
mint: async (command, call, signal) => {
if (cfg.provider.revokeSessionRule === undefined || cfg.sessionRowOwner() === undefined)
return undefined;
const binding = await bindCall(command, cfg.seat(call), bounded(signal)).catch(() => undefined);
if (binding === undefined || "unbindable" in binding)
return undefined;
return { offer: offerOfBinding(binding), binding };
},
settle: (screen, minted, at) => {
if (screen === undefined)
return undefined;
const ids = { toolName: at.toolName, toolCallId: at.toolCallId, checkpointId: at.checkpointId, sessionId: at.sessionId, runId: at.runId, ...legNoticeTaskId(at) };
const offered = minted?.offer.grant;
if (screen.verdict === "rejected") {
announceRejected(at, screen.reason, WHY[screen.reason], offered, screen.requested);
return undefined;
}
if (minted === undefined || minted.offer.grant !== screen.grant) {
announceRejected(at, "no_offer", WHY.no_offer, offered);
return undefined;
}
const signal = bounded(at.signal);
return write(minted.binding, at.toolCallId, signal).then((written) => {
if (!written.landed) {
announceRejected(at, "not_written", `the session row was not written (${written.reason})`, offered);
return;
}
deliverEngineNotice(at.onNotice, {
code: "approval.session_call_granted",
message: `the approval for "${at.toolName}" allows this call for the rest of this session: ${minted.offer.sentence}.`,
detail: { rule: minted.offer.grant, cwd: minted.offer.cwd, programs: [...minted.offer.programs], ...ids },
});
});
},
};
}