Skip to main content

multicast_codemode/
program.rs

1use crate::{ConnectorDescription, normalize_code};
2
3/// Builds a promise queue whose continuation belongs entirely to the JavaScript heap.
4///
5/// Executors drain jobs, save the heap, dispatch the first queued payload, and
6/// resolve its promise. The heap retains no host future or native callback.
7pub fn build_checkpoint_source(
8    code: &str,
9    connectors: &[ConnectorDescription],
10    execution_id: &str,
11) -> Result<String, String> {
12    let program = build_program_source(code, connectors, &ProgramSourceOptions {
13        dispatch: "payload => new Promise(resolve => globalThis.__incursDurable.pending.push({payload, resolve}))".into(),
14        execution_id: "globalThis.__incursDurable.executionId".into(),
15        timeout_ms: None,
16    })?;
17    let execution_id = serde_json::to_string(execution_id).map_err(|e| e.to_string())?;
18    Ok(format!(
19        r#"
20globalThis.__incursDurable = {{pending: [], output: null, failure: null, executionId: globalThis.__incursExecutionId ?? {execution_id}}};
21(async () => {{ {program} }})().then(
22  value => {{ globalThis.__incursDurable.output = JSON.stringify(value); }},
23  failure => {{ globalThis.__incursDurable.failure = String(failure); }}
24);
25"#
26    ))
27}
28
29/// Adapter-specific settings for the shared Code Mode JavaScript harness.
30#[derive(Debug, Clone)]
31pub struct ProgramSourceOptions {
32    /// JavaScript expression that evaluates to the asynchronous dispatch function.
33    pub dispatch: String,
34    /// JavaScript expression exposed as `codemode.executionId`.
35    pub execution_id: String,
36    /// Optional JavaScript timer timeout for hosts that provide `setTimeout`.
37    pub timeout_ms: Option<u64>,
38}
39
40/// Builds the shared body used by local and remote Code Mode executors.
41pub fn build_program_source(
42    code: &str,
43    connectors: &[ConnectorDescription],
44    options: &ProgramSourceOptions,
45) -> Result<String, String> {
46    validate_names(connectors)?;
47    let code = normalize_code(code);
48    // One lazy binding per namespace rather than a materialized object of methods.
49    // Writing the methods out required every connector's tool list, which meant
50    // describing — and so connecting to — every configured server before any
51    // program could run, including the ones the program never mentions. The proxy
52    // needs only the name; the connection opens on the first call.
53    let bindings = connectors
54        .iter()
55        .map(|connector| {
56            format!(
57                "const {} = __namespace({});",
58                connector.name,
59                serde_json::to_string(&connector.name).unwrap(),
60            )
61        })
62        .collect::<Vec<_>>()
63        .join("\n");
64    let run = if let Some(timeout_ms) = options.timeout_ms {
65        format!(
66            r#"await Promise.race([
67      __program(),
68      new Promise((_, reject) => setTimeout(() => reject(new Error("Code execution timed out after {timeout_ms}ms")), {timeout_ms}))
69    ])"#
70        )
71    } else {
72        "await __program()".to_string()
73    };
74    Ok(format!(
75        r#"const __logs = [];
76let __seq = 0;
77const console = {{
78  log: (...values) => __logs.push(values.map(String).join(" ")),
79  info: (...values) => __logs.push(values.map(String).join(" ")),
80  warn: (...values) => __logs.push(values.map(String).join(" ")),
81  error: (...values) => __logs.push(values.map(String).join(" "))
82}};
83const __base64Encode = (value) => {{
84  const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
85  let result = "";
86  for (let index = 0; index < value.length; index += 3) {{
87    const first = value[index];
88    const second = value[index + 1];
89    const third = value[index + 2];
90    result += alphabet[first >> 2];
91    result += alphabet[((first & 3) << 4) | ((second ?? 0) >> 4)];
92    result += second === undefined ? "=" : alphabet[((second & 15) << 2) | ((third ?? 0) >> 6)];
93    result += third === undefined ? "=" : alphabet[third & 63];
94  }}
95  return result;
96}};
97const __base64Decode = (value) => {{
98  const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
99  const clean = value.replace(/=+$/, "");
100  const bytes = [];
101  let buffer = 0;
102  let bits = 0;
103  for (const char of clean) {{
104    buffer = (buffer << 6) | alphabet.indexOf(char);
105    bits += 6;
106    if (bits >= 8) {{
107      bits -= 8;
108      bytes.push((buffer >> bits) & 255);
109    }}
110  }}
111  return new Uint8Array(bytes);
112}};
113const __encode = (value, ancestors = new WeakSet(), omitUndefinedProperties = false) => {{
114  if (typeof value === "function") {{
115    if (value.__workflow_ref) return {{__workflow_ref:__encode(value.__workflow_ref, ancestors, omitUndefinedProperties)}};
116    throw new TypeError("WORKFLOW_BINDINGS: functions require explicit portable definitions");
117  }}
118  if (value === undefined) return {{ __codemode_type: "undefined" }};
119  if (typeof value === "bigint") return {{ __codemode_type: "bigint", value: value.toString() }};
120  if (value instanceof Uint8Array) return {{ __codemode_type: "binary", value: __base64Encode(value) }};
121  if (value && typeof value === "object") {{
122    if (ancestors.has(value)) throw new TypeError("CODE_VALUE_CYCLE: cyclic values cannot cross the Code Mode boundary");
123    ancestors.add(value);
124    try {{
125      if (Array.isArray(value)) return value.map(child => __encode(child, ancestors, omitUndefinedProperties));
126      const entries = Object.entries(value);
127      return Object.fromEntries((omitUndefinedProperties ? entries.filter(([, child]) => child !== undefined) : entries)
128        .map(([key, child]) => [key, __encode(child, ancestors, omitUndefinedProperties)]));
129    }} finally {{
130      ancestors.delete(value);
131    }}
132  }}
133  return value;
134}};
135const __decode = (value) => {{
136  if (Array.isArray(value)) return value.map(__decode);
137  if (value && typeof value === "object") {{
138    if (value.__codemode_type === "undefined") return undefined;
139    if (value.__codemode_type === "bigint") return BigInt(value.value);
140    if (value.__codemode_type === "binary") return __base64Decode(value.value);
141    return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, __decode(child)]));
142  }}
143  return value;
144}};
145const __dispatch = {dispatch};
146const __unwrap = (response) => {{
147  if (response.__codemode_control__ === "pause") throw new Error("__CODEMODE_PAUSE__");
148  if (response.__codemode_control__ === "error") throw new Error(response.message);
149  if (response.result && response.result.__workflow_error) throw new Error(response.result.__workflow_error);
150  return __decode(response.result);
151}};
152const __namespace = (name) => new Proxy({{}}, {{
153  get: (_target, method) => {{
154    // Only `then` is withheld, and only because a namespace must not look
155    // thenable: awaiting one, or returning it from an async function, probes
156    // `then` and would otherwise receive a dispatch function and hang. Every
157    // other name is forwarded, because anything withheld here silently deletes a
158    // tool that is legitimately called that -- `inspect` and `constructor` are
159    // both real tool names in this workspace.
160    if (typeof method !== "string" || method === "then") return undefined;
161    return async (args = {{}}) => __unwrap(await __dispatch({{
162      kind: "call",
163      seq: __seq++,
164      connector: name,
165      method,
166      arguments: __encode(args, undefined, true)
167    }}));
168  }},
169  has: () => true
170}});
171{bindings}
172const __callBuiltin = async (method, args) => __unwrap(await __dispatch({{
173  kind: "call",
174  seq: __seq++,
175  connector: "codemode",
176  method,
177  arguments: __encode(args, undefined, true)
178}}));
179const codemode = {{
180  executionId: {execution_id},
181  search: (query) => __callBuiltin("search", {{ query }}),
182  describe: (target) => __callBuiltin("describe", {{ target }}),
183  step: async (name, fn) => {{
184    const seq = __seq++;
185    const decision = await __dispatch({{ kind: "begin_step", seq, name }});
186    if (decision.kind === "pause") throw new Error("__CODEMODE_PAUSE__");
187    if (decision.kind === "replay") return __decode(decision.result);
188    const result = await fn();
189    await __dispatch({{ kind: "record_step", seq, result: __encode(result) }});
190    return result;
191  }}
192}};
193{workflow_program}
194try {{
195  const __program = ({code});
196  const __result = {run};
197  return {{ result: __encode(__result), error: null, logs: __logs }};
198}} catch (error) {{
199  return {{
200    result: null,
201    error: error instanceof Error ? error.message : String(error),
202    logs: __logs
203  }};
204}}"#,
205        workflow_program = include_str!("workflow_program.js"),
206        dispatch = options.dispatch,
207        execution_id = options.execution_id,
208    ))
209}
210
211/// Names the generated program already binds, or that JavaScript refuses as a
212/// binding.
213///
214/// A connector taking one of these produces a `const` redeclaration or a parse
215/// error inside the sandbox, which surfaces far from its cause, so it is
216/// rejected here where the name is still attributable to a connector.
217pub(crate) const RESERVED_CONNECTOR_NAMES: &[&str] = &[
218    // Bindings emitted by `build_program_source`, in declaration order.
219    "__incursDispatch",
220    "__workflowAPI",
221    "__dispatch",
222    "__encode",
223    "__decode",
224    "__unwrap",
225    "__seq",
226    "__logs",
227    "__program",
228    "__result",
229    "__base64Encode",
230    "__base64Decode",
231    "__callBuiltin",
232    "codemode",
233    "console",
234    // Globals the harness itself calls.
235    "Promise",
236    "setTimeout",
237    "Error",
238    "fetch",
239    "JSON",
240    "Object",
241    "Array",
242    "String",
243    "Number",
244    "Boolean",
245    "BigInt",
246    "Uint8Array",
247    "Math",
248    "Symbol",
249    "globalThis",
250    // Reserved words. `valid_identifier` accepts these, but `const <word> = …`
251    // is a syntax error.
252    "await",
253    "break",
254    "case",
255    "catch",
256    "class",
257    "const",
258    "continue",
259    "debugger",
260    "default",
261    "delete",
262    "do",
263    "else",
264    "enum",
265    "export",
266    "extends",
267    "false",
268    "finally",
269    "for",
270    "function",
271    "if",
272    "implements",
273    "import",
274    "in",
275    "instanceof",
276    "interface",
277    "let",
278    "new",
279    "null",
280    "package",
281    "private",
282    "protected",
283    "public",
284    "return",
285    "static",
286    "super",
287    "switch",
288    "this",
289    "throw",
290    "true",
291    "try",
292    "typeof",
293    "var",
294    "void",
295    "while",
296    "with",
297    "yield",
298];
299
300fn validate_names(connectors: &[ConnectorDescription]) -> Result<(), String> {
301    let mut seen = std::collections::BTreeSet::new();
302    for connector in connectors {
303        if RESERVED_CONNECTOR_NAMES.contains(&connector.name.as_str()) {
304            return Err(format!("Connector name \"{}\" is reserved", connector.name));
305        }
306        if !valid_identifier(&connector.name) {
307            return Err(format!(
308                "Connector name \"{}\" is not a valid JavaScript identifier",
309                connector.name
310            ));
311        }
312        if !seen.insert(&connector.name) {
313            return Err(format!("Duplicate connector name \"{}\"", connector.name));
314        }
315        let mut methods = std::collections::BTreeSet::new();
316        for tool in &connector.tools {
317            if !methods.insert(&tool.name) {
318                return Err(format!(
319                    "Duplicate tool name \"{}\" in connector \"{}\"",
320                    tool.name, connector.name
321                ));
322            }
323        }
324    }
325    Ok(())
326}
327
328fn valid_identifier(value: &str) -> bool {
329    let mut chars = value.chars();
330    chars
331        .next()
332        .is_some_and(|ch| ch == '_' || ch == '$' || ch.is_ascii_alphabetic())
333        && chars.all(|ch| ch == '_' || ch == '$' || ch.is_ascii_alphanumeric())
334}
335
336#[cfg(test)]
337mod tests {
338    use serde_json::json;
339
340    use crate::{ConnectorTool, ToolAnnotations};
341
342    use super::*;
343
344    #[test]
345    fn emits_shared_connector_and_step_harness() {
346        let source = build_program_source(
347            "state.read({ id: 1 })",
348            &[ConnectorDescription {
349                name: "state".to_string(),
350                instructions: None,
351                tools: vec![ConnectorTool {
352                    name: "read".to_string(),
353                    description: None,
354                    input_schema: json!({"type": "object"}),
355                    output_schema: None,
356                    instructions: None,
357                    examples: Vec::new(),
358                    annotations: ToolAnnotations::default(),
359                    policy: crate::ToolPolicy::default(),
360                }],
361            }],
362            &ProgramSourceOptions {
363                dispatch: "async (payload) => payload".to_string(),
364                execution_id: "\"test\"".to_string(),
365                timeout_ms: None,
366            },
367        )
368        .unwrap();
369
370        assert!(source.contains("const state"));
371        assert!(source.contains("const __dispatch = async (payload) => payload"));
372        assert!(source.contains("step: async (name, fn)"));
373    }
374
375    fn named(name: &str) -> ConnectorDescription {
376        ConnectorDescription {
377            name: name.to_string(),
378            instructions: None,
379            tools: vec![ConnectorTool {
380                name: "read".to_string(),
381                description: None,
382                input_schema: json!({"type": "object"}),
383                output_schema: None,
384                instructions: None,
385                examples: Vec::new(),
386                annotations: ToolAnnotations::default(),
387                policy: crate::ToolPolicy::default(),
388            }],
389        }
390    }
391
392    fn build(name: &str) -> Result<String, String> {
393        build_program_source(
394            "return 1",
395            &[named(name)],
396            &ProgramSourceOptions {
397                dispatch: "async (payload) => payload".to_string(),
398                execution_id: "\"test\"".to_string(),
399                timeout_ms: None,
400            },
401        )
402    }
403
404    #[test]
405    fn rejects_names_the_harness_already_binds() {
406        // These are `const`-declared by `build_program_source` itself, so a
407        // connector taking one produces a redeclaration inside the sandbox.
408        for name in ["__callBuiltin", "__base64Encode", "__base64Decode"] {
409            assert!(
410                build(name).is_err(),
411                "{name} is bound by the harness but was accepted"
412            );
413        }
414    }
415
416    #[test]
417    fn rejects_reserved_words_that_cannot_be_bound() {
418        // `valid_identifier` accepts each of these, but `const class = {…}` is
419        // a syntax error that would surface far from the offending connector.
420        for name in ["class", "default", "delete", "new", "import", "return"] {
421            assert!(
422                build(name).is_err(),
423                "reserved word {name} was accepted as a connector name"
424            );
425        }
426    }
427
428    #[test]
429    fn accepts_an_ordinary_name_that_merely_resembles_a_reserved_one() {
430        // The guard is exact-match, so renaming around a collision works.
431        for name in ["mcp_fetch", "classroom", "defaults", "newRelic"] {
432            assert!(build(name).is_ok(), "{name} should be a usable namespace");
433        }
434    }
435}