#!/usr/bin/env raku
# Rakuish V3 Agent —— 类型化 JSON-RPC 服务入口（ADR-0001 / Phase 4）
#
# 用法：
#   raku bin/rakuish-agent --root /work --token SECRET
#       < requests.jsonl                      # JSONL over stdin/stdout（默认）
#   raku bin/rakuish-agent --root /work --mode tcp --port 0
#   raku bin/rakuish-agent --root /work --mode tcp --serve --worker
#
# 每行一个结构化请求（不是 shell 字符串）：
#   {"id":1,"token":"SECRET","op":"read_file","path":"a.txt"}
#   {"id":2,"token":"SECRET","op":"write_file","path":"b.txt","content":"hi"}
#   {"id":3,"token":"SECRET","op":"exec","argv":["git","status"]}
#
# 默认安全：只监听 127.0.0.1、必须带 token、显式 root、exec 默认关闭、
# 读写 1 MiB、超时 30s、输出 1 MiB、审计 JSONL。见 docs/DESIGN-RAKU-NATIVE.md §6.3。

use lib $?FILE.IO.parent.parent.add('lib');   # 不用 .dirname：Windows 上会丢盘符
use JSON::Fast;
use Rakuish::Sandbox;
use Rakuish::Agent::Server;
use Rakuish::Agent::Worker;
use Rakuish::Sys;

my constant VERSION = '0.74.0';   # 与 META6.json 同步

my constant AGENT-OPTIONS = <
    root token allow db engine max-rows sql-timeout-ms request-timeout-ms
    audit max-bytes timeout-ms max-output mode max-connections port
    idle-timeout-ms session
>;

sub help-text(--> Str) {
    q:to/END/
    Rakuish V3 Agent · 类型化 JSON-RPC

    用法
      raku bin/rakuish-agent --root DIR [选项]       默认 JSONL over stdin/stdout
      raku bin/rakuish-agent --root DIR --mode tcp   TCP（只绑 127.0.0.1）

    选项
      --root DIR          文件根（必填，所有路径必须在其内）
      --token STR         认证 token（不指定则启动时生成并打印到 stderr）
      --allow-exec        显式开启 exec（默认关闭）
      --allow-pty         显式开启 pty_exec（还需 --allow-exec；默认关闭）
      --allow LIST        逗号分隔的命令白名单，如 git,rg
      --allow-sql         显式开启只读 sql_query（默认关闭）
      --db PATH           只读数据库文件（配合 --allow-sql）
      --engine NAME       duckdb（默认）或 sqlite
      --max-rows N        sql_query 最大返回行数（默认 1000）
      --sql-timeout-ms N  DuckDB/SQLite 单次查询超时（默认 30000；0 = 不限制）
      --request-timeout-ms N  单个请求 deadline（默认 30000；0 = 不限制）
      --audit PATH        审计日志 JSONL 路径
      --max-bytes N       读写上限（默认 1 MiB）
      --timeout-ms N      exec 超时（默认 30s）
      --max-output N      输出上限（默认 1 MiB）
      --mode jsonl|tcp    传输模式（默认 jsonl）
      --serve             TCP 常驻多客户端（默认仍是 serve-once 单连接）
      --worker            --serve 时每连接独立子进程；超时可 OS 级 kill
      --max-connections N 常驻模式最大同时连接数（默认 16）
      --port N            TCP 端口（0 = 系统分配）
      --idle-timeout-ms N 连接空闲超时（默认 30000）
      --session STR       会话 id（写入审计；常驻模式按连接加 -cN 后缀）
      --help / --version
      注意：TCP 固定只绑 127.0.0.1，刻意不提供 --host 覆盖（设计 §6.3）。
      --worker 需与 --mode tcp --serve 同用；超时后该连接关闭，需重连。

    op（结构化参数，绝无 shell 字符串）
      read_file / read           path, max_bytes, encoding, binary, offset, limit
      write_file / write         path, content, atomic, append, mkdir, backup
      list_dir / list / ls       path, recursive, hidden, max_depth
      stat                       path
      exec                       argv[], cwd, env, timeout_ms, max_output
      pty_exec                   argv[], cwd, env, timeout_ms, cols, rows；PTY 捕获，需要 --allow-exec --allow-pty
      sql_query                  sql, params[]（只读，需 --allow-sql + --db）
      rm / mkdir / cp / mv / glob

    安全收紧
      eval 不开放（任意代码会绕过沙箱）；exec 的 cwd 必须过 root 校验；
      请求级 env 不允许覆盖 PATH（防白名单命令被劫持）；
      审计只记 op / path / argv / 结果，不记 token 与文件内容。
      worker 配置（含 token）走子进程 stdin，不进命令行；审计由监督进程统一写。
    END
}

# ── worker 子进程模式（0.67 / ADR-0004 §4）────────────────────────────
# 第一行 stdin 是配置 JSON，之后是普通请求 JSONL。stdout 只有响应，
# 任何诊断都走 stderr。不打印启动 banner、不写审计文件（父进程统一写）。
if @*ARGS.elems == 1 && @*ARGS[0] eq '--worker-child' {
    my $cfg-line = try { $*IN.get };
    my %cfg = try { from-json($cfg-line // '') } // {};
    unless %cfg<__rakuish_worker_config> && (%cfg<root> // '').chars {
        $*ERR.say('rakuish-agent: worker 配置缺失或非法');
        exit 2;
    }
    my %sb = :root(%cfg<root>),
             :token(%cfg<token>),
             :allow-exec(?%cfg<allow_exec>),
             :allow-pty(?%cfg<allow_pty>),
             :allow-sql(?%cfg<allow_sql>),
             :allowlist((%cfg<allowlist> // ()).map(*.Str).List),
             :max-bytes((%cfg<max_bytes> // 1048576).Int),
             :timeout-ms((%cfg<timeout_ms> // 30000).Int),
             :max-output((%cfg<max_output> // 1048576).Int),
             :max-rows((%cfg<max_rows> // 1000).Int),
             :sql-timeout-ms((%cfg<sql_timeout_ms> // 30000).Int),
             :request-timeout-ms((%cfg<request_timeout_ms> // 30000).Int);
    my $child-sandbox = Rakuish::Sandbox.new(|%sb);

    my $child-engine;
    if (%cfg<db> // '').chars {
        my Str $class = (%cfg<engine> // 'duckdb').lc eq 'sqlite'
            ?? 'Rakuish::Data::Engine::SQLite'
            !! 'Rakuish::Data::Engine::DuckDB';
        require ::($class);
        my $csys = Rakuish::Sys.new(:root($child-sandbox.root),
                                    :cwd($child-sandbox.root));
        my Str $dbp = $csys.resolve(%cfg<db>.Str).Str;
        $child-engine = ::($class).new(
            :path($dbp), :read-only, :safe,
            :max-execution-time-ms((%cfg<sql_timeout_ms> // 30000).Int));
    }

    my $child-server = Rakuish::Agent::Server.new(
        :sandbox($child-sandbox),
        :session-id(%cfg<session> // 'default'),
        :engine($child-engine));
    # 握手：父进程消费这一行后才认为 worker 就绪，避免把 Rakudo 启动时间
    # 算进第一个请求的 hard-timeout。客户端永远看不到它（父进程不转发）。
    $*OUT.say(to-json({ __rakuish_worker_ready => True }, :!pretty));
    $*OUT.flush;
    $child-server.run-jsonl($*IN, $*OUT);
    exit 0;
}

my @a = @*ARGS;
my %opt;
my Int $i = 0;
while $i < @a.elems {
    my $k = @a[$i];
    if $k eq '--help'    { say help-text(); exit 0 }
    if $k eq '--version' { say VERSION;     exit 0 }
    if $k eq '--allow-exec' {
        %opt<allow-exec> = True;
        $i = $i + 1;
        next;
    }
    if $k eq '--allow-sql' {
        %opt<allow-sql> = True;
        $i = $i + 1;
        next;
    }
    if $k eq '--allow-pty' {
        %opt<allow-pty> = True;
        $i = $i + 1;
        next;
    }
    if $k eq '--serve' {
        %opt<serve> = True;
        $i = $i + 1;
        next;
    }
    if $k eq '--worker' {
        %opt<worker> = True;
        $i = $i + 1;
        next;
    }
    unless $k.starts-with('--') && @a[$i + 1].defined {
        $*ERR.say("参数错误: $k");
        exit 2;
    }
    my Str $opt-name = $k.substr(2);
    unless $opt-name (elem) AGENT-OPTIONS {
        $*ERR.say("未知选项: {$k}（用 --help 查看）");
        exit 2;
    }
    %opt{$opt-name} = @a[$i + 1];
    $i = $i + 2;
}

unless %opt<root>.defined {
    $*ERR.say('必须指定 --root（文件根）');
    $*ERR.say('用法: raku bin/rakuish-agent --help');
    exit 2;
}
if %opt<worker> && (!%opt<serve> || (%opt<mode> // 'jsonl') ne 'tcp') {
    $*ERR.say('--worker 需要同时指定 --mode tcp --serve');
    exit 2;
}

my %sb = :root(%opt<root>),
         :allow-exec(?%opt<allow-exec>),
         :allow-pty(?%opt<allow-pty>),
         :allow-sql(?%opt<allow-sql>),
         :allowlist(%opt<allow>.defined
             ?? %opt<allow>.split(',').map(*.trim).grep(*.chars).List
             !! ()),
         :max-bytes((%opt<max-bytes>   // 1048576).Int),
         :timeout-ms((%opt<timeout-ms> // 30000).Int),
         :max-output((%opt<max-output> // 1048576).Int),
         :max-rows((%opt<max-rows> // 1000).Int),
         :sql-timeout-ms((%opt<sql-timeout-ms> // 30000).Int),
         :request-timeout-ms((%opt<request-timeout-ms> // 30000).Int);
%sb<token> = %opt<token> if %opt<token>.defined;
%sb<audit-log> = %opt<audit> if %opt<audit>.defined;

my $sandbox = Rakuish::Sandbox.new(|%sb);
my %sum = $sandbox.summary;

# 可选只读数据引擎：只有显式 --db 才创建；sql_query 仍需 --allow-sql。
# 常驻多客户端模式每连接要独立连接，所以构造收成 factory 闭包，由
# Server.serve 对每个连接调用一次（ADR-0002 §3.2）；worker 模式则由
# 子进程按 stdin 配置自建，父进程不共享 Engine。
my Str $db-path = '';
my $engine;
my &make-engine;
if %opt<db>.defined {
    my $sys = Rakuish::Sys.new(:root($sandbox.root), :cwd($sandbox.root));
    $db-path = $sys.resolve(%opt<db>.Str).Str;
    my Str $engine-name = (%opt<engine> // 'duckdb').lc;
    my Str $class = $engine-name eq 'sqlite'
        ?? 'Rakuish::Data::Engine::SQLite'
        !! 'Rakuish::Data::Engine::DuckDB';
    require ::($class);
    my Int $sql-timeout = $sandbox.sql-timeout-ms;
    if $sandbox.request-timeout-ms > 0
       && ($sql-timeout == 0 || $sandbox.request-timeout-ms < $sql-timeout) {
        $sql-timeout = $sandbox.request-timeout-ms;
    }
    &make-engine = -> {
        ::($class).new(:path($db-path), :read-only, :safe,
                       :max-execution-time-ms($sql-timeout));
    };
    # jsonl / serve-once 是单会话，直接建一个；常驻模式不预建以免共享连接。
    $engine = &make-engine.() unless %opt<serve>;
}

# 启动信息走 stderr，绝不污染 stdout 的 JSONL 协议；token 只在这里打印一次。
$*ERR.say("Rakuish V3 Agent {VERSION}");
$*ERR.say("  root      = ", %sum<root>);
$*ERR.say("  host      = ", %sum<host>);
$*ERR.say("  token     = ", $sandbox.token);
$*ERR.say("  exec      = ", %sum<allow_exec>
    ?? 'on (allowlist: ' ~ %sum<allowlist>.join(', ') ~ ')'
    !! 'off');
$*ERR.say("  pty       = ", %sum<allow_pty> ?? 'on' !! 'off');
$*ERR.say("  sql       = ", %sum<allow_sql>
    ?? "on ({$engine.defined ?? %opt<engine> // 'duckdb' !! 'no engine'})"
    !! 'off');
$*ERR.say("  limits    = ", %sum<max_bytes>, 'B / ',
    %sum<timeout_ms>, 'ms / ', %sum<max_output>, 'B');
$*ERR.say("  audit     = ", (%opt<audit> // '(memory only)'));

my $server = Rakuish::Agent::Server.new(
    :sandbox($sandbox), :session-id(%opt<session> // 'default'),
    :engine($engine));

my Str $mode = %opt<mode> // 'jsonl';
if $mode eq 'jsonl' {
    $server.run-jsonl();
}
elsif $mode eq 'tcp' {
    my Int $idle = (%opt<idle-timeout-ms> // 30000).Int;
    my Int $port = (%opt<port> // 0).Int;
    if %opt<serve> {
        # 常驻模式（ADR-0002）：不再一个连接就退出；Ctrl-C 收尾。
        my $stop = Promise.new;
        try { signal(SIGINT).tap({ $stop.keep unless $stop.status ~~ Kept }) };
        $*ERR.say('  mode      = serve（常驻多客户端，Ctrl-C 停止）',
                  %opt<worker> ?? ' + worker（每连接独立进程）' !! '');
        my %args = :port($port), :idle-timeout-ms($idle),
                   :max-connections((%opt<max-connections> // 16).Int),
                   :stop($stop),
                   :on-ready(-> $p { $*ERR.say("  listening = {$sandbox.host}:$p") });
        %args<engine-factory> = &make-engine if &make-engine.defined;
        if %opt<worker> {
            my @cmd = $*EXECUTABLE.Str, $?FILE.Str, '--worker-child';
            %args<worker> = True;
            %args<worker-command> = @cmd;
            %args<worker-config> = Rakuish::Agent::Worker::worker-config(
                $sandbox,
                :session-id(%opt<session> // 'default'),
                :db($db-path),
                :engine(%opt<engine> // 'duckdb'),
            );
        }
        my $info = $server.serve(|%args);
        unless $info<ok> {
            $*ERR.say('rakuish-agent: ', $info<err>);
            exit 2;
        }
        $*ERR.say('  处理请求  = ', $info<lines>,
                  ' · 连接 ', $info<connections>,
                  ' · 拒绝 ', $info<rejected>,
                  (%opt<worker> ?? " · worker kill {$info<worker_killed>}" !! ''));
    }
    else {
        my $info = $server.serve-once(
            :port($port), :idle-timeout-ms($idle),
            :on-ready(-> $p { $*ERR.say("  listening = {$sandbox.host}:$p") })
        );
        $*ERR.say("  处理请求  = ", $info<lines>);
    }
}
else {
    $*ERR.say("未知 --mode: $mode（可选 jsonl / tcp）");
    exit 2;
}
