bardd's picture
Deploy Mike backend-only Space
06671aa verified
Raw History Blame Contribute Delete
7.01 kB
import {
ASSISTANT_ROUTER_SCHEMA_VERSION,
AssistantRoutingValidationError,
type AssistantAmbiguityCode,
type AssistantOperation,
type AssistantRouterOutputV2,
type AssistantRouterReasonCode,
type AssistantTargetScope,
type AssistantWebNeed,
} from "./types";
const OPERATIONS: readonly AssistantOperation[] = [
"answer",
"analyze_documents",
"comment_documents",
"edit_documents",
"generate_document",
"run_workflow",
];
const WEB_NEEDS: readonly AssistantWebNeed[] = [
"required",
"preferred",
"not_needed",
"forbidden",
];
const TARGET_SCOPES: readonly AssistantTargetScope[] = [
"conversation",
"displayed_document",
"attached_documents",
"project_documents",
"selected_workflow",
];
const AMBIGUITIES: readonly AssistantAmbiguityCode[] = [
"empty_request",
"attachment_intent_missing",
"document_target_missing",
"document_target_ambiguous",
"editable_document_missing",
"workflow_missing",
"workflow_conflicts_with_other_operations",
"operation_targets_incompatible",
"unresolved_reference",
];
const REASON_CODES: readonly AssistantRouterReasonCode[] = [
"general_knowledge",
"current_information",
"explicit_web_request",
"explicit_no_web",
"document_analysis",
"document_comment_request",
"document_edit_request",
"document_generation_request",
"workflow_request",
"jurisdiction_specific",
"live_market_or_event",
"source_verification",
"ambiguous_request",
];
const ALLOWED_TOP_LEVEL_KEYS = new Set<string>([
"schemaVersion",
"operations",
"webNeed",
"targetScopes",
"ambiguities",
"reasonCodes",
]);
/** Forbidden keys that would let the model grant tools or authorization. */
const FORBIDDEN_KEYS = new Set<string>([
"tools",
"toolNames",
"capabilities",
"capabilitiesList",
"promptFamily",
"promptFragments",
"documentMutation",
"confirmation",
"path",
"confidence",
]);
export const ROUTER_OUTPUT_MAX_SERIALIZED_BYTES = 16_384;
export const ROUTER_OUTPUT_MAX_RAW_OPERATIONS = 4;
export const ROUTER_OUTPUT_MAX_AMBIGUITIES = 8;
export const ROUTER_OUTPUT_MAX_REASON_CODES = 12;
export const ROUTER_OUTPUT_MAX_TARGET_SCOPES = 5;
export const ROUTER_OUTPUT_MAX_ENUM_ARRAY_LENGTH = 12;
function fail(code: string, detail: unknown): never {
throw new AssistantRoutingValidationError(
`router_output_invalid: ${code} (${JSON.stringify(detail)})`,
code,
);
}
function isStringArray(value: unknown): value is string[] {
return Array.isArray(value) && value.every((v) => typeof v === "string");
}
function enumArray<T extends string>(
value: unknown,
allowed: readonly T[],
field: string,
cap: number,
): T[] {
if (!Array.isArray(value)) fail("not_array", { field });
if (value.length > cap) fail("too_many_entries", { field, count: value.length, cap });
if (!isStringArray(value)) fail("non_string_entry", { field });
const out: T[] = [];
for (const entry of value as string[]) {
if (!(allowed as readonly string[]).includes(entry)) {
fail("invalid_enum_value", { field, value: entry });
}
out.push(entry as T);
}
return out;
}
/**
* Strictly parse untrusted router output. Accepts raw JSON text or a parsed
* unknown value. Throws {@link AssistantRoutingValidationError} on any invalid
* input. Never coerces arbitrary strings into valid enums. Never accepts tool
* names or capability fields.
*/
export function parseAssistantRouterOutput(
raw: string | unknown,
): AssistantRouterOutputV2 {
let input: unknown;
if (typeof raw === "string") {
const trimmed = raw.trim();
if (trimmed === "") fail("empty_output", null);
// Reject markdown fences.
if (trimmed.startsWith("```")) fail("markdown_fence", null);
// Reject obvious commentary around JSON.
const firstBrace = trimmed.indexOf("{");
const lastBrace = trimmed.lastIndexOf("}");
if (firstBrace === -1 || lastBrace === -1 || lastBrace < firstBrace) {
fail("not_json_object", null);
}
const candidate = trimmed.slice(firstBrace, lastBrace + 1);
if (candidate.length !== trimmed.length) {
// Reject explanations outside JSON.
fail("extra_text_outside_json", null);
}
if (Buffer.byteLength(candidate, "utf8") > ROUTER_OUTPUT_MAX_SERIALIZED_BYTES) {
fail("oversized", { bytes: Buffer.byteLength(candidate, "utf8") });
}
try {
input = JSON.parse(candidate);
} catch {
fail("json_parse_error", null);
}
} else {
input = raw;
}
if (input === null || typeof input !== "object" || Array.isArray(input)) {
fail("not_object", null);
}
const obj = input as Record<string, unknown>;
for (const key of Object.keys(obj)) {
if (FORBIDDEN_KEYS.has(key)) fail("forbidden_field", { field: key });
if (!ALLOWED_TOP_LEVEL_KEYS.has(key)) fail("extra_top_level_field", { field: key });
}
if (obj.schemaVersion !== ASSISTANT_ROUTER_SCHEMA_VERSION) {
fail("invalid_schema_version", { value: obj.schemaVersion });
}
if (!Array.isArray(obj.operations)) fail("not_array", { field: "operations" });
if ((obj.operations as unknown[]).length === 0) fail("empty_operations", null);
if ((obj.operations as unknown[]).length > ROUTER_OUTPUT_MAX_RAW_OPERATIONS) {
fail("too_many_operations", {
count: (obj.operations as unknown[]).length,
cap: ROUTER_OUTPUT_MAX_RAW_OPERATIONS,
});
}
const operations = enumArray(
obj.operations,
OPERATIONS,
"operations",
ROUTER_OUTPUT_MAX_ENUM_ARRAY_LENGTH,
);
// Reject duplicates at the raw boundary.
const seenOps = new Set<string>();
for (const op of operations) {
if (seenOps.has(op)) fail("duplicate_operation", { value: op });
seenOps.add(op);
}
if (typeof obj.webNeed !== "string" || !(WEB_NEEDS as readonly string[]).includes(obj.webNeed)) {
fail("invalid_enum_value", { field: "webNeed", value: obj.webNeed });
}
const targetScopes = enumArray(
obj.targetScopes,
TARGET_SCOPES,
"targetScopes",
ROUTER_OUTPUT_MAX_TARGET_SCOPES,
);
const ambiguities = enumArray(
obj.ambiguities,
AMBIGUITIES,
"ambiguities",
ROUTER_OUTPUT_MAX_AMBIGUITIES,
);
const reasonCodes = enumArray(
obj.reasonCodes,
REASON_CODES,
"reasonCodes",
ROUTER_OUTPUT_MAX_REASON_CODES,
);
return Object.freeze({
schemaVersion: ASSISTANT_ROUTER_SCHEMA_VERSION,
operations,
webNeed: obj.webNeed as AssistantWebNeed,
targetScopes,
ambiguities,
reasonCodes,
}) as AssistantRouterOutputV2;
}