From 2e9987c2164e50ab7c9d37c31320102c9a329fac Mon Sep 17 00:00:00 2001 From: Adil Date: Sat, 21 Nov 2026 20:53:03 +0500 Subject: [PATCH] hive/dwarfstar: its models reach for tools, held to ds4's own templates The bee hands a prompt's tools to its model in the model family's own template (DeepSeek V4 and V4.1 DSML, GLM, Qwen), ported from ds4's server into src/chat.c, reads the calls the model writes back out, and reaches them as tendrils through humd. A bloom waiting on its grasps parks so the engine serves the queue meanwhile, and lets go after DWARFSTAR_REACH_MS. make test checks the templates and readers anywhere; make conform compiles ds4's own server code beside the port and holds them byte for byte. ds4's MIT notice travels with the port in LICENSE-ds4. The bee reports the release version and release.sh bumps it. Prose leaves dwarfstar's code files for its README. --- hives/dwarfstar/LICENSE-ds4 | 23 + hives/dwarfstar/Makefile | 52 +- hives/dwarfstar/Orchfile | 15 - hives/dwarfstar/README.md | 115 +- hives/dwarfstar/build | 4 - hives/dwarfstar/install | 4 - hives/dwarfstar/src/chat.c | 1282 ++++++++++++++++++++++ hives/dwarfstar/src/chat.h | 64 ++ hives/dwarfstar/src/ds4_bridge.c | 79 +- hives/dwarfstar/src/ds4_bridge.h | 24 +- hives/dwarfstar/src/ds4_stub.c | 194 +++- hives/dwarfstar/src/gpu.c | 4 - hives/dwarfstar/src/gpu.h | 15 - hives/dwarfstar/src/main.c | 821 +++++++++++--- hives/dwarfstar/src/models.c | 4 - hives/dwarfstar/src/models.h | 17 - hives/dwarfstar/src/shaders.c | 2 - hives/dwarfstar/src/shaders.h | 9 - hives/dwarfstar/tests/conform_with_ds4.c | 230 ++++ hives/dwarfstar/tests/ds4_reference.c | 63 ++ hives/dwarfstar/tests/ds4_reference.h | 16 + hives/dwarfstar/tests/test_chat.c | 329 ++++++ release.sh | 4 +- 23 files changed, 2987 insertions(+), 383 deletions(-) create mode 100644 hives/dwarfstar/LICENSE-ds4 create mode 100644 hives/dwarfstar/src/chat.c create mode 100644 hives/dwarfstar/src/chat.h create mode 100644 hives/dwarfstar/tests/conform_with_ds4.c create mode 100644 hives/dwarfstar/tests/ds4_reference.c create mode 100644 hives/dwarfstar/tests/ds4_reference.h create mode 100644 hives/dwarfstar/tests/test_chat.c diff --git a/hives/dwarfstar/LICENSE-ds4 b/hives/dwarfstar/LICENSE-ds4 new file mode 100644 index 00000000..c5b10d43 --- /dev/null +++ b/hives/dwarfstar/LICENSE-ds4 @@ -0,0 +1,23 @@ +MIT License + +Copyright (c) 2026 The ds4.c authors +Copyright (c) 2023-2026 The ggml authors +Copyright (c) 2023 DeepSeek + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/hives/dwarfstar/Makefile b/hives/dwarfstar/Makefile index 32330736..2c9a0e52 100644 --- a/hives/dwarfstar/Makefile +++ b/hives/dwarfstar/Makefile @@ -1,21 +1,3 @@ -# dwarfstar: the DwarfStar engine (antirez/ds4), linked into a hum nurse. -# -# make out/dwarfstar-bee and the Metal kernels beside it -# make check out/dwarfstar-bee-stub: the bee with no engine, for the -# thrum side, on any machine -# make fetch the pinned ds4 source into vendor/ds4 -# make clean drop out/ -# -# ds4 is a C library, and a C program takes a C library by compiling its -# sources into its own objects: exactly the objects ds4's own Makefile -# links into every binary on macOS, with its flags, so the numerics match -# upstream. The source is pinned by commit and fetched once; point DS4_DIR -# at a checkout you already have and nothing is fetched. The engine's -# Metal backend is what is wired, so the bee builds on macOS. -# -# The thrum side is the C client in thrum-clients/c, through thrum.mk, -# which brings cJSON in through pkg-config. - DS4_REPO ?= antirez/ds4 DS4_SHA ?= 5379c1c9ac315f1540371b06a3db88491d4059ff DS4_URL ?= https://codeload.github.com/$(DS4_REPO)/tar.gz/$(DS4_SHA) @@ -24,6 +6,8 @@ DS4_DIR ?= vendor/ds4 BUILD := out BIN := $(BUILD)/dwarfstar-bee STUB := $(BUILD)/dwarfstar-bee-stub +TESTS := $(BUILD)/test-chat +CONFORM := $(BUILD)/conform-with-ds4 THRUM_BUILD := $(BUILD)/thrum-c include ../../thrum-clients/c/thrum.mk @@ -34,11 +18,13 @@ DS4_LDLIBS := -lm -pthread -framework Foundation -framework Metal DS4_CORE := ds4 ds4_image ds4_distributed ds4_tp ds4_ssd ds4_layer_pack ds4_engram DS4_SOURCES := $(DS4_CORE:%=$(DS4_DIR)/%.c) $(DS4_DIR)/ds4_metal.m DS4_OBJ := $(DS4_CORE:%=$(BUILD)/ds4/%.o) $(BUILD)/ds4/ds4_metal.o +DS4_SERVER_OBJ := $(BUILD)/ds4/ds4_help.o $(BUILD)/ds4/ds4_kvstore.o $(BUILD)/ds4/rax.o BEE_CFLAGS ?= -std=c11 -O2 -g -Wall -Wextra -Wpedantic -Wshadow BEE_HDR := $(wildcard src/*.h) $(THRUM_HDR) +BEE_OBJ := $(BUILD)/main.o $(BUILD)/chat.o $(BUILD)/models.o $(BUILD)/gpu.o -.PHONY: all check fetch clean darwin +.PHONY: all check test conform fetch clean darwin all: $(BIN) @@ -47,24 +33,44 @@ darwin: echo "dwarfstar links ds4's Metal engine, which needs macOS; make check builds the rest anywhere" >&2; \ exit 1; } -$(BIN): $(BUILD)/main.o $(BUILD)/models.o $(BUILD)/gpu.o $(BUILD)/shaders.o $(BUILD)/ds4_bridge.o $(DS4_OBJ) $(THRUM_LIB) | darwin +$(BIN): $(BEE_OBJ) $(BUILD)/shaders.o $(BUILD)/ds4_bridge.o $(DS4_OBJ) $(THRUM_LIB) | darwin $(CC) -o $@ $(filter %.o,$^) $(THRUM_LIBS) $(DS4_LDLIBS) @rm -rf $(BUILD)/metal && cp -R $(DS4_DIR)/metal $(BUILD)/metal @echo "built $@" check: $(STUB) -$(STUB): $(BUILD)/main.o $(BUILD)/models.o $(BUILD)/gpu.o $(BUILD)/stub/ds4_stub.o $(THRUM_LIB) +$(STUB): $(BEE_OBJ) $(BUILD)/stub/ds4_stub.o $(THRUM_LIB) $(CC) -o $@ $(filter %.o,$^) $(THRUM_LIBS) @echo "built $@" -$(BUILD)/main.o $(BUILD)/models.o $(BUILD)/gpu.o $(BUILD)/shaders.o: $(BUILD)/%.o: src/%.c $(BEE_HDR) +test: $(TESTS) + @$(TESTS) + +$(TESTS): $(BUILD)/tests/test_chat.o $(BUILD)/chat.o + $(CC) -o $@ $^ $(THRUM_DEPS_LIBS) + +conform: $(CONFORM) + @$(CONFORM) + +$(CONFORM): $(BUILD)/tests/conform_with_ds4.o $(BUILD)/tests/ds4_reference.o $(BUILD)/chat.o $(DS4_SERVER_OBJ) $(DS4_OBJ) | darwin + $(CC) -o $@ $(filter %.o,$^) $(THRUM_DEPS_LIBS) $(DS4_LDLIBS) + +$(BEE_OBJ) $(BUILD)/shaders.o: $(BUILD)/%.o: src/%.c $(BEE_HDR) @mkdir -p $(dir $@) $(CC) $(BEE_CFLAGS) $(THRUM_CFLAGS) -c -o $@ $< $(BUILD)/stub/ds4_stub.o: src/ds4_stub.c $(BEE_HDR) @mkdir -p $(dir $@) - $(CC) $(BEE_CFLAGS) -c -o $@ $< + $(CC) $(BEE_CFLAGS) $(THRUM_CFLAGS) -c -o $@ $< + +$(BUILD)/tests/test_chat.o $(BUILD)/tests/conform_with_ds4.o: $(BUILD)/tests/%.o: tests/%.c src/chat.h tests/ds4_reference.h + @mkdir -p $(dir $@) + $(CC) $(BEE_CFLAGS) $(THRUM_CFLAGS) -Isrc -c -o $@ $< + +$(BUILD)/tests/ds4_reference.o: tests/ds4_reference.c tests/ds4_reference.h $(DS4_DIR)/ds4_server.c | darwin + @mkdir -p $(dir $@) + $(CC) $(DS4_CFLAGS) -Wno-unused-function -I$(DS4_DIR) -I$(DS4_DIR)/metal -c -o $@ $< $(BUILD)/ds4_bridge.o: src/ds4_bridge.c $(BEE_HDR) $(DS4_DIR)/ds4.h | darwin @mkdir -p $(dir $@) diff --git a/hives/dwarfstar/Orchfile b/hives/dwarfstar/Orchfile index 1a195af1..f577309d 100644 --- a/hives/dwarfstar/Orchfile +++ b/hives/dwarfstar/Orchfile @@ -1,18 +1,3 @@ -# dwarfstar: one unit per model, and each unit is its own bee. -# -# Every unit runs the same dwarfstar-bee, pinned to one GGUF and entered -# under its own label, so each model nestles with its own key, ids and -# headroom. A unit whose model is not on this machine logs so and stays -# down. The bees share the GPU through one lock: a model loads only when -# a prompt for it arrives, and hands the GPU to another model's bee when -# idle or asked. Set an ARG in the environment of -# `hum hive ./hives/dwarfstar install` to change it, for example -# DWARFSTAR_DIR=~/projects/ds4. -# -# MEMORY is the model's resident size with room for its KV cache. -# launchd records it as a soft resident-set limit and macOS does not -# enforce it; systemd enforces it as MemoryMax. - ARG HUM_SRC= ARG HUM_HIVE_STATE= ARG DWARFSTAR_DIR= diff --git a/hives/dwarfstar/README.md b/hives/dwarfstar/README.md index 1f2740cc..231d1eef 100644 --- a/hives/dwarfstar/README.md +++ b/hives/dwarfstar/README.md @@ -22,10 +22,11 @@ and token stream are the bee's own. | statefulness | richness | wire | hides | |---|---|---|---| -| stateless | lean | `dwarfstar/core` | tendrils, sepals, pollen, and how a prompt asks its bloom to grow | +| stateless | medium | `dwarfstar/core` | sepals, pollen, and how a prompt asks its bloom to grow | Each bee is a nurse and speaks `hello`, `prompt`, `cancel`, `unfurl`, -`wilt`, `error` and `pulse`. +`wilt`, `error`, `pulse`, `tendril-reach`, `tendril-result` and +`tendril-info`. ## Install @@ -115,48 +116,102 @@ as their engine is loaded: does not already hold. - The bee is stateless: a prompt's `graft` is the turns before it (the text petals of each bloom's `content` as the user's turn, of its - `grew` as the model's), and its own text petals, else its `text`, the - turn it asks for. `systemPrompt` is the system turn. Other petals are - dropped. + `grew` as the model's, its tendrils as the model's tool calls and its + grasps as what they came back with), and its own text petals, else its + `text`, the turn it asks for. `systemPrompt` is the system turn. Other + petals are dropped. - A prompt for a model the bee does not answer to is refused with - `no_such_model`, one with no words with `empty-prompt`, and one whose - only words are in its graft with `cannot-grow-on`, since the engine - grows only from new words. A refusal is an `error` with no wilt. + `no_such_model`, and one with no words with `empty-prompt`. One with no + new words grows on when its graft ends in grasps, the model answering + what its tendrils grasped, and is otherwise refused with + `cannot-grow-on`, since the engine grows only from new words. A refusal + is an `error` with no wilt. - Blooms grow one at a time, in order. A `cancel` stops its sid's bloom, - waiting or in flight, and drops its sid's queued blooms, each wilting - `cancel`. + waiting, in flight or awaiting its grasps, and drops its sid's queued + blooms, each wilting `cancel`. - Thinking is off, and every bloom samples at `DWARFSTAR_TEMPERATURE` with ds4's own top-p and min-p, up to `DWARFSTAR_MAX_TOKENS`. A prompt's own `temperature`, `prune`, `season`, `frost`, `seed`, - `trellis`, `sepal`, `scion` and `tools` are not read. -- The answer unfurls as one `text` petal. An unfurl carries whole UTF-8 - characters, even when a token ends inside one. -- A bloom wilts with `stop`, `max_tokens` (`DWARFSTAR_MAX_TOKENS` or - the context is full), `cancel`, or `error` after an `error` tone - (`gpu_busy`, `engine_unavailable`, `generation_failed`), and its - nectar is the tokens in and out. + `trellis`, `sepal` and `scion` are not read. +- The answer unfurls as `text` petals, each closed once it is whole. An + unfurl carries whole UTF-8 characters, even when a token ends inside + one. +- A bloom wilts with `stop`, `max_tokens` (`DWARFSTAR_MAX_TOKENS` across + the whole bloom, or the context is full), `cancel`, or `error` after an + `error` tone (`gpu_busy`, `engine_unavailable`, `generation_failed`, + `tendril_unanswered`), and its nectar is the tokens in and out, summed + over its rounds. - The bee outlives humd: when humd restarts, it reconnects and nestles again with its model still loaded, dropping the blooms the old humd gave. Only a refusal, or its link failing, ends the bee, and its unit restarts it. +## Tendrils + +A prompt's `tools` are handed to the model in its own family's template, +the way ds4's server renders them, so the model can reach for them: + +| family | how it is told its tools | how it reaches | +|---|---|---| +| DeepSeek V4 | a `## Tools` section after the system words, one JSON schema a line | a DSML `<|DSML|tool_calls>` block | +| DeepSeek V4.1 | the same preamble in a `<|System|>` turn | a DSML `<|DSML| calls>` block | +| GLM | a system turn listing `` | `` with `` and `` | +| Qwen | the system turn's `` | `` with `` and `` | + +The bee asks the engine which family a model is when it loads. A bloom +with tools, or with tendrils or grasps in its graft, is rendered whole in +that template and tokenized as it stands; a bloom with neither is +encoded as it always was. + +A bloom with tendrils grows in rounds: + +- The model's words unfurl as they grow, held back only where a call + might be starting, and never the whitespace before one. +- When the model stops on a call, the bee reads it out of what grew, + mints a `callId` for each, unfurls each as a closed `tendril` petal + with its arguments as `sap`, and reaches with `tendril-reach`. humd + routes each reach: `bash` to the builder where the bloom builds, an + attendant's tool to that attendant, the forager's own tool back to the + forager. +- While its reaches are out, the bloom is parked and the engine grows the + next bloom in the queue, so a client that takes a tool call away and + never answers holds nothing up. +- Each `tendril-result` is told to the forager as `tendril-info`. Once + every reach has come back, the bloom goes to the front of the queue and + grows its next round from the whole conversation, its own calls + rendered exactly as it sampled them so the KV cache still holds them. +- A bloom whose reaches have not all come back within + `DWARFSTAR_REACH_MS` breaks off with `tendril_unanswered`. A new prompt + on the sid lets a parked bloom go. + +`allowedTools` narrows the tools the model is told of, and a `tendrils` +whose `reach` is `none` tells it of none. A model that writes an argument +without saying whether it is a string, as GLM and Qwen do, has it read as +JSON unless the tool's schema says the argument is a string, or it is +not JSON. + ## Build ```sh make # fetch the pinned ds4 source if needed, then build out/dwarfstar-bee make DS4_DIR=~/src/ds4 # build against a ds4 checkout you already have make check # out/dwarfstar-bee-stub: the bee with no engine, on any machine +make test # the chat templates and the tool-call readers, on any machine +make conform # the same, held to ds4's own server code at the pinned commit make fetch # just fetch the pinned ds4 source into vendor/ds4 make clean # drop out/ ``` `install` runs `build`, which runs `make`. The engine objects are exactly the ones ds4's own Makefile links on macOS, compiled with its -flags, so the numerics match upstream. The `.metal` kernels are copied -beside the bee, which points ds4 at them, so the bee runs from any -directory. The stub runs the thrum side and the GPU handoff with no -model: several stub bees on one lock trade the GPU the way the real ones -do. +flags, so the numerics match upstream. ds4 compiles its Metal kernels at +runtime from `.metal` files; they are copied beside the bee, and the bee +points every one of ds4's `DS4_METAL_*_SOURCE` overrides at its copy by +absolute path, so it runs from any directory, as it must under orchd. +The stub runs the thrum side and the GPU handoff with no model: several +stub bees on one lock trade the GPU the way the real ones do. Offered +tools, it reaches for the one its prompt names, and told what came back, +it says so, so the tendril rounds run with no model too. ## Environment @@ -173,6 +228,7 @@ do. | `DWARFSTAR_SSD_STREAMING` | stream experts from SSD, unless `0` | off | | `DWARFSTAR_IDLE_MS` | give the GPU back after this long idle | `300000` | | `DWARFSTAR_WAIT_MS` | how long a bloom waits for the GPU | `300000` | +| `DWARFSTAR_REACH_MS` | how long a parked bloom waits for its reaches to come back | `1800000` | | `DWARFSTAR_GPU_LOCK` | the hive-wide GPU lock | none: the bee exits without it | | `DWARFSTAR_METAL_DIR` | the `.metal` kernels | `metal/` beside the bee | | `DS4_LOCK_FILE` | ds4's own lock | `/tmp/ds4.lock` | @@ -193,8 +249,11 @@ under the hive's units. of possession. - **Two models resident at once.** The handoff assumes one model fits; a machine that holds two would need the lock to count, not exclude. -- **Vision, tools and thinking.** The engine has them; the bee does not - use them. +- **Vision and thinking.** The engine has them; the bee does not use + them. +- **Forcing a reach.** A `tendrils` whose `reach` is `required` or names + a tool, and its `parallel`, are not read: the model reaches as it + chooses. - **CUDA and ROCm.** ds4 builds for both; this Makefile wires Metal only. ## Licence @@ -203,3 +262,11 @@ The engine is MIT, under the notices in its `LICENSE`: the ds4.c authors, DeepSeek, and the ggml authors, for the quantisation formats and kernels it adapts from llama.cpp and GGML. The `LICENSE` travels with the fetched source. + +`src/chat.c` is ported from ds4's `ds4_server.c` at the pinned commit: +its chat templates, the tool preambles, and the readers of the calls a +model writes. It lives in this repository, not in the fetched source, so +ds4's notice is kept beside it in [`LICENSE-ds4`](LICENSE-ds4), and it is +MIT under that notice. `make conform` holds the port to ds4: it compiles +ds4's own server code beside it and checks that both render the same +prompts and read the same calls. diff --git a/hives/dwarfstar/build b/hives/dwarfstar/build index a308465c..36dd87b1 100755 --- a/hives/dwarfstar/build +++ b/hives/dwarfstar/build @@ -1,8 +1,4 @@ #!/usr/bin/env bash -# Build this hive's bee: fetch the pinned ds4 source if it is not here, -# compile the engine into the bee, and put the Metal kernels beside it. -# Nothing is installed into the system's PATH: the bee is built here and -# runs here. DS4_DIR points at a ds4 checkout to build against instead. set -euo pipefail here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" diff --git a/hives/dwarfstar/install b/hives/dwarfstar/install index 1f8845bd..860c0497 100755 --- a/hives/dwarfstar/install +++ b/hives/dwarfstar/install @@ -1,8 +1,4 @@ #!/usr/bin/env bash -# Install this hive on a humd: build its bee and keep one unit per model -# running under orchd. Each unit's bee enters itself under the hive, as -# the unit's name, when it starts; a unit whose model is not on this -# machine stays down. set -euo pipefail here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" diff --git a/hives/dwarfstar/src/chat.c b/hives/dwarfstar/src/chat.c new file mode 100644 index 00000000..0dbde30d --- /dev/null +++ b/hives/dwarfstar/src/chat.c @@ -0,0 +1,1282 @@ +#define _POSIX_C_SOURCE 200809L + +#include "chat.h" + +#include +#include +#include +#include + +#define DEEPSEEK_BEGIN "<|begin▁of▁sentence|>" +#define DEEPSEEK_END_OF_TURN "<|end▁of▁sentence|>" +#define DEEPSEEK_SYSTEM "<|System|>" +#define DEEPSEEK_USER "<|User|>" +#define DEEPSEEK_ASSISTANT "<|Assistant|>" +#define THINKING_SKIPPED "" + +#define DSML_V4_CALLS "<|DSML|tool_calls>" +#define DSML_V4_INVOKE "<|DSML|invoke" +#define DSML_V4_PARAMETER "<|DSML|parameter" +#define DSML_V4_PARAMETER_END "" +#define DSML_V41_CALLS "<|DSML| calls>" +#define DSML_V41_INVOKE "<|DSML| invoke" +#define DSML_V41_INVOKE_END "" +#define DSML_V41_CALLS_END "" +#define DSML_V41_PARAMETER "<|DSML| parameter" +#define DSML_V41_PARAMETER_END "" + +typedef struct { + const char *calls; + const char *calls_end; + const char *invoke; + const char *invoke_end; + const char *parameter; + const char *parameter_end; +} dsml_spelling; + +static const dsml_spelling DSML_V4 = { + DSML_V4_CALLS, "", DSML_V4_INVOKE, "", + DSML_V4_PARAMETER, DSML_V4_PARAMETER_END, +}; +static const dsml_spelling DSML_V4_UNBARRED = { + "", "", "", + "", +}; +static const dsml_spelling DSML_PLAIN_XML = { + "", "", "", "", +}; +static const dsml_spelling DSML_V41 = { + DSML_V41_CALLS, DSML_V41_CALLS_END, DSML_V41_INVOKE, DSML_V41_INVOKE_END, + DSML_V41_PARAMETER, DSML_V41_PARAMETER_END, +}; + +static const char *const TENDRIL_OPENINGS[] = { + DSML_V41_CALLS, DSML_V4_CALLS, "", "", "", +}; + +static const char *const ARGUMENT_WRAPPERS[][2] = { + {DSML_V41_PARAMETER, DSML_V41_PARAMETER_END}, + {DSML_V4_PARAMETER, DSML_V4_PARAMETER_END}, + {""}, + {""}, + {"", ""}, + {"", ""}, +}; + +#define COUNT_OF(array) (sizeof(array) / sizeof((array)[0])) + +typedef struct { + char *bytes; + size_t len; + size_t room; + bool out_of_memory; +} page; + +static void page_add_n(page *p, const char *s, size_t n) { + if (p->out_of_memory || n == 0) return; + if (p->len + n + 1 > p->room) { + size_t room = p->room ? p->room : 1024; + char *grown; + while (room < p->len + n + 1) room *= 2; + grown = (char *)realloc(p->bytes, room); + if (!grown) { + p->out_of_memory = true; + return; + } + p->bytes = grown; + p->room = room; + } + memcpy(p->bytes + p->len, s, n); + p->len += n; + p->bytes[p->len] = '\0'; +} + +static void page_add(page *p, const char *s) { + if (s) page_add_n(p, s, strlen(s)); +} + +static void page_add_char(page *p, char c) { + page_add_n(p, &c, 1); +} + +static char *page_taken(page *p) { + if (p->out_of_memory) { + free(p->bytes); + return NULL; + } + return p->bytes ? p->bytes : strdup(""); +} + +static char *copy_of(const char *s) { + return s ? strdup(s) : NULL; +} + +static char *copy_of_n(const char *s, size_t n) { + char *copy = (char *)malloc(n + 1); + if (!copy) return NULL; + memcpy(copy, s, n); + copy[n] = '\0'; + return copy; +} + +static bool starts_with(const char *s, const char *prefix) { + return strncmp(s, prefix, strlen(prefix)) == 0; +} + +static const char *past_space(const char *s) { + while (*s && isspace((unsigned char)*s)) s++; + return s; +} + +static size_t without_trailing_space(const char *s, size_t n) { + while (n > 0 && isspace((unsigned char)s[n - 1])) n--; + return n; +} + +static char *trimmed_copy(const char *from, const char *to) { + while (from < to && isspace((unsigned char)*from)) from++; + while (to > from && isspace((unsigned char)to[-1])) to--; + return copy_of_n(from, (size_t)(to - from)); +} + +static void page_add_trimmed(page *p, const char *s) { + const char *from = s ? s : ""; + const char *to = from + strlen(from); + while (from < to && isspace((unsigned char)*from)) from++; + while (to > from && isspace((unsigned char)to[-1])) to--; + page_add_n(p, from, (size_t)(to - from)); +} + +static bool starts_thinking(const char *words) { + return words && (starts_with(words, "") || starts_with(words, "")); +} + +static bool is_escaped_closing(const char *s, const char *closing) { + if (*s != '&') return false; + s++; + while (starts_with(s, "amp;")) s += 4; + return starts_with(s, "lt;") && starts_with(s + 3, closing + 1); +} + +static bool would_close_early(const char *s, const char *closing) { + return starts_with(s, closing) || is_escaped_closing(s, closing); +} + +static void page_add_guarded(page *p, const char *body, const char *closing) { + const char *s; + for (s = body ? body : ""; *s; s++) { + if (would_close_early(s, closing)) { + page_add(p, *s == '<' ? "<" : "&"); + } else { + page_add_char(p, *s); + } + } +} + +static void unguard(char *s, const char *closing) { + char *out = s; + while (*s) { + if (!is_escaped_closing(s, closing)) { + *out++ = *s++; + } else if (starts_with(s, "&")) { + *out++ = '&'; + s += 5; + } else { + *out++ = '<'; + s += 4; + } + } + *out = '\0'; +} + +static void page_add_attribute(page *p, const char *value) { + const char *s; + for (s = value ? value : ""; *s; s++) { + switch (*s) { + case '&': page_add(p, "&"); break; + case '<': page_add(p, "<"); break; + case '>': page_add(p, ">"); break; + case '"': page_add(p, """); break; + default: page_add_char(p, *s); + } + } +} + +static char *attribute_unescaped(const char *from, const char *to) { + static const char *const entities[][2] = { + {"&", "&"}, {"<", "<"}, {">", ">"}, {""", "\""}, {"'", "'"}, + }; + page p = {0}; + while (from < to) { + size_t i; + bool replaced = false; + for (i = 0; i < COUNT_OF(entities) && *from == '&'; i++) { + size_t n = strlen(entities[i][0]); + if ((size_t)(to - from) >= n && strncmp(from, entities[i][0], n) == 0) { + page_add(&p, entities[i][1]); + from += n; + replaced = true; + break; + } + } + if (!replaced) page_add_char(&p, *from++); + } + return page_taken(&p); +} + +static char *attribute_in(const char *tag, const char *tag_end, const char *name) { + char wanted[32]; + const char *at; + const char *value; + const char *value_end; + + snprintf(wanted, sizeof wanted, "%s=\"", name); + for (at = tag; at < tag_end; at++) { + if (strncmp(at, wanted, strlen(wanted)) == 0) break; + } + if (at >= tag_end) return NULL; + value = at + strlen(wanted); + value_end = memchr(value, '"', (size_t)(tag_end - value)); + return value_end ? attribute_unescaped(value, value_end) : NULL; +} + +static char *json_text_of(const cJSON *item) { + char *printed = cJSON_PrintUnformatted(item); + char *copy = copy_of(printed); + cJSON_free(printed); + return copy; +} + +static void page_add_json(page *p, const cJSON *item) { + char *json = json_text_of(item); + page_add(p, json); + free(json); +} + +static void page_add_json_string(page *p, const char *s) { + cJSON *string = cJSON_CreateString(s ? s : ""); + page_add_json(p, string); + cJSON_Delete(string); +} + +static cJSON *whole_json_value(const char *text) { + const char *end = NULL; + cJSON *parsed = cJSON_ParseWithOpts(text, &end, true); + return parsed; +} + +static const cJSON *member(const cJSON *object, const char *key) { + return cJSON_GetObjectItemCaseSensitive(object, key); +} + +static const char *string_member(const cJSON *object, const char *key) { + const cJSON *value = member(object, key); + return cJSON_IsString(value) ? value->valuestring : NULL; +} + +static const cJSON *schema_of_tool(const cJSON *tool) { + const cJSON *function = member(tool, "function"); + if (cJSON_IsObject(function)) return member(function, "parameters"); + return cJSON_IsObject(member(tool, "inputSchema")) ? member(tool, "inputSchema") + : member(tool, "parameters"); +} + +static const char *name_of_tool(const cJSON *tool) { + const cJSON *function = member(tool, "function"); + return cJSON_IsObject(function) ? string_member(function, "name") : string_member(tool, "name"); +} + +static cJSON *function_of_tool(const cJSON *tool) { + const cJSON *function = member(tool, "function"); + const cJSON *schema = schema_of_tool(tool); + const char *description = string_member(tool, "description"); + cJSON *shaped; + + if (cJSON_IsObject(function)) return cJSON_Duplicate(function, true); + if (!name_of_tool(tool)) return NULL; + shaped = cJSON_CreateObject(); + if (!shaped) return NULL; + cJSON_AddStringToObject(shaped, "name", name_of_tool(tool)); + if (description) cJSON_AddStringToObject(shaped, "description", description); + if (cJSON_IsObject(schema)) { + cJSON_AddItemToObject(shaped, "parameters", cJSON_Duplicate(schema, true)); + } else { + cJSON *empty = cJSON_AddObjectToObject(shaped, "parameters"); + cJSON_AddStringToObject(empty, "type", "object"); + cJSON_AddObjectToObject(empty, "properties"); + } + return shaped; +} + +static bool offers_tools(const cJSON *tools) { + const cJSON *tool; + cJSON_ArrayForEach(tool, tools) { + if (name_of_tool(tool)) return true; + } + return false; +} + +static void page_add_functions_one_per_line(page *p, const cJSON *tools) { + const cJSON *tool; + bool first = true; + cJSON_ArrayForEach(tool, tools) { + cJSON *function = function_of_tool(tool); + if (!function) continue; + if (!first) page_add_char(p, '\n'); + page_add_json(p, function); + cJSON_Delete(function); + first = false; + } +} + +static void page_add_function_spaced(page *p, const cJSON *function) { + const cJSON *field; + bool first = true; + page_add_char(p, '{'); + cJSON_ArrayForEach(field, function) { + if (!first) page_add(p, ", "); + page_add_json_string(p, field->string); + page_add(p, ": "); + page_add_json(p, field); + first = false; + } + page_add_char(p, '}'); +} + +static void page_add_deepseek_tools(page *p, const cJSON *tools, bool v41) { + if (v41) { + page_add(p, + "## Tools\n\n" + "You can invoke tools using this format:\n\n" + DSML_V41_CALLS "\n" + DSML_V41_INVOKE " name=\"$TOOL_NAME\">\n" + DSML_V41_PARAMETER " name=\"$PARAMETER_NAME\" string=\"true|false\">$PARAMETER_VALUE" DSML_V41_PARAMETER_END "\n" + DSML_V41_INVOKE_END "\n" DSML_V41_CALLS_END "\n\n" + "String values use string=\"true\"; all other values use JSON and string=\"false\". " + "Inside string values only, escape a literal as </|DSML| parameter>. " + "To write that escaped spelling literally, use &lt;/|DSML| parameter>. Other HTML entities are unchanged.\n\n" + "Finish reasoning with before tool calls or a final response.\n\n" + "### Available Tool Schemas\n\n"); + } else { + page_add(p, + "## Tools\n\n" + "You have access to a set of tools to help answer the user question. " + "You can invoke tools by writing a \"<|DSML|tool_calls>\" block like the following:\n\n" + "<|DSML|tool_calls>\n" + "<|DSML|invoke name=\"$TOOL_NAME\">\n" + "<|DSML|parameter name=\"$PARAMETER_NAME\" string=\"true|false\">$PARAMETER_VALUE\n" + "...\n" + "\n" + "<|DSML|invoke name=\"$TOOL_NAME2\">\n" + "...\n" + "\n" + "\n\n" + "String parameters should be specified as raw text and set `string=\"true\"`. " + "Preserve characters such as `>`, `&`, and `&&` exactly; never replace normal string characters with XML or HTML entity escapes. " + "Only if a string value itself contains the exact closing parameter tag ``, write that tag as `</|DSML|parameter>` inside the value. " + "For all other types (numbers, booleans, arrays, objects), pass the value in JSON format and set `string=\"false\"`.\n\n" + "When thinking mode is enabled, finish reasoning with before any tool calls or final response.\n\n" + "Otherwise, output directly after with tool calls or final response.\n\n" + "### Available Tool Schemas\n\n"); + } + page_add_functions_one_per_line(p, tools); + page_add(p, "\n\nYou MUST strictly follow the above defined tool name and parameter schemas to invoke tool calls. " + "Use the exact parameter names from the schemas."); +} + +static void page_add_glm_tools(page *p, const cJSON *tools) { + const cJSON *tool; + page_add(p, + "\n# Tools\n\n" + "You may call one or more functions to assist with the user query.\n\n" + "You are provided with function signatures within XML tags:\n" + "\n\n"); + cJSON_ArrayForEach(tool, tools) { + cJSON *function = function_of_tool(tool); + if (!function) continue; + page_add_function_spaced(p, function); + page_add(p, "\n\n\n"); + cJSON_Delete(function); + } + page_add(p, + "\n\n" + "For each function call, output the function name and arguments within the following XML format:\n" + "{function-name}" + "{arg-key-1}" + "{arg-value-1}" + "{arg-key-2}" + "{arg-value-2}" + "..."); +} + +static void page_add_qwen_tools(page *p, const cJSON *tools) { + const cJSON *tool; + page_add(p, "# Tools\n\nYou have access to the following functions:\n\n"); + cJSON_ArrayForEach(tool, tools) { + cJSON *function = function_of_tool(tool); + if (!function) continue; + page_add(p, "\n{\"type\": \"function\", \"function\": "); + page_add_function_spaced(p, function); + page_add_char(p, '}'); + cJSON_Delete(function); + } + page_add(p, + "\n\n\n" + "If you choose to call a function ONLY reply in the following format with NO suffix:\n\n" + "\n\n\nvalue_1\n\n" + "\nThis is the value for the second parameter\nthat can span\nmultiple lines\n" + "\n\n\n\n\nReminder:\n" + "- Function calls MUST follow the specified format: an inner block must be nested " + "within XML tags\n" + "- Required parameters MUST be specified\n" + "- You may provide optional reasoning for your function call in natural language BEFORE the function call, " + "but NOT after\n" + "- If there is no function call available, answer the question like normal with your current knowledge and " + "do not tell the user about function calls\n"); +} + +static void page_add_json_guarded(page *p, const cJSON *value, const char *closing) { + char *json = json_text_of(value); + const char *s; + for (s = json ? json : ""; *s; s++) { + if (starts_with(s, closing)) { + page_add(p, "\\u003c"); + } else { + page_add_char(p, *s); + } + } + free(json); +} + +static void page_add_dsml_argument(page *p, const cJSON *argument, const dsml_spelling *dsml) { + bool is_string = cJSON_IsString(argument); + page_add(p, dsml->parameter); + page_add(p, " name=\""); + page_add_attribute(p, argument->string); + page_add(p, is_string ? "\" string=\"true\">" : "\" string=\"false\">"); + if (is_string) { + page_add_guarded(p, argument->valuestring, dsml->parameter_end); + } else { + page_add_json_guarded(p, argument, dsml->parameter_end); + } + page_add(p, dsml->parameter_end); + page_add_char(p, '\n'); +} + +static void page_add_dsml_tendrils(page *p, const turn *t, const dsml_spelling *dsml) { + size_t i; + if (t->tendril_count == 0) return; + if (t->tendrils_as_sampled) { + page_add(p, t->tendrils_as_sampled); + return; + } + page_add(p, "\n\n"); + page_add(p, dsml->calls); + page_add_char(p, '\n'); + for (i = 0; i < t->tendril_count; i++) { + const tendril *reached = &t->tendrils[i]; + cJSON *args = cJSON_Parse(reached->args_json ? reached->args_json : ""); + page_add(p, dsml->invoke); + page_add(p, " name=\""); + page_add_attribute(p, reached->name); + page_add(p, "\">\n"); + if (cJSON_IsObject(args)) { + const cJSON *argument; + cJSON_ArrayForEach(argument, args) page_add_dsml_argument(p, argument, dsml); + } else { + page_add(p, dsml->parameter); + page_add(p, " name=\"arguments\" string=\"true\">"); + page_add_guarded(p, reached->args_json, dsml->parameter_end); + page_add(p, dsml->parameter_end); + page_add_char(p, '\n'); + } + cJSON_Delete(args); + page_add(p, dsml->invoke_end); + page_add_char(p, '\n'); + } + page_add(p, dsml->calls_end); +} + +static char *argument_as_written(const cJSON *argument) { + return cJSON_IsString(argument) ? copy_of(argument->valuestring) : json_text_of(argument); +} + +static void page_add_glm_tendrils(page *p, const turn *t) { + size_t i; + if (t->tendril_count == 0) return; + if (t->tendrils_as_sampled) { + page_add(p, t->tendrils_as_sampled); + return; + } + for (i = 0; i < t->tendril_count; i++) { + const tendril *reached = &t->tendrils[i]; + cJSON *args = cJSON_Parse(reached->args_json ? reached->args_json : ""); + page_add(p, ""); + page_add(p, reached->name); + if (cJSON_IsObject(args)) { + const cJSON *argument; + cJSON_ArrayForEach(argument, args) { + char *written = argument_as_written(argument); + page_add(p, ""); + page_add_guarded(p, argument->string, ""); + page_add(p, ""); + page_add_guarded(p, written, ""); + page_add(p, ""); + free(written); + } + } else { + page_add(p, "arguments"); + page_add_guarded(p, reached->args_json, ""); + page_add(p, ""); + } + cJSON_Delete(args); + page_add(p, ""); + } +} + +static void page_add_qwen_tendrils(page *p, const turn *t, bool after_words) { + size_t i; + if (t->tendril_count == 0) return; + if (t->tendrils_as_sampled) { + page_add(p, t->tendrils_as_sampled); + return; + } + for (i = 0; i < t->tendril_count; i++) { + const tendril *reached = &t->tendrils[i]; + cJSON *args = cJSON_Parse(reached->args_json ? reached->args_json : ""); + if (i > 0) { + page_add(p, "\n\n\n\nname); + page_add(p, ">\n"); + if (cJSON_IsObject(args)) { + const cJSON *argument; + cJSON_ArrayForEach(argument, args) { + char *written = argument_as_written(argument); + page_add(p, "string, ">"); + page_add(p, ">\n"); + page_add_guarded(p, written, ""); + page_add(p, "\n\n"); + free(written); + } + } else if (reached->args_json && reached->args_json[0]) { + page_add(p, "\n"); + page_add_guarded(p, reached->args_json, ""); + page_add(p, "\n\n"); + } + cJSON_Delete(args); + page_add(p, "\n"); + } +} + +static void page_add_tool_result(page *p, const turn *t) { + page_add(p, ""); + page_add_guarded(p, t->words, ""); + page_add(p, ""); +} + +static char *deepseek_prompt(const char *system, const cJSON *tools, const chat *c) { + page p = {0}; + bool model_turn_due = false; + bool answers_open = false; + size_t i; + + page_add(&p, DEEPSEEK_BEGIN); + page_add(&p, system); + if (offers_tools(tools)) { + if (system) page_add(&p, "\n\n"); + page_add_deepseek_tools(&p, tools, false); + } + for (i = 0; i < c->count; i++) { + const turn *t = &c->turns[i]; + switch (t->by) { + case USER_SAYS: + page_add(&p, DEEPSEEK_USER); + page_add(&p, t->words); + model_turn_due = true; + answers_open = false; + break; + case TOOL_ANSWERS: + if (!answers_open) page_add(&p, DEEPSEEK_USER); + page_add_tool_result(&p, t); + model_turn_due = true; + answers_open = true; + break; + case MODEL_SAYS: + if (model_turn_due) page_add(&p, DEEPSEEK_ASSISTANT THINKING_SKIPPED); + page_add(&p, t->words); + page_add_dsml_tendrils(&p, t, &DSML_V4); + page_add(&p, DEEPSEEK_END_OF_TURN); + model_turn_due = false; + answers_open = false; + break; + } + } + if (model_turn_due) page_add(&p, DEEPSEEK_ASSISTANT THINKING_SKIPPED); + return page_taken(&p); +} + +static char *deepseek41_prompt(const char *system, const cJSON *tools, const chat *c) { + page p = {0}; + bool model_turn_due = false; + bool user_open = false; + size_t i; + + page_add(&p, DEEPSEEK_BEGIN); + if (offers_tools(tools)) { + page_add(&p, DEEPSEEK_SYSTEM); + page_add_deepseek_tools(&p, tools, true); + if (system) page_add(&p, "\n\n"); + } else if (system) { + page_add(&p, DEEPSEEK_SYSTEM); + } + page_add(&p, system); + for (i = 0; i < c->count; i++) { + const turn *t = &c->turns[i]; + if (t->by == MODEL_SAYS) { + if (model_turn_due) page_add(&p, DEEPSEEK_ASSISTANT THINKING_SKIPPED); + page_add(&p, t->words); + page_add_dsml_tendrils(&p, t, &DSML_V41); + page_add(&p, DEEPSEEK_END_OF_TURN); + model_turn_due = false; + user_open = false; + continue; + } + page_add(&p, user_open ? "\n\n" : DEEPSEEK_USER); + if (t->by == TOOL_ANSWERS) { + page_add_tool_result(&p, t); + } else { + page_add(&p, t->words); + } + model_turn_due = true; + user_open = true; + } + if (model_turn_due) page_add(&p, DEEPSEEK_ASSISTANT THINKING_SKIPPED); + return page_taken(&p); +} + +static char *glm_prompt(const char *system, const cJSON *tools, const chat *c) { + page p = {0}; + bool model_turn_due = false; + bool observing = false; + size_t i; + + page_add(&p, "[gMASK]"); + if (offers_tools(tools)) { + page_add(&p, "<|system|>"); + page_add_glm_tools(&p, tools); + } + if (system) { + page_add(&p, "<|system|>"); + page_add(&p, system); + } + for (i = 0; i < c->count; i++) { + const turn *t = &c->turns[i]; + switch (t->by) { + case TOOL_ANSWERS: + if (!observing) page_add(&p, "<|observation|>"); + page_add(&p, ""); + page_add_guarded(&p, t->words, ""); + page_add(&p, ""); + observing = true; + model_turn_due = true; + break; + case USER_SAYS: + page_add(&p, "<|user|>"); + page_add(&p, t->words); + observing = false; + model_turn_due = true; + break; + case MODEL_SAYS: + page_add(&p, "<|assistant|>"); + if (!starts_thinking(t->words)) page_add(&p, ""); + page_add_trimmed(&p, t->words); + page_add_glm_tendrils(&p, t); + observing = false; + model_turn_due = false; + break; + } + } + if (model_turn_due) page_add(&p, "<|assistant|>"); + return page_taken(&p); +} + +static void page_add_qwen_model_turn(page *p, const turn *t) { + const char *words = t->words ? t->words : ""; + page body = {0}; + bool has_words; + + page_add_trimmed(&body, words); + has_words = body.len > 0; + if (has_words && t->tendril_count == 0) { + const char *end = words + strlen(words); + while (end > words && isspace((unsigned char)end[-1])) end--; + page_add(&body, end); + } + page_add(p, "<|im_start|>assistant\n"); + if (!starts_thinking(words)) page_add(p, "\n\n\n\n"); + page_add(p, body.bytes); + free(body.bytes); + page_add_qwen_tendrils(p, t, has_words); + page_add(p, "<|im_end|>\n"); +} + +static char *qwen_prompt(const char *system, const cJSON *tools, const chat *c) { + page p = {0}; + page trimmed_system = {0}; + bool model_turn_due = false; + bool answers_open = false; + size_t i; + + page_add_trimmed(&trimmed_system, system); + if (offers_tools(tools) || trimmed_system.len > 0) { + page_add(&p, "<|im_start|>system\n"); + if (offers_tools(tools)) { + page_add_qwen_tools(&p, tools); + if (trimmed_system.len > 0) page_add(&p, "\n\n"); + } + page_add(&p, trimmed_system.bytes); + page_add(&p, "<|im_end|>\n"); + } + free(trimmed_system.bytes); + for (i = 0; i < c->count; i++) { + const turn *t = &c->turns[i]; + if (t->by == TOOL_ANSWERS) { + if (!answers_open) page_add(&p, "<|im_start|>user"); + page_add(&p, "\n\n"); + page_add_guarded(&p, t->words, ""); + page_add(&p, "\n"); + answers_open = true; + model_turn_due = true; + continue; + } + if (answers_open) page_add(&p, "<|im_end|>\n"); + answers_open = false; + if (t->by == USER_SAYS) { + page_add(&p, "<|im_start|>user\n"); + page_add_trimmed(&p, t->words); + page_add(&p, "<|im_end|>\n"); + model_turn_due = true; + } else { + page_add_qwen_model_turn(&p, t); + model_turn_due = false; + } + } + if (answers_open) page_add(&p, "<|im_end|>\n"); + if (model_turn_due) page_add(&p, "<|im_start|>assistant\n\n\n\n\n"); + return page_taken(&p); +} + +char *chat_as_prompt(dialect d, const char *system, const cJSON *tools, const chat *c) { + if (system && !system[0]) system = NULL; + switch (d) { + case DIALECT_DEEPSEEK41: return deepseek41_prompt(system, tools, c); + case DIALECT_GLM: return glm_prompt(system, tools, c); + case DIALECT_QWEN: return qwen_prompt(system, tools, c); + case DIALECT_DEEPSEEK: break; + } + return deepseek_prompt(system, tools, c); +} + +static size_t longest_opening_begun_at_end(const char *grown, size_t len) { + size_t longest = 0; + size_t i; + for (i = 0; i < COUNT_OF(TENDRIL_OPENINGS); i++) { + size_t k = strlen(TENDRIL_OPENINGS[i]) - 1; + if (k > len) k = len; + for (; k > longest; k--) { + if (memcmp(grown + len - k, TENDRIL_OPENINGS[i], k) == 0) { + longest = k; + break; + } + } + } + return longest; +} + +size_t words_safe_to_show(const char *grown, bool *tendrils_began) { + size_t len = strlen(grown); + const char *earliest = NULL; + size_t i; + for (i = 0; i < COUNT_OF(TENDRIL_OPENINGS); i++) { + const char *at = strstr(grown, TENDRIL_OPENINGS[i]); + if (at && (!earliest || at < earliest)) earliest = at; + } + if (earliest) { + *tendrils_began = true; + return without_trailing_space(grown, (size_t)(earliest - grown)); + } + return without_trailing_space(grown, len - longest_opening_begun_at_end(grown, len)); +} + +static bool reaching_add(reaching *r, char *name, cJSON *args) { + tendril *grown = (tendril *)realloc(r->tendrils, (r->count + 1) * sizeof *grown); + char *args_json = json_text_of(args); + if (!grown || !args_json) { + if (grown) r->tendrils = grown; + free(args_json); + return false; + } + r->tendrils = grown; + r->tendrils[r->count].call_id = NULL; + r->tendrils[r->count].name = name; + r->tendrils[r->count].args_json = args_json; + r->count++; + return true; +} + +static void add_argument_as_json_or_words(cJSON *args, const char *key, const char *value) { + cJSON *parsed = whole_json_value(value); + if (parsed) { + cJSON_AddItemToObject(args, key, parsed); + } else { + cJSON_AddStringToObject(args, key, value); + } +} + +static bool schema_says_string(const cJSON *tools, const char *tool_name, const char *key) { + const cJSON *tool; + cJSON_ArrayForEach(tool, tools) { + const char *name = name_of_tool(tool); + const cJSON *properties; + if (!name || strcmp(name, tool_name) != 0) continue; + properties = member(schema_of_tool(tool), "properties"); + return cJSON_IsObject(properties) && string_member(member(properties, key), "type") && + strcmp(string_member(member(properties, key), "type"), "string") == 0; + } + return false; +} + +static void add_argument_typed(cJSON *args, const cJSON *tools, const char *tool_name, + const char *key, char *value, const char *closing_if_words) { + cJSON *parsed = schema_says_string(tools, tool_name, key) ? NULL : whole_json_value(value); + if (parsed && !cJSON_IsString(parsed)) { + cJSON_AddItemToObject(args, key, parsed); + return; + } + cJSON_Delete(parsed); + if (closing_if_words) unguard(value, closing_if_words); + cJSON_AddStringToObject(args, key, value); +} + +static const char *opening_found(const char *grown, const char *opening) { + char after_gap[64]; + const char *at; + snprintf(after_gap, sizeof after_gap, "\n\n%s", opening); + at = strstr(grown, after_gap); + return at ? at : strstr(grown, opening); +} + +static bool read_dsml_leaf(const char **cursor, const dsml_spelling *dsml, cJSON *into) { + const char *p = *cursor; + const char *tag_end = strchr(p, '>'); + const char *value_end; + char *name; + char *is_string; + char *value; + + if (!starts_with(p, dsml->parameter) || !tag_end) return false; + name = attribute_in(p, tag_end, "name"); + is_string = attribute_in(p, tag_end, "string"); + value_end = strstr(tag_end + 1, dsml->parameter_end); + if (!name || !value_end) { + free(name); + free(is_string); + return false; + } + value = copy_of_n(tag_end + 1, (size_t)(value_end - tag_end - 1)); + if (!is_string || strcmp(is_string, "true") == 0) { + unguard(value, dsml->parameter_end); + cJSON_AddStringToObject(into, name, value); + } else { + add_argument_as_json_or_words(into, name, value); + } + free(name); + free(is_string); + free(value); + *cursor = value_end + strlen(dsml->parameter_end); + return true; +} + +static bool read_dsml_nested(const char **cursor, const dsml_spelling *dsml, cJSON *into) { + const char *p = *cursor; + bool any = false; + for (;;) { + p = past_space(p); + if (!starts_with(p, dsml->parameter)) break; + if (!read_dsml_leaf(&p, dsml, into)) return false; + any = true; + } + *cursor = p; + return any; +} + +static bool read_dsml_arguments(const char **cursor, const dsml_spelling *dsml, cJSON *args) { + const char *p = *cursor; + for (;;) { + const char *tag_end; + const char *value_start; + char *name; + char *is_string; + + p = past_space(p); + if (starts_with(p, dsml->invoke_end)) { + *cursor = p + strlen(dsml->invoke_end); + return true; + } + tag_end = strchr(p, '>'); + if (!starts_with(p, dsml->parameter) || !tag_end) return false; + name = attribute_in(p, tag_end, "name"); + is_string = attribute_in(p, tag_end, "string"); + value_start = tag_end + 1; + if (name && !is_string && starts_with(past_space(value_start), dsml->parameter)) { + cJSON *nested = cJSON_CreateObject(); + if (!read_dsml_nested(&value_start, dsml, nested)) { + cJSON_Delete(nested); + free(name); + return false; + } + cJSON_AddItemToObject(args, name, nested); + free(name); + p = past_space(value_start); + if (starts_with(p, dsml->parameter_end)) p += strlen(dsml->parameter_end); + continue; + } + free(name); + free(is_string); + if (!read_dsml_leaf(&p, dsml, args)) return false; + } +} + +static bool read_dsml(const char *grown, reaching *out) { + static const dsml_spelling *const v4_spellings[] = {&DSML_V4, &DSML_V4_UNBARRED, &DSML_PLAIN_XML}; + const dsml_spelling *dsml = NULL; + const char *start = NULL; + const char *v41_start = opening_found(grown, DSML_V41.calls); + const char *p; + size_t i; + + for (i = 0; i < COUNT_OF(v4_spellings) && !start; i++) { + start = opening_found(grown, v4_spellings[i]->calls); + dsml = v4_spellings[i]; + } + if (v41_start && (!start || v41_start < start)) { + start = v41_start; + dsml = &DSML_V41; + } + if (!start) return false; + out->words_end = without_trailing_space(grown, (size_t)(start - grown)); + out->tendrils_start = (size_t)(start - grown); + p = strstr(start, dsml->calls) + strlen(dsml->calls); + for (;;) { + const char *tag_end; + char *name; + cJSON *args; + + p = past_space(p); + if (starts_with(p, dsml->calls_end)) { + out->tendrils_end = (size_t)(p + strlen(dsml->calls_end) - grown); + return out->count > 0; + } + tag_end = strchr(p, '>'); + if (!starts_with(p, dsml->invoke) || !tag_end) return false; + name = attribute_in(p, tag_end, "name"); + if (!name) return false; + p = tag_end + 1; + args = cJSON_CreateObject(); + if (!read_dsml_arguments(&p, dsml, args) || !reaching_add(out, name, args)) { + cJSON_Delete(args); + free(name); + return false; + } + cJSON_Delete(args); + } +} + +static const char *found_outside_arguments(const char *s, const char *needle) { + while (*s) { + size_t i; + bool skipped = false; + if (starts_with(s, needle)) return s; + for (i = 0; i < COUNT_OF(ARGUMENT_WRAPPERS); i++) { + const char *tag_end; + const char *closing; + if (!starts_with(s, ARGUMENT_WRAPPERS[i][0])) continue; + tag_end = strchr(s, '>'); + closing = tag_end ? strstr(tag_end + 1, ARGUMENT_WRAPPERS[i][1]) : NULL; + if (!closing) return NULL; + s = closing + strlen(ARGUMENT_WRAPPERS[i][1]); + skipped = true; + break; + } + if (!skipped) s++; + } + return NULL; +} + +static bool read_glm_arguments(const char **cursor, const char *close, const cJSON *tools, + const char *tool_name, cJSON *args) { + const char *p = *cursor; + for (;;) { + const char *key_end; + const char *value_end; + char *key; + char *value; + + p = past_space(p); + if (starts_with(p, "")) { + *cursor = p + strlen(""); + return true; + } + if (!starts_with(p, "")) return false; + p += strlen(""); + key_end = strstr(p, ""); + if (!key_end || key_end > close) return false; + key = trimmed_copy(p, key_end); + unguard(key, ""); + p = past_space(key_end + strlen("")); + if (!starts_with(p, "")) { + free(key); + return false; + } + p += strlen(""); + value_end = strstr(p, ""); + if (!value_end || value_end > close) { + free(key); + return false; + } + value = copy_of_n(p, (size_t)(value_end - p)); + unguard(value, ""); + add_argument_typed(args, tools, tool_name, key, value, NULL); + free(key); + free(value); + p = value_end + strlen(""); + } +} + +static bool read_glm(const char *grown, const cJSON *tools, reaching *out) { + const char *start = strstr(grown, ""); + const char *block = start; + const char *p = start; + + if (!start) return false; + if (block >= grown + 2 && block[-2] == '\n' && block[-1] == '\n') block -= 2; + out->words_end = without_trailing_space(grown, (size_t)(block - grown)); + out->tendrils_start = (size_t)(block - grown); + for (;;) { + const char *close; + const char *first_key; + const char *name_end; + char *name; + cJSON *args; + + p = past_space(p); + if (!starts_with(p, "")) break; + p += strlen(""); + close = found_outside_arguments(p, ""); + if (!close) return false; + first_key = strstr(p, ""); + name_end = first_key && first_key < close ? first_key : close; + name = trimmed_copy(p, name_end); + if (!name || !name[0]) { + free(name); + return false; + } + p = name_end; + args = cJSON_CreateObject(); + if (!read_glm_arguments(&p, close, tools, name, args) || !reaching_add(out, name, args)) { + cJSON_Delete(args); + free(name); + return false; + } + cJSON_Delete(args); + if (!starts_with(past_space(p), "")) { + p = past_space(p); + break; + } + } + out->tendrils_end = (size_t)(p - grown); + return out->count > 0; +} + +static char *qwen_value(const char *from, const char *to) { + if (from < to && *from == '\n') from++; + if (to > from && to[-1] == '\n') to--; + return copy_of_n(from, (size_t)(to - from)); +} + +static bool read_qwen_arguments(const char **cursor, const cJSON *tools, const char *tool_name, + cJSON *args) { + const char *p = *cursor; + for (;;) { + const char *q = past_space(p); + const char *key_end; + const char *value_end; + char *key; + char *value; + + if (starts_with(q, "")) { + *cursor = q + strlen(""); + return true; + } + if (!starts_with(q, ""); + if (*key_end != '>') return false; + value_end = strstr(key_end + 1, ""); + if (!value_end) return false; + key = trimmed_copy(q, key_end); + value = qwen_value(key_end + 1, value_end); + add_argument_typed(args, tools, tool_name, key, value, ""); + free(key); + free(value); + p = value_end + strlen(""); + } +} + +static bool read_qwen(const char *grown, const cJSON *tools, reaching *out) { + const char *start = strstr(grown, ""); + const char *block = start; + const char *p = start; + + if (!start) return false; + while (block > grown && (block[-1] == '\n' || block[-1] == ' ')) block--; + out->words_end = without_trailing_space(grown, (size_t)(block - grown)); + out->tendrils_start = (size_t)(block - grown); + for (;;) { + const char *name_end; + char *name; + cJSON *args; + + p = past_space(p); + if (!starts_with(p, "")) break; + p = past_space(p + strlen("")); + if (!starts_with(p, ""); + if (*name_end != '>') return false; + name = trimmed_copy(p, name_end); + if (!name || !name[0]) { + free(name); + return false; + } + p = name_end + 1; + args = cJSON_CreateObject(); + if (!read_qwen_arguments(&p, tools, name, args)) { + cJSON_Delete(args); + free(name); + return false; + } + p = past_space(p); + if (!starts_with(p, "") || !reaching_add(out, name, args)) { + cJSON_Delete(args); + free(name); + return false; + } + cJSON_Delete(args); + p += strlen(""); + if (!starts_with(past_space(p), "")) { + p = past_space(p); + break; + } + } + out->tendrils_end = (size_t)(p - grown); + return out->count > 0; +} + +bool read_tendrils(dialect d, const char *grown, const cJSON *tools, reaching *out) { + bool read; + memset(out, 0, sizeof *out); + switch (d) { + case DIALECT_GLM: read = read_glm(grown, tools, out); break; + case DIALECT_QWEN: read = read_qwen(grown, tools, out); break; + case DIALECT_DEEPSEEK: + case DIALECT_DEEPSEEK41: + default: read = read_dsml(grown, out); break; + } + if (!read) reaching_free(out); + return read; +} + +void reaching_free(reaching *r) { + size_t i; + for (i = 0; i < r->count; i++) { + free(r->tendrils[i].call_id); + free(r->tendrils[i].name); + free(r->tendrils[i].args_json); + } + free(r->tendrils); + memset(r, 0, sizeof *r); +} + +turn *chat_add_turn(chat *c, speaker by) { + turn *t; + if (c->count == c->room) { + size_t room = c->room ? c->room * 2 : 8; + turn *grown = (turn *)realloc(c->turns, room * sizeof *grown); + if (!grown) return NULL; + c->turns = grown; + c->room = room; + } + t = &c->turns[c->count++]; + memset(t, 0, sizeof *t); + t->by = by; + return t; +} + +turn *chat_last_turn(const chat *c) { + return c->count > 0 ? &c->turns[c->count - 1] : NULL; +} + +int turn_add_words(turn *t, const char *words, const char *joiner) { + size_t had; + size_t joining; + char *grown; + + if (!words) return 0; + if (!t->words) { + t->words = copy_of(words); + return t->words ? 0 : -1; + } + had = strlen(t->words); + joining = joiner ? strlen(joiner) : 0; + grown = (char *)realloc(t->words, had + joining + strlen(words) + 1); + if (!grown) return -1; + memcpy(grown + had, joiner ? joiner : "", joining); + strcpy(grown + had + joining, words); + t->words = grown; + return 0; +} + +int turn_add_tendril(turn *t, const char *call_id, const char *name, const char *args_json) { + tendril *grown = (tendril *)realloc(t->tendrils, (t->tendril_count + 1) * sizeof *grown); + if (!grown) return -1; + t->tendrils = grown; + grown[t->tendril_count].call_id = copy_of(call_id); + grown[t->tendril_count].name = copy_of(name); + grown[t->tendril_count].args_json = copy_of(args_json ? args_json : "{}"); + t->tendril_count++; + return 0; +} + +void chat_free(chat *c) { + size_t i; + size_t k; + for (i = 0; i < c->count; i++) { + turn *t = &c->turns[i]; + for (k = 0; k < t->tendril_count; k++) { + free(t->tendrils[k].call_id); + free(t->tendrils[k].name); + free(t->tendrils[k].args_json); + } + free(t->tendrils); + free(t->words); + free(t->answering_call_id); + free(t->tendrils_as_sampled); + } + free(c->turns); + memset(c, 0, sizeof *c); +} diff --git a/hives/dwarfstar/src/chat.h b/hives/dwarfstar/src/chat.h new file mode 100644 index 00000000..22b2ca47 --- /dev/null +++ b/hives/dwarfstar/src/chat.h @@ -0,0 +1,64 @@ +#ifndef DWARFSTAR_CHAT_H +#define DWARFSTAR_CHAT_H + +#include +#include + +#include + +typedef enum { + DIALECT_DEEPSEEK, + DIALECT_DEEPSEEK41, + DIALECT_GLM, + DIALECT_QWEN, +} dialect; + +typedef enum { + USER_SAYS, + MODEL_SAYS, + TOOL_ANSWERS, +} speaker; + +typedef struct { + char *call_id; + char *name; + char *args_json; +} tendril; + +typedef struct { + speaker by; + char *words; + char *answering_call_id; + tendril *tendrils; + size_t tendril_count; + char *tendrils_as_sampled; +} turn; + +typedef struct { + turn *turns; + size_t count; + size_t room; +} chat; + +typedef struct { + size_t words_end; + size_t tendrils_start; + size_t tendrils_end; + tendril *tendrils; + size_t count; +} reaching; + +turn *chat_add_turn(chat *c, speaker by); +turn *chat_last_turn(const chat *c); +int turn_add_words(turn *t, const char *words, const char *joiner); +int turn_add_tendril(turn *t, const char *call_id, const char *name, const char *args_json); +void chat_free(chat *c); + +char *chat_as_prompt(dialect d, const char *system, const cJSON *tools, const chat *c); + +size_t words_safe_to_show(const char *grown, bool *tendrils_began); + +bool read_tendrils(dialect d, const char *grown, const cJSON *tools, reaching *out); +void reaching_free(reaching *r); + +#endif diff --git a/hives/dwarfstar/src/ds4_bridge.c b/hives/dwarfstar/src/ds4_bridge.c index 314d6ede..d3fcda26 100644 --- a/hives/dwarfstar/src/ds4_bridge.c +++ b/hives/dwarfstar/src/ds4_bridge.c @@ -1,7 +1,3 @@ -/* dwarfstar bridge: the engine, its one long-lived session, and the - * generation loop. See ds4_bridge.h. - */ - #define _POSIX_C_SOURCE 200809L #if defined(__APPLE__) #define _DARWIN_C_SOURCE @@ -195,32 +191,31 @@ static uint64_t seed(void) { return rng ? rng : SEED_IF_ZERO; } -int ds4_bridge_generate(ds4_bridge *bridge, const char *system, const ds4_message *messages, - size_t count, float temperature, int max_tokens, ds4_piece_fn on_piece, - void *user, ds4_wilt *wilt, char *err, size_t errlen) { - ds4_tokens tokens; - uint64_t rng = seed(); - int rc; +dialect ds4_bridge_dialect(const ds4_bridge *bridge) { + if (!bridge->engine) return DIALECT_DEEPSEEK; + if (ds4_engine_is_qwen4(bridge->engine)) return DIALECT_QWEN; + if (ds4_engine_is_glm_dsa(bridge->engine)) return DIALECT_GLM; + if (ds4_engine_is_deepseek41(bridge->engine)) return DIALECT_DEEPSEEK41; + return DIALECT_DEEPSEEK; +} +static void begin_wilt(ds4_wilt *wilt, char *err) { wilt->tokens_in = 0; wilt->tokens_out = 0; wilt->reason = "stop"; err[0] = '\0'; - if (!bridge->engine) { - snprintf(err, errlen, "no model is loaded"); - return -1; - } - if (count == 0) { - snprintf(err, errlen, "the prompt carried no text"); - return -1; - } - if (temperature < 0) temperature = DS4_DEFAULT_TEMPERATURE; +} - memset(&tokens, 0, sizeof tokens); - encode(bridge->engine, system, messages, count, &tokens); - wilt->tokens_in = tokens.len; - rc = ds4_session_sync(bridge->session, &tokens, err, errlen); - ds4_tokens_free(&tokens); +static int grow_from_tokens(ds4_bridge *bridge, ds4_tokens *tokens, float temperature, + int max_tokens, ds4_piece_fn on_piece, void *user, ds4_wilt *wilt, + char *err, size_t errlen) { + uint64_t rng = seed(); + int rc; + + if (temperature < 0) temperature = DS4_DEFAULT_TEMPERATURE; + wilt->tokens_in = tokens->len; + rc = ds4_session_sync(bridge->session, tokens, err, errlen); + ds4_tokens_free(tokens); if (rc == DS4_SESSION_SYNC_INTERRUPTED) { wilt->reason = "cancel"; return 0; @@ -264,3 +259,39 @@ int ds4_bridge_generate(ds4_bridge *bridge, const char *system, const ds4_messag } return 0; } + +int ds4_bridge_generate(ds4_bridge *bridge, const char *system, const ds4_message *messages, + size_t count, float temperature, int max_tokens, ds4_piece_fn on_piece, + void *user, ds4_wilt *wilt, char *err, size_t errlen) { + ds4_tokens tokens; + + begin_wilt(wilt, err); + if (!bridge->engine) { + snprintf(err, errlen, "no model is loaded"); + return -1; + } + if (count == 0) { + snprintf(err, errlen, "the prompt carried no text"); + return -1; + } + memset(&tokens, 0, sizeof tokens); + encode(bridge->engine, system, messages, count, &tokens); + return grow_from_tokens(bridge, &tokens, temperature, max_tokens, on_piece, user, wilt, err, + errlen); +} + +int ds4_bridge_generate_from_prompt(ds4_bridge *bridge, const char *prompt, float temperature, + int max_tokens, ds4_piece_fn on_piece, void *user, + ds4_wilt *wilt, char *err, size_t errlen) { + ds4_tokens tokens; + + begin_wilt(wilt, err); + if (!bridge->engine) { + snprintf(err, errlen, "no model is loaded"); + return -1; + } + memset(&tokens, 0, sizeof tokens); + ds4_tokenize_rendered_chat(bridge->engine, prompt, &tokens); + return grow_from_tokens(bridge, &tokens, temperature, max_tokens, on_piece, user, wilt, err, + errlen); +} diff --git a/hives/dwarfstar/src/ds4_bridge.h b/hives/dwarfstar/src/ds4_bridge.h index 0f5b9456..ed6c0073 100644 --- a/hives/dwarfstar/src/ds4_bridge.h +++ b/hives/dwarfstar/src/ds4_bridge.h @@ -1,27 +1,11 @@ -/* dwarfstar bridge: the only part of the bee that talks to the DwarfStar - * engine (ds4.h). - * - * The bee loads a model with ds4_bridge_load once it holds the GPU, and - * unloads it with ds4_bridge_unload before letting the GPU go. Loading - * first checks ds4's own lock (DS4_LOCK_FILE), because ds4 exits when - * another process holds it; a held lock is an error here instead. The - * loaded engine keeps one session, and every bloom syncs that session to - * the bloom's whole prompt, so ds4 evaluates only the part the KV cache - * does not already hold. The generation loop is ds4-server's: sync, - * sample, stop check, eval, detokenize, emit. - * - * Load, unload and generate run on one thread. ds4_bridge_arm, - * ds4_bridge_cancel and ds4_bridge_cancelled may be called from any - * thread: arm clears the cancel before a bloom starts, cancel asks the bloom - * in flight to stop, including one still waiting for the GPU. - */ - #ifndef DWARFSTAR_BRIDGE_H #define DWARFSTAR_BRIDGE_H #include #include +#include "chat.h" + typedef struct ds4_bridge ds4_bridge; typedef void (*ds4_piece_fn)(void *user, const char *text, size_t len); @@ -50,6 +34,7 @@ bool ds4_bridge_loaded(const ds4_bridge *bridge); bool ds4_bridge_ready(const ds4_bridge *bridge, const char *model_path); int ds4_bridge_load(ds4_bridge *bridge, const char *model_path, char *err, size_t errlen); void ds4_bridge_unload(ds4_bridge *bridge); +dialect ds4_bridge_dialect(const ds4_bridge *bridge); void ds4_bridge_arm(ds4_bridge *bridge); void ds4_bridge_cancel(ds4_bridge *bridge); @@ -58,5 +43,8 @@ bool ds4_bridge_cancelled(ds4_bridge *bridge); int ds4_bridge_generate(ds4_bridge *bridge, const char *system, const ds4_message *messages, size_t count, float temperature, int max_tokens, ds4_piece_fn on_piece, void *user, ds4_wilt *wilt, char *err, size_t errlen); +int ds4_bridge_generate_from_prompt(ds4_bridge *bridge, const char *prompt, float temperature, + int max_tokens, ds4_piece_fn on_piece, void *user, + ds4_wilt *wilt, char *err, size_t errlen); #endif diff --git a/hives/dwarfstar/src/ds4_stub.c b/hives/dwarfstar/src/ds4_stub.c index 60ee992b..e7ac9813 100644 --- a/hives/dwarfstar/src/ds4_stub.c +++ b/hives/dwarfstar/src/ds4_stub.c @@ -1,13 +1,3 @@ -/* dwarfstar stub: the bridge without the engine, for make check. - * - * It lets the bee's thrum side and its GPU handoff run with no model and - * no Metal: entering, the hello, the queue, the shared GPU lock, unfurls, - * wilts and cancels. Loading takes a moment, as a real model's does. A - * bloom answers with its last message, a word per piece, then "é" split - * across two pieces, so the bee's holding of a character a token ends - * inside of is exercised too. The shader overrides do nothing. - */ - #define _POSIX_C_SOURCE 200809L #include @@ -22,6 +12,10 @@ #define STUB_LOAD_MS 300 #define STUB_PIECE_MS 50 +#define USER_TURN "<|User|>" +#define MODEL_TURN "<|Assistant|>" +#define TOOLS_OFFERED "### Available Tool Schemas\n\n" + struct ds4_bridge { char path[1024]; atomic_int cancelled; @@ -67,6 +61,11 @@ void ds4_bridge_unload(ds4_bridge *bridge) { bridge->path[0] = '\0'; } +dialect ds4_bridge_dialect(const ds4_bridge *bridge) { + (void)bridge; + return DIALECT_DEEPSEEK; +} + void ds4_bridge_arm(ds4_bridge *bridge) { atomic_store(&bridge->cancelled, 0); } @@ -79,47 +78,162 @@ bool ds4_bridge_cancelled(ds4_bridge *bridge) { return atomic_load(&bridge->cancelled) != 0; } -int ds4_bridge_generate(ds4_bridge *bridge, const char *system, const ds4_message *messages, - size_t count, float temperature, int max_tokens, ds4_piece_fn on_piece, - void *user, ds4_wilt *wilt, char *err, size_t errlen) { - const char *text; - const char *at; - (void)system; - (void)temperature; - +static bool begin(ds4_bridge *bridge, ds4_wilt *wilt, char *err, size_t errlen) { wilt->tokens_in = 0; wilt->tokens_out = 0; wilt->reason = "stop"; err[0] = '\0'; - if (!bridge->path[0]) { - snprintf(err, errlen, "no model is loaded"); - return -1; + if (bridge->path[0]) return true; + snprintf(err, errlen, "no model is loaded"); + return false; +} + +static bool say_piece(ds4_bridge *bridge, const char *piece, size_t len, int max_tokens, + ds4_piece_fn on_piece, void *user, ds4_wilt *wilt) { + if (atomic_load(&bridge->cancelled)) { + wilt->reason = "cancel"; + return false; + } + if (wilt->tokens_out >= max_tokens) { + wilt->reason = "max_tokens"; + return false; } + on_piece(user, piece, len); + wilt->tokens_out++; + sleep_ms(STUB_PIECE_MS); + return true; +} + +static bool say_word_by_word(ds4_bridge *bridge, const char *words, int max_tokens, + ds4_piece_fn on_piece, void *user, ds4_wilt *wilt) { + const char *at = words; + while (*at) { + size_t n = strcspn(at, " "); + size_t step = n + (at[n] == ' ' ? 1 : 0); + if (!say_piece(bridge, at, step, max_tokens, on_piece, user, wilt)) return false; + at += step; + } + return true; +} + +static bool say_e_acute_split_in_two(ds4_bridge *bridge, int max_tokens, ds4_piece_fn on_piece, + void *user, ds4_wilt *wilt) { + return say_piece(bridge, " \xC3", 2, max_tokens, on_piece, user, wilt) && + say_piece(bridge, "\xA9", 1, max_tokens, on_piece, user, wilt); +} + +int ds4_bridge_generate(ds4_bridge *bridge, const char *system, const ds4_message *messages, + size_t count, float temperature, int max_tokens, ds4_piece_fn on_piece, + void *user, ds4_wilt *wilt, char *err, size_t errlen) { + (void)system; + (void)temperature; + if (!begin(bridge, wilt, err, errlen)) return -1; if (count == 0) { snprintf(err, errlen, "the prompt carried no text"); return -1; } - text = messages[count - 1].text; - wilt->tokens_in = (int)strlen(text); - for (at = text; *at;) { - size_t n = strcspn(at, " "); - size_t step = n + (at[n] == ' ' ? 1 : 0); - if (atomic_load(&bridge->cancelled)) { - wilt->reason = "cancel"; - return 0; - } - if (wilt->tokens_out >= max_tokens) { - wilt->reason = "max_tokens"; - return 0; + wilt->tokens_in = (int)strlen(messages[count - 1].text); + if (say_word_by_word(bridge, messages[count - 1].text, max_tokens, on_piece, user, wilt)) { + say_e_acute_split_in_two(bridge, max_tokens, on_piece, user, wilt); + } + return 0; +} + +static char *between(const char *text, const char *after, const char *before) { + const char *start = text ? strstr(text, after) : NULL; + const char *end; + if (!start) return NULL; + start += strlen(after); + end = strstr(start, before); + if (!end) end = start + strlen(start); + { + char *copy = (char *)malloc((size_t)(end - start) + 1); + if (!copy) return NULL; + memcpy(copy, start, (size_t)(end - start)); + copy[end - start] = '\0'; + return copy; + } +} + +static const char *last_of(const char *text, const char *needle) { + const char *last = NULL; + const char *at = text; + while ((at = strstr(at, needle)) != NULL) last = at++; + return last; +} + +static bool ends_with(const char *text, const char *suffix) { + size_t n = strlen(text); + size_t k = strlen(suffix); + return n >= k && strcmp(text + n - k, suffix) == 0; +} + +static bool tell_what_the_tool_said(ds4_bridge *bridge, const char *prompt, int max_tokens, + ds4_piece_fn on_piece, void *user, ds4_wilt *wilt) { + char *answer = between(last_of(prompt, ""), "", ""); + bool said = say_word_by_word(bridge, "the tool said ", max_tokens, on_piece, user, wilt) && + say_word_by_word(bridge, answer ? answer : "", max_tokens, on_piece, user, wilt); + free(answer); + return said; +} + +static char *tool_named_in(const char *prompt, const char *asked) { + const char *offered = strstr(prompt, TOOLS_OFFERED); + char *first = between(offered, "\"name\":\"", "\""); + const char *at = offered; + while (at && asked && (at = strstr(at, "\n{\"name\":\"")) != NULL) { + char *name = between(at, "\"name\":\"", "\""); + at++; + if (name && strstr(asked, name)) { + free(first); + return name; } - on_piece(user, at, step); - wilt->tokens_out++; - at += step; - sleep_ms(STUB_PIECE_MS); + free(name); + } + return first; +} + +static bool reach_for_the_tool_asked_for(ds4_bridge *bridge, const char *prompt, int max_tokens, + ds4_piece_fn on_piece, void *user, ds4_wilt *wilt) { + char *asked = between(last_of(prompt, USER_TURN), USER_TURN, MODEL_TURN); + char *name = tool_named_in(prompt, asked); + char invoke[512]; + char parameter[2048]; + bool said; + + snprintf(invoke, sizeof invoke, "_calls>\n<|DSML|invoke name=\"%s\">\n", name ? name : ""); + snprintf(parameter, sizeof parameter, + "<|DSML|parameter name=\"asked\" string=\"true\">%s\n" + "\n", + asked ? asked : ""); + said = say_word_by_word(bridge, "let me ask", max_tokens, on_piece, user, wilt) && + say_piece(bridge, "\n\n<|DSML|tool", strlen("\n\n<|DSML|tool"), max_tokens, on_piece, + user, wilt) && + say_piece(bridge, invoke, strlen(invoke), max_tokens, on_piece, user, wilt) && + say_piece(bridge, parameter, strlen(parameter), max_tokens, on_piece, user, wilt); + free(name); + free(asked); + return said; +} + +int ds4_bridge_generate_from_prompt(ds4_bridge *bridge, const char *prompt, float temperature, + int max_tokens, ds4_piece_fn on_piece, void *user, + ds4_wilt *wilt, char *err, size_t errlen) { + char *asked; + (void)temperature; + if (!begin(bridge, wilt, err, errlen)) return -1; + wilt->tokens_in = (int)strlen(prompt); + if (ends_with(prompt, "" MODEL_TURN)) { + tell_what_the_tool_said(bridge, prompt, max_tokens, on_piece, user, wilt); + return 0; + } + if (strstr(prompt, TOOLS_OFFERED)) { + reach_for_the_tool_asked_for(bridge, prompt, max_tokens, on_piece, user, wilt); + return 0; } - on_piece(user, " \xC3", 2); - on_piece(user, "\xA9", 1); - wilt->tokens_out += 2; + asked = between(last_of(prompt, USER_TURN), USER_TURN, MODEL_TURN); + say_word_by_word(bridge, asked ? asked : "", max_tokens, on_piece, user, wilt); + free(asked); return 0; } diff --git a/hives/dwarfstar/src/gpu.c b/hives/dwarfstar/src/gpu.c index 628bb511..09c02529 100644 --- a/hives/dwarfstar/src/gpu.c +++ b/hives/dwarfstar/src/gpu.c @@ -1,7 +1,3 @@ -/* dwarfstar gpu: the hive-wide flock and the want directory beside it. - * See gpu.h. - */ - #define _POSIX_C_SOURCE 200809L #if defined(__APPLE__) #define _DARWIN_C_SOURCE diff --git a/hives/dwarfstar/src/gpu.h b/hives/dwarfstar/src/gpu.h index a6bedec9..f28388f5 100644 --- a/hives/dwarfstar/src/gpu.h +++ b/hives/dwarfstar/src/gpu.h @@ -1,18 +1,3 @@ -/* dwarfstar gpu: one model on the GPU across every bee of the hive. - * - * Each model is its own unit and its own bee, and a bee loads its model - * only when a prompt needs it. ds4 refuses a second process on the GPU by - * exiting, so the bees take a hive-wide lock first: a flock on - * DWARFSTAR_GPU_LOCK, held for as long as the engine is loaded. A bee that - * needs the GPU while another holds it files a want, an empty file named - * by its pid in the directory beside the lock, and waits. The holder hands - * the GPU over when it is idle and someone wants it, after its current - * bloom when a want has waited a minute, and on its own after - * DWARFSTAR_IDLE_MS idle. A want left by a process that died is removed by - * whoever sees it. A probe holds the lock for an instant, so it tries a - * few times before it calls the GPU another bee's. - */ - #ifndef DWARFSTAR_GPU_H #define DWARFSTAR_GPU_H diff --git a/hives/dwarfstar/src/main.c b/hives/dwarfstar/src/main.c index 8257cfbf..a560317a 100644 --- a/hives/dwarfstar/src/main.c +++ b/hives/dwarfstar/src/main.c @@ -1,54 +1,3 @@ -/* dwarfstar-bee: the DwarfStar engine as a hum nurse. - * - * The bee reaches humd through the thrum C client, which runs - * `hum bee link` for it, and answers prompts from the engine linked into - * this process: a prompt tone becomes a chat prompt, the chat prompt becomes - * tokens, and the tokens unfurl as a text petal until the bloom wilts. No - * HTTP and no subprocess in between. - * - * A unit of the hive's Orchfile pins its bee to one model, so every model - * is its own bee with its own key, ids and headroom; without a pin the bee - * serves every model under DWARFSTAR_DIR. All of a hive's bees share one - * GPU (gpu.h): a bee takes it before loading its model, gives it back - * after DWARFSTAR_IDLE_MS idle or when another model's bee wants it, and - * claims one slot of headroom only while the GPU is its own or free, so a - * peer routes to the model that can start now. A local prompt for a model - * whose bee lacks the GPU still runs: it waits for the handoff. - * - * The bee outlives humd: when humd restarts, the link reconnects and the - * bee keeps its model loaded and drops the blooms the gone humd gave it. - * Only a refusal, or the link ending, ends the bee, non-zero, for its - * unit to restart. - * - * The engine grows one bloom at a time, so prompts queue and one thread - * takes them in order and tends the GPU between them, while the client's - * thread reads the link. A cancel stops its sid's bloom, waiting or in - * flight, and drops its sid's queued blooms. The bee is stateless: every - * prompt carries what it needs, the blooms its graft holds as the turns - * before it and the text petals of its content, else its text, as the - * turn it asks for, and the engine's session reuses whatever of it the KV - * cache already holds. A prompt with no words is refused: the engine - * grows only from them. An unfurl always carries whole UTF-8 characters, even - * when a token ends inside one. A bloom wilts with its nectar: the tokens - * in and out. - * - * Environment: - * DWARFSTAR_MODEL pin to this GGUF, absolute or under DWARFSTAR_DIR - * DWARFSTAR_MODELS the ids a pinned bee answers to (default: by name) - * DWARFSTAR_LABEL the label the bee enters as (default main) - * DWARFSTAR_DIR where the GGUFs live (default ~/ds4) - * DWARFSTAR_CTX context size in tokens (default 32768) - * DWARFSTAR_MAX_TOKENS cap on one bloom (default 4096) - * DWARFSTAR_TEMPERATURE sampling temperature (default ds4's) - * DWARFSTAR_THREADS engine CPU threads (default ds4's) - * DWARFSTAR_SSD_STREAMING 1 to stream experts from SSD - * DWARFSTAR_IDLE_MS give the GPU back after this long idle (default 300000) - * DWARFSTAR_WAIT_MS how long a bloom waits for the GPU (default 300000) - * DWARFSTAR_GPU_LOCK the hive-wide GPU lock; the Orchfile puts it in - * the hive's state, ${HUM_HIVE_STATE}/gpu.lock - * DWARFSTAR_METAL_DIR the .metal kernels (default metal/ beside the bee) - */ - #define _POSIX_C_SOURCE 200809L #if defined(__APPLE__) #define _DARWIN_C_SOURCE @@ -58,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -71,35 +21,68 @@ #include +#include "chat.h" #include "ds4_bridge.h" #include "gpu.h" #include "models.h" #include "shaders.h" #define HIVE "dwarfstar" -#define VERSION "0.33.1" +#define VERSION "0.35.1" #define SOURCE "https://github.com/adiled/hum/tree/main/hives/dwarfstar" #define WIRE "dwarfstar/core" #define TICK_MS 500 #define YIELD_AFTER_MS 60000 +struct awaited { + char *call_id; + char *name; + char *args_json; + char *answer; + bool is_error; + bool answered; +}; + struct bloom { char *sid; char *rid; char *model_path; char *system; - ds4_message *messages; - size_t count; + chat said; + cJSON *tools; + bool tendrils_in_play; + int next_petal; + ds4_wilt nectar; + struct awaited *awaited; + size_t awaited_count; + int64_t answers_due_by; struct bloom *next; }; -struct stream { +struct growth { const struct bloom *bloom; - char *held; + bool watching_for_tendrils; + bool tendrils_began; + char *grown; size_t len; - size_t cap; + size_t room; + size_t shown; + int *next_petal; + int words_petal; }; +typedef enum { + BLOOM_DONE, + BLOOM_AWAITS_ANSWERS, +} bloom_fate; + +typedef enum { + GROWS_FROM_NEW_WORDS, + GROWS_ON_FROM_ANSWERS, + NOTHING_NEW_TO_GROW_FROM, + NOTHING_AT_ALL, +} what_to_grow; + static thrum_bee *g_bee; static ds4_bridge *g_bridge; static dwarfstar_gpu *g_gpu; @@ -108,6 +91,7 @@ static int g_max_tokens = 4096; static float g_temperature = -1.0f; static int64_t g_idle_ms = 300000; static int64_t g_wait_ms = 300000; +static int64_t g_reach_ms = 1800000; static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t g_ready = PTHREAD_COND_INITIALIZER; @@ -115,6 +99,7 @@ static struct bloom *g_head; static struct bloom *g_tail; static const char *g_current_sid; static bool g_closing; +static struct bloom *g_parked; static atomic_int g_free_slots = -1; static const char *g_label = "main"; @@ -125,10 +110,27 @@ static const char *str_of(const cJSON *tone, const char *key) { return cJSON_IsString(value) ? value->valuestring : NULL; } +static bool is_kind(const cJSON *petal, const char *kind) { + const char *petal_kind = str_of(petal, "kind"); + return petal_kind && strcmp(petal_kind, kind) == 0; +} + static char *dup_of(const char *text) { return text ? strdup(text) : NULL; } +static char *json_text_of(const cJSON *item) { + char *printed = cJSON_PrintUnformatted(item); + char *copy = dup_of(printed); + cJSON_free(printed); + return copy; +} + +static char *answer_text_of(const cJSON *result) { + if (cJSON_IsString(result)) return strdup(result->valuestring); + return result ? json_text_of(result) : strdup(""); +} + static const char *env_of(const char *name) { const char *value = getenv(name); return value && value[0] ? value : NULL; @@ -140,6 +142,32 @@ static int64_t now_ms(void) { return (int64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000; } +static struct timespec tick_from_now(void) { + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + ts.tv_nsec += (long)TICK_MS * 1000000L; + ts.tv_sec += ts.tv_nsec / 1000000000L; + ts.tv_nsec %= 1000000000L; + return ts; +} + +static void mint_call_id(char *out, size_t cap) { + static atomic_uint minted; + unsigned char noise[12] = {0}; + FILE *urandom = fopen("/dev/urandom", "rb"); + size_t got = urandom ? fread(noise, 1, sizeof noise, urandom) : 0; + size_t i; + if (urandom) fclose(urandom); + if (got < sizeof noise) { + uint64_t fallback = (uint64_t)now_ms() ^ ((uint64_t)getpid() << 32) ^ atomic_fetch_add(&minted, 1); + for (i = 0; i < sizeof noise; i++) noise[i] = (unsigned char)(fallback >> ((i % 8) * 8)); + } + snprintf(out, cap, "call_"); + for (i = 0; i < sizeof noise && strlen(out) + 2 < cap; i++) { + snprintf(out + strlen(out), cap - strlen(out), "%02x", noise[i]); + } +} + static cJSON *tone_new(const char *chi, const char *rid, const char *sid) { cJSON *tone = cJSON_CreateObject(); if (!tone) return NULL; @@ -149,14 +177,24 @@ static cJSON *tone_new(const char *chi, const char *rid, const char *sid) { return tone; } -static void free_bloom(struct bloom *t) { +static void forget_awaited(struct bloom *t) { size_t i; - if (!t) return; - for (i = 0; i < t->count; i++) { - free((char *)t->messages[i].role); - free((char *)t->messages[i].text); + for (i = 0; i < t->awaited_count; i++) { + free(t->awaited[i].call_id); + free(t->awaited[i].name); + free(t->awaited[i].args_json); + free(t->awaited[i].answer); } - free(t->messages); + free(t->awaited); + t->awaited = NULL; + t->awaited_count = 0; +} + +static void free_bloom(struct bloom *t) { + if (!t) return; + forget_awaited(t); + chat_free(&t->said); + cJSON_Delete(t->tools); free(t->sid); free(t->rid); free(t->model_path); @@ -164,6 +202,14 @@ static void free_bloom(struct bloom *t) { free(t); } +static void free_blooms(struct bloom *t) { + while (t) { + struct bloom *next = t->next; + free_bloom(t); + t = next; + } +} + static void send_tone(cJSON *tone) { if (!tone) return; if (thrum_bee_send(g_bee, tone) != 0) { @@ -215,23 +261,81 @@ static void send_wilt(const struct bloom *t, const char *reason, int exit_code, send_tone(tone); } -static void send_unfurl(const struct bloom *t, const char *text, size_t len) { +static cJSON *unfurl_tone(const struct bloom *t, int petal, const char *kind) { cJSON *tone = tone_new(THRUM_CHI_UNFURL, t->rid, t->sid); - char *grew = (char *)malloc(len + 1); - if (!tone || !grew) { + if (!tone) return NULL; + cJSON_AddNumberToObject(tone, "petal", petal); + cJSON_AddStringToObject(tone, "kind", kind); + return tone; +} + +static void unfurl_words(const struct bloom *t, int petal, const char *text, size_t len) { + cJSON *tone = unfurl_tone(t, petal, THRUM_PETAL_TEXT); + char *words = (char *)malloc(len + 1); + if (!tone || !words) { cJSON_Delete(tone); - free(grew); + free(words); return; } - memcpy(grew, text, len); - grew[len] = '\0'; - cJSON_AddNumberToObject(tone, "petal", 0); - cJSON_AddStringToObject(tone, "kind", THRUM_PETAL_TEXT); - cJSON_AddStringToObject(tone, "text", grew); - free(grew); + memcpy(words, text, len); + words[len] = '\0'; + cJSON_AddStringToObject(tone, "text", words); + free(words); send_tone(tone); } +static cJSON *closed_petal_tone(const struct bloom *t, int petal, const char *kind) { + cJSON *tone = unfurl_tone(t, petal, kind); + if (tone) cJSON_AddBoolToObject(tone, "closed", 1); + return tone; +} + +static void close_petal(const struct bloom *t, int petal, const char *kind) { + send_tone(closed_petal_tone(t, petal, kind)); +} + +static cJSON *args_of(const char *args_json) { + cJSON *args = cJSON_Parse(args_json ? args_json : ""); + if (cJSON_IsObject(args)) return args; + cJSON_Delete(args); + return cJSON_CreateObject(); +} + +static cJSON *tendril_petal_tone(const struct bloom *t, int petal, const tendril *reached) { + cJSON *tone = unfurl_tone(t, petal, THRUM_PETAL_TENDRIL); + if (!tone) return NULL; + cJSON_AddStringToObject(tone, "callId", reached->call_id); + cJSON_AddStringToObject(tone, "name", reached->name); + cJSON_AddStringToObject(tone, "sap", reached->args_json); + return tone; +} + +static cJSON *reach_tone(const struct bloom *t, const tendril *reached) { + cJSON *tone = tone_new(THRUM_CHI_TENDRIL_REACH, NULL, t->sid); + if (!tone) return NULL; + cJSON_AddStringToObject(tone, "callId", reached->call_id); + cJSON_AddStringToObject(tone, "name", reached->name); + cJSON_AddItemToObject(tone, "args", args_of(reached->args_json)); + return tone; +} + +static cJSON *what_came_back_tone(const struct bloom *t, const struct awaited *a) { + cJSON *tone = tone_new(THRUM_CHI_TENDRIL_INFO, NULL, t->sid); + if (!tone) return NULL; + cJSON_AddStringToObject(tone, "callId", a->call_id); + cJSON_AddStringToObject(tone, "name", a->name); + cJSON_AddItemToObject(tone, "args", args_of(a->args_json)); + cJSON_AddStringToObject(tone, "result", a->answer ? a->answer : ""); + cJSON_AddBoolToObject(tone, "isError", a->is_error); + return tone; +} + +static void send_each(cJSON *tones) { + cJSON *tone; + while (tones && (tone = cJSON_DetachItemFromArray(tones, 0)) != NULL) send_tone(tone); + cJSON_Delete(tones); +} + static size_t complete_utf8(const unsigned char *bytes, size_t len) { size_t start = len; size_t tail = 0; @@ -252,26 +356,56 @@ static size_t complete_utf8(const unsigned char *bytes, size_t len) { return tail + 1 >= need ? len : start - 1; } -static void on_piece(void *user, const char *text, size_t len) { - struct stream *s = (struct stream *)user; - size_t ready; +static struct growth growth_of(const struct bloom *t, bool watching_for_tendrils, int *next_petal) { + struct growth g; + memset(&g, 0, sizeof g); + g.bloom = t; + g.watching_for_tendrils = watching_for_tendrils; + g.next_petal = next_petal; + g.words_petal = -1; + return g; +} - if (s->len + len > s->cap) { - size_t cap = s->cap ? s->cap : 256; +static bool grow_by(struct growth *g, const char *text, size_t len) { + if (g->len + len + 1 > g->room) { + size_t room = g->room ? g->room : 256; char *grown; - while (cap < s->len + len) cap *= 2; - grown = (char *)realloc(s->held, cap); - if (!grown) return; - s->held = grown; - s->cap = cap; + while (room < g->len + len + 1) room *= 2; + grown = (char *)realloc(g->grown, room); + if (!grown) return false; + g->grown = grown; + g->room = room; } - memcpy(s->held + s->len, text, len); - s->len += len; - ready = complete_utf8((const unsigned char *)s->held, s->len); - if (ready == 0) return; - send_unfurl(s->bloom, s->held, ready); - memmove(s->held, s->held + ready, s->len - ready); - s->len -= ready; + memcpy(g->grown + g->len, text, len); + g->len += len; + g->grown[g->len] = '\0'; + return true; +} + +static void show_words_up_to(struct growth *g, size_t safe) { + size_t ready; + if (safe <= g->shown) return; + ready = complete_utf8((const unsigned char *)g->grown, safe); + if (ready <= g->shown) return; + if (g->words_petal < 0) g->words_petal = (*g->next_petal)++; + unfurl_words(g->bloom, g->words_petal, g->grown + g->shown, ready - g->shown); + g->shown = ready; +} + +static void on_piece(void *user, const char *text, size_t len) { + struct growth *g = (struct growth *)user; + if (!grow_by(g, text, len)) return; + show_words_up_to(g, g->watching_for_tendrils ? words_safe_to_show(g->grown, &g->tendrils_began) + : g->len); +} + +static void close_words(struct growth *g) { + if (g->words_petal >= 0) close_petal(g->bloom, g->words_petal, THRUM_PETAL_TEXT); +} + +static void show_every_word_left(struct growth *g) { + show_words_up_to(g, g->len); + close_words(g); } static bool bloom_stopped(void *user) { @@ -320,16 +454,40 @@ static int take_gpu(const struct bloom *t) { return 0; } -static void run_bloom(const struct bloom *t) { - struct stream s = {t, NULL, 0, 0}; +static ds4_message *messages_of(const chat *said, size_t *count) { + ds4_message *messages = (ds4_message *)calloc(said->count ? said->count : 1, sizeof *messages); + size_t i; + *count = 0; + if (!messages) return NULL; + for (i = 0; i < said->count; i++) { + const turn *spoken = &said->turns[i]; + if (spoken->by == TOOL_ANSWERS || !spoken->words) continue; + messages[*count].role = spoken->by == USER_SAYS ? "user" : "assistant"; + messages[*count].text = spoken->words; + (*count)++; + } + return messages; +} + +static void grow_words_only(struct bloom *t) { + int next_petal = 0; + struct growth g = growth_of(t, false, &next_petal); + size_t count; + ds4_message *messages = messages_of(&t->said, &count); ds4_wilt result; char err[512]; int rc; - if (take_gpu(t) != 0) return; - rc = ds4_bridge_generate(g_bridge, t->system, t->messages, t->count, g_temperature, - g_max_tokens, on_piece, &s, &result, err, sizeof err); - free(s.held); + if (!messages) { + send_error(t, "generation_failed", "out of memory for the prompt"); + send_wilt(t, "error", 1, NULL); + return; + } + rc = ds4_bridge_generate(g_bridge, t->system, messages, count, g_temperature, g_max_tokens, + on_piece, &g, &result, err, sizeof err); + free(messages); + show_every_word_left(&g); + free(g.grown); if (rc != 0) { send_error(t, "generation_failed", err[0] ? err : "the engine failed"); send_wilt(t, "error", 1, &result); @@ -338,6 +496,201 @@ static void run_bloom(const struct bloom *t) { send_wilt(t, result.reason, 0, &result); } +static bool await_every_tendril(struct bloom *t, const reaching *r) { + size_t i; + t->awaited = (struct awaited *)calloc(r->count, sizeof *t->awaited); + if (!t->awaited) return false; + t->awaited_count = r->count; + for (i = 0; i < r->count; i++) { + t->awaited[i].call_id = dup_of(r->tendrils[i].call_id); + t->awaited[i].name = dup_of(r->tendrils[i].name); + t->awaited[i].args_json = dup_of(r->tendrils[i].args_json); + if (!t->awaited[i].call_id || !t->awaited[i].name || !t->awaited[i].args_json) return false; + } + t->answers_due_by = now_ms() + g_reach_ms; + return true; +} + +static bool every_answer_came(const struct bloom *t) { + size_t i; + for (i = 0; i < t->awaited_count; i++) { + if (!t->awaited[i].answered) return false; + } + return true; +} + +static bool remember_reaching(struct bloom *t, const struct growth *g, reaching *r) { + turn *spoken = chat_add_turn(&t->said, MODEL_SAYS); + size_t i; + if (!spoken) return false; + spoken->words = (char *)malloc(r->words_end + 1); + spoken->tendrils_as_sampled = (char *)malloc(r->tendrils_end - r->tendrils_start + 1); + if (!spoken->words || !spoken->tendrils_as_sampled) return false; + memcpy(spoken->words, g->grown, r->words_end); + spoken->words[r->words_end] = '\0'; + memcpy(spoken->tendrils_as_sampled, g->grown + r->tendrils_start, r->tendrils_end - r->tendrils_start); + spoken->tendrils_as_sampled[r->tendrils_end - r->tendrils_start] = '\0'; + for (i = 0; i < r->count; i++) { + char call_id[64]; + mint_call_id(call_id, sizeof call_id); + r->tendrils[i].call_id = strdup(call_id); + if (!r->tendrils[i].call_id || + turn_add_tendril(spoken, call_id, r->tendrils[i].name, r->tendrils[i].args_json) != 0) { + return false; + } + } + return true; +} + +static bool remember_answers(struct bloom *t) { + size_t i; + for (i = 0; i < t->awaited_count; i++) { + turn *answer = chat_add_turn(&t->said, TOOL_ANSWERS); + if (!answer || turn_add_words(answer, t->awaited[i].answer ? t->awaited[i].answer : "", NULL) != 0) { + return false; + } + answer->answering_call_id = dup_of(t->awaited[i].call_id); + } + forget_awaited(t); + return true; +} + +static void add_to_nectar(ds4_wilt *total, const ds4_wilt *round) { + total->tokens_in += round->tokens_in; + total->tokens_out += round->tokens_out; + total->reason = round->reason; +} + +static void break_off(const struct bloom *t, const char *code, const char *message) { + send_error(t, code, message); + send_wilt(t, "error", 1, &t->nectar); +} + +static cJSON *tones_reaching_for(struct bloom *t, const reaching *r) { + cJSON *tones = cJSON_CreateArray(); + size_t i; + if (!tones) return NULL; + for (i = 0; i < r->count; i++) { + int petal = t->next_petal++; + cJSON_AddItemToArray(tones, tendril_petal_tone(t, petal, &r->tendrils[i])); + cJSON_AddItemToArray(tones, closed_petal_tone(t, petal, THRUM_PETAL_TENDRIL)); + } + for (i = 0; i < r->count; i++) cJSON_AddItemToArray(tones, reach_tone(t, &r->tendrils[i])); + return tones; +} + +static void park(struct bloom *t) { + pthread_mutex_lock(&g_lock); + t->next = g_parked; + g_parked = t; + g_current_sid = NULL; + pthread_mutex_unlock(&g_lock); +} + +static struct bloom *unpark_where(bool (*fits)(const struct bloom *, const void *), const void *what) { + struct bloom *taken = NULL; + struct bloom **at = &g_parked; + while (*at) { + struct bloom *t = *at; + if (fits(t, what)) { + *at = t->next; + t->next = taken; + taken = t; + } else { + at = &t->next; + } + } + return taken; +} + +static bool of_sid(const struct bloom *t, const void *sid) { + return strcmp(t->sid, (const char *)sid) == 0; +} + +static bool overdue(const struct bloom *t, const void *now) { + return *(const int64_t *)now >= t->answers_due_by; +} + +static bool answered_whole(const struct bloom *t, const void *sid) { + return of_sid(t, sid) && every_answer_came(t); +} + +static void queue_first(struct bloom *t) { + t->next = g_head; + g_head = t; + if (!g_tail) g_tail = t; + pthread_cond_signal(&g_ready); +} + +static void break_off_overdue(void) { + int64_t now = now_ms(); + struct bloom *late; + pthread_mutex_lock(&g_lock); + late = unpark_where(overdue, &now); + pthread_mutex_unlock(&g_lock); + for (struct bloom *t = late; t; t = t->next) { + char why[512]; + snprintf(why, sizeof why, "%s did not come back within %llds", + t->awaited_count ? t->awaited[0].name : "a tendril", (long long)(g_reach_ms / 1000)); + fprintf(stderr, "dwarfstar: a bloom on %s let go: %s\n", t->sid, why); + break_off(t, "tendril_unanswered", why); + } + free_blooms(late); +} + +static bloom_fate grow_a_round(struct bloom *t) { + dialect d = ds4_bridge_dialect(g_bridge); + struct growth g = growth_of(t, true, &t->next_petal); + char *prompt; + reaching r; + ds4_wilt round; + char err[512]; + cJSON *tones; + int rc; + + if (!remember_answers(t) || !(prompt = chat_as_prompt(d, t->system, t->tools, &t->said))) { + break_off(t, "generation_failed", "out of memory for the prompt"); + return BLOOM_DONE; + } + rc = ds4_bridge_generate_from_prompt(g_bridge, prompt, g_temperature, + g_max_tokens - t->nectar.tokens_out, on_piece, &g, &round, + err, sizeof err); + free(prompt); + add_to_nectar(&t->nectar, &round); + if (rc != 0) { + show_every_word_left(&g); + free(g.grown); + break_off(t, "generation_failed", err[0] ? err : "the engine failed"); + return BLOOM_DONE; + } + if (strcmp(round.reason, "stop") != 0 || !read_tendrils(d, g.grown ? g.grown : "", t->tools, &r)) { + show_every_word_left(&g); + free(g.grown); + send_wilt(t, t->nectar.reason, 0, &t->nectar); + return BLOOM_DONE; + } + close_words(&g); + if (!remember_reaching(t, &g, &r) || !await_every_tendril(t, &r) || + !(tones = tones_reaching_for(t, &r))) { + reaching_free(&r); + free(g.grown); + break_off(t, "generation_failed", "out of memory for the tendrils"); + return BLOOM_DONE; + } + reaching_free(&r); + free(g.grown); + park(t); + send_each(tones); + return BLOOM_AWAITS_ANSWERS; +} + +static bloom_fate run_bloom(struct bloom *t) { + if (take_gpu(t) != 0) return BLOOM_DONE; + if (t->tendrils_in_play) return grow_a_round(t); + grow_words_only(t); + return BLOOM_DONE; +} + static void tend_gpu(bool after_bloom) { int64_t want_age; bool queued; @@ -361,15 +714,6 @@ static void tend_gpu(bool after_bloom) { } } -static struct timespec tick_from_now(void) { - struct timespec ts; - clock_gettime(CLOCK_REALTIME, &ts); - ts.tv_nsec += (long)TICK_MS * 1000000L; - ts.tv_sec += ts.tv_nsec / 1000000000L; - ts.tv_nsec %= 1000000000L; - return ts; -} - static void *take_blooms(void *arg) { (void)arg; for (;;) { @@ -380,6 +724,7 @@ static void *take_blooms(void *arg) { if (pthread_cond_timedwait(&g_ready, &g_lock, &until) == ETIMEDOUT) { pthread_mutex_unlock(&g_lock); tend_gpu(false); + break_off_overdue(); pthread_mutex_lock(&g_lock); } } @@ -390,17 +735,19 @@ static void *take_blooms(void *arg) { t = g_head; g_head = t->next; if (!g_head) g_tail = NULL; + t->next = NULL; g_current_sid = t->sid; ds4_bridge_arm(g_bridge); pthread_mutex_unlock(&g_lock); - run_bloom(t); - - pthread_mutex_lock(&g_lock); - g_current_sid = NULL; - pthread_mutex_unlock(&g_lock); + if (run_bloom(t) == BLOOM_DONE) { + pthread_mutex_lock(&g_lock); + g_current_sid = NULL; + pthread_mutex_unlock(&g_lock); + free_bloom(t); + } g_last_bloom_ms = now_ms(); - free_bloom(t); + break_off_overdue(); tend_gpu(true); } ds4_bridge_unload(g_bridge); @@ -408,72 +755,134 @@ static void *take_blooms(void *arg) { return NULL; } -static int add_message(struct bloom *t, const char *role, const char *text) { - ds4_message *grown = (ds4_message *)realloc(t->messages, (t->count + 1) * sizeof *grown); - if (!grown) return -1; - t->messages = grown; - t->messages[t->count].role = dup_of(role); - t->messages[t->count].text = dup_of(text); - t->count++; - return 0; +static bool began_here(const chat *said, size_t first_of_these) { + return said->count > first_of_these; } -static char *words_of(const cJSON *petals) { - const cJSON *petal; - char *joined = NULL; - size_t len = 0; +static turn *turn_for_words(chat *said, speaker by, size_t first_of_these) { + turn *last = chat_last_turn(said); + if (last && last->by == by && began_here(said, first_of_these)) return last; + return chat_add_turn(said, by); +} - cJSON_ArrayForEach(petal, petals) { - const char *kind = str_of(petal, "kind"); - const char *piece = str_of(petal, "text"); - size_t n; - char *grown; +static turn *turn_for_tendril(chat *said, size_t first_of_these) { + turn *last = chat_last_turn(said); + if (last && last->by == MODEL_SAYS && began_here(said, first_of_these)) return last; + return chat_add_turn(said, MODEL_SAYS); +} - if (!piece || !kind || strcmp(kind, THRUM_PETAL_TEXT) != 0) continue; - n = strlen(piece); - grown = (char *)realloc(joined, len + n + 2); - if (!grown) { - free(joined); - return NULL; - } - joined = grown; - if (len > 0) joined[len++] = '\n'; - memcpy(joined + len, piece, n + 1); - len += n; - } - return joined; +static int hear_words(chat *said, speaker by, const char *words, size_t first_of_these) { + turn *speaking = turn_for_words(said, by, first_of_these); + return speaking ? turn_add_words(speaking, words, "\n") : -1; } -static int add_words(struct bloom *t, const char *role, const cJSON *petals) { - char *words = words_of(petals); - int rc = 0; +static int hear_tendril(chat *said, const cJSON *petal, size_t first_of_these) { + turn *speaking = turn_for_tendril(said, first_of_these); + char *args_json = json_text_of(cJSON_GetObjectItemCaseSensitive(petal, "args")); + int rc = speaking ? turn_add_tendril(speaking, str_of(petal, "callId"), str_of(petal, "name"), + args_json && strcmp(args_json, "null") != 0 ? args_json : "{}") + : -1; + free(args_json); + return rc; +} - if (words && words[0]) rc = add_message(t, role, words); +static int hear_answer(chat *said, const cJSON *petal) { + turn *answer = chat_add_turn(said, TOOL_ANSWERS); + char *words = answer_text_of(cJSON_GetObjectItemCaseSensitive(petal, "result")); + int rc = answer && words ? turn_add_words(answer, words, NULL) : -1; + if (rc == 0) answer->answering_call_id = dup_of(str_of(petal, "callId")); free(words); return rc; } -static int read_messages(const cJSON *tone, struct bloom *t) { +static int hear_petals(struct bloom *t, const cJSON *petals, speaker words_by) { + const size_t first_of_these = t->said.count; + const cJSON *petal; + cJSON_ArrayForEach(petal, petals) { + int rc = 0; + if (is_kind(petal, THRUM_PETAL_TEXT) && str_of(petal, "text")) { + rc = hear_words(&t->said, words_by, str_of(petal, "text"), first_of_these); + } else if (is_kind(petal, THRUM_PETAL_TENDRIL)) { + rc = hear_tendril(&t->said, petal, first_of_these); + t->tendrils_in_play = true; + } else if (is_kind(petal, THRUM_PETAL_GRASP)) { + rc = hear_answer(&t->said, petal); + t->tendrils_in_play = true; + } + if (rc != 0) return -1; + } + return 0; +} + +static bool said_something_new(const chat *said, size_t first_new) { + size_t i; + for (i = first_new; i < said->count; i++) { + if (said->turns[i].by == USER_SAYS) return true; + } + return false; +} + +static what_to_grow hear_the_chat(const cJSON *tone, struct bloom *t) { const cJSON *graft = cJSON_GetObjectItemCaseSensitive(tone, "graft"); const cJSON *bloom; const char *text = str_of(tone, "text"); - size_t before; + const turn *last; + size_t first_new; cJSON_ArrayForEach(bloom, graft) { - if (add_words(t, "user", cJSON_GetObjectItemCaseSensitive(bloom, "content")) != 0) return -1; - if (add_words(t, "assistant", cJSON_GetObjectItemCaseSensitive(bloom, "grew")) != 0) return -1; + if (hear_petals(t, cJSON_GetObjectItemCaseSensitive(bloom, "content"), USER_SAYS) != 0 || + hear_petals(t, cJSON_GetObjectItemCaseSensitive(bloom, "grew"), MODEL_SAYS) != 0) { + return NOTHING_AT_ALL; + } } - before = t->count; - if (add_words(t, "user", cJSON_GetObjectItemCaseSensitive(tone, "content")) != 0) return -1; - if (t->count == before && text && text[0] && add_message(t, "user", text) != 0) return -1; - if (t->count == before) return before > 0 ? -2 : -1; - return 0; + first_new = t->said.count; + if (hear_petals(t, cJSON_GetObjectItemCaseSensitive(tone, "content"), USER_SAYS) != 0) { + return NOTHING_AT_ALL; + } + if (!said_something_new(&t->said, first_new) && text && text[0]) { + turn *asked = chat_add_turn(&t->said, USER_SAYS); + if (!asked || turn_add_words(asked, text, NULL) != 0) return NOTHING_AT_ALL; + } + last = chat_last_turn(&t->said); + if (!last) return NOTHING_AT_ALL; + if (said_something_new(&t->said, first_new)) return GROWS_FROM_NEW_WORDS; + if (last->by == TOOL_ANSWERS) return GROWS_ON_FROM_ANSWERS; + return NOTHING_NEW_TO_GROW_FROM; +} + +static bool names_include(const cJSON *names, const char *name) { + const cJSON *allowed; + cJSON_ArrayForEach(allowed, names) { + if (cJSON_IsString(allowed) && strcmp(allowed->valuestring, name) == 0) return true; + } + return false; +} + +static cJSON *tools_offered(const cJSON *tone) { + const cJSON *tools = cJSON_GetObjectItemCaseSensitive(tone, "tools"); + const cJSON *allowed = cJSON_GetObjectItemCaseSensitive(tone, "allowedTools"); + const char *reach_how = str_of(cJSON_GetObjectItemCaseSensitive(tone, "tendrils"), "reach"); + const cJSON *tool; + cJSON *offered; + + if (!cJSON_IsArray(tools) || (reach_how && strcmp(reach_how, "none") == 0)) return NULL; + offered = cJSON_CreateArray(); + if (!offered) return NULL; + cJSON_ArrayForEach(tool, tools) { + const char *name = str_of(tool, "name"); + if (!name || (cJSON_IsArray(allowed) && !names_include(allowed, name))) continue; + cJSON_AddItemToArray(offered, cJSON_Duplicate(tool, true)); + } + if (cJSON_GetArraySize(offered) > 0) return offered; + cJSON_Delete(offered); + return NULL; } static void on_prompt(const cJSON *tone) { const char *model = str_of(tone, "modelId"); const char *path = ds4_models_path(&g_models, model); struct bloom *t = (struct bloom *)calloc(1, sizeof *t); + struct bloom *superseded; if (!t) return; t->sid = strdup(str_of(tone, "sid") ? str_of(tone, "sid") : ""); @@ -486,22 +895,27 @@ static void on_prompt(const cJSON *tone) { free_bloom(t); return; } - switch (read_messages(tone, t)) { - case 0: + t->tools = tools_offered(tone); + t->tendrils_in_play = t->tools != NULL; + switch (hear_the_chat(tone, t)) { + case GROWS_FROM_NEW_WORDS: + case GROWS_ON_FROM_ANSWERS: break; - case -2: - send_error(t, "cannot-grow-on", "dwarfstar grows a bloom only from new words, and cannot grow one on from its graft"); + case NOTHING_NEW_TO_GROW_FROM: + send_error(t, "cannot-grow-on", "dwarfstar grows a bloom only from new words, or on from what its tendrils grasped, and cannot grow one on from its graft's words"); free_bloom(t); return; - default: + case NOTHING_AT_ALL: send_error(t, "empty-prompt", "the prompt carried no words"); free_bloom(t); return; } t->model_path = strdup(path); t->system = dup_of(str_of(tone, "systemPrompt")); + t->nectar.reason = "stop"; pthread_mutex_lock(&g_lock); + superseded = unpark_where(of_sid, t->sid); if (g_tail) { g_tail->next = t; } else { @@ -510,11 +924,59 @@ static void on_prompt(const cJSON *tone) { g_tail = t; pthread_cond_signal(&g_ready); pthread_mutex_unlock(&g_lock); + free_blooms(superseded); +} + +static struct awaited *awaited_unanswered(struct bloom *t, const char *call_id) { + size_t i; + for (i = 0; i < t->awaited_count; i++) { + if (!t->awaited[i].answered && strcmp(t->awaited[i].call_id, call_id) == 0) return &t->awaited[i]; + } + return NULL; +} + +static struct bloom *parked_of_sid(const char *sid) { + struct bloom *t; + for (t = g_parked; t; t = t->next) { + if (strcmp(t->sid, sid) == 0) return t; + } + return NULL; +} + +static void on_tendril_result(const cJSON *tone) { + const char *sid = str_of(tone, "sid"); + const char *call_id = str_of(tone, "callId"); + const char *output = str_of(tone, "output"); + cJSON *what_came_back = NULL; + struct bloom *t; + struct awaited *a; + bool resume = false; + + if (!sid || !call_id) return; + pthread_mutex_lock(&g_lock); + t = parked_of_sid(sid); + a = t ? awaited_unanswered(t, call_id) : NULL; + if (a) { + a->answer = output ? strdup(output) + : answer_text_of(cJSON_GetObjectItemCaseSensitive(tone, "result")); + a->is_error = cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(tone, "isError")); + a->answered = true; + what_came_back = what_came_back_tone(t, a); + resume = every_answer_came(t); + } + pthread_mutex_unlock(&g_lock); + send_tone(what_came_back); + if (!resume) return; + pthread_mutex_lock(&g_lock); + t = unpark_where(answered_whole, sid); + if (t) queue_first(t); + pthread_mutex_unlock(&g_lock); } static void on_cancel(const cJSON *tone) { const char *sid = str_of(tone, "sid"); struct bloom *dropped = NULL; + struct bloom *parked; struct bloom **at; if (!sid) return; @@ -533,14 +995,13 @@ static void on_cancel(const cJSON *tone) { at = &t->next; } } + parked = unpark_where(of_sid, sid); pthread_mutex_unlock(&g_lock); - while (dropped) { - struct bloom *t = dropped; - dropped = t->next; - send_wilt(t, "cancel", 0, NULL); - free_bloom(t); - } + for (struct bloom *t = parked; t; t = t->next) send_wilt(t, "cancel", 0, &t->nectar); + free_blooms(parked); + for (struct bloom *t = dropped; t; t = t->next) send_wilt(t, "cancel", 0, NULL); + free_blooms(dropped); } static void on_tone(thrum_bee *bee, const cJSON *tone, void *user) { @@ -550,6 +1011,8 @@ static void on_tone(thrum_bee *bee, const cJSON *tone, void *user) { if (!chi) return; if (strcmp(chi, THRUM_CHI_PROMPT) == 0) { on_prompt(tone); + } else if (strcmp(chi, THRUM_CHI_TENDRIL_RESULT) == 0) { + on_tendril_result(tone); } else if (strcmp(chi, THRUM_CHI_CANCEL) == 0) { on_cancel(tone); } @@ -584,9 +1047,11 @@ static int metal_dir(char *out, size_t cap) { } static cJSON *hello_for(void) { - static const char *const chis[] = {THRUM_CHI_HELLO, THRUM_CHI_PROMPT, THRUM_CHI_CANCEL, - THRUM_CHI_UNFURL, THRUM_CHI_WILT, THRUM_CHI_ERROR, - THRUM_CHI_PULSE}; + static const char *const chis[] = {THRUM_CHI_HELLO, THRUM_CHI_PROMPT, + THRUM_CHI_CANCEL, THRUM_CHI_UNFURL, + THRUM_CHI_WILT, THRUM_CHI_ERROR, + THRUM_CHI_PULSE, THRUM_CHI_TENDRIL_REACH, + THRUM_CHI_TENDRIL_RESULT, THRUM_CHI_TENDRIL_INFO}; cJSON *hello = cJSON_CreateObject(); cJSON *propensity; @@ -597,7 +1062,7 @@ static cJSON *hello_for(void) { cJSON_CreateStringArray(chis, (int)(sizeof chis / sizeof chis[0]))); propensity = cJSON_AddObjectToObject(hello, "propensity"); cJSON_AddStringToObject(propensity, "statefulness", "stateless"); - cJSON_AddStringToObject(propensity, "richness", "lean"); + cJSON_AddStringToObject(propensity, "richness", "medium"); cJSON_AddStringToObject(propensity, "wire", WIRE); cJSON_AddItemToObject(hello, "headroom", headroom_of(atomic_load(&g_free_slots))); cJSON_AddStringToObject(hello, "source", SOURCE); @@ -612,19 +1077,19 @@ static void on_nestled(thrum_bee *bee, void *user) { static void on_astray(thrum_bee *bee, void *user) { struct bloom *dropped; + struct bloom *parked; (void)bee; (void)user; pthread_mutex_lock(&g_lock); if (g_current_sid) ds4_bridge_cancel(g_bridge); dropped = g_head; + parked = g_parked; g_head = NULL; g_tail = NULL; + g_parked = NULL; pthread_mutex_unlock(&g_lock); - while (dropped) { - struct bloom *t = dropped; - dropped = t->next; - free_bloom(t); - } + free_blooms(dropped); + free_blooms(parked); fprintf(stderr, "dwarfstar: humd went away; its blooms are dropped and the link is dialing again\n"); } @@ -684,6 +1149,7 @@ int main(void) { if ((env = env_of("DWARFSTAR_TEMPERATURE"))) g_temperature = (float)atof(env); if ((env = env_of("DWARFSTAR_IDLE_MS"))) g_idle_ms = atoll(env); if ((env = env_of("DWARFSTAR_WAIT_MS"))) g_wait_ms = atoll(env); + if ((env = env_of("DWARFSTAR_REACH_MS"))) g_reach_ms = atoll(env); if (find_models(dir) != 0) return 0; if (metal_dir(kernels, sizeof kernels) != 0 || dwarfstar_shaders_point_at(kernels) != 0) { @@ -733,11 +1199,8 @@ int main(void) { pthread_mutex_unlock(&g_lock); pthread_join(blooms, NULL); - while (g_head) { - struct bloom *t = g_head; - g_head = t->next; - free_bloom(t); - } + free_blooms(g_head); + free_blooms(g_parked); thrum_bee_free(g_bee); ds4_bridge_free(g_bridge); gpu_close(g_gpu); diff --git a/hives/dwarfstar/src/models.c b/hives/dwarfstar/src/models.c index 23e5ca85..403f480f 100644 --- a/hives/dwarfstar/src/models.c +++ b/hives/dwarfstar/src/models.c @@ -1,7 +1,3 @@ -/* dwarfstar models: scanning DWARFSTAR_DIR for GGUFs and naming them. - * See models.h. - */ - #define _POSIX_C_SOURCE 200809L #if defined(__APPLE__) #define _DARWIN_C_SOURCE diff --git a/hives/dwarfstar/src/models.h b/hives/dwarfstar/src/models.h index bad4f7ff..5a7f3762 100644 --- a/hives/dwarfstar/src/models.h +++ b/hives/dwarfstar/src/models.h @@ -1,20 +1,3 @@ -/* dwarfstar models: the DwarfStar models on this machine, by id. - * - * The bee looks in DWARFSTAR_DIR and in the gguf/ directory under it, - * follows the symlinks ds4 keeps for its current defaults, and gives each - * model it can serve an id humd routes on: the family (deepseek-v4-flash, - * deepseek-v4.1-flash, glm-5.3-flash, glm-5.3, glm-5.2, qwen3.8-flash-next, - * deepseek-v4-pro), and the family with its quantisation (-q4, -q2, - * -q2-q4, -mxfp4, -fp8) when the file name says which. Vision encoders, - * DSpark support files and split layer pieces are not models. A prompt - * that names no model gets ds4's own default, ds4flash.gguf, when there - * is one, and otherwise the first model found. - * - * A unit that pins its bee to one model uses ds4_models_pin instead: the - * one file, answering to the ids given (comma separated), or to the ids - * its file name earns when none are given. - */ - #ifndef DWARFSTAR_MODELS_H #define DWARFSTAR_MODELS_H diff --git a/hives/dwarfstar/src/shaders.c b/hives/dwarfstar/src/shaders.c index cec45c54..a22256a0 100644 --- a/hives/dwarfstar/src/shaders.c +++ b/hives/dwarfstar/src/shaders.c @@ -1,5 +1,3 @@ -/* dwarfstar shaders: one override per Metal kernel. See shaders.h. */ - #define _POSIX_C_SOURCE 200809L #include "shaders.h" diff --git a/hives/dwarfstar/src/shaders.h b/hives/dwarfstar/src/shaders.h index 0a2269ed..357031fa 100644 --- a/hives/dwarfstar/src/shaders.h +++ b/hives/dwarfstar/src/shaders.h @@ -1,12 +1,3 @@ -/* dwarfstar shaders: point the engine at its Metal kernel sources. - * - * ds4 compiles its Metal kernels at runtime from .metal files, found next - * to the binary or wherever DS4_METAL_*_SOURCE points. The build copies - * them beside the bee, and this sets every override to an absolute path, - * so the bee works from any working directory, as it must when orchd - * starts it. - */ - #ifndef DWARFSTAR_SHADERS_H #define DWARFSTAR_SHADERS_H diff --git a/hives/dwarfstar/tests/conform_with_ds4.c b/hives/dwarfstar/tests/conform_with_ds4.c new file mode 100644 index 00000000..fd26aaef --- /dev/null +++ b/hives/dwarfstar/tests/conform_with_ds4.c @@ -0,0 +1,230 @@ +#include +#include +#include +#include + +#include + +#include "chat.h" +#include "ds4_reference.h" + +typedef struct { + dialect ours; + reference_family theirs; + const char *name; +} family; + +typedef struct { + const char *name; + const char *openai_messages; + bool has_system; +} conversation; + +typedef struct { + family of; + const char *grown; +} sample; + +static const family DEEPSEEK = {DIALECT_DEEPSEEK, RENDERED_AS_DEEPSEEK, "DeepSeek V4"}; +static const family DEEPSEEK41 = {DIALECT_DEEPSEEK41, RENDERED_AS_DEEPSEEK41, "DeepSeek V4.1"}; +static const family GLM = {DIALECT_GLM, RENDERED_AS_GLM, "GLM"}; +static const family QWEN = {DIALECT_QWEN, RENDERED_AS_QWEN, "Qwen"}; + +static const char *const TOOLS = + "[{\"type\":\"function\",\"function\":{\"name\":\"get_weather\",\"description\":\"Current weather for a city\"," + "\"parameters\":{\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"},\"days\":{\"type\":\"integer\"}}," + "\"required\":[\"city\"]}}}," + "{\"type\":\"function\",\"function\":{\"name\":\"bash\",\"description\":\"Run a command\"," + "\"parameters\":{\"type\":\"object\",\"properties\":{\"command\":{\"type\":\"string\"}}}}}]"; + +static const conversation CONVERSATIONS[] = { + {"a question", + "[{\"role\":\"user\",\"content\":\"What is the weather in Oslo?\"}]", false}, + {"a system and a question", + "[{\"role\":\"system\",\"content\":\"Be brief.\"},{\"role\":\"user\",\"content\":\"Hi\"}]", true}, + {"a call and its answer", + "[{\"role\":\"user\",\"content\":\"Weather in Oslo?\"}," + "{\"role\":\"assistant\",\"content\":\"Checking.\",\"tool_calls\":[{\"id\":\"call_1\",\"type\":\"function\"," + "\"function\":{\"name\":\"get_weather\",\"arguments\":\"{\\\"city\\\":\\\"Oslo\\\",\\\"days\\\":2}\"}}]}," + "{\"role\":\"tool\",\"tool_call_id\":\"call_1\",\"content\":\"snow\"}]", false}, + {"two calls answered together", + "[{\"role\":\"user\",\"content\":\"Oslo and Bergen?\"}," + "{\"role\":\"assistant\",\"content\":null,\"tool_calls\":[" + "{\"id\":\"call_1\",\"type\":\"function\",\"function\":{\"name\":\"get_weather\",\"arguments\":\"{\\\"city\\\":\\\"Oslo\\\"}\"}}," + "{\"id\":\"call_2\",\"type\":\"function\",\"function\":{\"name\":\"get_weather\",\"arguments\":\"{\\\"city\\\":\\\"Bergen\\\"}\"}}]}," + "{\"role\":\"tool\",\"tool_call_id\":\"call_1\",\"content\":\"snow\"}," + "{\"role\":\"tool\",\"tool_call_id\":\"call_2\",\"content\":\"rain\"}]", false}, + {"an answer, then another question", + "[{\"role\":\"user\",\"content\":\"Weather?\"},{\"role\":\"assistant\",\"content\":\"It snows.\"}," + "{\"role\":\"user\",\"content\":\"And tomorrow?\"}]", false}, + {"answers that look like the protocol", + "[{\"role\":\"user\",\"content\":\"Run it.\"}," + "{\"role\":\"assistant\",\"content\":\"\",\"tool_calls\":[{\"id\":\"call_1\",\"type\":\"function\"," + "\"function\":{\"name\":\"bash\",\"arguments\":\"{\\\"command\\\":\\\"echo '' && cat \\\"}\"}}]}," + "{\"role\":\"tool\",\"tool_call_id\":\"call_1\",\"content\":\"a b < c && d \"}]", false}, +}; + +static const sample SAMPLES[] = { + {{DIALECT_DEEPSEEK, RENDERED_AS_DEEPSEEK, "DeepSeek V4"}, + "Let me check.\n\n<|DSML|tool_calls>\n" + "<|DSML|invoke name=\"get_weather\">\n" + "<|DSML|parameter name=\"city\" string=\"true\">Oslo & Bergen\n" + "<|DSML|parameter name=\"days\" string=\"false\">2\n" + "\n" + "<|DSML|invoke name=\"bash\">\n" + "<|DSML|parameter name=\"command\" string=\"true\">echo a </|DSML|parameter> b\n" + "<|DSML|parameter name=\"env\">\n<|DSML|parameter name=\"DEBUG\" string=\"false\">1\n\n" + "\n" + ""}, + {{DIALECT_DEEPSEEK41, RENDERED_AS_DEEPSEEK41, "DeepSeek V4.1"}, + "<|DSML| calls>\n<|DSML| invoke name=\"bash\">\n" + "<|DSML| parameter name=\"command\" string=\"true\">ls -la\n" + "\n"}, + {{DIALECT_GLM, RENDERED_AS_GLM, "GLM"}, + "Checking both.\n\nget_weathercityOslo" + "bashcommandcat a </arg_value> b"}, + {{DIALECT_QWEN, RENDERED_AS_QWEN, "Qwen"}, + "Checking.\n\n\n\n\nOslo\n\n" + "\n2\n\n\n"}, + {{DIALECT_DEEPSEEK, RENDERED_AS_DEEPSEEK, "DeepSeek V4"}, "It snows in Oslo."}, + {{DIALECT_GLM, RENDERED_AS_GLM, "GLM"}, "It snows in Oslo."}, + {{DIALECT_QWEN, RENDERED_AS_QWEN, "Qwen"}, "It snows in Oslo."}, +}; + +static int checks; +static int disagreements; + +static const char *string_in(const cJSON *object, const char *key) { + const cJSON *value = cJSON_GetObjectItemCaseSensitive(object, key); + return cJSON_IsString(value) ? value->valuestring : NULL; +} + +static char *system_words_of(const cJSON *messages) { + const cJSON *message; + cJSON_ArrayForEach(message, messages) { + const char *role = string_in(message, "role"); + if (role && strcmp(role, "system") == 0) return strdup(string_in(message, "content")); + } + return NULL; +} + +static void hear_model(chat *c, const cJSON *message) { + turn *spoken = chat_add_turn(c, MODEL_SAYS); + const cJSON *call; + if (string_in(message, "content")) turn_add_words(spoken, string_in(message, "content"), NULL); + cJSON_ArrayForEach(call, cJSON_GetObjectItemCaseSensitive(message, "tool_calls")) { + const cJSON *function = cJSON_GetObjectItemCaseSensitive(call, "function"); + turn_add_tendril(spoken, string_in(call, "id"), string_in(function, "name"), + string_in(function, "arguments")); + } +} + +static chat chat_of(const cJSON *messages) { + chat c = {0}; + const cJSON *message; + cJSON_ArrayForEach(message, messages) { + const char *role = string_in(message, "role"); + if (!role || strcmp(role, "system") == 0) continue; + if (strcmp(role, "assistant") == 0) { + hear_model(&c, message); + } else { + turn *spoken = chat_add_turn(&c, strcmp(role, "tool") == 0 ? TOOL_ANSWERS : USER_SAYS); + turn_add_words(spoken, string_in(message, "content"), NULL); + } + } + return c; +} + +static void report_where_they_part(const char *what, const char *ours, const char *theirs) { + size_t at = 0; + disagreements++; + if (!ours || !theirs) { + fprintf(stderr, "DISAGREE %s: %s rendered nothing\n", what, ours ? "ds4" : "the bee"); + return; + } + while (ours[at] && ours[at] == theirs[at]) at++; + fprintf(stderr, "DISAGREE %s at byte %zu\n bee: %.120s\n ds4: %.120s\n", what, at, + ours + (at > 40 ? at - 40 : 0), theirs + (at > 40 ? at - 40 : 0)); +} + +static bool ds4_orders_system_differently(const family *f, const conversation *talk, bool with_tools) { + return f->ours == DIALECT_DEEPSEEK && talk->has_system && with_tools; +} + +static void prompts_agree(const family *f, const conversation *talk, bool with_tools) { + cJSON *messages = cJSON_Parse(talk->openai_messages); + cJSON *tools = with_tools ? cJSON_Parse(TOOLS) : NULL; + char *system = system_words_of(messages); + chat c = chat_of(messages); + char *ours = chat_as_prompt(f->ours, system, tools, &c); + char *theirs = ds4_server_prompt(f->theirs, talk->openai_messages, with_tools ? TOOLS : NULL); + char what[256]; + + snprintf(what, sizeof what, "%s prompt for %s%s", f->name, talk->name, + with_tools ? ", tools offered" : ""); + checks++; + if (!ours || !theirs || strcmp(ours, theirs) != 0) report_where_they_part(what, ours, theirs); + free(ours); + free(theirs); + free(system); + chat_free(&c); + cJSON_Delete(tools); + cJSON_Delete(messages); +} + +static cJSON *calls_the_bee_reads(dialect d, const char *grown) { + reaching r; + cJSON *calls; + if (!read_tendrils(d, grown, NULL, &r)) return NULL; + calls = cJSON_CreateArray(); + for (size_t i = 0; i < r.count; i++) { + cJSON *call = cJSON_CreateObject(); + cJSON_AddStringToObject(call, "name", r.tendrils[i].name); + cJSON_AddItemToObject(call, "arguments", cJSON_Parse(r.tendrils[i].args_json)); + cJSON_AddItemToArray(calls, call); + } + reaching_free(&r); + return calls; +} + +static void calls_agree(const sample *s) { + cJSON *ours = calls_the_bee_reads(s->of.ours, s->grown); + char *theirs_text = ds4_server_calls(s->of.theirs, s->grown); + cJSON *theirs = theirs_text ? cJSON_Parse(theirs_text) : NULL; + char what[256]; + + snprintf(what, sizeof what, "%s calls read from \"%.30s...\"", s->of.name, s->grown); + checks++; + if ((ours || theirs) && !cJSON_Compare(ours, theirs, true)) { + char *ours_text = ours ? cJSON_PrintUnformatted(ours) : NULL; + disagreements++; + fprintf(stderr, "DISAGREE %s\n bee: %s\n ds4: %s\n", what, ours_text ? ours_text : "none", + theirs_text ? theirs_text : "none"); + cJSON_free(ours_text); + } + cJSON_Delete(ours); + cJSON_Delete(theirs); + free(theirs_text); +} + +int main(void) { + const family *families[] = {&DEEPSEEK, &DEEPSEEK41, &GLM, &QWEN}; + size_t f; + size_t t; + + for (f = 0; f < sizeof families / sizeof families[0]; f++) { + for (t = 0; t < sizeof CONVERSATIONS / sizeof CONVERSATIONS[0]; t++) { + prompts_agree(families[f], &CONVERSATIONS[t], false); + if (!ds4_orders_system_differently(families[f], &CONVERSATIONS[t], true)) { + prompts_agree(families[f], &CONVERSATIONS[t], true); + } + } + } + for (t = 0; t < sizeof SAMPLES / sizeof SAMPLES[0]; t++) calls_agree(&SAMPLES[t]); + if (disagreements) { + fprintf(stderr, "the bee and ds4 part on %d of %d\n", disagreements, checks); + return 1; + } + printf("conform: the bee renders and reads as ds4 does, %d of %d\n", checks, checks); + return 0; +} diff --git a/hives/dwarfstar/tests/ds4_reference.c b/hives/dwarfstar/tests/ds4_reference.c new file mode 100644 index 00000000..fd4d010b --- /dev/null +++ b/hives/dwarfstar/tests/ds4_reference.c @@ -0,0 +1,63 @@ +#define DS4_SERVER_TEST +#define DS4_SERVER_TEST_NO_MAIN +#include "ds4_server.c" + +#include "ds4_reference.h" + +static server_model_syntax syntax_of(reference_family family) { + switch (family) { + case RENDERED_AS_DEEPSEEK41: return SERVER_MODEL_SYNTAX_DEEPSEEK41; + case RENDERED_AS_GLM: return SERVER_MODEL_SYNTAX_GLM; + case RENDERED_AS_QWEN: return SERVER_MODEL_SYNTAX_QWEN; + case RENDERED_AS_DEEPSEEK: break; + } + return SERVER_MODEL_SYNTAX_DEEPSEEK; +} + +char *ds4_server_prompt(reference_family family, const char *openai_messages, + const char *openai_tools) { + const char *messages_at = openai_messages; + const char *tools_at = openai_tools; + chat_msgs msgs = {0}; + tool_schema_orders orders = {0}; + char *schemas = NULL; + char *prompt = NULL; + + if (parse_messages(&messages_at, &msgs) && + (!openai_tools || parse_tools_value(&tools_at, &schemas, &orders))) { + prompt = render_chat_prompt_text_for_syntax(syntax_of(family), &msgs, schemas, &orders, + DS4_THINK_NONE); + } + chat_msgs_free(&msgs); + tool_schema_orders_free(&orders); + free(schemas); + return prompt; +} + +char *ds4_server_calls(reference_family family, const char *grown) { + tool_calls calls = {0}; + char *words = NULL; + char *reasoning = NULL; + buf listed = {0}; + bool read = parse_generated_message_ex_for_syntax(syntax_of(family), grown, false, &words, + &reasoning, &calls); + + free(words); + free(reasoning); + if (!read || calls.len == 0) { + tool_calls_free(&calls); + return NULL; + } + buf_putc(&listed, '['); + for (int i = 0; i < calls.len; i++) { + if (i > 0) buf_putc(&listed, ','); + buf_puts(&listed, "{\"name\":"); + json_escape(&listed, calls.v[i].name); + buf_puts(&listed, ",\"arguments\":"); + buf_puts(&listed, calls.v[i].arguments ? calls.v[i].arguments : "null"); + buf_putc(&listed, '}'); + } + buf_putc(&listed, ']'); + tool_calls_free(&calls); + return buf_take(&listed); +} diff --git a/hives/dwarfstar/tests/ds4_reference.h b/hives/dwarfstar/tests/ds4_reference.h new file mode 100644 index 00000000..e94c1ac8 --- /dev/null +++ b/hives/dwarfstar/tests/ds4_reference.h @@ -0,0 +1,16 @@ +#ifndef DWARFSTAR_DS4_REFERENCE_H +#define DWARFSTAR_DS4_REFERENCE_H + +typedef enum { + RENDERED_AS_DEEPSEEK, + RENDERED_AS_DEEPSEEK41, + RENDERED_AS_GLM, + RENDERED_AS_QWEN, +} reference_family; + +char *ds4_server_prompt(reference_family family, const char *openai_messages, + const char *openai_tools); + +char *ds4_server_calls(reference_family family, const char *grown); + +#endif diff --git a/hives/dwarfstar/tests/test_chat.c b/hives/dwarfstar/tests/test_chat.c new file mode 100644 index 00000000..271628bf --- /dev/null +++ b/hives/dwarfstar/tests/test_chat.c @@ -0,0 +1,329 @@ +#include +#include +#include +#include + +#include "chat.h" + +static int failures; + +static void expect(bool ok, const char *what, int line) { + if (ok) return; + failures++; + fprintf(stderr, "test_chat.c:%d: expected %s\n", line, what); +} + +static void expect_same(const char *got, const char *want, int line) { + if (got && strcmp(got, want) == 0) return; + failures++; + fprintf(stderr, "test_chat.c:%d: got\n---\n%s\n---\nwanted\n---\n%s\n---\n", line, + got ? got : "(null)", want); +} + +static void expect_ends_with(const char *got, const char *tail, int line) { + size_t n = got ? strlen(got) : 0; + size_t k = strlen(tail); + if (got && n >= k && strcmp(got + n - k, tail) == 0) return; + failures++; + fprintf(stderr, "test_chat.c:%d: got\n---\n%s\n---\nwhich does not end with\n---\n%s\n---\n", + line, got ? got : "(null)", tail); +} + +static bool starts_with(const char *text, const char *prefix) { + return text && strncmp(text, prefix, strlen(prefix)) == 0; +} + +#define EXPECT(condition) expect((condition), #condition, __LINE__) +#define EXPECT_SAME(got, want) expect_same((got), (want), __LINE__) +#define EXPECT_ENDS_WITH(got, tail) expect_ends_with((got), (tail), __LINE__) + +static const char *const WEATHER_TOOL = + "[{\"name\":\"weather\",\"description\":\"what the sky does\"," + "\"inputSchema\":{\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"}," + "\"days\":{\"type\":\"integer\"}}}}]"; + +static void say(chat *c, speaker by, const char *words) { + turn_add_words(chat_add_turn(c, by), words, NULL); +} + +static void ask_weather_and_hear_snow(chat *c) { + turn *checking; + say(c, USER_SAYS, "weather in oslo?"); + checking = chat_add_turn(c, MODEL_SAYS); + turn_add_words(checking, "checking", NULL); + turn_add_tendril(checking, "call_1", "weather", "{\"city\":\"Oslo\",\"days\":2}"); + say(c, TOOL_ANSWERS, "snow"); +} + +static void deepseek_offers_tools_after_the_system_words(void) { + cJSON *tools = cJSON_Parse(WEATHER_TOOL); + chat c = {0}; + char *prompt; + + say(&c, USER_SAYS, "hi"); + prompt = chat_as_prompt(DIALECT_DEEPSEEK, "be brief", tools, &c); + EXPECT(starts_with(prompt, "<|begin▁of▁sentence|>be brief\n\n## Tools\n\nYou have access")); + EXPECT(strstr(prompt, "### Available Tool Schemas\n\n" + "{\"name\":\"weather\",\"description\":\"what the sky does\"," + "\"parameters\":{\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"}," + "\"days\":{\"type\":\"integer\"}}}}\n\nYou MUST strictly follow") != NULL); + EXPECT_ENDS_WITH(prompt, "Use the exact parameter names from the schemas." + "<|User|>hi<|Assistant|>"); + free(prompt); + chat_free(&c); + cJSON_Delete(tools); +} + +static void deepseek_renders_a_graft_tendril_and_grows_on_from_its_answer(void) { + chat c = {0}; + char *prompt; + + ask_weather_and_hear_snow(&c); + prompt = chat_as_prompt(DIALECT_DEEPSEEK, NULL, NULL, &c); + EXPECT_SAME(prompt, + "<|begin▁of▁sentence|><|User|>weather in oslo?<|Assistant|>checking\n\n" + "<|DSML|tool_calls>\n" + "<|DSML|invoke name=\"weather\">\n" + "<|DSML|parameter name=\"city\" string=\"true\">Oslo\n" + "<|DSML|parameter name=\"days\" string=\"false\">2\n" + "\n" + "<|end▁of▁sentence|>" + "<|User|>snow<|Assistant|>"); + free(prompt); + chat_free(&c); +} + +static void deepseek_renders_sampled_tendrils_as_they_were_grown(void) { + chat c = {0}; + turn *checking; + char *prompt; + + say(&c, USER_SAYS, "q"); + checking = chat_add_turn(&c, MODEL_SAYS); + turn_add_tendril(checking, "call_1", "weather", "{\"city\":\"Oslo\"}"); + checking->tendrils_as_sampled = strdup("\n\n<|DSML|tool_calls>AS GROWN"); + say(&c, TOOL_ANSWERS, "a < b && c"); + prompt = chat_as_prompt(DIALECT_DEEPSEEK, NULL, NULL, &c); + EXPECT_SAME(prompt, "<|begin▁of▁sentence|><|User|>q<|Assistant|>\n\n" + "<|DSML|tool_calls>AS GROWN<|end▁of▁sentence|>" + "<|User|>a < b && c<|Assistant|>"); + free(prompt); + chat_free(&c); +} + +static void deepseek41_keeps_answers_in_one_user_turn(void) { + chat c = {0}; + turn *checking; + char *prompt; + + say(&c, USER_SAYS, "q"); + checking = chat_add_turn(&c, MODEL_SAYS); + turn_add_tendril(checking, "call_1", "a", "{}"); + turn_add_tendril(checking, "call_2", "b", "{}"); + say(&c, TOOL_ANSWERS, "one"); + say(&c, TOOL_ANSWERS, "two"); + prompt = chat_as_prompt(DIALECT_DEEPSEEK41, "sys", NULL, &c); + EXPECT_SAME(prompt, "<|begin▁of▁sentence|><|System|>sys<|User|>q<|Assistant|>\n\n" + "<|DSML| calls>\n" + "<|DSML| invoke name=\"a\">\n\n" + "<|DSML| invoke name=\"b\">\n\n" + "<|end▁of▁sentence|>" + "<|User|>one\n\ntwo" + "<|Assistant|>"); + free(prompt); + chat_free(&c); +} + +static void deepseek41_puts_tools_and_system_in_one_system_turn(void) { + cJSON *tools = cJSON_Parse(WEATHER_TOOL); + chat c = {0}; + char *prompt; + + say(&c, USER_SAYS, "hi"); + prompt = chat_as_prompt(DIALECT_DEEPSEEK41, "sys", tools, &c); + EXPECT(starts_with(prompt, "<|begin▁of▁sentence|><|System|>## Tools\n\nYou can invoke tools")); + EXPECT_ENDS_WITH(prompt, "from the schemas.\n\nsys<|User|>hi<|Assistant|>"); + free(prompt); + chat_free(&c); + cJSON_Delete(tools); +} + +static void glm_renders_tendrils_inline_and_answers_as_observations(void) { + chat c = {0}; + char *prompt; + + ask_weather_and_hear_snow(&c); + prompt = chat_as_prompt(DIALECT_GLM, "sys", NULL, &c); + EXPECT_SAME(prompt, "[gMASK]<|system|>sys<|user|>weather in oslo?" + "<|assistant|>checking" + "weathercityOslo" + "days2" + "<|observation|>snow" + "<|assistant|>"); + free(prompt); + chat_free(&c); +} + +static void glm_lists_tools_spaced_in_a_system_turn(void) { + cJSON *tools = cJSON_Parse(WEATHER_TOOL); + chat c = {0}; + char *prompt; + + say(&c, USER_SAYS, "hi"); + prompt = chat_as_prompt(DIALECT_GLM, NULL, tools, &c); + EXPECT(starts_with(prompt, "[gMASK]<|system|>\n# Tools\n\n")); + EXPECT(strstr(prompt, "\n\n{\"name\": \"weather\", \"description\": \"what the sky does\", " + "\"parameters\": {\"type\":\"object\",") != NULL); + EXPECT_ENDS_WITH(prompt, "...<|user|>hi<|assistant|>"); + free(prompt); + chat_free(&c); +} + +static void qwen_renders_its_chatml_with_tool_responses(void) { + chat c = {0}; + char *prompt; + + ask_weather_and_hear_snow(&c); + prompt = chat_as_prompt(DIALECT_QWEN, "sys", NULL, &c); + EXPECT_SAME(prompt, "<|im_start|>system\nsys<|im_end|>\n" + "<|im_start|>user\nweather in oslo?<|im_end|>\n" + "<|im_start|>assistant\n\n\n\n\nchecking\n\n" + "\n\n" + "\nOslo\n\n" + "\n2\n\n" + "\n<|im_end|>\n" + "<|im_start|>user\n\nsnow\n<|im_end|>\n" + "<|im_start|>assistant\n\n\n\n\n"); + free(prompt); + chat_free(&c); +} + +static void a_dsml_block_is_read_into_tendrils(void) { + const char *grown = + "let me look\n\n<|DSML|tool_calls>\n" + "<|DSML|invoke name=\"weather\">\n" + "<|DSML|parameter name=\"city\" string=\"true\">Oslo & Bergen\n" + "<|DSML|parameter name=\"days\" string=\"false\">2\n" + "\n" + "<|DSML|invoke name=\"clock\">\n" + "\n" + ""; + reaching r; + + EXPECT(read_tendrils(DIALECT_DEEPSEEK, grown, NULL, &r)); + EXPECT(r.count == 2); + EXPECT(r.words_end == strlen("let me look")); + EXPECT(r.tendrils_start == strlen("let me look")); + EXPECT(r.tendrils_end == strlen(grown)); + EXPECT_SAME(r.tendrils[0].name, "weather"); + EXPECT_SAME(r.tendrils[0].args_json, "{\"city\":\"Oslo & Bergen\",\"days\":2}"); + EXPECT_SAME(r.tendrils[1].name, "clock"); + EXPECT_SAME(r.tendrils[1].args_json, "{}"); + reaching_free(&r); +} + +static void a_dsml_closing_tag_inside_a_string_survives_the_round_trip(void) { + chat c = {0}; + turn *writing = NULL; + char *prompt; + const char *block; + reaching r; + + say(&c, USER_SAYS, "q"); + writing = chat_add_turn(&c, MODEL_SAYS); + turn_add_tendril(writing, "call_1", "write", + "{\"text\":\"a b </|DSML|parameter> c\"}"); + prompt = chat_as_prompt(DIALECT_DEEPSEEK, NULL, NULL, &c); + block = strstr(prompt, ""); + EXPECT(block != NULL); + EXPECT(read_tendrils(DIALECT_DEEPSEEK, block ? block + strlen("") : "", NULL, &r)); + EXPECT(r.count == 1); + if (r.count == 1) { + EXPECT_SAME(r.tendrils[0].args_json, + "{\"text\":\"a b </|DSML|parameter> c\"}"); + } + reaching_free(&r); + free(prompt); + chat_free(&c); +} + +static void a_dsml41_block_is_read_into_tendrils(void) { + const char *grown = "<|DSML| calls>\n<|DSML| invoke name=\"bash\">\n" + "<|DSML| parameter name=\"command\" string=\"true\">ls -la\n" + "\n"; + reaching r; + + EXPECT(read_tendrils(DIALECT_DEEPSEEK41, grown, NULL, &r)); + EXPECT(r.count == 1 && r.words_end == 0); + if (r.count == 1) { + EXPECT_SAME(r.tendrils[0].name, "bash"); + EXPECT_SAME(r.tendrils[0].args_json, "{\"command\":\"ls -la\"}"); + } + reaching_free(&r); +} + +static void glm_arguments_follow_the_schema_types(void) { + cJSON *tools = cJSON_Parse(WEATHER_TOOL); + const char *grown = "sure\n\nweathercity2" + "days2"; + reaching r; + + EXPECT(read_tendrils(DIALECT_GLM, grown, tools, &r)); + EXPECT(r.count == 1 && r.words_end == strlen("sure") && r.tendrils_start == strlen("sure")); + if (r.count == 1) EXPECT_SAME(r.tendrils[0].args_json, "{\"city\":\"2\",\"days\":2}"); + reaching_free(&r); + cJSON_Delete(tools); +} + +static void qwen_parameters_lose_their_framing_newlines(void) { + const char *grown = "\n\n\n\n\nOslo\n\n" + "\n2\n\n\n"; + reaching r; + + EXPECT(read_tendrils(DIALECT_QWEN, grown, NULL, &r)); + EXPECT(r.count == 1 && r.words_end == 0); + if (r.count == 1) EXPECT_SAME(r.tendrils[0].args_json, "{\"city\":\"Oslo\",\"days\":2}"); + reaching_free(&r); +} + +static void a_block_cut_off_is_only_words(void) { + reaching r; + EXPECT(!read_tendrils(DIALECT_DEEPSEEK, "x <|DSML|tool_calls>\n<|DSML|invoke name=\"a\">", NULL, &r)); + EXPECT(r.count == 0 && r.tendrils == NULL); + EXPECT(!read_tendrils(DIALECT_GLM, "ak", NULL, &r)); + EXPECT(!read_tendrils(DIALECT_QWEN, "plain words", NULL, &r)); +} + +static void words_are_shown_until_a_tendril_might_begin(void) { + bool began = false; + EXPECT(words_safe_to_show("hello wor", &began) == 9 && !began); + EXPECT(words_safe_to_show("hello ", &began) == 5 && !began); + EXPECT(words_safe_to_show("hello <|DS", &began) == 5 && !began); + EXPECT(words_safe_to_show("x \n