a3s-code-core 3.1.0

A3S Code Core - Embeddable AI agent library with tool execution
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
//! Tool wrapper for programmatic tool calling.

use crate::program::ProgramCatalog;
use crate::text::truncate_utf8;
use crate::tools::types::{Tool, ToolContext, ToolOutput};
use crate::tools::ToolRegistry;
use anyhow::{anyhow, Result};
use async_trait::async_trait;
use rquickjs::function::{Async, Func};
use rquickjs::{async_with, AsyncContext, AsyncRuntime, CatchResultExt, Error as JsError, Promise};
use serde::Deserialize;
use std::collections::HashSet;
use std::sync::Arc;
use std::time::Instant;
use tokio::sync::Mutex;
use tokio::time::{timeout, Duration};

const DEFAULT_SCRIPT_TIMEOUT_MS: u64 = 30_000;
const DEFAULT_SCRIPT_MAX_TOOL_CALLS: usize = 20;
const DEFAULT_SCRIPT_MAX_OUTPUT_BYTES: usize = 64 * 1024;
const MAX_SCRIPT_SOURCE_BYTES: usize = 64 * 1024;

pub struct ProgramTool {
    registry: Arc<ToolRegistry>,
}

impl ProgramTool {
    pub fn new(registry: Arc<ToolRegistry>) -> Self {
        Self { registry }
    }

    pub fn with_catalog(registry: Arc<ToolRegistry>, _catalog: ProgramCatalog) -> Self {
        Self { registry }
    }
}

#[async_trait]
impl Tool for ProgramTool {
    fn name(&self) -> &str {
        "program"
    }

    fn description(&self) -> &str {
        "Run a sandboxed JavaScript PTC script. The script defines async function run(ctx, inputs) and may call only allowed ctx tools."
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "additionalProperties": false,
            "properties": {
                "type": {
                    "type": "string",
                    "description": "Required. Program kind. Only \"script\" is supported.",
                    "enum": ["script"]
                },
                "inputs": {
                    "type": "object",
                    "description": "Optional. JSON inputs passed to the script as the second argument."
                },
                "language": {
                    "type": "string",
                    "description": "Script language. Only JavaScript is supported.",
                    "enum": ["javascript"]
                },
                "source": {
                    "type": "string",
                    "description": "Inline JavaScript source defining async function run(ctx, inputs)."
                },
                "path": {
                    "type": "string",
                    "description": "Workspace-relative path to a .js or .mjs script defining async function run(ctx, inputs). Used when source is omitted."
                },
                "allowed_tools": {
                    "type": "array",
                    "description": "Tool names the script may call through ctx. Defaults to all registered tools except program.",
                    "items": { "type": "string" }
                },
                "limits": {
                    "type": "object",
                    "description": "Optional timeoutMs, maxToolCalls, and maxOutputBytes.",
                    "additionalProperties": false,
                    "properties": {
                        "timeoutMs": { "type": "integer", "minimum": 1 },
                        "maxToolCalls": { "type": "integer", "minimum": 1 },
                        "maxOutputBytes": { "type": "integer", "minimum": 1 }
                    }
                }
            },
            "required": ["type"]
        })
    }

    async fn execute(&self, args: &serde_json::Value, ctx: &ToolContext) -> Result<ToolOutput> {
        let Some(kind) = args.get("type").and_then(|value| value.as_str()) else {
            return Ok(ToolOutput::error("type parameter is required"));
        };
        if kind != "script" {
            return Ok(ToolOutput::error(format!(
                "Unsupported program type: {kind}. Only \"script\" is supported."
            )));
        }
        let inputs = args
            .get("inputs")
            .cloned()
            .unwrap_or_else(|| serde_json::json!({}));

        execute_script_program(args, inputs, Arc::clone(&self.registry), ctx).await
    }
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ScriptLimits {
    timeout_ms: Option<u64>,
    max_tool_calls: Option<usize>,
    max_output_bytes: Option<usize>,
}

#[derive(Debug, Clone)]
struct ScriptCallRecord {
    tool_name: String,
    success: bool,
    exit_code: i32,
    output_bytes: usize,
    metadata: Option<serde_json::Value>,
}

async fn execute_script_program(
    args: &serde_json::Value,
    inputs: serde_json::Value,
    registry: Arc<ToolRegistry>,
    ctx: &ToolContext,
) -> Result<ToolOutput> {
    let language = args
        .get("language")
        .and_then(|value| value.as_str())
        .unwrap_or("javascript");
    if language != "javascript" {
        return Ok(ToolOutput::error(format!(
            "Unsupported script language: {language}"
        )));
    }

    let source = match load_script_source(args, ctx).await {
        Ok(source) => source,
        Err(message) => return Ok(ToolOutput::error(message)),
    };
    if source.len() > MAX_SCRIPT_SOURCE_BYTES {
        return Ok(ToolOutput::error(format!(
            "script source is too large: {} bytes exceeds {} bytes",
            source.len(),
            MAX_SCRIPT_SOURCE_BYTES
        )));
    }
    if let Err(message) = validate_script_source(&source) {
        return Ok(ToolOutput::error(message));
    }

    let allowed_tools = script_allowed_tools(args, &registry);
    let limits = script_limits(args);
    match run_quickjs_script(
        &source,
        inputs,
        registry,
        ctx.clone(),
        allowed_tools,
        limits,
    )
    .await
    {
        Ok(output) => Ok(output),
        Err(err) => Ok(ToolOutput::error(format!("program script failed: {err}"))),
    }
}

async fn load_script_source(
    args: &serde_json::Value,
    ctx: &ToolContext,
) -> std::result::Result<String, String> {
    if let Some(source) = args.get("source").and_then(|value| value.as_str()) {
        return Ok(source.to_string());
    }

    let Some(path) = args.get("path").and_then(|value| value.as_str()) else {
        return Err("program script requires either source or path".to_string());
    };
    if !(path.ends_with(".js") || path.ends_with(".mjs")) {
        return Err("program script path must point to a .js or .mjs file".to_string());
    }

    let workspace_path = ctx
        .resolve_workspace_path(path)
        .map_err(|err| format!("failed to resolve script path: {err}"))?;
    ctx.workspace_services
        .fs()
        .read_text(&workspace_path)
        .await
        .map_err(|err| format!("failed to read script path '{}': {err}", path))
}

fn script_allowed_tools(args: &serde_json::Value, registry: &ToolRegistry) -> HashSet<String> {
    let mut allowed = args
        .get("allowed_tools")
        .and_then(|value| value.as_array())
        .map(|items| {
            items
                .iter()
                .filter_map(|item| item.as_str())
                .map(ToString::to_string)
                .collect::<HashSet<_>>()
        })
        .unwrap_or_else(|| registry.list().into_iter().collect());

    allowed.remove("program");
    allowed
}

fn script_limits(args: &serde_json::Value) -> ScriptLimits {
    args.get("limits")
        .cloned()
        .and_then(|value| serde_json::from_value(value).ok())
        .unwrap_or(ScriptLimits {
            timeout_ms: None,
            max_tool_calls: None,
            max_output_bytes: None,
        })
}

fn validate_script_source(source: &str) -> std::result::Result<(), String> {
    let forbidden = [
        ("import ", "imports are not allowed inside PTC scripts"),
        (
            "import(",
            "dynamic imports are not allowed inside PTC scripts",
        ),
        ("eval(", "eval is not allowed inside PTC scripts"),
        (
            "Function(",
            "Function constructor is not allowed inside PTC scripts",
        ),
        ("Worker(", "Worker is not allowed inside PTC scripts"),
        ("WebSocket", "WebSocket is not allowed inside PTC scripts"),
        (
            "fetch(",
            "fetch is not allowed inside PTC scripts; use ctx tools instead",
        ),
    ];

    for (needle, message) in forbidden {
        if source.contains(needle) {
            return Err(message.to_string());
        }
    }
    Ok(())
}

async fn run_quickjs_script(
    source: &str,
    inputs: serde_json::Value,
    registry: Arc<ToolRegistry>,
    ctx: ToolContext,
    allowed_tools: HashSet<String>,
    limits: ScriptLimits,
) -> Result<ToolOutput> {
    let timeout_ms = limits.timeout_ms.unwrap_or(DEFAULT_SCRIPT_TIMEOUT_MS);
    let max_tool_calls = limits
        .max_tool_calls
        .unwrap_or(DEFAULT_SCRIPT_MAX_TOOL_CALLS);
    let max_output_bytes = limits
        .max_output_bytes
        .unwrap_or(DEFAULT_SCRIPT_MAX_OUTPUT_BYTES);
    let executable_source = script_source_with_host_entrypoint(source)?;
    let state = Arc::new(Mutex::new(ScriptVmState {
        registry,
        ctx,
        allowed_tools,
        max_tool_calls,
        max_output_bytes,
        tool_calls: 0,
        records: Vec::new(),
    }));

    let vm_state = Arc::clone(&state);
    let result = timeout(
        Duration::from_millis(timeout_ms),
        tokio::task::spawn_blocking(move || {
            let runtime = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .map_err(|err| anyhow!("failed to create program VM runtime: {err}"))?;
            runtime.block_on(run_embedded_script(
                executable_source,
                inputs,
                vm_state,
                timeout_ms,
            ))
        }),
    )
    .await;

    match result {
        Ok(Ok(Ok(result))) => {
            let records = state.lock().await.records.clone();
            let output = render_script_output(&result, &records, "");
            Ok(ToolOutput::success(output).with_metadata(serde_json::json!({
                "program": {
                    "name": "script",
                    "language": "javascript",
                    "runtime": "embedded-quickjs",
                    "success": true,
                    "tool_calls": records.iter().map(script_record_to_value).collect::<Vec<_>>(),
                },
                "script_result": result,
            })))
        }
        Ok(Ok(Err(err))) if is_quickjs_timeout(&err) => Ok(ToolOutput::error(format!(
            "program script timed out after {timeout_ms} ms"
        ))),
        Ok(Ok(Err(err))) => Ok(ToolOutput::error(format!("program script error:\n{err}"))),
        Ok(Err(err)) => Ok(ToolOutput::error(format!(
            "program VM thread failed: {err}"
        ))),
        Err(_) => Ok(ToolOutput::error(format!(
            "program script timed out after {timeout_ms} ms"
        ))),
    }
}

fn script_source_with_host_entrypoint(source: &str) -> Result<String> {
    let rewritten = if source.contains("export default async function run") {
        source.replacen("export default async function run", "async function run", 1)
    } else if source.contains("export default function run") {
        source.replacen("export default function run", "function run", 1)
    } else if source.contains("async function run") || source.contains("function run") {
        source.to_string()
    } else {
        return Err(anyhow!(
            "PTC script must define async function run(ctx, inputs)"
        ));
    };

    Ok(format!(
        r#"{rewritten}

globalThis.__a3sResultJson = (async () => JSON.stringify(await run(globalThis.__a3sCtx, globalThis.__a3sInputs)))();
"#
    ))
}

async fn run_embedded_script(
    source: String,
    inputs: serde_json::Value,
    state: Arc<Mutex<ScriptVmState>>,
    timeout_ms: u64,
) -> Result<serde_json::Value> {
    let runtime = AsyncRuntime::new()?;
    let started = Instant::now();
    runtime
        .set_interrupt_handler(Some(Box::new(move || {
            started.elapsed() >= Duration::from_millis(timeout_ms)
        })))
        .await;
    runtime.set_memory_limit(64 * 1024 * 1024).await;
    runtime.set_max_stack_size(512 * 1024).await;

    let context = AsyncContext::full(&runtime).await?;
    let inputs_json = serde_json::to_string(&inputs)?;
    let script = format!("{}\n{}", embedded_script_bootstrap(&inputs_json), source);
    let result_json = async_with!(context => |ctx| {
        let state = Arc::clone(&state);
        let host_tool = move |tool: String, args_json: String| {
            let state = Arc::clone(&state);
            async move { execute_host_tool_json(state, tool, args_json).await }
        };
        if let Err(err) = ctx.globals().set("__a3sHostTool", Func::from(Async(host_tool))) {
            return Err(format!("failed to install program host tool: {err}"));
        }
        let promise: Promise = match ctx.eval(script) {
            Ok(promise) => promise,
            Err(err) => return Err(format!("failed to evaluate program script: {err}")),
        };
        promise
            .into_future::<String>()
            .await
            .catch(&ctx)
            .map_err(|err| err.to_string())
    })
    .await
    .map_err(anyhow::Error::msg)?;

    serde_json::from_str(&result_json)
        .map_err(|err| anyhow!("program script returned invalid JSON: {err}"))
}

struct ScriptVmState {
    registry: Arc<ToolRegistry>,
    ctx: ToolContext,
    allowed_tools: HashSet<String>,
    max_tool_calls: usize,
    max_output_bytes: usize,
    tool_calls: usize,
    records: Vec<ScriptCallRecord>,
}

fn embedded_script_bootstrap(inputs_json: &str) -> String {
    format!(
        r#"
const __a3sCallTool = async (tool, args = {{}}) => {{
  const response = await globalThis.__a3sHostTool(String(tool), JSON.stringify(args ?? {{}}));
  return JSON.parse(response);
}};

const __a3sCtx = Object.freeze({{
  tool: __a3sCallTool,
  readFile: (path) => __a3sCallTool("read", {{ file_path: path }}).then((r) => r.output),
  read: (path) => __a3sCallTool("read", {{ file_path: path }}),
  grep: (pattern, options = {{}}) => __a3sCallTool("grep", {{ pattern, ...options }}).then((r) => r.output),
  glob: (pattern, options = {{}}) => __a3sCallTool("glob", {{ pattern, ...options }}).then((r) => r.output),
  ls: (path = ".") => __a3sCallTool("ls", {{ path }}).then((r) => r.output),
  bash: (command) => __a3sCallTool("bash", {{ command }}).then((r) => r.output),
  git: (args = {{}}) => __a3sCallTool("git", args),
  webSearch: (params) => __a3sCallTool("web_search", params),
  verify: (args) => __a3sCallTool("bash", args),
}});

Object.defineProperty(globalThis, "__a3sCtx", {{ value: __a3sCtx, configurable: false }});
Object.defineProperty(globalThis, "__a3sInputs", {{ value: {inputs_json}, configurable: false }});
Object.defineProperty(globalThis, "fetch", {{ value: undefined, configurable: false, writable: false }});
Object.defineProperty(globalThis, "WebSocket", {{ value: undefined, configurable: false, writable: false }});
Object.defineProperty(globalThis, "Worker", {{ value: undefined, configurable: false, writable: false }});
"#
    )
}

async fn execute_host_tool_json(
    state: Arc<Mutex<ScriptVmState>>,
    tool: String,
    args_json: String,
) -> rquickjs::Result<String> {
    let args = serde_json::from_str(&args_json).map_err(|err| {
        JsError::new_from_js_message("string", "object", format!("invalid tool args JSON: {err}"))
    })?;
    let (registry, ctx, max_output_bytes) = {
        let mut script = state.lock().await;
        if !script.allowed_tools.contains(&tool) {
            return Err(JsError::new_from_js_message(
                "tool",
                "allowed tool",
                format!("tool '{tool}' is not allowed for this PTC script"),
            ));
        }
        script.tool_calls += 1;
        if script.tool_calls > script.max_tool_calls {
            return Err(JsError::new_from_js_message(
                "tool call",
                "limited tool call",
                format!("PTC script exceeded maxToolCalls={}", script.max_tool_calls),
            ));
        }
        (
            Arc::clone(&script.registry),
            script.ctx.clone(),
            script.max_output_bytes,
        )
    };

    let result = registry
        .execute_with_context(&tool, &args, &ctx)
        .await
        .map_err(|err| JsError::new_from_js_message("tool", "result", err.to_string()))?;
    let mut output = result.output;
    if output.len() > max_output_bytes {
        output = truncate_utf8(&output, max_output_bytes).to_string();
    }
    let success = result.exit_code == 0;
    let metadata = result.metadata.clone();
    let exit_code = result.exit_code;
    let name = result.name;

    {
        let mut script = state.lock().await;
        script.records.push(ScriptCallRecord {
            tool_name: tool,
            success,
            exit_code,
            output_bytes: output.len(),
            metadata: metadata.clone(),
        });
    }

    serde_json::to_string(&serde_json::json!({
        "name": name,
        "output": output,
        "exitCode": exit_code,
        "metadata": metadata,
    }))
    .map_err(|err| JsError::new_from_js_message("tool result", "json", err.to_string()))
}

fn is_quickjs_timeout(err: &anyhow::Error) -> bool {
    let text = err.to_string();
    text.contains("interrupted") || text.contains("InternalError")
}

fn script_record_to_value(record: &ScriptCallRecord) -> serde_json::Value {
    serde_json::json!({
        "tool_name": record.tool_name,
        "success": record.success,
        "exit_code": record.exit_code,
        "output_bytes": record.output_bytes,
        "metadata": record.metadata,
    })
}

fn render_script_output(
    result: &serde_json::Value,
    records: &[ScriptCallRecord],
    stderr: &str,
) -> String {
    let mut output = String::from("Program script completed.");
    if let Some(summary) = result.get("summary").and_then(|value| value.as_str()) {
        output.push('\n');
        output.push_str(summary);
    }

    output.push_str(&format!("\n\nTool calls: {}", records.len()));
    for (index, record) in records.iter().enumerate() {
        output.push_str(&format!(
            "\n{}. {} ({}, exit_code={}, output_bytes={})",
            index + 1,
            record.tool_name,
            if record.success { "ok" } else { "failed" },
            record.exit_code,
            record.output_bytes
        ));
    }

    output.push_str("\n\nResult:\n");
    output.push_str(&serde_json::to_string_pretty(result).unwrap_or_else(|_| result.to_string()));

    if !stderr.is_empty() {
        output.push_str("\n\nstderr:\n");
        output.push_str(stderr);
    }

    output
}

#[cfg(test)]
mod tests {
    use super::*;
    use async_trait::async_trait;
    use std::path::PathBuf;

    struct EchoTool;

    #[async_trait]
    impl Tool for EchoTool {
        fn name(&self) -> &str {
            "echo"
        }

        fn description(&self) -> &str {
            "Echo test tool"
        }

        fn parameters(&self) -> serde_json::Value {
            serde_json::json!({
                "type": "object",
                "properties": {
                    "message": { "type": "string" }
                }
            })
        }

        async fn execute(
            &self,
            args: &serde_json::Value,
            _ctx: &ToolContext,
        ) -> Result<ToolOutput> {
            let message = args
                .get("message")
                .and_then(|value| value.as_str())
                .unwrap_or("");
            Ok(ToolOutput::success(format!("echo:{message}")))
        }
    }

    #[tokio::test]
    async fn program_tool_rejects_non_script_type() {
        let tool = ProgramTool::new(Arc::new(ToolRegistry::new(PathBuf::from("/tmp"))));
        let output = tool
            .execute(
                &serde_json::json!({ "type": "program_code_search" }),
                &ToolContext::new(PathBuf::from("/tmp")),
            )
            .await
            .unwrap();

        assert!(!output.success);
        assert!(output.content.contains("Only \"script\" is supported"));
    }

    #[tokio::test]
    async fn program_tool_rejects_missing_script_source_and_path() {
        let tool = ProgramTool::new(Arc::new(ToolRegistry::new(PathBuf::from("/tmp"))));
        let output = tool
            .execute(
                &serde_json::json!({ "type": "script" }),
                &ToolContext::new(PathBuf::from("/tmp")),
            )
            .await
            .unwrap();

        assert!(!output.success);
        assert!(output.content.contains("requires either source or path"));
    }

    #[tokio::test]
    async fn program_tool_rejects_unsupported_language() {
        let tool = ProgramTool::new(Arc::new(ToolRegistry::new(PathBuf::from("/tmp"))));
        let output = tool
            .execute(
                &serde_json::json!({
                    "type": "script",
                    "language": "typescript",
                    "source": "async function run() { return {}; }"
                }),
                &ToolContext::new(PathBuf::from("/tmp")),
            )
            .await
            .unwrap();

        assert!(!output.success);
        assert!(output.content.contains("Unsupported script language"));
    }

    #[tokio::test]
    async fn program_tool_rejects_unsupported_script_path() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("script.txt"), "async function run() {}").unwrap();
        let tool = ProgramTool::new(Arc::new(ToolRegistry::new(dir.path().to_path_buf())));
        let output = tool
            .execute(
                &serde_json::json!({
                    "type": "script",
                    "path": "script.txt"
                }),
                &ToolContext::new(dir.path().to_path_buf()),
            )
            .await
            .unwrap();

        assert!(!output.success);
        assert!(output.content.contains(".js or .mjs file"));
    }

    #[test]
    fn program_tool_default_allowed_tools_include_registry_tools_except_program() {
        let registry = ToolRegistry::new(PathBuf::from("/tmp"));
        registry.register(Arc::new(EchoTool));
        registry.register_builtin(Arc::new(ProgramTool::new(Arc::new(ToolRegistry::new(
            PathBuf::from("/tmp"),
        )))));

        let allowed = script_allowed_tools(&serde_json::json!({}), &registry);

        assert!(allowed.contains("echo"));
        assert!(!allowed.contains("program"));
    }

    #[tokio::test]
    async fn program_tool_source_uses_default_all_registered_tools() {
        let registry = Arc::new(ToolRegistry::new(PathBuf::from("/tmp")));
        registry.register(Arc::new(EchoTool));
        let tool = ProgramTool::new(Arc::clone(&registry));
        let output = tool
            .execute(
                &serde_json::json!({
                    "type": "script",
                    "source": r#"
                        async function run(ctx, inputs) {
                            const result = await ctx.tool("echo", { message: inputs.message });
                            return { summary: result.output, result };
                        }
                    "#,
                    "inputs": { "message": "hello" }
                }),
                &ToolContext::new(PathBuf::from("/tmp")),
            )
            .await
            .unwrap();

        assert!(output.success, "{}", output.content);
        assert!(output.content.contains("echo:hello"));
        let metadata = output.metadata.unwrap();
        assert_eq!(metadata["program"]["runtime"], "embedded-quickjs");
        assert_eq!(metadata["script_result"]["summary"], "echo:hello");
    }

    #[tokio::test]
    async fn program_tool_explicit_allowed_tools_restrict_default_tools() {
        let registry = Arc::new(ToolRegistry::new(PathBuf::from("/tmp")));
        registry.register(Arc::new(EchoTool));
        let tool = ProgramTool::new(Arc::clone(&registry));
        let output = tool
            .execute(
                &serde_json::json!({
                    "type": "script",
                    "source": r#"
                        async function run(ctx) {
                            await ctx.tool("echo", { message: "blocked" });
                            return {};
                        }
                    "#,
                    "allowed_tools": ["read"]
                }),
                &ToolContext::new(PathBuf::from("/tmp")),
            )
            .await
            .unwrap();

        assert!(!output.success);
        assert!(output.content.contains("tool 'echo' is not allowed"));
    }

    #[tokio::test]
    async fn program_tool_enforces_max_tool_calls() {
        let registry = Arc::new(ToolRegistry::new(PathBuf::from("/tmp")));
        registry.register(Arc::new(EchoTool));
        let tool = ProgramTool::new(Arc::clone(&registry));
        let output = tool
            .execute(
                &serde_json::json!({
                    "type": "script",
                    "source": r#"
                        async function run(ctx) {
                            await ctx.tool("echo", { message: "one" });
                            await ctx.tool("echo", { message: "two" });
                            return {};
                        }
                    "#,
                    "limits": { "maxToolCalls": 1 }
                }),
                &ToolContext::new(PathBuf::from("/tmp")),
            )
            .await
            .unwrap();

        assert!(!output.success);
        assert!(output.content.contains("exceeded maxToolCalls=1"));
    }

    #[test]
    fn program_tool_rejects_fetch_source_access() {
        let err =
            validate_script_source("export default async function run() { return fetch('/'); }")
                .unwrap_err();
        assert!(err.contains("fetch is not allowed"));
    }

    #[test]
    fn program_tool_accepts_plain_function_run_entrypoint() {
        let source = script_source_with_host_entrypoint(
            "async function run(ctx, inputs) { return { summary: inputs.message }; }",
        )
        .unwrap();

        assert!(source.contains("globalThis.__a3sResultJson"));
        assert!(source.contains("async function run"));
    }

    #[test]
    fn program_tool_renders_result_summary_and_tool_records() {
        let output = render_script_output(
            &serde_json::json!({ "summary": "done", "items": [1] }),
            &[ScriptCallRecord {
                tool_name: "echo".to_string(),
                success: true,
                exit_code: 0,
                output_bytes: 8,
                metadata: Some(serde_json::json!({ "kind": "test" })),
            }],
            "",
        );

        assert!(output.contains("Program script completed."));
        assert!(output.contains("done"));
        assert!(output.contains("echo (ok"));
        assert!(output.contains("\"items\""));
    }
}