[System] You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.

[User]
Review this excerpt for correctness risks, memory lifetime issues, and performance bottlenecks.

File: ds4_server.c

```c
attn = parse_float_arg(need_arg(&i, argc, argv, arg), arg, -100.0f, 100.0f);
            directional_steering_scale_set = true;
        } else if (!strcmp(arg, "--warm-weights")) {
            c.engine.warm_weights = true;
        } else if (!strcmp(arg, "--metal")) {
            c.engine.backend = DS4_BACKEND_METAL;
        } else if (!strcmp(arg, "--cuda")) {
            c.engine.backend = DS4_BACKEND_CUDA;
        } else if (!strcmp(arg, "--backend")) {
            c.engine.backend = parse_backend_arg(need_arg(&i, argc, argv, arg), arg);
        } else if (!strcmp(arg, "--cpu")) {
            c.engine.backend = DS4_BACKEND_CPU;
        } else {
            server_log(DS4_LOG_DEFAULT, "ds4-server: unknown option: %s", arg);
            usage(stderr);
            exit(2);
        }
    }
    if (c.kv_cache.cold_max_tokens > 0 &&
        c.kv_cache.cold_max_tokens < c.kv_cache.min_tokens)
    {
        server_log(DS4_LOG_DEFAULT,
                   "ds4-server: --kv-cache-cold-max-tokens must be 0 or >= --kv-cache-min-tokens");
        exit(2);
    }
    if (c.engine.directional_steering_file && !directional_steering_scale_set) {
        c.engine.directional_steering_ffn = 1.0f;
    }
    return c;
}

#ifndef DS4_SERVER_TEST
int main(int argc, char **argv) {
    signal(SIGPIPE, SIG_IGN);
    struct sigaction sa;
    memset(&sa, 0, sizeof(sa));
    sa.sa_handler = stop_signal_handler;
    sigemptyset(&sa.sa_mask);
    sigaction(SIGINT, &sa, NULL);
    sigaction(SIGTERM, &sa, NULL);

    server_config cfg = parse_options(argc, argv);

    ds4_engine *engine = NULL;
    if (ds4_engine_open(&engine, &cfg.engine) != 0) return 1;

    log_context_memory(cfg.engine.backend, cfg.ctx_size);

    ds4_session *session = NULL;
    if (ds4_session_create(&session, engine, cfg.ctx_size) != 0) {
        server_log(DS4_LOG_DEFAULT, "ds4-server: failed to create %s session",
                   ds4_backend_name(cfg.engine.backend));
        ds4_engine_close(engine);
        return 1;
    }

    server s;
    memset(&s, 0, sizeof(s));
    s.engine = engine;
    s.session = session;
    s.default_tokens = cfg.default_tokens;
    s.disable_exact_dsml_tool_replay = cfg.disable_exact_dsml_tool_replay;
    s.tool_mem.max_entries = cfg.tool_memory_max_ids;
    s.enable_cors = cfg.enable_cors;
    if (cfg.kv_disk_dir) {
        kv_cache_open(&s.kv, cfg.kv_disk_dir, cfg.kv_disk_space_mb,
                      cfg.kv_cache_reject_different_quant, cfg.kv_cache);
    }
    if (s.disable_exact_dsml_tool_replay) {
        server_log(DS4_LOG_DEFAULT,
```

<｜begin▁of▁sentence｜>You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.<｜User｜>Review this excerpt for correctness risks, memory lifetime issues, and performance bottlenecks.

File: ds4_server.c

```c
attn = parse_float_arg(need_arg(&i, argc, argv, arg), arg, -100.0f, 100.0f);
            directional_steering_scale_set = true;
        } else if (!strcmp(arg, "--warm-weights")) {
            c.engine.warm_weights = true;
        } else if (!strcmp(arg, "--metal")) {
            c.engine.backend = DS4_BACKEND_METAL;
        } else if (!strcmp(arg, "--cuda")) {
            c.engine.backend = DS4_BACKEND_CUDA;
        } else if (!strcmp(arg, "--backend")) {
            c.engine.backend = parse_backend_arg(need_arg(&i, argc, argv, arg), arg);
        } else if (!strcmp(arg, "--cpu")) {
            c.engine.backend = DS4_BACKEND_CPU;
        } else {
            server_log(DS4_LOG_DEFAULT, "ds4-server: unknown option: %s", arg);
            usage(stderr);
            exit(2);
        }
    }
    if (c.kv_cache.cold_max_tokens > 0 &&
        c.kv_cache.cold_max_tokens < c.kv_cache.min_tokens)
    {
        server_log(DS4_LOG_DEFAULT,
                   "ds4-server: --kv-cache-cold-max-tokens must be 0 or >= --kv-cache-min-tokens");
        exit(2);
    }
    if (c.engine.directional_steering_file && !directional_steering_scale_set) {
        c.engine.directional_steering_ffn = 1.0f;
    }
    return c;
}

#ifndef DS4_SERVER_TEST
int main(int argc, char **argv) {
    signal(SIGPIPE, SIG_IGN);
    struct sigaction sa;
    memset(&sa, 0, sizeof(sa));
    sa.sa_handler = stop_signal_handler;
    sigemptyset(&sa.sa_mask);
    sigaction(SIGINT, &sa, NULL);
    sigaction(SIGTERM, &sa, NULL);

    server_config cfg = parse_options(argc, argv);

    ds4_engine *engine = NULL;
    if (ds4_engine_open(&engine, &cfg.engine) != 0) return 1;

    log_context_memory(cfg.engine.backend, cfg.ctx_size);

    ds4_session *session = NULL;
    if (ds4_session_create(&session, engine, cfg.ctx_size) != 0) {
        server_log(DS4_LOG_DEFAULT, "ds4-server: failed to create %s session",
                   ds4_backend_name(cfg.engine.backend));
        ds4_engine_close(engine);
        return 1;
    }

    server s;
    memset(&s, 0, sizeof(s));
    s.engine = engine;
    s.session = session;
    s.default_tokens = cfg.default_tokens;
    s.disable_exact_dsml_tool_replay = cfg.disable_exact_dsml_tool_replay;
    s.tool_mem.max_entries = cfg.tool_memory_max_ids;
    s.enable_cors = cfg.enable_cors;
    if (cfg.kv_disk_dir) {
        kv_cache_open(&s.kv, cfg.kv_disk_dir, cfg.kv_disk_space_mb,
                      cfg.kv_cache_reject_different_quant, cfg.kv_cache);
    }
    if (s.disable_exact_dsml_tool_replay) {
        server_log(DS4_LOG_DEFAULT,
```<｜Assistant｜></think>


[System] You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.

[User]
Review this excerpt for correctness risks, memory lifetime issues, and performance bottlenecks.

File: ds4_server.c

```c
attn = parse_float_arg(need_arg(&i, argc, argv, arg), arg, -100.0f, 100.0f);
            directional_steering_scale_set = true;
        } else if (!strcmp(arg, "--warm-weights")) {
            c.engine.warm_weights = true;
        } else if (!strcmp(arg, "--metal")) {
            c.engine.backend = DS4_BACKEND_METAL;
        } else if (!strcmp(arg, "--cuda")) {
            c.engine.backend = DS4_BACKEND_CUDA;
        } else if (!strcmp(arg, "--backend")) {
            c.engine.backend = parse_backend_arg(need_arg(&i, argc, argv, arg), arg);
        } else if (!strcmp(arg, "--cpu")) {
            c.engine.backend = DS4_BACKEND_CPU;
        } else {
            server_log(DS4_LOG_DEFAULT, "ds4-server: unknown option: %s", arg);
            usage(stderr);
            exit(2);
        }
    }
    if (c.kv_cache.cold_max_tokens > 0 &&
        c.kv_cache.cold_max_tokens < c.kv_cache.min_tokens)
    {
        server_log(DS4_LOG_DEFAULT,
                   "ds4-server: --kv-cache-cold-max-tokens must be 0 or >= --kv-cache-min-tokens");
        exit(2);
    }
    if (c.engine.directional_steering_file && !directional_steering_scale_set) {
        c.engine.directional_steering_ffn = 1.0f;
    }
    return c;
}

#ifndef DS4_SERVER_TEST
int main(int argc, char **argv) {
    signal(SIGPIPE, SIG_IGN);
    struct sigaction sa;
    memset(&sa, 0, sizeof(sa));
    sa.sa_handler = stop_signal_handler;
    sigemptyset(&sa.sa_mask);
    sigaction(SIGINT, &sa, NULL);
    sigaction(SIGTERM, &sa, NULL);

    server_config cfg = parse_options(argc, argv);

    ds4_engine *engine = NULL;
    if (ds4_engine_open(&engine, &cfg.engine) != 0) return 1;

    log_context_memory(cfg.engine.backend, cfg.ctx_size);

    ds4_session *session = NULL;
    if (ds4_session_create(&session, engine, cfg.ctx_size) != 0) {
        server_log(DS4_LOG_DEFAULT, "ds4-server: failed to create %s session",
                   ds4_backend_name(cfg.engine.backend));
        ds4_engine_close(engine);
        return 1;
    }

    server s;
    memset(&s, 0, sizeof(s));
    s.engine = engine;
    s.session = session;
    s.default_tokens = cfg.default_tokens;
    s.disable_exact_dsml_tool_replay = cfg.disable_exact_dsml_tool_replay;
    s.tool_mem.max_entries = cfg.tool_memory_max_ids;
    s.enable_cors = cfg.enable_cors;
    if (cfg.kv_disk_dir) {
        kv_cache_open(&s.kv, cfg.kv_disk_dir, cfg.kv_disk_space_mb,
                      cfg.kv_cache_reject_different_quant, cfg.kv_cache);
    }
    if (s.disable_exact_dsml_tool_replay) {
        server_log(DS4_LOG_DEFAULT,
```

<｜begin▁of▁sentence｜>You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.<｜User｜>Review this excerpt for correctness risks, memory lifetime issues, and performance bottlenecks.

File: ds4_server.c

```c
attn = parse_float_arg(need_arg(&i, argc, argv, arg), arg, -100.0f, 100.0f);
            directional_steering_scale_set = true;
        } else if (!strcmp(arg, "--warm-weights")) {
            c.engine.warm_weights = true;
        } else if (!strcmp(arg, "--metal")) {
            c.engine.backend = DS4_BACKEND_METAL;
        } else if (!strcmp(arg, "--cuda")) {
            c.engine.backend = DS4_BACKEND_CUDA;
        } else if (!strcmp(arg, "--backend")) {
            c.engine.backend = parse_backend_arg(need_arg(&i, argc, argv, arg), arg);
        } else if (!strcmp(arg, "--cpu")) {
            c.engine.backend = DS4_BACKEND_CPU;
        } else {
            server_log(DS4_LOG_DEFAULT, "ds4-server: unknown option: %s", arg);
            usage(stderr);
            exit(2);
        }
    }
    if (c.kv_cache.cold_max_tokens > 0 &&
        c.kv_cache.cold_max_tokens < c.kv_cache.min_tokens)
    {
        server_log(DS4_LOG_DEFAULT,
                   "ds4-server: --kv-cache-cold-max-tokens must be 0 or >= --kv-cache-min-tokens");
        exit(2);
    }
    if (c.engine.directional_steering_file && !directional_steering_scale_set) {
        c.engine.directional_steering_ffn = 1.0f;
    }
    return c;
}

#ifndef DS4_SERVER_TEST
int main(int argc, char **argv) {
    signal(SIGPIPE, SIG_IGN);
    struct sigaction sa;
    memset(&sa, 0, sizeof(sa));
    sa.sa_handler = stop_signal_handler;
    sigemptyset(&sa.sa_mask);
    sigaction(SIGINT, &sa, NULL);
    sigaction(SIGTERM, &sa, NULL);

    server_config cfg = parse_options(argc, argv);

    ds4_engine *engine = NULL;
    if (ds4_engine_open(&engine, &cfg.engine) != 0) return 1;

    log_context_memory(cfg.engine.backend, cfg.ctx_size);

    ds4_session *session = NULL;
    if (ds4_session_create(&session, engine, cfg.ctx_size) != 0) {
        server_log(DS4_LOG_DEFAULT, "ds4-server: failed to create %s session",
                   ds4_backend_name(cfg.engine.backend));
        ds4_engine_close(engine);
        return 1;
    }

    server s;
    memset(&s, 0, sizeof(s));
    s.engine = engine;
    s.session = session;
    s.default_tokens = cfg.default_tokens;
    s.disable_exact_dsml_tool_replay = cfg.disable_exact_dsml_tool_replay;
    s.tool_mem.max_entries = cfg.tool_memory_max_ids;
    s.enable_cors = cfg.enable_cors;
    if (cfg.kv_disk_dir) {
        kv_cache_open(&s.kv, cfg.kv_disk_dir, cfg.kv_disk_space_mb,
                      cfg.kv_cache_reject_different_quant, cfg.kv_cache);
    }
    if (s.disable_exact_dsml_tool_replay) {
        server_log(DS4_LOG_DEFAULT,
```<｜Assistant｜><think>


[System] You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.

[User]
Explain what this code does and identify the inference stage it belongs to.

File: ds4_server.c

```c
fg.kv_disk_space_mb,
                      cfg.kv_cache_reject_different_quant, cfg.kv_cache);
    }
    if (s.disable_exact_dsml_tool_replay) {
        server_log(DS4_LOG_DEFAULT,
                   "ds4-server: exact DSML tool replay disabled; tool history uses canonical JSON rendering");
    }
    pthread_mutex_init(&s.mu, NULL);
    pthread_cond_init(&s.cv, NULL);
    pthread_cond_init(&s.clients_cv, NULL);
    pthread_mutex_init(&s.tool_mu, NULL);
    pthread_mutex_init(&s.trace_mu, NULL);
    if (cfg.trace_path) {
        s.trace = fopen(cfg.trace_path, "w");
        if (!s.trace) {
            server_log(DS4_LOG_DEFAULT, "ds4-server: failed to open trace file %s: %s",
                       cfg.trace_path, strerror(errno));
            server_close_resources(&s);
            return 1;
        }
        setvbuf(s.trace, NULL, _IONBF, 0);
        server_log(DS4_LOG_DEFAULT, "ds4-server: tracing session to %s", cfg.trace_path);
    }

    pthread_t worker;
    if (pthread_create(&worker, NULL, worker_main, &s) != 0) die("failed to start worker");

    int lfd = listen_on(cfg.host, cfg.port);
    if (lfd < 0) {
        server_log(DS4_LOG_DEFAULT, "ds4-server: failed to listen on %s:%d: %s", cfg.host, cfg.port, strerror(errno));
        pthread_mutex_lock(&s.mu);
        s.stopping = true;
        pthread_cond_broadcast(&s.cv);
        pthread_mutex_unlock(&s.mu);
        pthread_join(worker, NULL);
        server_close_resources(&s);
        return 1;
    }
    g_listen_fd = lfd;
    server_log(DS4_LOG_DEFAULT, "ds4-server: listening on http://%s:%d", cfg.host, cfg.port);

    while (!g_stop_requested) {
        int fd = accept(lfd, NULL, NULL);
        if (fd < 0) {
            if (g_stop_requested) break;
            if (errno == EINTR) continue;
            server_log(DS4_LOG_DEFAULT, "ds4-server: accept failed: %s", strerror(errno));
            continue;
        }
        if (g_stop_requested) {
            close(fd);
            break;
        }

        configure_client_socket(fd);
        client_arg *ca = xmalloc(sizeof(*ca));
        ca->srv = &s;
        ca->fd = fd;
        pthread_mutex_lock(&s.mu);
        s.clients++;
        pthread_mutex_unlock(&s.mu);
        pthread_t th;
        if (pthread_create(&th, NULL, client_main, ca) != 0) {
            pthread_mutex_lock(&s.mu);
            s.clients--;
            pthread_cond_broadcast(&s.clients_cv);
            pthread_mutex_unlock(&s.mu);
            free(ca);
            close(fd);
            continue;
        }
        pthread_detach(th);
    }
    if (g_listen_fd >= 0) {
```

<｜begin▁of▁sentence｜>You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.<｜User｜>Explain what this code does and identify the inference stage it belongs to.

File: ds4_server.c

```c
fg.kv_disk_space_mb,
                      cfg.kv_cache_reject_different_quant, cfg.kv_cache);
    }
    if (s.disable_exact_dsml_tool_replay) {
        server_log(DS4_LOG_DEFAULT,
                   "ds4-server: exact DSML tool replay disabled; tool history uses canonical JSON rendering");
    }
    pthread_mutex_init(&s.mu, NULL);
    pthread_cond_init(&s.cv, NULL);
    pthread_cond_init(&s.clients_cv, NULL);
    pthread_mutex_init(&s.tool_mu, NULL);
    pthread_mutex_init(&s.trace_mu, NULL);
    if (cfg.trace_path) {
        s.trace = fopen(cfg.trace_path, "w");
        if (!s.trace) {
            server_log(DS4_LOG_DEFAULT, "ds4-server: failed to open trace file %s: %s",
                       cfg.trace_path, strerror(errno));
            server_close_resources(&s);
            return 1;
        }
        setvbuf(s.trace, NULL, _IONBF, 0);
        server_log(DS4_LOG_DEFAULT, "ds4-server: tracing session to %s", cfg.trace_path);
    }

    pthread_t worker;
    if (pthread_create(&worker, NULL, worker_main, &s) != 0) die("failed to start worker");

    int lfd = listen_on(cfg.host, cfg.port);
    if (lfd < 0) {
        server_log(DS4_LOG_DEFAULT, "ds4-server: failed to listen on %s:%d: %s", cfg.host, cfg.port, strerror(errno));
        pthread_mutex_lock(&s.mu);
        s.stopping = true;
        pthread_cond_broadcast(&s.cv);
        pthread_mutex_unlock(&s.mu);
        pthread_join(worker, NULL);
        server_close_resources(&s);
        return 1;
    }
    g_listen_fd = lfd;
    server_log(DS4_LOG_DEFAULT, "ds4-server: listening on http://%s:%d", cfg.host, cfg.port);

    while (!g_stop_requested) {
        int fd = accept(lfd, NULL, NULL);
        if (fd < 0) {
            if (g_stop_requested) break;
            if (errno == EINTR) continue;
            server_log(DS4_LOG_DEFAULT, "ds4-server: accept failed: %s", strerror(errno));
            continue;
        }
        if (g_stop_requested) {
            close(fd);
            break;
        }

        configure_client_socket(fd);
        client_arg *ca = xmalloc(sizeof(*ca));
        ca->srv = &s;
        ca->fd = fd;
        pthread_mutex_lock(&s.mu);
        s.clients++;
        pthread_mutex_unlock(&s.mu);
        pthread_t th;
        if (pthread_create(&th, NULL, client_main, ca) != 0) {
            pthread_mutex_lock(&s.mu);
            s.clients--;
            pthread_cond_broadcast(&s.clients_cv);
            pthread_mutex_unlock(&s.mu);
            free(ca);
            close(fd);
            continue;
        }
        pthread_detach(th);
    }
    if (g_listen_fd >= 0) {
```<｜Assistant｜></think>


[System] You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.

[User]
Explain what this code does and identify the inference stage it belongs to.

File: ds4_server.c

```c
fg.kv_disk_space_mb,
                      cfg.kv_cache_reject_different_quant, cfg.kv_cache);
    }
    if (s.disable_exact_dsml_tool_replay) {
        server_log(DS4_LOG_DEFAULT,
                   "ds4-server: exact DSML tool replay disabled; tool history uses canonical JSON rendering");
    }
    pthread_mutex_init(&s.mu, NULL);
    pthread_cond_init(&s.cv, NULL);
    pthread_cond_init(&s.clients_cv, NULL);
    pthread_mutex_init(&s.tool_mu, NULL);
    pthread_mutex_init(&s.trace_mu, NULL);
    if (cfg.trace_path) {
        s.trace = fopen(cfg.trace_path, "w");
        if (!s.trace) {
            server_log(DS4_LOG_DEFAULT, "ds4-server: failed to open trace file %s: %s",
                       cfg.trace_path, strerror(errno));
            server_close_resources(&s);
            return 1;
        }
        setvbuf(s.trace, NULL, _IONBF, 0);
        server_log(DS4_LOG_DEFAULT, "ds4-server: tracing session to %s", cfg.trace_path);
    }

    pthread_t worker;
    if (pthread_create(&worker, NULL, worker_main, &s) != 0) die("failed to start worker");

    int lfd = listen_on(cfg.host, cfg.port);
    if (lfd < 0) {
        server_log(DS4_LOG_DEFAULT, "ds4-server: failed to listen on %s:%d: %s", cfg.host, cfg.port, strerror(errno));
        pthread_mutex_lock(&s.mu);
        s.stopping = true;
        pthread_cond_broadcast(&s.cv);
        pthread_mutex_unlock(&s.mu);
        pthread_join(worker, NULL);
        server_close_resources(&s);
        return 1;
    }
    g_listen_fd = lfd;
    server_log(DS4_LOG_DEFAULT, "ds4-server: listening on http://%s:%d", cfg.host, cfg.port);

    while (!g_stop_requested) {
        int fd = accept(lfd, NULL, NULL);
        if (fd < 0) {
            if (g_stop_requested) break;
            if (errno == EINTR) continue;
            server_log(DS4_LOG_DEFAULT, "ds4-server: accept failed: %s", strerror(errno));
            continue;
        }
        if (g_stop_requested) {
            close(fd);
            break;
        }

        configure_client_socket(fd);
        client_arg *ca = xmalloc(sizeof(*ca));
        ca->srv = &s;
        ca->fd = fd;
        pthread_mutex_lock(&s.mu);
        s.clients++;
        pthread_mutex_unlock(&s.mu);
        pthread_t th;
        if (pthread_create(&th, NULL, client_main, ca) != 0) {
            pthread_mutex_lock(&s.mu);
            s.clients--;
            pthread_cond_broadcast(&s.clients_cv);
            pthread_mutex_unlock(&s.mu);
            free(ca);
            close(fd);
            continue;
        }
        pthread_detach(th);
    }
    if (g_listen_fd >= 0) {
```

<｜begin▁of▁sentence｜>You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.<｜User｜>Explain what this code does and identify the inference stage it belongs to.

File: ds4_server.c

```c
fg.kv_disk_space_mb,
                      cfg.kv_cache_reject_different_quant, cfg.kv_cache);
    }
    if (s.disable_exact_dsml_tool_replay) {
        server_log(DS4_LOG_DEFAULT,
                   "ds4-server: exact DSML tool replay disabled; tool history uses canonical JSON rendering");
    }
    pthread_mutex_init(&s.mu, NULL);
    pthread_cond_init(&s.cv, NULL);
    pthread_cond_init(&s.clients_cv, NULL);
    pthread_mutex_init(&s.tool_mu, NULL);
    pthread_mutex_init(&s.trace_mu, NULL);
    if (cfg.trace_path) {
        s.trace = fopen(cfg.trace_path, "w");
        if (!s.trace) {
            server_log(DS4_LOG_DEFAULT, "ds4-server: failed to open trace file %s: %s",
                       cfg.trace_path, strerror(errno));
            server_close_resources(&s);
            return 1;
        }
        setvbuf(s.trace, NULL, _IONBF, 0);
        server_log(DS4_LOG_DEFAULT, "ds4-server: tracing session to %s", cfg.trace_path);
    }

    pthread_t worker;
    if (pthread_create(&worker, NULL, worker_main, &s) != 0) die("failed to start worker");

    int lfd = listen_on(cfg.host, cfg.port);
    if (lfd < 0) {
        server_log(DS4_LOG_DEFAULT, "ds4-server: failed to listen on %s:%d: %s", cfg.host, cfg.port, strerror(errno));
        pthread_mutex_lock(&s.mu);
        s.stopping = true;
        pthread_cond_broadcast(&s.cv);
        pthread_mutex_unlock(&s.mu);
        pthread_join(worker, NULL);
        server_close_resources(&s);
        return 1;
    }
    g_listen_fd = lfd;
    server_log(DS4_LOG_DEFAULT, "ds4-server: listening on http://%s:%d", cfg.host, cfg.port);

    while (!g_stop_requested) {
        int fd = accept(lfd, NULL, NULL);
        if (fd < 0) {
            if (g_stop_requested) break;
            if (errno == EINTR) continue;
            server_log(DS4_LOG_DEFAULT, "ds4-server: accept failed: %s", strerror(errno));
            continue;
        }
        if (g_stop_requested) {
            close(fd);
            break;
        }

        configure_client_socket(fd);
        client_arg *ca = xmalloc(sizeof(*ca));
        ca->srv = &s;
        ca->fd = fd;
        pthread_mutex_lock(&s.mu);
        s.clients++;
        pthread_mutex_unlock(&s.mu);
        pthread_t th;
        if (pthread_create(&th, NULL, client_main, ca) != 0) {
            pthread_mutex_lock(&s.mu);
            s.clients--;
            pthread_cond_broadcast(&s.clients_cv);
            pthread_mutex_unlock(&s.mu);
            free(ca);
            close(fd);
            continue;
        }
        pthread_detach(th);
    }
    if (g_listen_fd >= 0) {
```<｜Assistant｜><think>


[System] You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.

[User]
Trova bug sottili e spiega quali invarianti dell'inferenza possono rompersi.

File: ds4_server.c

```c
, &msg.role)) {
                    free(key);
                    goto fail;
                }
            } else if (!strcmp(key, "content")) {
                free(msg.content);
                if (!json_content(p, &msg.content)) {
                    free(key);
                    goto fail;
                }
            } else if (!strcmp(key, "reasoning_content")) {
                free(msg.reasoning);
                if (!json_content(p, &msg.reasoning)) {
                    free(key);
                    goto fail;
                }
            } else if (!strcmp(key, "tool_call_id")) {
                char *id = NULL;
                if (!json_string(p, &id)) {
                    free(key);
                    goto fail;
                }
                chat_msg_add_tool_call_id(&msg, id);
                free(id);
            } else if (!strcmp(key, "tool_calls")) {
                tool_calls_free(&msg.calls);
                if (!parse_tool_calls_value(p, &msg.calls)) {
                    free(key);
                    goto fail;
                }
            } else if (!json_skip_value(p)) {
                free(key);
                goto fail;
            }
            free(key);
            json_ws(p);
            if (**p == ',') (*p)++;
            json_ws(p);
        }
        if (**p != '}') goto fail;
        (*p)++;
        if (!msg.role) msg.role = xstrdup("user");
        if (!msg.content) msg.content = xstrdup("");
        chat_msgs_push(msgs, msg);
        memset(&msg, 0, sizeof(msg));
        json_ws(p);
        if (**p == ',') (*p)++;
        json_ws(p);
        continue;
fail:
        chat_msg_free(&msg);
        return false;
    }
    if (**p != ']') return false;
    (*p)++;
    return true;
}

static void append_tool_result_text(buf *b, const char *s);

static bool append_anthropic_block_content(buf *dst, const char *text) {
    if (!text || !text[0]) return true;
    buf_puts(dst, text);
    return true;
}

/* Anthropic content is block-structured, while the engine consumes one compact
 * chat_msg per role.  Parsing collapses text/thinking into strings, converts
 * assistant tool_use blocks to tool_calls, and keeps tool_result blocks as
 * escaped text because DS4 sees tool results in its chat template. */
static bool parse_anthropic_content_block(const char **p, const char *role, chat_msg *msg) {
    (void)role;
    if (**p != '{') return false;
    (*p)++;
    char *type = NULL;
    char *text = NULL;
    char *thinking = NULL;
    char *id = NULL;
    char *name = NULL;
    char *input = NULL;
```

<｜begin▁of▁sentence｜>You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.<｜User｜>Trova bug sottili e spiega quali invarianti dell'inferenza possono rompersi.

File: ds4_server.c

```c
, &msg.role)) {
                    free(key);
                    goto fail;
                }
            } else if (!strcmp(key, "content")) {
                free(msg.content);
                if (!json_content(p, &msg.content)) {
                    free(key);
                    goto fail;
                }
            } else if (!strcmp(key, "reasoning_content")) {
                free(msg.reasoning);
                if (!json_content(p, &msg.reasoning)) {
                    free(key);
                    goto fail;
                }
            } else if (!strcmp(key, "tool_call_id")) {
                char *id = NULL;
                if (!json_string(p, &id)) {
                    free(key);
                    goto fail;
                }
                chat_msg_add_tool_call_id(&msg, id);
                free(id);
            } else if (!strcmp(key, "tool_calls")) {
                tool_calls_free(&msg.calls);
                if (!parse_tool_calls_value(p, &msg.calls)) {
                    free(key);
                    goto fail;
                }
            } else if (!json_skip_value(p)) {
                free(key);
                goto fail;
            }
            free(key);
            json_ws(p);
            if (**p == ',') (*p)++;
            json_ws(p);
        }
        if (**p != '}') goto fail;
        (*p)++;
        if (!msg.role) msg.role = xstrdup("user");
        if (!msg.content) msg.content = xstrdup("");
        chat_msgs_push(msgs, msg);
        memset(&msg, 0, sizeof(msg));
        json_ws(p);
        if (**p == ',') (*p)++;
        json_ws(p);
        continue;
fail:
        chat_msg_free(&msg);
        return false;
    }
    if (**p != ']') return false;
    (*p)++;
    return true;
}

static void append_tool_result_text(buf *b, const char *s);

static bool append_anthropic_block_content(buf *dst, const char *text) {
    if (!text || !text[0]) return true;
    buf_puts(dst, text);
    return true;
}

/* Anthropic content is block-structured, while the engine consumes one compact
 * chat_msg per role.  Parsing collapses text/thinking into strings, converts
 * assistant tool_use blocks to tool_calls, and keeps tool_result blocks as
 * escaped text because DS4 sees tool results in its chat template. */
static bool parse_anthropic_content_block(const char **p, const char *role, chat_msg *msg) {
    (void)role;
    if (**p != '{') return false;
    (*p)++;
    char *type = NULL;
    char *text = NULL;
    char *thinking = NULL;
    char *id = NULL;
    char *name = NULL;
    char *input = NULL;
```<｜Assistant｜></think>


[System] You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.

[User]
Trova bug sottili e spiega quali invarianti dell'inferenza possono rompersi.

File: ds4_server.c

```c
, &msg.role)) {
                    free(key);
                    goto fail;
                }
            } else if (!strcmp(key, "content")) {
                free(msg.content);
                if (!json_content(p, &msg.content)) {
                    free(key);
                    goto fail;
                }
            } else if (!strcmp(key, "reasoning_content")) {
                free(msg.reasoning);
                if (!json_content(p, &msg.reasoning)) {
                    free(key);
                    goto fail;
                }
            } else if (!strcmp(key, "tool_call_id")) {
                char *id = NULL;
                if (!json_string(p, &id)) {
                    free(key);
                    goto fail;
                }
                chat_msg_add_tool_call_id(&msg, id);
                free(id);
            } else if (!strcmp(key, "tool_calls")) {
                tool_calls_free(&msg.calls);
                if (!parse_tool_calls_value(p, &msg.calls)) {
                    free(key);
                    goto fail;
                }
            } else if (!json_skip_value(p)) {
                free(key);
                goto fail;
            }
            free(key);
            json_ws(p);
            if (**p == ',') (*p)++;
            json_ws(p);
        }
        if (**p != '}') goto fail;
        (*p)++;
        if (!msg.role) msg.role = xstrdup("user");
        if (!msg.content) msg.content = xstrdup("");
        chat_msgs_push(msgs, msg);
        memset(&msg, 0, sizeof(msg));
        json_ws(p);
        if (**p == ',') (*p)++;
        json_ws(p);
        continue;
fail:
        chat_msg_free(&msg);
        return false;
    }
    if (**p != ']') return false;
    (*p)++;
    return true;
}

static void append_tool_result_text(buf *b, const char *s);

static bool append_anthropic_block_content(buf *dst, const char *text) {
    if (!text || !text[0]) return true;
    buf_puts(dst, text);
    return true;
}

/* Anthropic content is block-structured, while the engine consumes one compact
 * chat_msg per role.  Parsing collapses text/thinking into strings, converts
 * assistant tool_use blocks to tool_calls, and keeps tool_result blocks as
 * escaped text because DS4 sees tool results in its chat template. */
static bool parse_anthropic_content_block(const char **p, const char *role, chat_msg *msg) {
    (void)role;
    if (**p != '{') return false;
    (*p)++;
    char *type = NULL;
    char *text = NULL;
    char *thinking = NULL;
    char *id = NULL;
    char *name = NULL;
    char *input = NULL;
```

<｜begin▁of▁sentence｜>You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.<｜User｜>Trova bug sottili e spiega quali invarianti dell'inferenza possono rompersi.

File: ds4_server.c

```c
, &msg.role)) {
                    free(key);
                    goto fail;
                }
            } else if (!strcmp(key, "content")) {
                free(msg.content);
                if (!json_content(p, &msg.content)) {
                    free(key);
                    goto fail;
                }
            } else if (!strcmp(key, "reasoning_content")) {
                free(msg.reasoning);
                if (!json_content(p, &msg.reasoning)) {
                    free(key);
                    goto fail;
                }
            } else if (!strcmp(key, "tool_call_id")) {
                char *id = NULL;
                if (!json_string(p, &id)) {
                    free(key);
                    goto fail;
                }
                chat_msg_add_tool_call_id(&msg, id);
                free(id);
            } else if (!strcmp(key, "tool_calls")) {
                tool_calls_free(&msg.calls);
                if (!parse_tool_calls_value(p, &msg.calls)) {
                    free(key);
                    goto fail;
                }
            } else if (!json_skip_value(p)) {
                free(key);
                goto fail;
            }
            free(key);
            json_ws(p);
            if (**p == ',') (*p)++;
            json_ws(p);
        }
        if (**p != '}') goto fail;
        (*p)++;
        if (!msg.role) msg.role = xstrdup("user");
        if (!msg.content) msg.content = xstrdup("");
        chat_msgs_push(msgs, msg);
        memset(&msg, 0, sizeof(msg));
        json_ws(p);
        if (**p == ',') (*p)++;
        json_ws(p);
        continue;
fail:
        chat_msg_free(&msg);
        return false;
    }
    if (**p != ']') return false;
    (*p)++;
    return true;
}

static void append_tool_result_text(buf *b, const char *s);

static bool append_anthropic_block_content(buf *dst, const char *text) {
    if (!text || !text[0]) return true;
    buf_puts(dst, text);
    return true;
}

/* Anthropic content is block-structured, while the engine consumes one compact
 * chat_msg per role.  Parsing collapses text/thinking into strings, converts
 * assistant tool_use blocks to tool_calls, and keeps tool_result blocks as
 * escaped text because DS4 sees tool results in its chat template. */
static bool parse_anthropic_content_block(const char **p, const char *role, chat_msg *msg) {
    (void)role;
    if (**p != '{') return false;
    (*p)++;
    char *type = NULL;
    char *text = NULL;
    char *thinking = NULL;
    char *id = NULL;
    char *name = NULL;
    char *input = NULL;
```<｜Assistant｜><think>


[System] You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.

[User]
Suggest a minimal correctness-preserving optimization for this excerpt.

File: ds4_server.c

```c
pthread_mutex_unlock(&s.mu);
            free(ca);
            close(fd);
            continue;
        }
        pthread_detach(th);
    }
    if (g_listen_fd >= 0) {
        close(lfd);
        g_listen_fd = -1;
    }

    server_log(DS4_LOG_DEFAULT, "ds4-server: shutdown requested, draining requests");
    pthread_mutex_lock(&s.mu);
    s.stopping = true;
    pthread_cond_broadcast(&s.cv);
    pthread_mutex_unlock(&s.mu);
    pthread_join(worker, NULL);
    pthread_mutex_lock(&s.mu);
    while (s.clients > 0) pthread_cond_wait(&s.clients_cv, &s.mu);
    pthread_mutex_unlock(&s.mu);

    const ds4_tokens *tokens = ds4_session_tokens(s.session);
    if (s.kv.enabled && tokens && tokens->len >= s.kv.opt.min_tokens) {
        server_log(DS4_LOG_KVCACHE,
                   "ds4-server: persisting current KV cache before shutdown tokens=%d",
                   tokens->len);
        kv_cache_store_current(&s, "shutdown");
    }
    server_close_resources(&s);
    return 0;
}
#else

static int test_failures = 0;

static void test_assert(bool cond, const char *file, int line, const char *expr) {
    if (cond) return;
    fprintf(stderr, "%s:%d: assertion failed: %s\n", file, line, expr);
    test_failures++;
}

#define TEST_ASSERT(expr) test_assert((expr), __FILE__, __LINE__, #expr)

static void test_tool_schema_order_from_anthropic_schema(void) {
    tool_schema_orders orders = {0};
    tool_schema_orders_add_json(&orders,
        "{\"name\":\"bash\",\"input_schema\":{\"type\":\"object\",\"properties\":{"
        "\"command\":{\"type\":\"string\"},"
        "\"description\":{\"type\":\"string\"}}}}");
    const tool_schema_order *order = tool_schema_orders_find(&orders, "bash");
    TEST_ASSERT(order != NULL);
    TEST_ASSERT(order && order->len == 2);
    TEST_ASSERT(order && !strcmp(order->prop[0], "command"));
    TEST_ASSERT(order && !strcmp(order->prop[1], "description"));
    tool_schema_orders_free(&orders);
}

static void test_tool_schema_order_from_openai_tools(void) {
    const char *json =
        "[{\"type\":\"function\",\"function\":{\"name\":\"edit\",\"parameters\":{"
        "\"type\":\"object\",\"properties\":{"
        "\"filePath\":{\"type\":\"string\"},"
        "\"oldString\":{\"type\":\"string\"},"
        "\"newString\":{\"type\":\"string\"}}}}}]";
    const char *p = json;
    char *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&p, &schemas, &orders));
    TEST_ASSERT(schemas && strstr(schemas, "\"name\":\"edit\""));
```

<｜begin▁of▁sentence｜>You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.<｜User｜>Suggest a minimal correctness-preserving optimization for this excerpt.

File: ds4_server.c

```c
pthread_mutex_unlock(&s.mu);
            free(ca);
            close(fd);
            continue;
        }
        pthread_detach(th);
    }
    if (g_listen_fd >= 0) {
        close(lfd);
        g_listen_fd = -1;
    }

    server_log(DS4_LOG_DEFAULT, "ds4-server: shutdown requested, draining requests");
    pthread_mutex_lock(&s.mu);
    s.stopping = true;
    pthread_cond_broadcast(&s.cv);
    pthread_mutex_unlock(&s.mu);
    pthread_join(worker, NULL);
    pthread_mutex_lock(&s.mu);
    while (s.clients > 0) pthread_cond_wait(&s.clients_cv, &s.mu);
    pthread_mutex_unlock(&s.mu);

    const ds4_tokens *tokens = ds4_session_tokens(s.session);
    if (s.kv.enabled && tokens && tokens->len >= s.kv.opt.min_tokens) {
        server_log(DS4_LOG_KVCACHE,
                   "ds4-server: persisting current KV cache before shutdown tokens=%d",
                   tokens->len);
        kv_cache_store_current(&s, "shutdown");
    }
    server_close_resources(&s);
    return 0;
}
#else

static int test_failures = 0;

static void test_assert(bool cond, const char *file, int line, const char *expr) {
    if (cond) return;
    fprintf(stderr, "%s:%d: assertion failed: %s\n", file, line, expr);
    test_failures++;
}

#define TEST_ASSERT(expr) test_assert((expr), __FILE__, __LINE__, #expr)

static void test_tool_schema_order_from_anthropic_schema(void) {
    tool_schema_orders orders = {0};
    tool_schema_orders_add_json(&orders,
        "{\"name\":\"bash\",\"input_schema\":{\"type\":\"object\",\"properties\":{"
        "\"command\":{\"type\":\"string\"},"
        "\"description\":{\"type\":\"string\"}}}}");
    const tool_schema_order *order = tool_schema_orders_find(&orders, "bash");
    TEST_ASSERT(order != NULL);
    TEST_ASSERT(order && order->len == 2);
    TEST_ASSERT(order && !strcmp(order->prop[0], "command"));
    TEST_ASSERT(order && !strcmp(order->prop[1], "description"));
    tool_schema_orders_free(&orders);
}

static void test_tool_schema_order_from_openai_tools(void) {
    const char *json =
        "[{\"type\":\"function\",\"function\":{\"name\":\"edit\",\"parameters\":{"
        "\"type\":\"object\",\"properties\":{"
        "\"filePath\":{\"type\":\"string\"},"
        "\"oldString\":{\"type\":\"string\"},"
        "\"newString\":{\"type\":\"string\"}}}}}]";
    const char *p = json;
    char *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&p, &schemas, &orders));
    TEST_ASSERT(schemas && strstr(schemas, "\"name\":\"edit\""));
```<｜Assistant｜></think>


[System] You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.

[User]
Suggest a minimal correctness-preserving optimization for this excerpt.

File: ds4_server.c

```c
pthread_mutex_unlock(&s.mu);
            free(ca);
            close(fd);
            continue;
        }
        pthread_detach(th);
    }
    if (g_listen_fd >= 0) {
        close(lfd);
        g_listen_fd = -1;
    }

    server_log(DS4_LOG_DEFAULT, "ds4-server: shutdown requested, draining requests");
    pthread_mutex_lock(&s.mu);
    s.stopping = true;
    pthread_cond_broadcast(&s.cv);
    pthread_mutex_unlock(&s.mu);
    pthread_join(worker, NULL);
    pthread_mutex_lock(&s.mu);
    while (s.clients > 0) pthread_cond_wait(&s.clients_cv, &s.mu);
    pthread_mutex_unlock(&s.mu);

    const ds4_tokens *tokens = ds4_session_tokens(s.session);
    if (s.kv.enabled && tokens && tokens->len >= s.kv.opt.min_tokens) {
        server_log(DS4_LOG_KVCACHE,
                   "ds4-server: persisting current KV cache before shutdown tokens=%d",
                   tokens->len);
        kv_cache_store_current(&s, "shutdown");
    }
    server_close_resources(&s);
    return 0;
}
#else

static int test_failures = 0;

static void test_assert(bool cond, const char *file, int line, const char *expr) {
    if (cond) return;
    fprintf(stderr, "%s:%d: assertion failed: %s\n", file, line, expr);
    test_failures++;
}

#define TEST_ASSERT(expr) test_assert((expr), __FILE__, __LINE__, #expr)

static void test_tool_schema_order_from_anthropic_schema(void) {
    tool_schema_orders orders = {0};
    tool_schema_orders_add_json(&orders,
        "{\"name\":\"bash\",\"input_schema\":{\"type\":\"object\",\"properties\":{"
        "\"command\":{\"type\":\"string\"},"
        "\"description\":{\"type\":\"string\"}}}}");
    const tool_schema_order *order = tool_schema_orders_find(&orders, "bash");
    TEST_ASSERT(order != NULL);
    TEST_ASSERT(order && order->len == 2);
    TEST_ASSERT(order && !strcmp(order->prop[0], "command"));
    TEST_ASSERT(order && !strcmp(order->prop[1], "description"));
    tool_schema_orders_free(&orders);
}

static void test_tool_schema_order_from_openai_tools(void) {
    const char *json =
        "[{\"type\":\"function\",\"function\":{\"name\":\"edit\",\"parameters\":{"
        "\"type\":\"object\",\"properties\":{"
        "\"filePath\":{\"type\":\"string\"},"
        "\"oldString\":{\"type\":\"string\"},"
        "\"newString\":{\"type\":\"string\"}}}}}]";
    const char *p = json;
    char *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&p, &schemas, &orders));
    TEST_ASSERT(schemas && strstr(schemas, "\"name\":\"edit\""));
```

<｜begin▁of▁sentence｜>You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.<｜User｜>Suggest a minimal correctness-preserving optimization for this excerpt.

File: ds4_server.c

```c
pthread_mutex_unlock(&s.mu);
            free(ca);
            close(fd);
            continue;
        }
        pthread_detach(th);
    }
    if (g_listen_fd >= 0) {
        close(lfd);
        g_listen_fd = -1;
    }

    server_log(DS4_LOG_DEFAULT, "ds4-server: shutdown requested, draining requests");
    pthread_mutex_lock(&s.mu);
    s.stopping = true;
    pthread_cond_broadcast(&s.cv);
    pthread_mutex_unlock(&s.mu);
    pthread_join(worker, NULL);
    pthread_mutex_lock(&s.mu);
    while (s.clients > 0) pthread_cond_wait(&s.clients_cv, &s.mu);
    pthread_mutex_unlock(&s.mu);

    const ds4_tokens *tokens = ds4_session_tokens(s.session);
    if (s.kv.enabled && tokens && tokens->len >= s.kv.opt.min_tokens) {
        server_log(DS4_LOG_KVCACHE,
                   "ds4-server: persisting current KV cache before shutdown tokens=%d",
                   tokens->len);
        kv_cache_store_current(&s, "shutdown");
    }
    server_close_resources(&s);
    return 0;
}
#else

static int test_failures = 0;

static void test_assert(bool cond, const char *file, int line, const char *expr) {
    if (cond) return;
    fprintf(stderr, "%s:%d: assertion failed: %s\n", file, line, expr);
    test_failures++;
}

#define TEST_ASSERT(expr) test_assert((expr), __FILE__, __LINE__, #expr)

static void test_tool_schema_order_from_anthropic_schema(void) {
    tool_schema_orders orders = {0};
    tool_schema_orders_add_json(&orders,
        "{\"name\":\"bash\",\"input_schema\":{\"type\":\"object\",\"properties\":{"
        "\"command\":{\"type\":\"string\"},"
        "\"description\":{\"type\":\"string\"}}}}");
    const tool_schema_order *order = tool_schema_orders_find(&orders, "bash");
    TEST_ASSERT(order != NULL);
    TEST_ASSERT(order && order->len == 2);
    TEST_ASSERT(order && !strcmp(order->prop[0], "command"));
    TEST_ASSERT(order && !strcmp(order->prop[1], "description"));
    tool_schema_orders_free(&orders);
}

static void test_tool_schema_order_from_openai_tools(void) {
    const char *json =
        "[{\"type\":\"function\",\"function\":{\"name\":\"edit\",\"parameters\":{"
        "\"type\":\"object\",\"properties\":{"
        "\"filePath\":{\"type\":\"string\"},"
        "\"oldString\":{\"type\":\"string\"},"
        "\"newString\":{\"type\":\"string\"}}}}}]";
    const char *p = json;
    char *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&p, &schemas, &orders));
    TEST_ASSERT(schemas && strstr(schemas, "\"name\":\"edit\""));
```<｜Assistant｜><think>


[System] You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.

[User]
Trova bug sottili e spiega quali invarianti dell'inferenza possono rompersi.

File: ds4_server.c

```c
r *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&p, &schemas, &orders));
    TEST_ASSERT(schemas && strstr(schemas, "\"name\":\"edit\""));
    const tool_schema_order *order = tool_schema_orders_find(&orders, "edit");
    TEST_ASSERT(order != NULL);
    TEST_ASSERT(order && order->len == 3);
    TEST_ASSERT(order && !strcmp(order->prop[0], "filePath"));
    TEST_ASSERT(order && !strcmp(order->prop[1], "oldString"));
    TEST_ASSERT(order && !strcmp(order->prop[2], "newString"));
    free(schemas);
    tool_schema_orders_free(&orders);
}

static void test_tool_schema_order_from_responses_tool_search(void) {
    const char *json =
        "[{\"type\":\"tool_search\",\"execution\":\"client\","
        "\"description\":\"Search deferred tools\","
        "\"parameters\":{\"type\":\"object\",\"properties\":{"
        "\"query\":{\"type\":\"string\"},"
        "\"limit\":{\"type\":\"number\"}},\"required\":[\"query\"]}}]";
    const char *p = json;
    char *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&p, &schemas, &orders));
    TEST_ASSERT(schemas && strstr(schemas, "\"name\":\"tool_search\""));
    TEST_ASSERT(schemas && strstr(schemas, "\"description\":\"Search deferred tools\""));
    const tool_schema_order *order = tool_schema_orders_find(&orders, "tool_search");
    TEST_ASSERT(order != NULL);
    TEST_ASSERT(order && order->responses_tool_search);
    TEST_ASSERT(order && order->len == 2);
    TEST_ASSERT(order && !strcmp(order->prop[0], "query"));
    TEST_ASSERT(order && !strcmp(order->prop[1], "limit"));
    free(schemas);
    tool_schema_orders_free(&orders);
}

static void test_responses_function_named_tool_search_stays_function_call(void) {
    const char *json =
        "[{\"type\":\"function\",\"function\":{\"name\":\"tool_search\","
        "\"description\":\"A normal user function that happens to use a reserved name\","
        "\"parameters\":{\"type\":\"object\",\"properties\":{"
        "\"query\":{\"type\":\"string\"}}}}}]";
    const char *p = json;
    char *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&p, &schemas, &orders));
    const tool_schema_order *order = tool_schema_orders_find(&orders, "tool_search");
    TEST_ASSERT(order != NULL);
    TEST_ASSERT(order && !order->responses_tool_search);

    tool_calls calls = {0};
    tool_call tc = {0};
    tc.id = xstrdup("call_user_tool_search");
    tc.name = xstrdup("tool_search");
    tc.arguments = xstrdup("{\"query\":\"plain function\"}");
```

<｜begin▁of▁sentence｜>You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.<｜User｜>Trova bug sottili e spiega quali invarianti dell'inferenza possono rompersi.

File: ds4_server.c

```c
r *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&p, &schemas, &orders));
    TEST_ASSERT(schemas && strstr(schemas, "\"name\":\"edit\""));
    const tool_schema_order *order = tool_schema_orders_find(&orders, "edit");
    TEST_ASSERT(order != NULL);
    TEST_ASSERT(order && order->len == 3);
    TEST_ASSERT(order && !strcmp(order->prop[0], "filePath"));
    TEST_ASSERT(order && !strcmp(order->prop[1], "oldString"));
    TEST_ASSERT(order && !strcmp(order->prop[2], "newString"));
    free(schemas);
    tool_schema_orders_free(&orders);
}

static void test_tool_schema_order_from_responses_tool_search(void) {
    const char *json =
        "[{\"type\":\"tool_search\",\"execution\":\"client\","
        "\"description\":\"Search deferred tools\","
        "\"parameters\":{\"type\":\"object\",\"properties\":{"
        "\"query\":{\"type\":\"string\"},"
        "\"limit\":{\"type\":\"number\"}},\"required\":[\"query\"]}}]";
    const char *p = json;
    char *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&p, &schemas, &orders));
    TEST_ASSERT(schemas && strstr(schemas, "\"name\":\"tool_search\""));
    TEST_ASSERT(schemas && strstr(schemas, "\"description\":\"Search deferred tools\""));
    const tool_schema_order *order = tool_schema_orders_find(&orders, "tool_search");
    TEST_ASSERT(order != NULL);
    TEST_ASSERT(order && order->responses_tool_search);
    TEST_ASSERT(order && order->len == 2);
    TEST_ASSERT(order && !strcmp(order->prop[0], "query"));
    TEST_ASSERT(order && !strcmp(order->prop[1], "limit"));
    free(schemas);
    tool_schema_orders_free(&orders);
}

static void test_responses_function_named_tool_search_stays_function_call(void) {
    const char *json =
        "[{\"type\":\"function\",\"function\":{\"name\":\"tool_search\","
        "\"description\":\"A normal user function that happens to use a reserved name\","
        "\"parameters\":{\"type\":\"object\",\"properties\":{"
        "\"query\":{\"type\":\"string\"}}}}}]";
    const char *p = json;
    char *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&p, &schemas, &orders));
    const tool_schema_order *order = tool_schema_orders_find(&orders, "tool_search");
    TEST_ASSERT(order != NULL);
    TEST_ASSERT(order && !order->responses_tool_search);

    tool_calls calls = {0};
    tool_call tc = {0};
    tc.id = xstrdup("call_user_tool_search");
    tc.name = xstrdup("tool_search");
    tc.arguments = xstrdup("{\"query\":\"plain function\"}");
```<｜Assistant｜></think>


[System] You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.

[User]
Trova bug sottili e spiega quali invarianti dell'inferenza possono rompersi.

File: ds4_server.c

```c
r *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&p, &schemas, &orders));
    TEST_ASSERT(schemas && strstr(schemas, "\"name\":\"edit\""));
    const tool_schema_order *order = tool_schema_orders_find(&orders, "edit");
    TEST_ASSERT(order != NULL);
    TEST_ASSERT(order && order->len == 3);
    TEST_ASSERT(order && !strcmp(order->prop[0], "filePath"));
    TEST_ASSERT(order && !strcmp(order->prop[1], "oldString"));
    TEST_ASSERT(order && !strcmp(order->prop[2], "newString"));
    free(schemas);
    tool_schema_orders_free(&orders);
}

static void test_tool_schema_order_from_responses_tool_search(void) {
    const char *json =
        "[{\"type\":\"tool_search\",\"execution\":\"client\","
        "\"description\":\"Search deferred tools\","
        "\"parameters\":{\"type\":\"object\",\"properties\":{"
        "\"query\":{\"type\":\"string\"},"
        "\"limit\":{\"type\":\"number\"}},\"required\":[\"query\"]}}]";
    const char *p = json;
    char *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&p, &schemas, &orders));
    TEST_ASSERT(schemas && strstr(schemas, "\"name\":\"tool_search\""));
    TEST_ASSERT(schemas && strstr(schemas, "\"description\":\"Search deferred tools\""));
    const tool_schema_order *order = tool_schema_orders_find(&orders, "tool_search");
    TEST_ASSERT(order != NULL);
    TEST_ASSERT(order && order->responses_tool_search);
    TEST_ASSERT(order && order->len == 2);
    TEST_ASSERT(order && !strcmp(order->prop[0], "query"));
    TEST_ASSERT(order && !strcmp(order->prop[1], "limit"));
    free(schemas);
    tool_schema_orders_free(&orders);
}

static void test_responses_function_named_tool_search_stays_function_call(void) {
    const char *json =
        "[{\"type\":\"function\",\"function\":{\"name\":\"tool_search\","
        "\"description\":\"A normal user function that happens to use a reserved name\","
        "\"parameters\":{\"type\":\"object\",\"properties\":{"
        "\"query\":{\"type\":\"string\"}}}}}]";
    const char *p = json;
    char *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&p, &schemas, &orders));
    const tool_schema_order *order = tool_schema_orders_find(&orders, "tool_search");
    TEST_ASSERT(order != NULL);
    TEST_ASSERT(order && !order->responses_tool_search);

    tool_calls calls = {0};
    tool_call tc = {0};
    tc.id = xstrdup("call_user_tool_search");
    tc.name = xstrdup("tool_search");
    tc.arguments = xstrdup("{\"query\":\"plain function\"}");
```

<｜begin▁of▁sentence｜>You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.<｜User｜>Trova bug sottili e spiega quali invarianti dell'inferenza possono rompersi.

File: ds4_server.c

```c
r *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&p, &schemas, &orders));
    TEST_ASSERT(schemas && strstr(schemas, "\"name\":\"edit\""));
    const tool_schema_order *order = tool_schema_orders_find(&orders, "edit");
    TEST_ASSERT(order != NULL);
    TEST_ASSERT(order && order->len == 3);
    TEST_ASSERT(order && !strcmp(order->prop[0], "filePath"));
    TEST_ASSERT(order && !strcmp(order->prop[1], "oldString"));
    TEST_ASSERT(order && !strcmp(order->prop[2], "newString"));
    free(schemas);
    tool_schema_orders_free(&orders);
}

static void test_tool_schema_order_from_responses_tool_search(void) {
    const char *json =
        "[{\"type\":\"tool_search\",\"execution\":\"client\","
        "\"description\":\"Search deferred tools\","
        "\"parameters\":{\"type\":\"object\",\"properties\":{"
        "\"query\":{\"type\":\"string\"},"
        "\"limit\":{\"type\":\"number\"}},\"required\":[\"query\"]}}]";
    const char *p = json;
    char *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&p, &schemas, &orders));
    TEST_ASSERT(schemas && strstr(schemas, "\"name\":\"tool_search\""));
    TEST_ASSERT(schemas && strstr(schemas, "\"description\":\"Search deferred tools\""));
    const tool_schema_order *order = tool_schema_orders_find(&orders, "tool_search");
    TEST_ASSERT(order != NULL);
    TEST_ASSERT(order && order->responses_tool_search);
    TEST_ASSERT(order && order->len == 2);
    TEST_ASSERT(order && !strcmp(order->prop[0], "query"));
    TEST_ASSERT(order && !strcmp(order->prop[1], "limit"));
    free(schemas);
    tool_schema_orders_free(&orders);
}

static void test_responses_function_named_tool_search_stays_function_call(void) {
    const char *json =
        "[{\"type\":\"function\",\"function\":{\"name\":\"tool_search\","
        "\"description\":\"A normal user function that happens to use a reserved name\","
        "\"parameters\":{\"type\":\"object\",\"properties\":{"
        "\"query\":{\"type\":\"string\"}}}}}]";
    const char *p = json;
    char *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&p, &schemas, &orders));
    const tool_schema_order *order = tool_schema_orders_find(&orders, "tool_search");
    TEST_ASSERT(order != NULL);
    TEST_ASSERT(order && !order->responses_tool_search);

    tool_calls calls = {0};
    tool_call tc = {0};
    tc.id = xstrdup("call_user_tool_search");
    tc.name = xstrdup("tool_search");
    tc.arguments = xstrdup("{\"query\":\"plain function\"}");
```<｜Assistant｜><think>


[System] You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.

[User]
Review this excerpt for correctness risks, memory lifetime issues, and performance bottlenecks.

File: ds4_server.c

```c
lls = {0};
    tool_call tc = {0};
    tc.id = xstrdup("call_user_tool_search");
    tc.name = xstrdup("tool_search");
    tc.arguments = xstrdup("{\"query\":\"plain function\"}");
    tool_calls_push(&calls, tc);
    responses_tool_item item = {
        .fc_id = "fc_user_tool_search",
        .call_id = "call_user_tool_search",
        .is_custom = false,
        .output_index = 0,
    };

    buf out = {0};
    responses_append_function_call_item(&out, &calls.v[0], &item,
                                        "completed", true, &orders);
    TEST_ASSERT(strstr(out.ptr, "\"type\":\"function_call\"") != NULL);
    TEST_ASSERT(strstr(out.ptr, "\"type\":\"tool_search_call\"") == NULL);

    buf_free(&out);
    tool_calls_free(&calls);
    free(schemas);
    tool_schema_orders_free(&orders);
}

static void test_responses_namespace_tool_schemas_restore_wire_namespace(void) {
    const char *json =
        "[{\"type\":\"namespace\",\"name\":\"mcp__perplexity__\","
        "\"description\":\"Perplexity tools\","
        "\"tools\":[{\"type\":\"function\",\"name\":\"perplexity_search\","
        "\"description\":\"Search the web\","
        "\"parameters\":{\"type\":\"object\",\"properties\":{"
        "\"query\":{\"type\":\"string\"},"
        "\"recency\":{\"type\":\"number\"}}}}]}]";
    const char *p = json;
    char *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&p, &schemas, &orders));
    TEST_ASSERT(schemas && strstr(schemas, "\"name\":\"mcp__perplexity__perplexity_search\""));
    TEST_ASSERT(schemas && strstr(schemas, "\"name\":\"perplexity_search\"") == NULL);

    const tool_schema_order *order =
        tool_schema_orders_find(&orders, "mcp__perplexity__perplexity_search");
    TEST_ASSERT(order != NULL);
    TEST_ASSERT(order && order->namespace && !strcmp(order->namespace, "mcp__perplexity__"));
    TEST_ASSERT(order && order->wire_name && !strcmp(order->wire_name, "perplexity_search"));
    TEST_ASSERT(order && order->len == 2);

    tool_calls calls = {0};
    tool_call tc = {0};
    tc.id = xstrdup("call_ns");
    tc.name = xstrdup("mcp__perplexity__perplexity_search");
    tc.arguments = xstrdup("{\"query\":\"deepseek\",\"recency\":7}");
    tool_calls_push(&calls, tc);
    responses_tool_item item = {
        .fc_id = "fc_ns",
        .call_id = "call_ns",
        .is_custom = false,
        .output_index = 0,
    };
    buf out = {0};
    responses_append_function_call_item(&out, &calls.v[0], &item,
                                        "completed", true, &orders);
```

<｜begin▁of▁sentence｜>You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.<｜User｜>Review this excerpt for correctness risks, memory lifetime issues, and performance bottlenecks.

File: ds4_server.c

```c
lls = {0};
    tool_call tc = {0};
    tc.id = xstrdup("call_user_tool_search");
    tc.name = xstrdup("tool_search");
    tc.arguments = xstrdup("{\"query\":\"plain function\"}");
    tool_calls_push(&calls, tc);
    responses_tool_item item = {
        .fc_id = "fc_user_tool_search",
        .call_id = "call_user_tool_search",
        .is_custom = false,
        .output_index = 0,
    };

    buf out = {0};
    responses_append_function_call_item(&out, &calls.v[0], &item,
                                        "completed", true, &orders);
    TEST_ASSERT(strstr(out.ptr, "\"type\":\"function_call\"") != NULL);
    TEST_ASSERT(strstr(out.ptr, "\"type\":\"tool_search_call\"") == NULL);

    buf_free(&out);
    tool_calls_free(&calls);
    free(schemas);
    tool_schema_orders_free(&orders);
}

static void test_responses_namespace_tool_schemas_restore_wire_namespace(void) {
    const char *json =
        "[{\"type\":\"namespace\",\"name\":\"mcp__perplexity__\","
        "\"description\":\"Perplexity tools\","
        "\"tools\":[{\"type\":\"function\",\"name\":\"perplexity_search\","
        "\"description\":\"Search the web\","
        "\"parameters\":{\"type\":\"object\",\"properties\":{"
        "\"query\":{\"type\":\"string\"},"
        "\"recency\":{\"type\":\"number\"}}}}]}]";
    const char *p = json;
    char *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&p, &schemas, &orders));
    TEST_ASSERT(schemas && strstr(schemas, "\"name\":\"mcp__perplexity__perplexity_search\""));
    TEST_ASSERT(schemas && strstr(schemas, "\"name\":\"perplexity_search\"") == NULL);

    const tool_schema_order *order =
        tool_schema_orders_find(&orders, "mcp__perplexity__perplexity_search");
    TEST_ASSERT(order != NULL);
    TEST_ASSERT(order && order->namespace && !strcmp(order->namespace, "mcp__perplexity__"));
    TEST_ASSERT(order && order->wire_name && !strcmp(order->wire_name, "perplexity_search"));
    TEST_ASSERT(order && order->len == 2);

    tool_calls calls = {0};
    tool_call tc = {0};
    tc.id = xstrdup("call_ns");
    tc.name = xstrdup("mcp__perplexity__perplexity_search");
    tc.arguments = xstrdup("{\"query\":\"deepseek\",\"recency\":7}");
    tool_calls_push(&calls, tc);
    responses_tool_item item = {
        .fc_id = "fc_ns",
        .call_id = "call_ns",
        .is_custom = false,
        .output_index = 0,
    };
    buf out = {0};
    responses_append_function_call_item(&out, &calls.v[0], &item,
                                        "completed", true, &orders);
```<｜Assistant｜></think>


[System] You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.

[User]
Review this excerpt for correctness risks, memory lifetime issues, and performance bottlenecks.

File: ds4_server.c

```c
lls = {0};
    tool_call tc = {0};
    tc.id = xstrdup("call_user_tool_search");
    tc.name = xstrdup("tool_search");
    tc.arguments = xstrdup("{\"query\":\"plain function\"}");
    tool_calls_push(&calls, tc);
    responses_tool_item item = {
        .fc_id = "fc_user_tool_search",
        .call_id = "call_user_tool_search",
        .is_custom = false,
        .output_index = 0,
    };

    buf out = {0};
    responses_append_function_call_item(&out, &calls.v[0], &item,
                                        "completed", true, &orders);
    TEST_ASSERT(strstr(out.ptr, "\"type\":\"function_call\"") != NULL);
    TEST_ASSERT(strstr(out.ptr, "\"type\":\"tool_search_call\"") == NULL);

    buf_free(&out);
    tool_calls_free(&calls);
    free(schemas);
    tool_schema_orders_free(&orders);
}

static void test_responses_namespace_tool_schemas_restore_wire_namespace(void) {
    const char *json =
        "[{\"type\":\"namespace\",\"name\":\"mcp__perplexity__\","
        "\"description\":\"Perplexity tools\","
        "\"tools\":[{\"type\":\"function\",\"name\":\"perplexity_search\","
        "\"description\":\"Search the web\","
        "\"parameters\":{\"type\":\"object\",\"properties\":{"
        "\"query\":{\"type\":\"string\"},"
        "\"recency\":{\"type\":\"number\"}}}}]}]";
    const char *p = json;
    char *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&p, &schemas, &orders));
    TEST_ASSERT(schemas && strstr(schemas, "\"name\":\"mcp__perplexity__perplexity_search\""));
    TEST_ASSERT(schemas && strstr(schemas, "\"name\":\"perplexity_search\"") == NULL);

    const tool_schema_order *order =
        tool_schema_orders_find(&orders, "mcp__perplexity__perplexity_search");
    TEST_ASSERT(order != NULL);
    TEST_ASSERT(order && order->namespace && !strcmp(order->namespace, "mcp__perplexity__"));
    TEST_ASSERT(order && order->wire_name && !strcmp(order->wire_name, "perplexity_search"));
    TEST_ASSERT(order && order->len == 2);

    tool_calls calls = {0};
    tool_call tc = {0};
    tc.id = xstrdup("call_ns");
    tc.name = xstrdup("mcp__perplexity__perplexity_search");
    tc.arguments = xstrdup("{\"query\":\"deepseek\",\"recency\":7}");
    tool_calls_push(&calls, tc);
    responses_tool_item item = {
        .fc_id = "fc_ns",
        .call_id = "call_ns",
        .is_custom = false,
        .output_index = 0,
    };
    buf out = {0};
    responses_append_function_call_item(&out, &calls.v[0], &item,
                                        "completed", true, &orders);
```

<｜begin▁of▁sentence｜>You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.<｜User｜>Review this excerpt for correctness risks, memory lifetime issues, and performance bottlenecks.

File: ds4_server.c

```c
lls = {0};
    tool_call tc = {0};
    tc.id = xstrdup("call_user_tool_search");
    tc.name = xstrdup("tool_search");
    tc.arguments = xstrdup("{\"query\":\"plain function\"}");
    tool_calls_push(&calls, tc);
    responses_tool_item item = {
        .fc_id = "fc_user_tool_search",
        .call_id = "call_user_tool_search",
        .is_custom = false,
        .output_index = 0,
    };

    buf out = {0};
    responses_append_function_call_item(&out, &calls.v[0], &item,
                                        "completed", true, &orders);
    TEST_ASSERT(strstr(out.ptr, "\"type\":\"function_call\"") != NULL);
    TEST_ASSERT(strstr(out.ptr, "\"type\":\"tool_search_call\"") == NULL);

    buf_free(&out);
    tool_calls_free(&calls);
    free(schemas);
    tool_schema_orders_free(&orders);
}

static void test_responses_namespace_tool_schemas_restore_wire_namespace(void) {
    const char *json =
        "[{\"type\":\"namespace\",\"name\":\"mcp__perplexity__\","
        "\"description\":\"Perplexity tools\","
        "\"tools\":[{\"type\":\"function\",\"name\":\"perplexity_search\","
        "\"description\":\"Search the web\","
        "\"parameters\":{\"type\":\"object\",\"properties\":{"
        "\"query\":{\"type\":\"string\"},"
        "\"recency\":{\"type\":\"number\"}}}}]}]";
    const char *p = json;
    char *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&p, &schemas, &orders));
    TEST_ASSERT(schemas && strstr(schemas, "\"name\":\"mcp__perplexity__perplexity_search\""));
    TEST_ASSERT(schemas && strstr(schemas, "\"name\":\"perplexity_search\"") == NULL);

    const tool_schema_order *order =
        tool_schema_orders_find(&orders, "mcp__perplexity__perplexity_search");
    TEST_ASSERT(order != NULL);
    TEST_ASSERT(order && order->namespace && !strcmp(order->namespace, "mcp__perplexity__"));
    TEST_ASSERT(order && order->wire_name && !strcmp(order->wire_name, "perplexity_search"));
    TEST_ASSERT(order && order->len == 2);

    tool_calls calls = {0};
    tool_call tc = {0};
    tc.id = xstrdup("call_ns");
    tc.name = xstrdup("mcp__perplexity__perplexity_search");
    tc.arguments = xstrdup("{\"query\":\"deepseek\",\"recency\":7}");
    tool_calls_push(&calls, tc);
    responses_tool_item item = {
        .fc_id = "fc_ns",
        .call_id = "call_ns",
        .is_custom = false,
        .output_index = 0,
    };
    buf out = {0};
    responses_append_function_call_item(&out, &calls.v[0], &item,
                                        "completed", true, &orders);
```<｜Assistant｜><think>


[System] You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.

[User]
Explain what this code does and identify the inference stage it belongs to.

File: ds4_server.c

```c
.output_index = 0,
    };
    buf out = {0};
    responses_append_function_call_item(&out, &calls.v[0], &item,
                                        "completed", true, &orders);
    TEST_ASSERT(strstr(out.ptr, "\"name\":\"perplexity_search\"") != NULL);
    TEST_ASSERT(strstr(out.ptr, "\"namespace\":\"mcp__perplexity__\"") != NULL);
    TEST_ASSERT(strstr(out.ptr, "mcp__perplexity__perplexity_search") == NULL);

    buf_free(&out);
    tool_calls_free(&calls);
    free(schemas);
    tool_schema_orders_free(&orders);
}

static void test_responses_input_tool_search_output_loads_tools(void) {
    const char *json =
        "["
        "{\"type\":\"tool_search_call\",\"call_id\":\"call_search\","
        "\"execution\":\"client\",\"arguments\":{\"query\":\"perplexity\"}},"
        "{\"type\":\"tool_search_output\",\"call_id\":\"call_search\","
        "\"status\":\"completed\",\"execution\":\"client\",\"tools\":["
        "{\"type\":\"namespace\",\"name\":\"mcp__perplexity__\","
        "\"description\":\"Perplexity tools\","
        "\"tools\":[{\"type\":\"function\",\"name\":\"perplexity_search\","
        "\"description\":\"Search with Perplexity\","
        "\"parameters\":{\"type\":\"object\",\"properties\":{"
        "\"query\":{\"type\":\"string\"}}}}]}]}"
        "]";
    const char *p = json;
    chat_msgs msgs = {0};
    buf loaded = {0};
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_responses_input(&p, &msgs, &loaded, &orders));
    TEST_ASSERT(loaded.ptr && strstr(loaded.ptr, "\"name\":\"mcp__perplexity__perplexity_search\""));
    const tool_schema_order *order =
        tool_schema_orders_find(&orders, "mcp__perplexity__perplexity_search");
    TEST_ASSERT(order != NULL);
    TEST_ASSERT(order && order->namespace && !strcmp(order->namespace, "mcp__perplexity__"));
    TEST_ASSERT(order && order->wire_name && !strcmp(order->wire_name, "perplexity_search"));
    TEST_ASSERT(msgs.len == 2);
    TEST_ASSERT(msgs.v[0].calls.len == 1);
    TEST_ASSERT(!strcmp(msgs.v[0].calls.v[0].name, "tool_search"));
    TEST_ASSERT(strstr(msgs.v[1].content, "mcp__perplexity__") != NULL);

    buf_free(&loaded);
    tool_schema_orders_free(&orders);
    chat_msgs_free(&msgs);
}

static void test_responses_input_tool_search_output_rejects_bad_tools(void) {
    const char *json =
        "[{\"type\":\"tool_search_output\",\"call_id\":\"call_search\","
        "\"status\":\"completed\",\"tools\":{\"not\":\"a tool array\"}}]";
    const char *p = json;
    chat_msgs msgs = {0};
    buf loaded = {0};
    tool_schema_orders orders = {0};
```

<｜begin▁of▁sentence｜>You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.<｜User｜>Explain what this code does and identify the inference stage it belongs to.

File: ds4_server.c

```c
.output_index = 0,
    };
    buf out = {0};
    responses_append_function_call_item(&out, &calls.v[0], &item,
                                        "completed", true, &orders);
    TEST_ASSERT(strstr(out.ptr, "\"name\":\"perplexity_search\"") != NULL);
    TEST_ASSERT(strstr(out.ptr, "\"namespace\":\"mcp__perplexity__\"") != NULL);
    TEST_ASSERT(strstr(out.ptr, "mcp__perplexity__perplexity_search") == NULL);

    buf_free(&out);
    tool_calls_free(&calls);
    free(schemas);
    tool_schema_orders_free(&orders);
}

static void test_responses_input_tool_search_output_loads_tools(void) {
    const char *json =
        "["
        "{\"type\":\"tool_search_call\",\"call_id\":\"call_search\","
        "\"execution\":\"client\",\"arguments\":{\"query\":\"perplexity\"}},"
        "{\"type\":\"tool_search_output\",\"call_id\":\"call_search\","
        "\"status\":\"completed\",\"execution\":\"client\",\"tools\":["
        "{\"type\":\"namespace\",\"name\":\"mcp__perplexity__\","
        "\"description\":\"Perplexity tools\","
        "\"tools\":[{\"type\":\"function\",\"name\":\"perplexity_search\","
        "\"description\":\"Search with Perplexity\","
        "\"parameters\":{\"type\":\"object\",\"properties\":{"
        "\"query\":{\"type\":\"string\"}}}}]}]}"
        "]";
    const char *p = json;
    chat_msgs msgs = {0};
    buf loaded = {0};
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_responses_input(&p, &msgs, &loaded, &orders));
    TEST_ASSERT(loaded.ptr && strstr(loaded.ptr, "\"name\":\"mcp__perplexity__perplexity_search\""));
    const tool_schema_order *order =
        tool_schema_orders_find(&orders, "mcp__perplexity__perplexity_search");
    TEST_ASSERT(order != NULL);
    TEST_ASSERT(order && order->namespace && !strcmp(order->namespace, "mcp__perplexity__"));
    TEST_ASSERT(order && order->wire_name && !strcmp(order->wire_name, "perplexity_search"));
    TEST_ASSERT(msgs.len == 2);
    TEST_ASSERT(msgs.v[0].calls.len == 1);
    TEST_ASSERT(!strcmp(msgs.v[0].calls.v[0].name, "tool_search"));
    TEST_ASSERT(strstr(msgs.v[1].content, "mcp__perplexity__") != NULL);

    buf_free(&loaded);
    tool_schema_orders_free(&orders);
    chat_msgs_free(&msgs);
}

static void test_responses_input_tool_search_output_rejects_bad_tools(void) {
    const char *json =
        "[{\"type\":\"tool_search_output\",\"call_id\":\"call_search\","
        "\"status\":\"completed\",\"tools\":{\"not\":\"a tool array\"}}]";
    const char *p = json;
    chat_msgs msgs = {0};
    buf loaded = {0};
    tool_schema_orders orders = {0};
```<｜Assistant｜></think>


[System] You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.

[User]
Explain what this code does and identify the inference stage it belongs to.

File: ds4_server.c

```c
.output_index = 0,
    };
    buf out = {0};
    responses_append_function_call_item(&out, &calls.v[0], &item,
                                        "completed", true, &orders);
    TEST_ASSERT(strstr(out.ptr, "\"name\":\"perplexity_search\"") != NULL);
    TEST_ASSERT(strstr(out.ptr, "\"namespace\":\"mcp__perplexity__\"") != NULL);
    TEST_ASSERT(strstr(out.ptr, "mcp__perplexity__perplexity_search") == NULL);

    buf_free(&out);
    tool_calls_free(&calls);
    free(schemas);
    tool_schema_orders_free(&orders);
}

static void test_responses_input_tool_search_output_loads_tools(void) {
    const char *json =
        "["
        "{\"type\":\"tool_search_call\",\"call_id\":\"call_search\","
        "\"execution\":\"client\",\"arguments\":{\"query\":\"perplexity\"}},"
        "{\"type\":\"tool_search_output\",\"call_id\":\"call_search\","
        "\"status\":\"completed\",\"execution\":\"client\",\"tools\":["
        "{\"type\":\"namespace\",\"name\":\"mcp__perplexity__\","
        "\"description\":\"Perplexity tools\","
        "\"tools\":[{\"type\":\"function\",\"name\":\"perplexity_search\","
        "\"description\":\"Search with Perplexity\","
        "\"parameters\":{\"type\":\"object\",\"properties\":{"
        "\"query\":{\"type\":\"string\"}}}}]}]}"
        "]";
    const char *p = json;
    chat_msgs msgs = {0};
    buf loaded = {0};
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_responses_input(&p, &msgs, &loaded, &orders));
    TEST_ASSERT(loaded.ptr && strstr(loaded.ptr, "\"name\":\"mcp__perplexity__perplexity_search\""));
    const tool_schema_order *order =
        tool_schema_orders_find(&orders, "mcp__perplexity__perplexity_search");
    TEST_ASSERT(order != NULL);
    TEST_ASSERT(order && order->namespace && !strcmp(order->namespace, "mcp__perplexity__"));
    TEST_ASSERT(order && order->wire_name && !strcmp(order->wire_name, "perplexity_search"));
    TEST_ASSERT(msgs.len == 2);
    TEST_ASSERT(msgs.v[0].calls.len == 1);
    TEST_ASSERT(!strcmp(msgs.v[0].calls.v[0].name, "tool_search"));
    TEST_ASSERT(strstr(msgs.v[1].content, "mcp__perplexity__") != NULL);

    buf_free(&loaded);
    tool_schema_orders_free(&orders);
    chat_msgs_free(&msgs);
}

static void test_responses_input_tool_search_output_rejects_bad_tools(void) {
    const char *json =
        "[{\"type\":\"tool_search_output\",\"call_id\":\"call_search\","
        "\"status\":\"completed\",\"tools\":{\"not\":\"a tool array\"}}]";
    const char *p = json;
    chat_msgs msgs = {0};
    buf loaded = {0};
    tool_schema_orders orders = {0};
```

<｜begin▁of▁sentence｜>You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.<｜User｜>Explain what this code does and identify the inference stage it belongs to.

File: ds4_server.c

```c
.output_index = 0,
    };
    buf out = {0};
    responses_append_function_call_item(&out, &calls.v[0], &item,
                                        "completed", true, &orders);
    TEST_ASSERT(strstr(out.ptr, "\"name\":\"perplexity_search\"") != NULL);
    TEST_ASSERT(strstr(out.ptr, "\"namespace\":\"mcp__perplexity__\"") != NULL);
    TEST_ASSERT(strstr(out.ptr, "mcp__perplexity__perplexity_search") == NULL);

    buf_free(&out);
    tool_calls_free(&calls);
    free(schemas);
    tool_schema_orders_free(&orders);
}

static void test_responses_input_tool_search_output_loads_tools(void) {
    const char *json =
        "["
        "{\"type\":\"tool_search_call\",\"call_id\":\"call_search\","
        "\"execution\":\"client\",\"arguments\":{\"query\":\"perplexity\"}},"
        "{\"type\":\"tool_search_output\",\"call_id\":\"call_search\","
        "\"status\":\"completed\",\"execution\":\"client\",\"tools\":["
        "{\"type\":\"namespace\",\"name\":\"mcp__perplexity__\","
        "\"description\":\"Perplexity tools\","
        "\"tools\":[{\"type\":\"function\",\"name\":\"perplexity_search\","
        "\"description\":\"Search with Perplexity\","
        "\"parameters\":{\"type\":\"object\",\"properties\":{"
        "\"query\":{\"type\":\"string\"}}}}]}]}"
        "]";
    const char *p = json;
    chat_msgs msgs = {0};
    buf loaded = {0};
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_responses_input(&p, &msgs, &loaded, &orders));
    TEST_ASSERT(loaded.ptr && strstr(loaded.ptr, "\"name\":\"mcp__perplexity__perplexity_search\""));
    const tool_schema_order *order =
        tool_schema_orders_find(&orders, "mcp__perplexity__perplexity_search");
    TEST_ASSERT(order != NULL);
    TEST_ASSERT(order && order->namespace && !strcmp(order->namespace, "mcp__perplexity__"));
    TEST_ASSERT(order && order->wire_name && !strcmp(order->wire_name, "perplexity_search"));
    TEST_ASSERT(msgs.len == 2);
    TEST_ASSERT(msgs.v[0].calls.len == 1);
    TEST_ASSERT(!strcmp(msgs.v[0].calls.v[0].name, "tool_search"));
    TEST_ASSERT(strstr(msgs.v[1].content, "mcp__perplexity__") != NULL);

    buf_free(&loaded);
    tool_schema_orders_free(&orders);
    chat_msgs_free(&msgs);
}

static void test_responses_input_tool_search_output_rejects_bad_tools(void) {
    const char *json =
        "[{\"type\":\"tool_search_output\",\"call_id\":\"call_search\","
        "\"status\":\"completed\",\"tools\":{\"not\":\"a tool array\"}}]";
    const char *p = json;
    chat_msgs msgs = {0};
    buf loaded = {0};
    tool_schema_orders orders = {0};
```<｜Assistant｜><think>


[System] You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.

[User]
Suggest a minimal correctness-preserving optimization for this excerpt.

File: ds4_server.c

```c
"\"status\":\"completed\",\"tools\":{\"not\":\"a tool array\"}}]";
    const char *p = json;
    chat_msgs msgs = {0};
    buf loaded = {0};
    tool_schema_orders orders = {0};
    TEST_ASSERT(!parse_responses_input(&p, &msgs, &loaded, &orders));
    buf_free(&loaded);
    tool_schema_orders_free(&orders);
    chat_msgs_free(&msgs);
}

static void test_responses_input_function_call_namespace_round_trips_to_dsml(void) {
    const char *tools_json =
        "[{\"type\":\"namespace\",\"name\":\"mcp__perplexity__\","
        "\"tools\":[{\"type\":\"function\",\"name\":\"perplexity_search\","
        "\"parameters\":{\"type\":\"object\",\"properties\":{"
        "\"query\":{\"type\":\"string\"}}}}]}]";
    const char *tools_p = tools_json;
    char *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&tools_p, &schemas, &orders));

    const char *input_json =
        "[{\"type\":\"function_call\",\"call_id\":\"call_ns\","
        "\"name\":\"perplexity_search\",\"namespace\":\"mcp__perplexity__\","
        "\"arguments\":{\"query\":\"deepseek\"}}]";
    const char *input_p = input_json;
    chat_msgs msgs = {0};
    TEST_ASSERT(parse_responses_input(&input_p, &msgs, NULL, NULL));
    TEST_ASSERT(msgs.len == 1);
    TEST_ASSERT(msgs.v[0].calls.len == 1);
    TEST_ASSERT(!strcmp(msgs.v[0].calls.v[0].name,
                        "mcp__perplexity__perplexity_search"));

    char *prompt = render_chat_prompt_text(&msgs, schemas, &orders, DS4_THINK_HIGH);
    TEST_ASSERT(prompt != NULL);
    TEST_ASSERT(strstr(prompt,
        "<｜DSML｜invoke name=\"mcp__perplexity__perplexity_search\">") != NULL);
    TEST_ASSERT(strstr(prompt, "<｜DSML｜invoke name=\"perplexity_search\">") == NULL);

    free(prompt);
    chat_msgs_free(&msgs);
    free(schemas);
    tool_schema_orders_free(&orders);
}

static void test_responses_output_sends_tool_search_call_item(void) {
    tool_calls calls = {0};
    tool_call tc = {0};
    tc.id = xstrdup("call_search");
    tc.name = xstrdup("tool_search");
    tc.arguments = xstrdup("{\"limit\":3,\"query\":\"perplexity\"}");
    tool_calls_push(&calls, tc);
    const char *tools_json =
        "[{\"type\":\"tool_search\",\"execution\":\"client\","
        "\"parameters\":{\"type\":\"object\",\"properties\":{"
        "\"query\":{\"type\":\"string\"},\"limit\":{\"type\":\"number\"}}}}]";
    const char *tools_p = tools_json;
    char *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&tools_p, &schemas, &orders));
    responses_tool_item item = {
```

<｜begin▁of▁sentence｜>You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.<｜User｜>Suggest a minimal correctness-preserving optimization for this excerpt.

File: ds4_server.c

```c
"\"status\":\"completed\",\"tools\":{\"not\":\"a tool array\"}}]";
    const char *p = json;
    chat_msgs msgs = {0};
    buf loaded = {0};
    tool_schema_orders orders = {0};
    TEST_ASSERT(!parse_responses_input(&p, &msgs, &loaded, &orders));
    buf_free(&loaded);
    tool_schema_orders_free(&orders);
    chat_msgs_free(&msgs);
}

static void test_responses_input_function_call_namespace_round_trips_to_dsml(void) {
    const char *tools_json =
        "[{\"type\":\"namespace\",\"name\":\"mcp__perplexity__\","
        "\"tools\":[{\"type\":\"function\",\"name\":\"perplexity_search\","
        "\"parameters\":{\"type\":\"object\",\"properties\":{"
        "\"query\":{\"type\":\"string\"}}}}]}]";
    const char *tools_p = tools_json;
    char *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&tools_p, &schemas, &orders));

    const char *input_json =
        "[{\"type\":\"function_call\",\"call_id\":\"call_ns\","
        "\"name\":\"perplexity_search\",\"namespace\":\"mcp__perplexity__\","
        "\"arguments\":{\"query\":\"deepseek\"}}]";
    const char *input_p = input_json;
    chat_msgs msgs = {0};
    TEST_ASSERT(parse_responses_input(&input_p, &msgs, NULL, NULL));
    TEST_ASSERT(msgs.len == 1);
    TEST_ASSERT(msgs.v[0].calls.len == 1);
    TEST_ASSERT(!strcmp(msgs.v[0].calls.v[0].name,
                        "mcp__perplexity__perplexity_search"));

    char *prompt = render_chat_prompt_text(&msgs, schemas, &orders, DS4_THINK_HIGH);
    TEST_ASSERT(prompt != NULL);
    TEST_ASSERT(strstr(prompt,
        "<｜DSML｜invoke name=\"mcp__perplexity__perplexity_search\">") != NULL);
    TEST_ASSERT(strstr(prompt, "<｜DSML｜invoke name=\"perplexity_search\">") == NULL);

    free(prompt);
    chat_msgs_free(&msgs);
    free(schemas);
    tool_schema_orders_free(&orders);
}

static void test_responses_output_sends_tool_search_call_item(void) {
    tool_calls calls = {0};
    tool_call tc = {0};
    tc.id = xstrdup("call_search");
    tc.name = xstrdup("tool_search");
    tc.arguments = xstrdup("{\"limit\":3,\"query\":\"perplexity\"}");
    tool_calls_push(&calls, tc);
    const char *tools_json =
        "[{\"type\":\"tool_search\",\"execution\":\"client\","
        "\"parameters\":{\"type\":\"object\",\"properties\":{"
        "\"query\":{\"type\":\"string\"},\"limit\":{\"type\":\"number\"}}}}]";
    const char *tools_p = tools_json;
    char *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&tools_p, &schemas, &orders));
    responses_tool_item item = {
```<｜Assistant｜></think>


[System] You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.

[User]
Suggest a minimal correctness-preserving optimization for this excerpt.

File: ds4_server.c

```c
"\"status\":\"completed\",\"tools\":{\"not\":\"a tool array\"}}]";
    const char *p = json;
    chat_msgs msgs = {0};
    buf loaded = {0};
    tool_schema_orders orders = {0};
    TEST_ASSERT(!parse_responses_input(&p, &msgs, &loaded, &orders));
    buf_free(&loaded);
    tool_schema_orders_free(&orders);
    chat_msgs_free(&msgs);
}

static void test_responses_input_function_call_namespace_round_trips_to_dsml(void) {
    const char *tools_json =
        "[{\"type\":\"namespace\",\"name\":\"mcp__perplexity__\","
        "\"tools\":[{\"type\":\"function\",\"name\":\"perplexity_search\","
        "\"parameters\":{\"type\":\"object\",\"properties\":{"
        "\"query\":{\"type\":\"string\"}}}}]}]";
    const char *tools_p = tools_json;
    char *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&tools_p, &schemas, &orders));

    const char *input_json =
        "[{\"type\":\"function_call\",\"call_id\":\"call_ns\","
        "\"name\":\"perplexity_search\",\"namespace\":\"mcp__perplexity__\","
        "\"arguments\":{\"query\":\"deepseek\"}}]";
    const char *input_p = input_json;
    chat_msgs msgs = {0};
    TEST_ASSERT(parse_responses_input(&input_p, &msgs, NULL, NULL));
    TEST_ASSERT(msgs.len == 1);
    TEST_ASSERT(msgs.v[0].calls.len == 1);
    TEST_ASSERT(!strcmp(msgs.v[0].calls.v[0].name,
                        "mcp__perplexity__perplexity_search"));

    char *prompt = render_chat_prompt_text(&msgs, schemas, &orders, DS4_THINK_HIGH);
    TEST_ASSERT(prompt != NULL);
    TEST_ASSERT(strstr(prompt,
        "<｜DSML｜invoke name=\"mcp__perplexity__perplexity_search\">") != NULL);
    TEST_ASSERT(strstr(prompt, "<｜DSML｜invoke name=\"perplexity_search\">") == NULL);

    free(prompt);
    chat_msgs_free(&msgs);
    free(schemas);
    tool_schema_orders_free(&orders);
}

static void test_responses_output_sends_tool_search_call_item(void) {
    tool_calls calls = {0};
    tool_call tc = {0};
    tc.id = xstrdup("call_search");
    tc.name = xstrdup("tool_search");
    tc.arguments = xstrdup("{\"limit\":3,\"query\":\"perplexity\"}");
    tool_calls_push(&calls, tc);
    const char *tools_json =
        "[{\"type\":\"tool_search\",\"execution\":\"client\","
        "\"parameters\":{\"type\":\"object\",\"properties\":{"
        "\"query\":{\"type\":\"string\"},\"limit\":{\"type\":\"number\"}}}}]";
    const char *tools_p = tools_json;
    char *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&tools_p, &schemas, &orders));
    responses_tool_item item = {
```

<｜begin▁of▁sentence｜>You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.<｜User｜>Suggest a minimal correctness-preserving optimization for this excerpt.

File: ds4_server.c

```c
"\"status\":\"completed\",\"tools\":{\"not\":\"a tool array\"}}]";
    const char *p = json;
    chat_msgs msgs = {0};
    buf loaded = {0};
    tool_schema_orders orders = {0};
    TEST_ASSERT(!parse_responses_input(&p, &msgs, &loaded, &orders));
    buf_free(&loaded);
    tool_schema_orders_free(&orders);
    chat_msgs_free(&msgs);
}

static void test_responses_input_function_call_namespace_round_trips_to_dsml(void) {
    const char *tools_json =
        "[{\"type\":\"namespace\",\"name\":\"mcp__perplexity__\","
        "\"tools\":[{\"type\":\"function\",\"name\":\"perplexity_search\","
        "\"parameters\":{\"type\":\"object\",\"properties\":{"
        "\"query\":{\"type\":\"string\"}}}}]}]";
    const char *tools_p = tools_json;
    char *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&tools_p, &schemas, &orders));

    const char *input_json =
        "[{\"type\":\"function_call\",\"call_id\":\"call_ns\","
        "\"name\":\"perplexity_search\",\"namespace\":\"mcp__perplexity__\","
        "\"arguments\":{\"query\":\"deepseek\"}}]";
    const char *input_p = input_json;
    chat_msgs msgs = {0};
    TEST_ASSERT(parse_responses_input(&input_p, &msgs, NULL, NULL));
    TEST_ASSERT(msgs.len == 1);
    TEST_ASSERT(msgs.v[0].calls.len == 1);
    TEST_ASSERT(!strcmp(msgs.v[0].calls.v[0].name,
                        "mcp__perplexity__perplexity_search"));

    char *prompt = render_chat_prompt_text(&msgs, schemas, &orders, DS4_THINK_HIGH);
    TEST_ASSERT(prompt != NULL);
    TEST_ASSERT(strstr(prompt,
        "<｜DSML｜invoke name=\"mcp__perplexity__perplexity_search\">") != NULL);
    TEST_ASSERT(strstr(prompt, "<｜DSML｜invoke name=\"perplexity_search\">") == NULL);

    free(prompt);
    chat_msgs_free(&msgs);
    free(schemas);
    tool_schema_orders_free(&orders);
}

static void test_responses_output_sends_tool_search_call_item(void) {
    tool_calls calls = {0};
    tool_call tc = {0};
    tc.id = xstrdup("call_search");
    tc.name = xstrdup("tool_search");
    tc.arguments = xstrdup("{\"limit\":3,\"query\":\"perplexity\"}");
    tool_calls_push(&calls, tc);
    const char *tools_json =
        "[{\"type\":\"tool_search\",\"execution\":\"client\","
        "\"parameters\":{\"type\":\"object\",\"properties\":{"
        "\"query\":{\"type\":\"string\"},\"limit\":{\"type\":\"number\"}}}}]";
    const char *tools_p = tools_json;
    char *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&tools_p, &schemas, &orders));
    responses_tool_item item = {
```<｜Assistant｜><think>


[System] You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.

[User]
Trova bug sottili e spiega quali invarianti dell'inferenza possono rompersi.

File: ds4_server.c

```c
ols_p = tools_json;
    char *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&tools_p, &schemas, &orders));
    responses_tool_item item = {
        .fc_id = "fc_search",
        .call_id = "call_search",
        .is_custom = false,
        .output_index = 0,
    };

    buf out = {0};
    responses_append_function_call_item(&out, &calls.v[0], &item,
                                        "completed", true, &orders);
    TEST_ASSERT(strstr(out.ptr, "\"type\":\"tool_search_call\"") != NULL);
    TEST_ASSERT(strstr(out.ptr, "\"execution\":\"client\"") != NULL);
    TEST_ASSERT(strstr(out.ptr, "\"status\":\"completed\"") != NULL);
    TEST_ASSERT(strstr(out.ptr, "\"arguments\":{\"limit\":3,\"query\":\"perplexity\"}") != NULL);
    TEST_ASSERT(strstr(out.ptr, "\"type\":\"function_call\"") == NULL);

    buf_free(&out);
    free(schemas);
    tool_schema_orders_free(&orders);
    tool_calls_free(&calls);
}

static tool_calls make_swapped_bash_call(void) {
    tool_calls calls = {0};
    tool_call tc = {0};
    tc.name = xstrdup("bash");
    tc.arguments = xstrdup("{\"description\":\"list files\",\"command\":\"ls -la\",\"timeout\":10}");
    tool_calls_push(&calls, tc);
    return calls;
}

static tool_schema_orders make_bash_order(void) {
    tool_schema_orders orders = {0};
    tool_schema_orders_add_json(&orders,
        "{\"name\":\"bash\",\"input_schema\":{\"type\":\"object\",\"properties\":{"
        "\"command\":{\"type\":\"string\"},"
        "\"description\":{\"type\":\"string\"}}}}");
    return orders;
}

static char *read_socket_text(int fd) {
    buf b = {0};
    char tmp[1024];
    ssize_t n;
    while ((n = read(fd, tmp, sizeof(tmp))) > 0) {
        buf_append(&b, tmp, (size_t)n);
    }
    return buf_take(&b);
}

static void test_context_length_error_uses_protocol_standard_shape(void) {
    request r;
    request_init(&r, REQ_CHAT, 128);
    r.api = API_OPENAI;
    r.prompt.len = 16;
    TEST_ASSERT(request_exceeds_context(&r, 16));
    TEST_ASSERT(!request_exceeds_context(&r, 17));

    int sv[2];
    TEST_ASSERT(socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == 0);
    if (sv[0] >= 0 && sv[1] >= 0) {
        TEST_ASSERT(http_error_context_length_exceeded(sv[0], false, &r, 16, 16));
        shutdown(sv[0], SHUT_WR);
        char *out = read_socket_text(sv[1]);
        TEST_ASSERT(strstr(out, "HTTP/1.1 400") != NULL);
        TEST_ASSERT(strstr(out, "\"type\":\"invalid_request_error\"") != NULL);
        TEST_ASSERT(strstr(out, "\"code\":\"context_length_exceeded\"") != NULL);
```

<｜begin▁of▁sentence｜>You are DeepSeek V4 Flash running locally. Answer accurately, preserve technical details, and use tools only when the prompt asks for tool use.<｜User｜>Trova bug sottili e spiega quali invarianti dell'inferenza possono rompersi.

File: ds4_server.c

```c
ols_p = tools_json;
    char *schemas = NULL;
    tool_schema_orders orders = {0};
    TEST_ASSERT(parse_tools_value(&tools_p, &schemas, &orders));
    responses_tool_item item = {
        .fc_id = "fc_search",
        .call_id = "call_search",
        .is_custom = false,
        .output_index = 0,
    };

    buf out = {0};
    responses_append_function_call_item(&out, &calls.v[0], &item,
                                        "completed", true, &orders);
    TEST_ASSERT(strstr(out.ptr, "\"type\":\"tool_search_call\"") != NULL);
    TEST_ASSERT(strstr(out.ptr, "\"execution\":\"client\"") != NULL);
    TEST_ASSERT(strstr(out.ptr, "\"status\":\"completed\"") != NULL);
    TEST_ASSERT(strstr(out.ptr, "\"arguments\":{\"limit\":3,\"query\":\"perplexity\"}") != NULL);
    TEST_ASSERT(strstr(out.ptr, "\"type\":\"function_call\"") == NULL);

    buf_free(&out);
    free(schemas);
    tool_schema_orders_free(&orders);
    tool_calls_free(&calls);
}

static tool_calls make_swapped_bash_call(void) {
    tool_calls calls = {0};
    tool_call tc = {0};
    tc.name = xstrdup("bash");
    tc.arguments = xstrdup("{\"description\":\"list files\",\"command\":\"ls -la\",\"timeout\":10}");
    tool_calls_push(&calls, tc);
    return calls;
}

static tool_schema_orders make_bash_order(void) {
    tool_schema_orders orders = {0};
    tool_schema_orders_add_json(&orders,
        "{\"name\":\"bash\",\"input_schema\":{\"type\":\"object\",\"properties\":{"
        "\"command\":{\"type\":\"string\"},"
        "\"description\":{\"type\":\"string\"}}}}");
    return orders;
}

static char *read_socket_text(int fd) {
    buf b = {0};
    char tmp[1024];
    ssize_t n;
    while ((n = read(fd, tmp, sizeof(tmp))) > 0) {
        buf_append(&b, tmp, (size_t)n);
    }
    return buf_take(&b);
}

static void test_context_length_error_uses_protocol_standard_shape(void) {
    request r;
    request_init(&r, REQ_CHAT, 128);
    r.api = API_OPENAI;
    r.prompt.len = 16;
    TEST_ASSERT(request_exceeds_context(&r, 16));
    TEST_ASSERT(!request_exceeds_context(&r, 17));

    int sv[2];
    TEST_ASSERT(socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == 0);
    if (sv[0] >= 0 && sv[1] >= 0) {
        TEST_ASSERT(http_error_context_length_exceeded(sv[0], false, &r, 16, 16));
        shutdown(sv[0], SHUT_WR);
        char *out = read_socket_text(sv[1]);
        TEST_ASSERT(strstr(out, "HTTP/1.1 400") != NULL);
        TEST_ASSERT(strstr(out, "\"type\":\"invalid_request_error\"") != NULL);
        TEST_ASSERT(strstr(out, "\"code\":\"context_length_exceeded\"") != NULL);
```<｜Assistant｜></think>