1
/**2
* Codemode source format: JavaScript, optionally preceded by one options line.3
*4
* ```js5
* // @options: {"max_output_tokens": 2000, "timeout_ms": 30000}6
* const text = await tools.read({ path: "package.json" });7
* text(JSON.parse(text).name);8
* ```9
*/11
export const CODEMODE_OPTIONS_PREFIX = "// @options:";13
const SUPPORTED_FIELDS = ["max_output_tokens", "timeout_ms"] as const;14
const SUPPORTED_FIELDS_TEXT = "`max_output_tokens` and `timeout_ms`";15
/** Largest delay `setTimeout` supports, which bounds `timeout_ms`. */16
const MAX_TIMEOUT_MS = 2_147_483_647;18
/**19
* Lark grammar for providers with grammar-constrained tool input. It only fixes the shape of the20
* options line; the options JSON and the code are checked by {@link parseCodemodeSource}.21
*/22
export const CODEMODE_SOURCE_GRAMMAR = String.raw`23
start: options_source | plain_source24
options_source: OPTIONS_LINE NEWLINE SOURCE25
plain_source: SOURCE27
OPTIONS_LINE: /[ \t]*\/\/ @options:[^\r\n]*/28
NEWLINE: /\r?\n/29
SOURCE: /[\s\S]+/30
`;32
export interface CodemodeSourceOptions {33
/** Token budget for the script's output. */34
maxOutputTokens?: number;35
/** Hard deadline for the whole script in milliseconds, including tool calls. */36
timeoutMs?: number;37
}39
export interface ParsedCodemodeSource {40
/** The script with the options line replaced by an empty line, so line numbers are unchanged. */41
code: string;42
options: CodemodeSourceOptions;43
}45
export class CodemodeSourceError extends Error {46
constructor(message: string) {47
super(message);48
this.name = "CodemodeSourceError";49
}50
}52
function isSafeInteger(value: unknown): value is number {53
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;54
}56
function parseOptions(directive: string): CodemodeSourceOptions {57
if (directive === "") {58
throw new CodemodeSourceError(`@options must be a JSON object with supported fields ${SUPPORTED_FIELDS_TEXT}`);59
}60
let value: unknown;61
try {62
value = JSON.parse(directive);63
} catch (error) {64
throw new CodemodeSourceError(65
`@options must be valid JSON with supported fields ${SUPPORTED_FIELDS_TEXT}: ${error instanceof Error ? error.message : String(error)}`,66
);67
}68
if (typeof value !== "object" || value === null || Array.isArray(value)) {69
throw new CodemodeSourceError(`@options must be a JSON object with supported fields ${SUPPORTED_FIELDS_TEXT}`);70
}71
const fields = value as Record<string, unknown>;72
for (const key of Object.keys(fields)) {73
if (!(SUPPORTED_FIELDS as readonly string[]).includes(key)) {74
throw new CodemodeSourceError(`@options only supports ${SUPPORTED_FIELDS_TEXT}; got \`${key}\``);75
}76
}77
const options: CodemodeSourceOptions = {};78
const { max_output_tokens, timeout_ms } = fields;79
if (max_output_tokens !== undefined) {80
if (!isSafeInteger(max_output_tokens)) {81
throw new CodemodeSourceError("@options field `max_output_tokens` must be a non-negative safe integer");82
}83
options.maxOutputTokens = max_output_tokens;84
}85
if (timeout_ms !== undefined) {86
if (!isSafeInteger(timeout_ms) || timeout_ms === 0 || timeout_ms > MAX_TIMEOUT_MS) {87
throw new CodemodeSourceError(88
`@options field \`timeout_ms\` must be a positive integer up to ${MAX_TIMEOUT_MS}`,89
);90
}91
options.timeoutMs = timeout_ms;92
}93
return options;94
}96
/**97
* Split an optional first-line `// @options: {...}` from the script. Throws98
* {@link CodemodeSourceError} for empty input, invalid options, and an options line that is not the99
* first line, which would otherwise be ignored without notice.100
*/101
export function parseCodemodeSource(input: string): ParsedCodemodeSource {102
if (input.trim() === "") {103
throw new CodemodeSourceError(104
'Expected JavaScript source text (non-empty). Provide JS only, optionally with a first line `// @options: {"max_output_tokens": 1000}`.',105
);106
}107
const lines = input.split("\n");108
const misplaced = lines.findIndex(109
(line, index) => index > 0 && line.trimStart().startsWith(CODEMODE_OPTIONS_PREFIX),110
);111
if (misplaced !== -1) {112
throw new CodemodeSourceError(113
`The ${CODEMODE_OPTIONS_PREFIX} line must be the first line of the input; found one on line ${misplaced + 1}`,114
);115
}116
const newline = input.indexOf("\n");117
const firstLine = lines[0].replace(/\r$/, "");118
const trimmed = firstLine.trimStart();119
if (!trimmed.startsWith(CODEMODE_OPTIONS_PREFIX)) return { code: input, options: {} };120
const code = newline === -1 ? "" : input.slice(newline);121
if (code.trim() === "") {122
throw new CodemodeSourceError("The @options line must be followed by JavaScript source on subsequent lines");123
}124
return { code, options: parseOptions(trimmed.slice(CODEMODE_OPTIONS_PREFIX.length).trim()) };125
}