mike-backend / backend /src /lib /assistantExecution /toolAuthorization.ts
bardd's picture
Deploy Mike backend-only Space
06671aa verified
Raw History Blame Contribute Delete
5.99 kB
import type { AssistantCapability, AssistantOperation, ApprovedAssistantTurnPlanV2 } from "../assistantRouting/types";
import type { CompiledToolAuthorization } from "./types";
import type { AssistantTurnMode } from "../documentMode";
/**
* Single source of truth for the capability -> assistant tool-name mapping.
* The same mapping controls tool-schema exposure and runtime tool-call
* validation. Tabular tools (e.g. read_table_cells) are deliberately absent.
*/
export const CAPABILITY_TOOLS: Record<AssistantCapability, readonly string[]> = {
"document.read": [
"read_document",
"find_in_document",
"list_documents",
"fetch_documents",
"inspect_document",
"search_document",
"list_workflows",
"read_workflow",
],
"document.comment": [
"comment_on_document",
"plan_comments_on_document",
"correct_comment_anchors",
"fix_comment_findings",
],
"document.edit.direct": ["edit_document"],
"document.generate": ["generate_docx", "replicate_document"],
"project.read": ["list_documents", "fetch_documents"],
"workflow.read": ["list_workflows", "read_workflow"],
"workflow.run": [], // workflow execution is driven by the workflow flag, not a function tool
};
/** All assistant tool names recognized by the plan authorization. */
export const ASSISTANT_AUTHORIZED_TOOL_NAMES: readonly string[] = Array.from(
new Set(Object.values(CAPABILITY_TOOLS).flat()),
);
const TABULAR_TOOL_NAMES = new Set<string>(["read_table_cells"]);
/** Tool schemas exposed to the model (OpenAI function-tool shape). */
export interface ToolSchemaLike {
function?: { name?: string };
type?: string;
}
function freezeAuthorization(source: CompiledToolAuthorization["source"], names: Iterable<string>): CompiledToolAuthorization {
return { source, allowedToolNames: new Set(names) };
}
/**
* Compile the immutable tool authorization from an approved turn plan.
* Unknown tools are denied by construction. No tabular tools ever appear.
*/
export function compileToolAuthorization(
plan: ApprovedAssistantTurnPlanV2,
): CompiledToolAuthorization {
const allowed = new Set<string>();
for (const cap of plan.capabilities) {
for (const name of CAPABILITY_TOOLS[cap] ?? []) {
allowed.add(name);
}
}
// Defense in depth: strip any tabular tool even if somehow mapped.
for (const t of TABULAR_TOOL_NAMES) allowed.delete(t);
return freezeAuthorization("assistant_plan", allowed);
}
/**
* Filter tool schemas to only those authorized. Uses the SAME authorization
* instance the runtime validation uses.
*/
export function filterToolSchemasByAuthorization<T extends ToolSchemaLike>(
schemas: readonly T[],
auth: CompiledToolAuthorization,
): T[] {
return schemas.filter((s) => {
const name = s.function?.name;
return typeof name === "string" && auth.allowedToolNames.has(name);
});
}
/**
* Runtime validation: assert a model-emitted tool call is authorized. Throws a
* tagged error when the tool is unknown or forbidden. This is mandatory even
* when schema filtering already removed the tool.
*/
export function assertToolCallAuthorized(
toolName: string,
auth: CompiledToolAuthorization,
): void {
if (!auth.allowedToolNames.has(toolName)) {
throw new Error(`forbidden_tool_call: ${toolName}`);
}
}
/**
* Legacy mode adapter: preserve the existing turnMode -> tool capability
* behavior for callers that have not migrated to the plan-based flow.
*/
export function compileLegacyModeAuthorization(
turnMode: AssistantTurnMode,
): CompiledToolAuthorization {
const READ_ONLY = [
"read_document",
"find_in_document",
"list_documents",
"fetch_documents",
"list_workflows",
"read_workflow",
"inspect_document",
"search_document",
];
const COMMENT = [
"comment_on_document",
"plan_comments_on_document",
"correct_comment_anchors",
"fix_comment_findings",
];
const DIRECT_EDIT = ["edit_document"];
const GENERATION = ["generate_docx", "replicate_document"];
let tools: string[];
switch (turnMode) {
case "comments":
tools = [...READ_ONLY, ...COMMENT];
break;
case "workflow_review":
tools = [...READ_ONLY, ...COMMENT, ...GENERATION];
break;
case "document_generation":
tools = [...READ_ONLY, ...GENERATION];
break;
case "document_direct_edit":
case "document_edit_with_web_search":
tools = [...READ_ONLY, ...DIRECT_EDIT];
break;
case "project_chat":
tools = [...READ_ONLY, ...COMMENT, ...GENERATION];
break;
case "answer":
case "web_search":
default:
tools = [...READ_ONLY];
break;
}
return freezeAuthorization("legacy_mode_adapter", tools);
}
/**
* Reduce capabilities after a required-research failure (§28). Removes
* side-effect capabilities and recomputes a frozen authorization. Read-only
* capabilities are retained. Research can only reduce, never widen.
*/
export function reduceCapabilitiesAfterResearchFailure(
plan: ApprovedAssistantTurnPlanV2,
): AssistantCapability[] {
const sideEffects: AssistantCapability[] = [
"document.comment",
"document.edit.direct",
"document.generate",
"workflow.run",
];
return plan.capabilities.filter((c) => !sideEffects.includes(c));
}
/** Helper for tests/observability: which operations a capability reduction removes. */
export function researchFailureStrippedOperations(
operations: readonly AssistantOperation[],
): AssistantOperation[] {
return operations.filter((o) =>
["comment_documents", "edit_documents", "generate_document", "run_workflow"].includes(o),
);
}