Skip to content

Gemma 4 26B-A4B inference in ~2 GB of RAM on any M-series MacBook

Give every adapted object tool-schema node an explicit properties mapping (#142)

Andrey Mikhaylov972226a2b3ce
diff --git a/Sources/TurboFieldfare/Tokenization/Tokenizer.swift b/Sources/TurboFieldfare/Tokenization/Tokenizer.swift
index ac845f26..e0f51272 100644
--- a/Sources/TurboFieldfare/Tokenization/Tokenizer.swift
+++ b/Sources/TurboFieldfare/Tokenization/Tokenizer.swift
@@ -400,12 +400,21 @@ public struct GFTokenizer: @unchecked Sendable {
}
let callStart = starts[starts.count - callCount]
let callSequence = Array(prefix[callStart...callEnd])
- let matches = full.subsequenceStartIndices(matching: callSequence)
- guard matches.count == 1 else {
- throw GFTokenizerError.invalidChatTemplate(
- "cached assistant tool-call boundary is ambiguous")
+ // A verbatim-repeated call renders an identical token sequence, so
+ // requiring a unique match dropped the cache for the rest of the
+ // conversation. The boundary is positional whenever both renders agree
+ // through the call block; otherwise only a unique match is trusted.
+ let suffixStart: Int
+ if full.count > callEnd, full[...callEnd] == prefix[...callEnd] {
+ suffixStart = callEnd + 1
+ } else {
+ let matches = full.subsequenceStartIndices(matching: callSequence)
+ guard matches.count == 1 else {
+ throw GFTokenizerError.invalidChatTemplate(
+ "cached assistant tool-call boundary is ambiguous")
+ }
+ suffixStart = matches[0] + callSequence.count
}
- let suffixStart = matches[0] + callSequence.count
let suffix = Array(full[suffixStart...])
guard suffix.first == toolResponseID else {
throw GFTokenizerError.invalidChatTemplate(
diff --git a/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift b/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift
index 7bd348f2..1ce8faf0 100644
--- a/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift
+++ b/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift
@@ -17,7 +17,7 @@ public enum AboutPanelPresentation {
// Most users build from a clone, where there is no Info.plist to read a
// version from, so this constant is what they see. Scripts/check_app_version.rb
// fails CI when it falls behind the newest published release.
- public static let fallbackShortVersion = "0.4.5"
+ public static let fallbackShortVersion = "0.4.6"
private static let licenseURL = URL(
string: "https://github.com/drumih/turbo-fieldfare/blob/main/LICENSE")!
diff --git a/Sources/TurboFieldfareServer/Core/GemmaToolSchema.swift b/Sources/TurboFieldfareServer/Core/GemmaToolSchema.swift
index 590f04dd..7281cc45 100644
--- a/Sources/TurboFieldfareServer/Core/GemmaToolSchema.swift
+++ b/Sources/TurboFieldfareServer/Core/GemmaToolSchema.swift
@@ -58,6 +58,15 @@ enum GemmaToolSchema {
}
object["properties"] = .object(adapted)
}
+ if type == "object", object["properties"] == nil {
+ // The chat template routes an object node without `properties`
+ // through a branch that iterates the node's own keys as if they
+ // were property schemas; preserved keywords such as
+ // `additionalProperties` or `default` then crash the `upper`
+ // filter. An explicit empty mapping selects the safe branch and
+ // renders identically (`properties:{}`).
+ object["properties"] = .object([:])
+ }
if let items = object["items"] {
guard type == "array" else {
diff --git a/Tests/TurboFieldfareServer/Fixtures/README.md b/Tests/TurboFieldfareServer/Fixtures/README.md
index 40b34c2b..d0f96f54 100644
--- a/Tests/TurboFieldfareServer/Fixtures/README.md
+++ b/Tests/TurboFieldfareServer/Fixtures/README.md
@@ -1,4 +1,6 @@
-# OpenCode request fixtures
+# Client request fixtures
+
+## OpenCode
Sanitized request bodies captured on 2026-07-23 from `[email protected]`.
That source release pins `ai` 6.0.168,
@@ -8,5 +10,21 @@ That source release pins `ai` 6.0.168,
- `opencode-1.15.11-tool-result.json`: 12,153-byte follow-up containing the
fake server's assistant `read` call and OpenCode's tool result.
+## DeepSeek Harness
+
+Sanitized request bodies captured on 2026-08-21 from
+`@deepseek-ai/[email protected]` (headless profile, Node v24.19.0) driven against
+the compatibility harness through a logging proxy. dsh's LLM layer is
+`@earendil-works/pi-ai` over `openai-completions`.
+
+- `dsh-0.1.1-rc.1-initial.json`: initial streamed agent request with all 25
+ default tools. The `workflow` tool's `args` parameter is a bare
+ `{type: object}` node carrying `additionalProperties` — the schema shape
+ that crashed chat-template rendering (PR 138).
+- `dsh-0.1.1-rc.1-tool-result.json`: follow-up containing the fake server's
+ assistant `bash` call and dsh's tool result.
+
+The workspace path is sanitized to `/tmp/dsh-workspace`.
+
Temporary paths and call IDs are deterministic and sanitized. The fixtures
contain no credentials or user repository content.
diff --git a/Tests/TurboFieldfareServer/Fixtures/dsh-0.1.1-rc.1-initial.json b/Tests/TurboFieldfareServer/Fixtures/dsh-0.1.1-rc.1-initial.json
new file mode 100644
index 00000000..b1b4b438
--- /dev/null
+++ b/Tests/TurboFieldfareServer/Fixtures/dsh-0.1.1-rc.1-initial.json
@@ -0,0 +1,792 @@
+{
+ "model": "gemma-4-26b-a4b-it",
+ "messages": [
+ {
+ "role": "system",
+ "content": "You are an AI agent powered by DeepSeek Harness.\n\nYou are a coding agent powered by the gemma-4-26b-a4b-it model. Your working directory is /tmp/dsh-workspace.\n\nUse the read tool \u2014 not shell commands like cat \u2014 to inspect text files. Results include line numbers. Use offset and limit to continue reading large files.\n\nUse the write tool to create files or completely replace file contents. Existing files are overwritten, so read an existing file first (the default fs-observation-policy requires it) and prefer edit for targeted changes.\n\nUse the edit tool for targeted changes to existing UTF-8 text files. It replaces literal old_string with new_string; by default old_string must appear exactly once. If old_string appears multiple times, provide a more specific old_string or set replace_all to true. Read the file first (the default fs-observation-policy requires it), unless you just created or edited it in this session.\n\nUse the glob tool \u2014 not shell find \u2014 to discover files by path pattern. A pattern with no \"/\" matches basenames at any depth, so \"*\" matches every file in the tree rather than its top level. Results are files only, never directories, and include hidden and ignored files: a result that fits comes back in modification-time order, while a larger one keeps the modification-time-ordered head.\n\nUse the grep tool \u2014 not shell grep or rg \u2014 to search file contents. Use read on a matched file when you need surrounding context.\n\nCheck the [exit code: N] marker on every bash result; investigate failures before moving on.\n\nTrack every background job id you start. You are notified in-session when a job finishes \u2014 do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running job's work. Before giving a final answer, collect every still-relevant job with job_output (set wait: true only when you are genuinely blocked on it), and job_kill jobs that stopped mattering.\n\nUse the web_search tool to discover current information on the web. The required queries array accepts 1\u20134 non-empty search queries; use a one-item array for a single search. It returns an optional answer plus a list of source URLs. Use the returned source snippets when available, and cite the relevant URLs as markdown links.\n\nUse goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked.\n\nUse the workflow tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls.\n\nUse the ralph tool ONLY when the direct human explicitly asks for a Ralph loop or fresh-agent iterative execution. Each Ralph round starts a fresh child with no conversation seed and uses the shared workspace as durable memory. Completion and blockers are worker reports, not independent evaluation. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out.\n\nUse subagent in the background by default. Start independent delegations together in one assistant message and continue useful work while they run. Set `run_in_background: false` only when your next action depends on that subagent's result. When a background run settles, the runtime sends you a notice containing its outcome and any final assistant message."
+ },
+ {
+ "role": "user",
+ "content": "say hello"
+ },
+ {
+ "role": "user",
+ "content": "Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"/tmp/dsh-workspace\". Some platform temporary areas may also be writable.\n\nApproval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."
+ }
+ ],
+ "stream": true,
+ "stream_options": {
+ "include_usage": true
+ },
+ "store": false,
+ "max_completion_tokens": 32768,
+ "tools": [
+ {
+ "type": "function",
+ "function": {
+ "name": "bash",
+ "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls \u2014 pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]` \u2014 a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a job id immediately; read its output with `job_output` and stop it with `job_kill`. Attempting a command the sandbox may deny is safe and expected: run it and read the marker rather than assuming the denial. When a command is denied and a wider mode would let it succeed, escalate immediately in the same turn \u2014 the one sanctioned exception to a denial: retry the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a one-sentence `justification`. Do not detour through chat to ask permission first \u2014 the approval prompt raised by that retry is how the user consents. If the session states approval prompts are disabled, there is no exception: a denial is final \u2014 do not set `sandbox_permissions`. Never escalate speculatively: ground the request in a real denial \u2014 normally the one this command just hit; escalating up front is fine only when this session already denied the same access. A rejected escalation is final for that command \u2014 stop and explain, never work around it \u2014 but it does not forbid attempting or escalating other commands later.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "command": {
+ "type": "string",
+ "description": "The bash command to execute."
+ },
+ "description": {
+ "type": "string",
+ "description": "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" \u2192 \"List files in current directory\"; \"git status\" \u2192 \"Show working tree status\"; \"npm install\" \u2192 \"Install package dependencies\"."
+ },
+ "timeoutMs": {
+ "type": "number",
+ "description": "Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry."
+ },
+ "workdir": {
+ "type": "string",
+ "description": "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it."
+ },
+ "run_in_background": {
+ "type": "boolean",
+ "description": "Run in the background and return a job id immediately (collect with job_output, stop with job_kill). No timeout applies."
+ },
+ "sandbox_permissions": {
+ "type": "string",
+ "description": "The wider sandbox mode this command needs. Only valid as a one-shot retry of a command the sandbox just denied; requires justification and user approval.",
+ "enum": [
+ "workspace-write",
+ "danger-full-access"
+ ]
+ },
+ "justification": {
+ "type": "string",
+ "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access."
+ }
+ },
+ "required": [
+ "command",
+ "description"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "create_goal",
+ "description": "Create one persisted same-session completion goal when the current direct human request is a long-running objective that should continue across autonomous goal rounds. You may infer that intent without requiring the user to say \"create a goal\". Do not use this for trivial single-turn work. Execution rejects non-human and subagent authority.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "objective": {
+ "type": "string",
+ "description": "The concrete completion objective inferred from the direct human request."
+ },
+ "max_goal_rounds": {
+ "type": "number",
+ "description": "Optional positive safe-integer limit on automatic continuation rounds."
+ }
+ },
+ "required": [
+ "objective"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "edit",
+ "description": "Edit an existing UTF-8 text file by replacing literal text.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "file_path": {
+ "type": "string",
+ "description": "Path to edit, resolved by the filesystem backend."
+ },
+ "old_string": {
+ "type": "string",
+ "description": "Literal text to replace. Must match exactly."
+ },
+ "new_string": {
+ "type": "string",
+ "description": "Literal replacement text. Use an empty string to delete the match."
+ },
+ "replace_all": {
+ "type": "boolean",
+ "description": "Replace all matches. Defaults to false; when false, old_string must appear exactly once."
+ },
+ "sandbox_permissions": {
+ "type": "string",
+ "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.",
+ "enum": [
+ "workspace-write",
+ "danger-full-access"
+ ]
+ },
+ "justification": {
+ "type": "string",
+ "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access."
+ }
+ },
+ "required": [
+ "file_path",
+ "old_string",
+ "new_string"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "exit_plan_mode",
+ "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. Send the COMPLETE plan as markdown, starting with a # heading that names it. The user may approve (carry out the plan from your next step) or keep planning \u2014 their feedback comes back in the tool result; revise and present again.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "plan": {
+ "type": "string",
+ "description": "The complete plan, as markdown, starting with a # heading that names it."
+ }
+ },
+ "required": [
+ "plan"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "get_goal",
+ "description": "Read the current same-session goal, including its exact id/revision, objective, phase, completed continuation rounds, round limit, blocker reason when present, and whether another continuation is armed. Call this before updating a goal.",
+ "parameters": {
+ "type": "object",
+ "properties": {}
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "glob",
+ "description": "Find files whose paths match a glob pattern. Returns matching file paths \u2014 never directories \u2014 including hidden and ignored files (VCS metadata directories are excluded). Up to 100 paths come back in modification-time order; a larger result returns the first 100 paths in modification-time order, says so, and reports where the complete sorted list was saved. This tool does not enumerate directory entries.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "pattern": {
+ "type": "string",
+ "description": "Glob pattern to match file paths against (e.g. \"**/*.ts\", \"src/**/*.test.js\"). A pattern with no \"/\" matches the basename at any depth, so \"*\" and \"*.ts\" both search the whole tree; include a separator to anchor the depth."
+ },
+ "path": {
+ "type": "string",
+ "description": "Directory to search in. Defaults to the session workspace; a relative path resolves against it."
+ }
+ },
+ "required": [
+ "pattern"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "grep",
+ "description": "Search file contents with a ripgrep regular expression. Returns matching lines with line numbers, grouped by file. Returns the first 250 matches inline; a capped result reports where the complete match list was saved. Use read on a matched file for surrounding context.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "pattern": {
+ "type": "string",
+ "description": "Regular expression to search for (ripgrep syntax)."
+ },
+ "path": {
+ "type": "string",
+ "description": "File or directory to search. Defaults to the session workspace; a relative path resolves against it."
+ },
+ "include": {
+ "type": "string",
+ "description": "One glob filter for which files to search (e.g. \"*.ts\", \"*.{js,jsx}\"). Not a list; negation is not supported."
+ }
+ },
+ "required": [
+ "pattern"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "interrupt_agent",
+ "description": "Request cancellation of a background agent's current turn by its agent id. The target may be your direct child or a deeper agent created under you. Only the current turn stops: messages already queued for the agent stay parked until a later send_message, agents it started keep running, and the agent itself stays available for follow-ups. This call returns as soon as the stop request is accepted, so the target may keep running briefly; interrupting an agent that already finished is an accepted no-op.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "agent_id": {
+ "type": "string",
+ "description": "The agent id of the running agent to interrupt."
+ }
+ },
+ "required": [
+ "agent_id"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "job_kill",
+ "description": "Request cancellation of a running background job by job id. Returns immediately; the job settles as killed once its work actually stops.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "job_id": {
+ "type": "string",
+ "description": "Job id returned by the tool that started the background work."
+ },
+ "reason": {
+ "type": "string",
+ "description": "Optional short reason, recorded in the log and forwarded to the job."
+ }
+ },
+ "required": [
+ "job_id"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "job_list",
+ "description": "List your background jobs (running and finished) with their ids, kinds, and statuses.",
+ "parameters": {
+ "type": "object",
+ "properties": {}
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "job_output",
+ "description": "Read a background job. Stream jobs return only output since the previous read; final-output jobs return their result after settlement. Every response ends with `[status: ...]`. Reads are non-blocking unless `wait: true`, which waits up to the configured cap.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "job_id": {
+ "type": "string",
+ "description": "Job id returned by the tool that started the background work."
+ },
+ "wait": {
+ "type": "boolean",
+ "description": "Block until the job reaches a terminal status or the timeout expires. A timed-out wait returns [status: running] and leaves the job alive."
+ },
+ "timeout_ms": {
+ "type": "number",
+ "description": "Max wait in milliseconds (only meaningful with wait: true). Defaults to the configured wait timeout; capped by the configured maximum."
+ }
+ },
+ "required": [
+ "job_id"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "list_agents",
+ "description": "List your continuable background subagents by durable id and label. Use it to recall which ones you started, not to poll for completion \u2014 you are told when one finishes. Status comes from the live registry: running means the agent is working right now, idle means it is loaded but between turns (it may be waiting on agents it started), and ready means it exists only in storage \u2014 resumable, not terminal, and not a result waiting to be collected; a `send_message` starts a new turn on the same conversation, and a direct child remains a `send_message` candidate in every status. The snapshot is not a delivery promise \u2014 `send_message` performs the authoritative check and may still fail. Children that could not be read are reported as diagnostics instead of being silently dropped. Scope `descendants` walks the whole tree below you in stable pre-order, annotating each entry with its durable direct-parent session id and depth. You may use `send_message` only for depth-1 entries; deeper entries are candidates for `interrupt_agent` only.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "scope": {
+ "type": "string",
+ "description": "children (default) lists direct children only; descendants walks the complete tree below you.",
+ "enum": [
+ "children",
+ "descendants"
+ ]
+ }
+ }
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "ralph",
+ "description": "Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns when a worker reports completion or a concrete blocker, or at the round limit. Ordinary long-running same-session work belongs to goal tools.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "objective": {
+ "type": "string",
+ "description": "The immutable completion objective for every fresh Ralph round."
+ },
+ "maxRounds": {
+ "type": "number",
+ "description": "Optional positive safe-integer round cap, bounded by the deployment ceiling."
+ }
+ },
+ "required": [
+ "objective"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "read",
+ "description": "Read a UTF-8 text file and return line-numbered content.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "file_path": {
+ "type": "string",
+ "description": "Path to read, resolved by the filesystem backend."
+ },
+ "offset": {
+ "type": "number",
+ "description": "1-based first line to return. Defaults to 1."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Maximum number of lines to return. Defaults to 2000."
+ }
+ },
+ "required": [
+ "file_path"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "read_image",
+ "description": "Read a PNG/JPEG/WebP/GIF file and return the image itself. Requires the current model to accept image input.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "file_path": {
+ "type": "string",
+ "description": "Path to the image file, resolved by the filesystem backend."
+ }
+ },
+ "required": [
+ "file_path"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "send_message",
+ "description": "Send a message to a background subagent by its subagent id, continuing the same conversation. It becomes the subagent's next turn: if it is still working, the message waits until its current turn finishes, so it cannot redirect work already underway. This call returns no answer from the subagent \u2014 only confirmation that the message was delivered \u2014 so use it to give it more work. A failure means the message was NOT delivered.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "subagent_id": {
+ "type": "string",
+ "description": "The subagent id returned when the background subagent was started."
+ },
+ "message": {
+ "type": "string",
+ "description": "The message to deliver to the subagent."
+ }
+ },
+ "required": [
+ "subagent_id",
+ "message"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "skill",
+ "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "The exact skill name from the available skills list."
+ }
+ },
+ "required": [
+ "name"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "str_replace_editor",
+ "description": "Custom editing tool for viewing, creating and editing files\n* State is persistent across command calls and discussions with the user\n* If `path` is a file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep\n* The `create` command cannot be used if the specified `path` already exists as a file\n* If a `command` generates a long output, it will be truncated and marked with `<response clipped>`\n\nNotes for using the `str_replace` command:\n* The `old_str` parameter should match EXACTLY one or more consecutive lines from the original file. Be mindful of whitespaces!\n* If the `old_str` parameter is not unique in the file, the replacement will not be performed. Make sure to include enough context in `old_str` to make it unique\n* The `new_str` parameter should contain the edited lines that should replace the `old_str`",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "command": {
+ "type": "string",
+ "description": "The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`.",
+ "enum": [
+ "view",
+ "create",
+ "str_replace",
+ "insert"
+ ]
+ },
+ "path": {
+ "type": "string",
+ "description": "Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`."
+ },
+ "file_text": {
+ "type": "string",
+ "description": "Required parameter of `create` command, with the content of the file to be created."
+ },
+ "insert_line": {
+ "type": "integer",
+ "description": "Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`."
+ },
+ "new_str": {
+ "type": "string",
+ "description": "Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert."
+ },
+ "old_str": {
+ "type": "string",
+ "description": "Required parameter of `str_replace` command containing the string in `path` to replace."
+ },
+ "view_range": {
+ "type": "array",
+ "description": "Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.",
+ "items": {
+ "type": "integer"
+ }
+ }
+ },
+ "required": [
+ "command",
+ "path"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "subagent",
+ "description": "Delegate a self-contained task to a subagent (a separate agent that works in its own context) to offload focused, independent work \u2014 research, a scoped implementation, an analysis \u2014 so it does not consume this conversation's context. The subagent returns its result, not its intermediate steps. Give it a complete, standalone prompt: it does not see this conversation. This tool runs in the background by default, immediately returns a durable subagent id, and keeps the child conversation available for later turns. When that run settles, the runtime sends the parent a notice containing its outcome and any final assistant message; `send_message` starts a later turn in the same child conversation. Set `run_in_background: false` only when your next action depends on receiving the result.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "description": {
+ "type": "string",
+ "description": "A short (3-5 word) description of the delegated task, for display."
+ },
+ "prompt": {
+ "type": "string",
+ "description": "The complete, self-contained task for the subagent. It does not share this conversation's context, so include everything it needs."
+ },
+ "run_in_background": {
+ "type": "boolean",
+ "description": "Whether to run in the background and return a durable subagent id immediately. Defaults to true. Set false to wait for the result when your next action depends on it."
+ }
+ },
+ "required": [
+ "description",
+ "prompt"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "subagent_fork",
+ "description": "Delegate a task to a subagent that inherits this conversation: a child agent seeded with all completed turns so far (it does not see the current in-flight turn). Use this when the subtask builds on this conversation's context \u2014 a follow-up analysis, a review, a continuation \u2014 without consuming this conversation's context for the work itself. You receive its result, not its intermediate steps. This call waits for the result by default. Set `run_in_background: true` to return a job id; collect with `job_output` and stop with `job_kill`.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "description": {
+ "type": "string",
+ "description": "A short (3-5 word) description of the delegated task, for display."
+ },
+ "prompt": {
+ "type": "string",
+ "description": "The task for the subagent. It already sees this conversation's completed turns, so build on them freely and state only what is new."
+ },
+ "run_in_background": {
+ "type": "boolean",
+ "description": "Whether to run as a background job and return its id. Defaults to false; collect with job_output or stop with job_kill."
+ }
+ },
+ "required": [
+ "description",
+ "prompt"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "todo_write",
+ "description": "Record and update a structured task list for the current work. Send the ENTIRE list every call \u2014 it REPLACES the previous list (there are no partial updates, no per-item edits). Use it to plan multi-step work and show progress: add one todo per concrete step before you start. Mark every todo being actively worked on `in_progress` \u2014 several at once when work genuinely runs in parallel (e.g. concurrent subagents or background commands), one for sequential work; while work remains, at least one task should be `in_progress`. Mark a todo `completed` the moment it is done (do not batch completions), and allow no `in_progress` item only once all work is complete. Skip the list for trivial single-step tasks. Statuses: `pending` (not started), `in_progress` (being worked on now), `completed` (finished).",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "todos": {
+ "type": "array",
+ "description": "The COMPLETE task list, replacing any previous list.",
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "content": {
+ "type": "string",
+ "description": "What the task is \u2014 a short imperative line."
+ },
+ "status": {
+ "type": "string",
+ "description": "pending (not started) | in_progress (now) | completed (done).",
+ "enum": [
+ "pending",
+ "in_progress",
+ "completed"
+ ]
+ }
+ },
+ "required": [
+ "content",
+ "status"
+ ]
+ }
+ }
+ },
+ "required": [
+ "todos"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "update_goal",
+ "description": "Update the exact current goal revision. edit, pause, and resume require a direct top-level human request. During an automatic continuation of the current goal, complete and blocked are also allowed. blocked is rejected before the configured minimum round count; the model remains responsible for judging that the same condition persisted across those rounds and must explain it in blocked_reason.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "goal_id": {
+ "type": "string",
+ "description": "Exact id returned by get_goal."
+ },
+ "revision": {
+ "type": "number",
+ "description": "Exact positive revision returned by get_goal."
+ },
+ "action": {
+ "type": "string",
+ "description": "edit | pause | resume | complete | blocked",
+ "enum": [
+ "edit",
+ "pause",
+ "resume",
+ "complete",
+ "blocked"
+ ]
+ },
+ "objective": {
+ "type": "string",
+ "description": "Replacement objective; valid only with action edit."
+ },
+ "max_goal_rounds": {
+ "type": "number",
+ "description": "Replacement cap; valid only with action edit."
+ },
+ "blocked_reason": {
+ "type": "string",
+ "description": "Concrete blocking condition; required only with action blocked."
+ }
+ },
+ "required": [
+ "goal_id",
+ "revision",
+ "action"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "web_search",
+ "description": "Search the web for current information. Provide 1\u20134 queries in the required queries array. Returns an optional summary answer and a list of source URLs.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "queries": {
+ "type": "array",
+ "description": "Required search queries; accepts 1\u20134 items and merges their results.",
+ "items": {
+ "type": "string"
+ }
+ }
+ },
+ "required": [
+ "queries"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "workflow",
+ "description": "Run a JavaScript workflow script that orchestrates subagents at scale. Use this for work that fans out across many independent pieces \u2014 an audit over many files, a migration, multi-angle research, adversarial verification of findings \u2014 where you write the orchestration as a script instead of delegating turn by turn.\n\nThe workflow's identity rides the `meta` parameter as JSON: required `name` (short kebab-case) and `description` strings, optional `whenToUse` string and `phases` array (`{title, detail?, provider?, model?}`). The `script` parameter is the plain JavaScript body ONLY (NOT TypeScript, and NO `export const meta` statement \u2014 meta is a parameter, not code), running with top-level await; end with `return <value>` \u2014 the value must be JSON-serializable and is this tool's result.\n\nScript-body hooks:\n- `agent(prompt, opts?): Promise<any>` \u2014 run one subagent to completion. Without `opts.schema` it resolves to the child's final text; with `opts.schema` (an object-rooted JSON Schema using ONLY type/properties/required/additionalProperties/items/enum/const/oneOf \u2014 no pattern/format/numeric bounds) it resolves to the validated object. Resolves `null` when the child fails (filter with `.filter(Boolean)`). Other opts: `label` (display), `phase` (progress group), and independent `provider`/`model` LLM target overrides (either may be provided alone). Anything else (`effort`/`isolation`/`agentType`) is rejected loudly.\n- `pipeline(items, ...stages): Promise<any[]>` \u2014 run each item through the stages independently with NO barrier between stages (prefer this for multi-stage work). Each stage receives `(prev, item, index)`. An ordinary stage throw drops that ITEM to `null` and skips its remaining stages.\n- `parallel(thunks): Promise<any[]>` \u2014 run zero-argument functions concurrently and await ALL of them (a barrier; use only when a stage genuinely needs every prior result together). A throwing thunk resolves to `null`.\n- `phase(title)` \u2014 start a progress phase; `log(message)` \u2014 narrate progress; `args` \u2014 the tool call's `args` input, verbatim.\n\nMisused hooks (bad arguments, unknown options, unsupported schemas, tripped caps) throw errors that ALWAYS kill the script \u2014 they never dissolve into a per-item `null`.\n\nConstraints: concurrency and total-agent caps apply; no filesystem, network, timers, or Node.js APIs are provided \u2014 the agents do the work, the script only coordinates them. The run executes in the foreground: this call returns when the whole script finishes.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "script": {
+ "type": "string",
+ "description": "The plain-JS workflow script body (top-level await allowed; NO `export const meta` statement; end with `return <json-value>`)."
+ },
+ "meta": {
+ "type": "object",
+ "description": "The workflow identity block (plain JSON \u2014 never code).",
+ "additionalProperties": true,
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "Short kebab-case workflow name."
+ },
+ "description": {
+ "type": "string",
+ "description": "One-line description of what the workflow does."
+ },
+ "whenToUse": {
+ "type": "string",
+ "description": "Optional guidance on when this workflow applies."
+ },
+ "phases": {
+ "type": "array",
+ "description": "Optional phase declarations matched by phase() calls.",
+ "items": {
+ "type": "object",
+ "additionalProperties": true,
+ "properties": {
+ "title": {
+ "type": "string",
+ "description": "The phase title phase() calls match by exact string."
+ },
+ "detail": {
+ "type": "string",
+ "description": "Optional one-line description of the phase."
+ },
+ "provider": {
+ "type": "string",
+ "description": "Optional provider override this phase is expected to use."
+ },
+ "model": {
+ "type": "string",
+ "description": "Optional model override this phase is expected to use."
+ }
+ },
+ "required": [
+ "title"
+ ]
+ }
+ }
+ },
+ "required": [
+ "name",
+ "description"
+ ]
+ },
+ "args": {
+ "type": "object",
+ "description": "Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {\"files\": [...]}).",
+ "additionalProperties": true
+ }
+ },
+ "required": [
+ "script",
+ "meta"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "write",
+ "description": "Create or fully replace a UTF-8 text file.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "file_path": {
+ "type": "string",
+ "description": "Path to write, resolved by the filesystem backend."
+ },
+ "content": {
+ "type": "string",
+ "description": "Full UTF-8 text content to write."
+ },
+ "sandbox_permissions": {
+ "type": "string",
+ "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.",
+ "enum": [
+ "workspace-write",
+ "danger-full-access"
+ ]
+ },
+ "justification": {
+ "type": "string",
+ "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access."
+ }
+ },
+ "required": [
+ "file_path",
+ "content"
+ ]
+ },
+ "strict": false
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/Tests/TurboFieldfareServer/Fixtures/dsh-0.1.1-rc.1-tool-result.json b/Tests/TurboFieldfareServer/Fixtures/dsh-0.1.1-rc.1-tool-result.json
new file mode 100644
index 00000000..d359f15d
--- /dev/null
+++ b/Tests/TurboFieldfareServer/Fixtures/dsh-0.1.1-rc.1-tool-result.json
@@ -0,0 +1,811 @@
+{
+ "model": "gemma-4-26b-a4b-it",
+ "messages": [
+ {
+ "role": "system",
+ "content": "You are an AI agent powered by DeepSeek Harness.\n\nYou are a coding agent powered by the gemma-4-26b-a4b-it model. Your working directory is /tmp/dsh-workspace.\n\nUse the read tool \u2014 not shell commands like cat \u2014 to inspect text files. Results include line numbers. Use offset and limit to continue reading large files.\n\nUse the write tool to create files or completely replace file contents. Existing files are overwritten, so read an existing file first (the default fs-observation-policy requires it) and prefer edit for targeted changes.\n\nUse the edit tool for targeted changes to existing UTF-8 text files. It replaces literal old_string with new_string; by default old_string must appear exactly once. If old_string appears multiple times, provide a more specific old_string or set replace_all to true. Read the file first (the default fs-observation-policy requires it), unless you just created or edited it in this session.\n\nUse the glob tool \u2014 not shell find \u2014 to discover files by path pattern. A pattern with no \"/\" matches basenames at any depth, so \"*\" matches every file in the tree rather than its top level. Results are files only, never directories, and include hidden and ignored files: a result that fits comes back in modification-time order, while a larger one keeps the modification-time-ordered head.\n\nUse the grep tool \u2014 not shell grep or rg \u2014 to search file contents. Use read on a matched file when you need surrounding context.\n\nCheck the [exit code: N] marker on every bash result; investigate failures before moving on.\n\nTrack every background job id you start. You are notified in-session when a job finishes \u2014 do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running job's work. Before giving a final answer, collect every still-relevant job with job_output (set wait: true only when you are genuinely blocked on it), and job_kill jobs that stopped mattering.\n\nUse the web_search tool to discover current information on the web. The required queries array accepts 1\u20134 non-empty search queries; use a one-item array for a single search. It returns an optional answer plus a list of source URLs. Use the returned source snippets when available, and cite the relevant URLs as markdown links.\n\nUse goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked.\n\nUse the workflow tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls.\n\nUse the ralph tool ONLY when the direct human explicitly asks for a Ralph loop or fresh-agent iterative execution. Each Ralph round starts a fresh child with no conversation seed and uses the shared workspace as durable memory. Completion and blockers are worker reports, not independent evaluation. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out.\n\nUse subagent in the background by default. Start independent delegations together in one assistant message and continue useful work while they run. Set `run_in_background: false` only when your next action depends on that subagent's result. When a background run settles, the runtime sends you a notice containing its outcome and any final assistant message."
+ },
+ {
+ "role": "user",
+ "content": "say hello"
+ },
+ {
+ "role": "user",
+ "content": "Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"/tmp/dsh-workspace\". Some platform temporary areas may also be writable.\n\nApproval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."
+ },
+ {
+ "role": "assistant",
+ "content": null,
+ "tool_calls": [
+ {
+ "id": "call_0123456789abcdef01234567",
+ "type": "function",
+ "function": {
+ "name": "bash",
+ "arguments": "{}"
+ }
+ }
+ ]
+ },
+ {
+ "role": "tool",
+ "content": "Error: invalid arguments: missing required property \"command\"; missing required property \"description\"",
+ "tool_call_id": "call_0123456789abcdef01234567"
+ }
+ ],
+ "stream": true,
+ "stream_options": {
+ "include_usage": true
+ },
+ "store": false,
+ "max_completion_tokens": 32768,
+ "tools": [
+ {
+ "type": "function",
+ "function": {
+ "name": "bash",
+ "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls \u2014 pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]` \u2014 a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a job id immediately; read its output with `job_output` and stop it with `job_kill`. Attempting a command the sandbox may deny is safe and expected: run it and read the marker rather than assuming the denial. When a command is denied and a wider mode would let it succeed, escalate immediately in the same turn \u2014 the one sanctioned exception to a denial: retry the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a one-sentence `justification`. Do not detour through chat to ask permission first \u2014 the approval prompt raised by that retry is how the user consents. If the session states approval prompts are disabled, there is no exception: a denial is final \u2014 do not set `sandbox_permissions`. Never escalate speculatively: ground the request in a real denial \u2014 normally the one this command just hit; escalating up front is fine only when this session already denied the same access. A rejected escalation is final for that command \u2014 stop and explain, never work around it \u2014 but it does not forbid attempting or escalating other commands later.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "command": {
+ "type": "string",
+ "description": "The bash command to execute."
+ },
+ "description": {
+ "type": "string",
+ "description": "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" \u2192 \"List files in current directory\"; \"git status\" \u2192 \"Show working tree status\"; \"npm install\" \u2192 \"Install package dependencies\"."
+ },
+ "timeoutMs": {
+ "type": "number",
+ "description": "Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry."
+ },
+ "workdir": {
+ "type": "string",
+ "description": "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it."
+ },
+ "run_in_background": {
+ "type": "boolean",
+ "description": "Run in the background and return a job id immediately (collect with job_output, stop with job_kill). No timeout applies."
+ },
+ "sandbox_permissions": {
+ "type": "string",
+ "description": "The wider sandbox mode this command needs. Only valid as a one-shot retry of a command the sandbox just denied; requires justification and user approval.",
+ "enum": [
+ "workspace-write",
+ "danger-full-access"
+ ]
+ },
+ "justification": {
+ "type": "string",
+ "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access."
+ }
+ },
+ "required": [
+ "command",
+ "description"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "create_goal",
+ "description": "Create one persisted same-session completion goal when the current direct human request is a long-running objective that should continue across autonomous goal rounds. You may infer that intent without requiring the user to say \"create a goal\". Do not use this for trivial single-turn work. Execution rejects non-human and subagent authority.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "objective": {
+ "type": "string",
+ "description": "The concrete completion objective inferred from the direct human request."
+ },
+ "max_goal_rounds": {
+ "type": "number",
+ "description": "Optional positive safe-integer limit on automatic continuation rounds."
+ }
+ },
+ "required": [
+ "objective"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "edit",
+ "description": "Edit an existing UTF-8 text file by replacing literal text.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "file_path": {
+ "type": "string",
+ "description": "Path to edit, resolved by the filesystem backend."
+ },
+ "old_string": {
+ "type": "string",
+ "description": "Literal text to replace. Must match exactly."
+ },
+ "new_string": {
+ "type": "string",
+ "description": "Literal replacement text. Use an empty string to delete the match."
+ },
+ "replace_all": {
+ "type": "boolean",
+ "description": "Replace all matches. Defaults to false; when false, old_string must appear exactly once."
+ },
+ "sandbox_permissions": {
+ "type": "string",
+ "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.",
+ "enum": [
+ "workspace-write",
+ "danger-full-access"
+ ]
+ },
+ "justification": {
+ "type": "string",
+ "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access."
+ }
+ },
+ "required": [
+ "file_path",
+ "old_string",
+ "new_string"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "exit_plan_mode",
+ "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. Send the COMPLETE plan as markdown, starting with a # heading that names it. The user may approve (carry out the plan from your next step) or keep planning \u2014 their feedback comes back in the tool result; revise and present again.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "plan": {
+ "type": "string",
+ "description": "The complete plan, as markdown, starting with a # heading that names it."
+ }
+ },
+ "required": [
+ "plan"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "get_goal",
+ "description": "Read the current same-session goal, including its exact id/revision, objective, phase, completed continuation rounds, round limit, blocker reason when present, and whether another continuation is armed. Call this before updating a goal.",
+ "parameters": {
+ "type": "object",
+ "properties": {}
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "glob",
+ "description": "Find files whose paths match a glob pattern. Returns matching file paths \u2014 never directories \u2014 including hidden and ignored files (VCS metadata directories are excluded). Up to 100 paths come back in modification-time order; a larger result returns the first 100 paths in modification-time order, says so, and reports where the complete sorted list was saved. This tool does not enumerate directory entries.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "pattern": {
+ "type": "string",
+ "description": "Glob pattern to match file paths against (e.g. \"**/*.ts\", \"src/**/*.test.js\"). A pattern with no \"/\" matches the basename at any depth, so \"*\" and \"*.ts\" both search the whole tree; include a separator to anchor the depth."
+ },
+ "path": {
+ "type": "string",
+ "description": "Directory to search in. Defaults to the session workspace; a relative path resolves against it."
+ }
+ },
+ "required": [
+ "pattern"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "grep",
+ "description": "Search file contents with a ripgrep regular expression. Returns matching lines with line numbers, grouped by file. Returns the first 250 matches inline; a capped result reports where the complete match list was saved. Use read on a matched file for surrounding context.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "pattern": {
+ "type": "string",
+ "description": "Regular expression to search for (ripgrep syntax)."
+ },
+ "path": {
+ "type": "string",
+ "description": "File or directory to search. Defaults to the session workspace; a relative path resolves against it."
+ },
+ "include": {
+ "type": "string",
+ "description": "One glob filter for which files to search (e.g. \"*.ts\", \"*.{js,jsx}\"). Not a list; negation is not supported."
+ }
+ },
+ "required": [
+ "pattern"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "interrupt_agent",
+ "description": "Request cancellation of a background agent's current turn by its agent id. The target may be your direct child or a deeper agent created under you. Only the current turn stops: messages already queued for the agent stay parked until a later send_message, agents it started keep running, and the agent itself stays available for follow-ups. This call returns as soon as the stop request is accepted, so the target may keep running briefly; interrupting an agent that already finished is an accepted no-op.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "agent_id": {
+ "type": "string",
+ "description": "The agent id of the running agent to interrupt."
+ }
+ },
+ "required": [
+ "agent_id"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "job_kill",
+ "description": "Request cancellation of a running background job by job id. Returns immediately; the job settles as killed once its work actually stops.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "job_id": {
+ "type": "string",
+ "description": "Job id returned by the tool that started the background work."
+ },
+ "reason": {
+ "type": "string",
+ "description": "Optional short reason, recorded in the log and forwarded to the job."
+ }
+ },
+ "required": [
+ "job_id"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "job_list",
+ "description": "List your background jobs (running and finished) with their ids, kinds, and statuses.",
+ "parameters": {
+ "type": "object",
+ "properties": {}
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "job_output",
+ "description": "Read a background job. Stream jobs return only output since the previous read; final-output jobs return their result after settlement. Every response ends with `[status: ...]`. Reads are non-blocking unless `wait: true`, which waits up to the configured cap.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "job_id": {
+ "type": "string",
+ "description": "Job id returned by the tool that started the background work."
+ },
+ "wait": {
+ "type": "boolean",
+ "description": "Block until the job reaches a terminal status or the timeout expires. A timed-out wait returns [status: running] and leaves the job alive."
+ },
+ "timeout_ms": {
+ "type": "number",
+ "description": "Max wait in milliseconds (only meaningful with wait: true). Defaults to the configured wait timeout; capped by the configured maximum."
+ }
+ },
+ "required": [
+ "job_id"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "list_agents",
+ "description": "List your continuable background subagents by durable id and label. Use it to recall which ones you started, not to poll for completion \u2014 you are told when one finishes. Status comes from the live registry: running means the agent is working right now, idle means it is loaded but between turns (it may be waiting on agents it started), and ready means it exists only in storage \u2014 resumable, not terminal, and not a result waiting to be collected; a `send_message` starts a new turn on the same conversation, and a direct child remains a `send_message` candidate in every status. The snapshot is not a delivery promise \u2014 `send_message` performs the authoritative check and may still fail. Children that could not be read are reported as diagnostics instead of being silently dropped. Scope `descendants` walks the whole tree below you in stable pre-order, annotating each entry with its durable direct-parent session id and depth. You may use `send_message` only for depth-1 entries; deeper entries are candidates for `interrupt_agent` only.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "scope": {
+ "type": "string",
+ "description": "children (default) lists direct children only; descendants walks the complete tree below you.",
+ "enum": [
+ "children",
+ "descendants"
+ ]
+ }
+ }
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "ralph",
+ "description": "Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns when a worker reports completion or a concrete blocker, or at the round limit. Ordinary long-running same-session work belongs to goal tools.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "objective": {
+ "type": "string",
+ "description": "The immutable completion objective for every fresh Ralph round."
+ },
+ "maxRounds": {
+ "type": "number",
+ "description": "Optional positive safe-integer round cap, bounded by the deployment ceiling."
+ }
+ },
+ "required": [
+ "objective"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "read",
+ "description": "Read a UTF-8 text file and return line-numbered content.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "file_path": {
+ "type": "string",
+ "description": "Path to read, resolved by the filesystem backend."
+ },
+ "offset": {
+ "type": "number",
+ "description": "1-based first line to return. Defaults to 1."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Maximum number of lines to return. Defaults to 2000."
+ }
+ },
+ "required": [
+ "file_path"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "read_image",
+ "description": "Read a PNG/JPEG/WebP/GIF file and return the image itself. Requires the current model to accept image input.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "file_path": {
+ "type": "string",
+ "description": "Path to the image file, resolved by the filesystem backend."
+ }
+ },
+ "required": [
+ "file_path"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "send_message",
+ "description": "Send a message to a background subagent by its subagent id, continuing the same conversation. It becomes the subagent's next turn: if it is still working, the message waits until its current turn finishes, so it cannot redirect work already underway. This call returns no answer from the subagent \u2014 only confirmation that the message was delivered \u2014 so use it to give it more work. A failure means the message was NOT delivered.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "subagent_id": {
+ "type": "string",
+ "description": "The subagent id returned when the background subagent was started."
+ },
+ "message": {
+ "type": "string",
+ "description": "The message to deliver to the subagent."
+ }
+ },
+ "required": [
+ "subagent_id",
+ "message"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "skill",
+ "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "The exact skill name from the available skills list."
+ }
+ },
+ "required": [
+ "name"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "str_replace_editor",
+ "description": "Custom editing tool for viewing, creating and editing files\n* State is persistent across command calls and discussions with the user\n* If `path` is a file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep\n* The `create` command cannot be used if the specified `path` already exists as a file\n* If a `command` generates a long output, it will be truncated and marked with `<response clipped>`\n\nNotes for using the `str_replace` command:\n* The `old_str` parameter should match EXACTLY one or more consecutive lines from the original file. Be mindful of whitespaces!\n* If the `old_str` parameter is not unique in the file, the replacement will not be performed. Make sure to include enough context in `old_str` to make it unique\n* The `new_str` parameter should contain the edited lines that should replace the `old_str`",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "command": {
+ "type": "string",
+ "description": "The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`.",
+ "enum": [
+ "view",
+ "create",
+ "str_replace",
+ "insert"
+ ]
+ },
+ "path": {
+ "type": "string",
+ "description": "Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`."
+ },
+ "file_text": {
+ "type": "string",
+ "description": "Required parameter of `create` command, with the content of the file to be created."
+ },
+ "insert_line": {
+ "type": "integer",
+ "description": "Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`."
+ },
+ "new_str": {
+ "type": "string",
+ "description": "Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert."
+ },
+ "old_str": {
+ "type": "string",
+ "description": "Required parameter of `str_replace` command containing the string in `path` to replace."
+ },
+ "view_range": {
+ "type": "array",
+ "description": "Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.",
+ "items": {
+ "type": "integer"
+ }
+ }
+ },
+ "required": [
+ "command",
+ "path"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "subagent",
+ "description": "Delegate a self-contained task to a subagent (a separate agent that works in its own context) to offload focused, independent work \u2014 research, a scoped implementation, an analysis \u2014 so it does not consume this conversation's context. The subagent returns its result, not its intermediate steps. Give it a complete, standalone prompt: it does not see this conversation. This tool runs in the background by default, immediately returns a durable subagent id, and keeps the child conversation available for later turns. When that run settles, the runtime sends the parent a notice containing its outcome and any final assistant message; `send_message` starts a later turn in the same child conversation. Set `run_in_background: false` only when your next action depends on receiving the result.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "description": {
+ "type": "string",
+ "description": "A short (3-5 word) description of the delegated task, for display."
+ },
+ "prompt": {
+ "type": "string",
+ "description": "The complete, self-contained task for the subagent. It does not share this conversation's context, so include everything it needs."
+ },
+ "run_in_background": {
+ "type": "boolean",
+ "description": "Whether to run in the background and return a durable subagent id immediately. Defaults to true. Set false to wait for the result when your next action depends on it."
+ }
+ },
+ "required": [
+ "description",
+ "prompt"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "subagent_fork",
+ "description": "Delegate a task to a subagent that inherits this conversation: a child agent seeded with all completed turns so far (it does not see the current in-flight turn). Use this when the subtask builds on this conversation's context \u2014 a follow-up analysis, a review, a continuation \u2014 without consuming this conversation's context for the work itself. You receive its result, not its intermediate steps. This call waits for the result by default. Set `run_in_background: true` to return a job id; collect with `job_output` and stop with `job_kill`.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "description": {
+ "type": "string",
+ "description": "A short (3-5 word) description of the delegated task, for display."
+ },
+ "prompt": {
+ "type": "string",
+ "description": "The task for the subagent. It already sees this conversation's completed turns, so build on them freely and state only what is new."
+ },
+ "run_in_background": {
+ "type": "boolean",
+ "description": "Whether to run as a background job and return its id. Defaults to false; collect with job_output or stop with job_kill."
+ }
+ },
+ "required": [
+ "description",
+ "prompt"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "todo_write",
+ "description": "Record and update a structured task list for the current work. Send the ENTIRE list every call \u2014 it REPLACES the previous list (there are no partial updates, no per-item edits). Use it to plan multi-step work and show progress: add one todo per concrete step before you start. Mark every todo being actively worked on `in_progress` \u2014 several at once when work genuinely runs in parallel (e.g. concurrent subagents or background commands), one for sequential work; while work remains, at least one task should be `in_progress`. Mark a todo `completed` the moment it is done (do not batch completions), and allow no `in_progress` item only once all work is complete. Skip the list for trivial single-step tasks. Statuses: `pending` (not started), `in_progress` (being worked on now), `completed` (finished).",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "todos": {
+ "type": "array",
+ "description": "The COMPLETE task list, replacing any previous list.",
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "content": {
+ "type": "string",
+ "description": "What the task is \u2014 a short imperative line."
+ },
+ "status": {
+ "type": "string",
+ "description": "pending (not started) | in_progress (now) | completed (done).",
+ "enum": [
+ "pending",
+ "in_progress",
+ "completed"
+ ]
+ }
+ },
+ "required": [
+ "content",
+ "status"
+ ]
+ }
+ }
+ },
+ "required": [
+ "todos"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "update_goal",
+ "description": "Update the exact current goal revision. edit, pause, and resume require a direct top-level human request. During an automatic continuation of the current goal, complete and blocked are also allowed. blocked is rejected before the configured minimum round count; the model remains responsible for judging that the same condition persisted across those rounds and must explain it in blocked_reason.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "goal_id": {
+ "type": "string",
+ "description": "Exact id returned by get_goal."
+ },
+ "revision": {
+ "type": "number",
+ "description": "Exact positive revision returned by get_goal."
+ },
+ "action": {
+ "type": "string",
+ "description": "edit | pause | resume | complete | blocked",
+ "enum": [
+ "edit",
+ "pause",
+ "resume",
+ "complete",
+ "blocked"
+ ]
+ },
+ "objective": {
+ "type": "string",
+ "description": "Replacement objective; valid only with action edit."
+ },
+ "max_goal_rounds": {
+ "type": "number",
+ "description": "Replacement cap; valid only with action edit."
+ },
+ "blocked_reason": {
+ "type": "string",
+ "description": "Concrete blocking condition; required only with action blocked."
+ }
+ },
+ "required": [
+ "goal_id",
+ "revision",
+ "action"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "web_search",
+ "description": "Search the web for current information. Provide 1\u20134 queries in the required queries array. Returns an optional summary answer and a list of source URLs.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "queries": {
+ "type": "array",
+ "description": "Required search queries; accepts 1\u20134 items and merges their results.",
+ "items": {
+ "type": "string"
+ }
+ }
+ },
+ "required": [
+ "queries"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "workflow",
+ "description": "Run a JavaScript workflow script that orchestrates subagents at scale. Use this for work that fans out across many independent pieces \u2014 an audit over many files, a migration, multi-angle research, adversarial verification of findings \u2014 where you write the orchestration as a script instead of delegating turn by turn.\n\nThe workflow's identity rides the `meta` parameter as JSON: required `name` (short kebab-case) and `description` strings, optional `whenToUse` string and `phases` array (`{title, detail?, provider?, model?}`). The `script` parameter is the plain JavaScript body ONLY (NOT TypeScript, and NO `export const meta` statement \u2014 meta is a parameter, not code), running with top-level await; end with `return <value>` \u2014 the value must be JSON-serializable and is this tool's result.\n\nScript-body hooks:\n- `agent(prompt, opts?): Promise<any>` \u2014 run one subagent to completion. Without `opts.schema` it resolves to the child's final text; with `opts.schema` (an object-rooted JSON Schema using ONLY type/properties/required/additionalProperties/items/enum/const/oneOf \u2014 no pattern/format/numeric bounds) it resolves to the validated object. Resolves `null` when the child fails (filter with `.filter(Boolean)`). Other opts: `label` (display), `phase` (progress group), and independent `provider`/`model` LLM target overrides (either may be provided alone). Anything else (`effort`/`isolation`/`agentType`) is rejected loudly.\n- `pipeline(items, ...stages): Promise<any[]>` \u2014 run each item through the stages independently with NO barrier between stages (prefer this for multi-stage work). Each stage receives `(prev, item, index)`. An ordinary stage throw drops that ITEM to `null` and skips its remaining stages.\n- `parallel(thunks): Promise<any[]>` \u2014 run zero-argument functions concurrently and await ALL of them (a barrier; use only when a stage genuinely needs every prior result together). A throwing thunk resolves to `null`.\n- `phase(title)` \u2014 start a progress phase; `log(message)` \u2014 narrate progress; `args` \u2014 the tool call's `args` input, verbatim.\n\nMisused hooks (bad arguments, unknown options, unsupported schemas, tripped caps) throw errors that ALWAYS kill the script \u2014 they never dissolve into a per-item `null`.\n\nConstraints: concurrency and total-agent caps apply; no filesystem, network, timers, or Node.js APIs are provided \u2014 the agents do the work, the script only coordinates them. The run executes in the foreground: this call returns when the whole script finishes.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "script": {
+ "type": "string",
+ "description": "The plain-JS workflow script body (top-level await allowed; NO `export const meta` statement; end with `return <json-value>`)."
+ },
+ "meta": {
+ "type": "object",
+ "description": "The workflow identity block (plain JSON \u2014 never code).",
+ "additionalProperties": true,
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "Short kebab-case workflow name."
+ },
+ "description": {
+ "type": "string",
+ "description": "One-line description of what the workflow does."
+ },
+ "whenToUse": {
+ "type": "string",
+ "description": "Optional guidance on when this workflow applies."
+ },
+ "phases": {
+ "type": "array",
+ "description": "Optional phase declarations matched by phase() calls.",
+ "items": {
+ "type": "object",
+ "additionalProperties": true,
+ "properties": {
+ "title": {
+ "type": "string",
+ "description": "The phase title phase() calls match by exact string."
+ },
+ "detail": {
+ "type": "string",
+ "description": "Optional one-line description of the phase."
+ },
+ "provider": {
+ "type": "string",
+ "description": "Optional provider override this phase is expected to use."
+ },
+ "model": {
+ "type": "string",
+ "description": "Optional model override this phase is expected to use."
+ }
+ },
+ "required": [
+ "title"
+ ]
+ }
+ }
+ },
+ "required": [
+ "name",
+ "description"
+ ]
+ },
+ "args": {
+ "type": "object",
+ "description": "Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {\"files\": [...]}).",
+ "additionalProperties": true
+ }
+ },
+ "required": [
+ "script",
+ "meta"
+ ]
+ },
+ "strict": false
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "write",
+ "description": "Create or fully replace a UTF-8 text file.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "file_path": {
+ "type": "string",
+ "description": "Path to write, resolved by the filesystem backend."
+ },
+ "content": {
+ "type": "string",
+ "description": "Full UTF-8 text content to write."
+ },
+ "sandbox_permissions": {
+ "type": "string",
+ "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.",
+ "enum": [
+ "workspace-write",
+ "danger-full-access"
+ ]
+ },
+ "justification": {
+ "type": "string",
+ "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access."
+ }
+ },
+ "required": [
+ "file_path",
+ "content"
+ ]
+ },
+ "strict": false
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/Tests/TurboFieldfareServer/OpenAIValidationTests.swift b/Tests/TurboFieldfareServer/OpenAIValidationTests.swift
index d2a8b30e..9db9560a 100644
--- a/Tests/TurboFieldfareServer/OpenAIValidationTests.swift
+++ b/Tests/TurboFieldfareServer/OpenAIValidationTests.swift
@@ -34,6 +34,40 @@ struct OpenAIValidationTests {
#expect(ids.count <= 16_384 - 4_096)
}
+ @Test func capturedDshInitialRequestValidatesAndRenders() async throws {
+ // DeepSeek Harness 0.1.1-rc.1's `workflow` tool declares its `args`
+ // parameter as a bare object node with `additionalProperties` — the
+ // shape that crashed template rendering with "upper filter requires
+ // string" (PR 138). Rendering here is the regression: the fixture
+ // must survive the full validate + render path.
+ let request = try fixture("dsh-0.1.1-rc.1-initial.json")
+ let validated = try OpenAIRequestValidator.validate(
+ request, modelID: "gemma-4-26b-a4b-it")
+ #expect(validated.stream)
+ #expect(validated.includeUsage)
+ #expect(validated.tools.count == 25)
+ let workflow = try #require(validated.tools.first { $0.name == "workflow" })
+ let args = workflow.parameters.objectValue?["properties"]?
+ .objectValue?["args"]?.objectValue
+ #expect(args?["properties"] == .object([:]))
+ let tokenizer = try await GFTokenizer.load()
+ _ = try tokenizer.encodeToolChat(
+ messages: validated.messages, tools: validated.tools)
+ }
+
+ @Test func capturedDshToolResultValidatesAndRenders() async throws {
+ let request = try fixture("dsh-0.1.1-rc.1-tool-result.json")
+ let validated = try OpenAIRequestValidator.validate(
+ request, modelID: "gemma-4-26b-a4b-it")
+ #expect(validated.messages.count == 5)
+ let call = try #require(
+ validated.messages.first { !$0.toolCalls.isEmpty }?.toolCalls.first)
+ #expect(call.id == "call_0123456789abcdef01234567")
+ let tokenizer = try await GFTokenizer.load()
+ _ = try tokenizer.encodeToolChat(
+ messages: validated.messages, tools: validated.tools)
+ }
+
@Test func requiredToolChoiceIsRejected() throws {
let data = Data(#"""
{"model":"m","messages":[{"role":"user","content":"x"}],"tool_choice":"required"}
@@ -349,6 +383,89 @@ struct OpenAIValidationTests {
#expect(item?["oneOf"] == nil)
}
+ @Test func bareObjectNodesWithSiblingKeywordsRender() async throws {
+ // Regression: the chat template routes an object node without
+ // `properties` through its filter_keys branch, which iterates the
+ // node's own keys as property schemas; preserved keywords such as
+ // `additionalProperties`, `default`, or `title` then hit
+ // `value['type'] | upper` on a non-string and rendering fails with
+ // Jinja runtime("upper filter requires string") — the 500 reported by
+ // a DeepSeek Harness user in PR 138. Without the injected empty
+ // `properties` mapping, encodeToolChat throws here.
+ let data = Data(#"""
+ {
+ "model":"m",
+ "messages":[{"role":"user","content":"go"}],
+ "tools":[{
+ "type":"function",
+ "function":{
+ "name":"probe",
+ "parameters":{
+ "type":"object",
+ "properties":{
+ "closed":{"type":"object","additionalProperties":false},
+ "annotated":{"type":"object","default":{},"title":"Config"},
+ "bare":{"type":"object"}
+ }
+ }
+ }
+ }]
+ }
+ """#.utf8)
+ let request = try JSONDecoder().decode(OpenAIChatRequest.self, from: data)
+ let validated = try OpenAIRequestValidator.validate(request, modelID: "m")
+ let tokenizer = try await GFTokenizer.load()
+ let rendered = tokenizer.decode(
+ try tokenizer.encodeToolChat(
+ messages: validated.messages,
+ tools: validated.tools),
+ skipSpecialTokens: false)
+ // All three nodes render through the same branch a bare object node
+ // already used, so the output shape stays `properties:{}` (the
+ // detokenized text carries token-boundary spaces).
+ #expect(rendered.contains("closed:{ properties:{ },type:"))
+ #expect(rendered.contains("annotated:{ properties:{ },type:"))
+ #expect(rendered.contains("bare:{ properties:{ },type:"))
+ }
+
+ @Test func adaptedObjectNodesAlwaysCarryProperties() throws {
+ // Invariant: no adapted object node reaches the template without a
+ // `properties` mapping, so the template's key-iterating fallback
+ // branch is unreachable for adapter output.
+ let schemas = [
+ #"{"type":"object","properties":{"v":{"type":"object","additionalProperties":true}}}"#,
+ #"{"type":"object","properties":{"v":{"type":"array","items":{"type":"object","default":{"a":1}}}}}"#,
+ #"{"type":"object","properties":{"v":{"anyOf":[{"type":"object","examples":{"a":1}},{"type":"null"}]}}}"#,
+ #"{"type":"object","properties":{"v":{"type":"object","properties":{"w":{"type":"object"}}}}}"#,
+ ]
+ for encoded in schemas {
+ let schema = try JSONDecoder().decode(JSONValue.self, from: Data(encoded.utf8))
+ let adapted = try GemmaToolSchema.adapted(schema, toolName: "probe")
+ try assertObjectNodesCarryProperties(adapted, path: "parameters")
+ let again = try GemmaToolSchema.adapted(adapted, toolName: "probe")
+ #expect(again == adapted)
+ }
+ }
+
+ private func assertObjectNodesCarryProperties(
+ _ schema: JSONValue, path: String
+ ) throws {
+ guard case .object(let object) = schema else { return }
+ if object["type"] == .string("object") {
+ let properties = object["properties"]
+ #expect(properties?.objectValue != nil,
+ "object node at \(path) lacks a properties mapping")
+ }
+ if case .object(let definitions)? = object["properties"] {
+ for (key, value) in definitions {
+ try assertObjectNodesCarryProperties(value, path: "\(path).properties.\(key)")
+ }
+ }
+ if let items = object["items"] {
+ try assertObjectNodesCarryProperties(items, path: "\(path).items")
+ }
+ }
+
@Test func unsupportedToolSchemaUnionsFailClosed() throws {
let schemas = [
#"{"type":"object","properties":{"v":{"anyOf":[{"type":"string"},{"type":"object"}]}}}"#,
diff --git a/Tests/TurboFieldfareServer/ServerPromptCacheTests.swift b/Tests/TurboFieldfareServer/ServerPromptCacheTests.swift
index 4731faaf..caddd15c 100644
--- a/Tests/TurboFieldfareServer/ServerPromptCacheTests.swift
+++ b/Tests/TurboFieldfareServer/ServerPromptCacheTests.swift
@@ -195,6 +195,64 @@ struct ServerPromptCacheTests {
#expect(cache.entry == nil)
}
+ /// A verbatim-repeated tool call must keep its cache; the unique-match
+ /// rule refused this shape and dropped the cache from that turn on.
+ @Test func repeatedIdenticalToolCallKeepsTheBoundaryResolvable() async throws {
+ let tokenizer = try await GFTokenizer.load()
+ let tools = [GFTokenizer.FunctionDefinition(
+ name: "ls",
+ description: "list a directory",
+ parameters: .object([
+ "type": .string("object"),
+ "properties": .object([
+ "path": .object(["type": .string("string")]),
+ ]),
+ ]))]
+ let call = { (id: String) in
+ GFTokenizer.HistoricalToolCall(
+ id: id,
+ name: "ls",
+ arguments: .object(["path": .string(".")]))
+ }
+ let first = GFTokenizer.Message(
+ role: .assistant, content: nil, toolCalls: [call("call_1")])
+ let firstResult = GFTokenizer.Message(
+ role: .tool, content: "pkg/", toolCallID: "call_1", name: "ls")
+ // Byte-identical to the first call; only the call id differs.
+ let repeated = GFTokenizer.Message(
+ role: .assistant, content: nil, toolCalls: [call("call_2")])
+ let repeatedResult = GFTokenizer.Message(
+ role: .tool, content: "pkg/", toolCallID: "call_2", name: "ls")
+ let cachedMessages = [
+ GFTokenizer.Message(role: .user, content: "list the tree"),
+ first,
+ firstResult,
+ ]
+
+ let bridge = try tokenizer.encodeToolResultContinuation(
+ cachedMessages: cachedMessages,
+ assistant: repeated,
+ incomingMessages: cachedMessages + [repeated, repeatedResult],
+ tools: tools)
+
+ // Both twins are followed by a response; only the counts tell a
+ // twin-anchored bridge apart.
+ #expect(bridge.first == tokenizer.toolResponseID)
+ #expect(bridge.filter { $0 == tokenizer.toolResponseID }.count == 1)
+ #expect(!bridge.contains(tokenizer.toolCallStartID))
+
+ // A diverged cached history cannot anchor by position and still refuses.
+ let diverged = [GFTokenizer.Message(role: .user, content: "list the other tree")]
+ + cachedMessages.dropFirst()
+ #expect(throws: (any Error).self) {
+ try tokenizer.encodeToolResultContinuation(
+ cachedMessages: diverged,
+ assistant: repeated,
+ incomingMessages: cachedMessages + [repeated, repeatedResult],
+ tools: tools)
+ }
+ }
+
private func request(
messages: [GFTokenizer.Message],
tools: [GFTokenizer.FunctionDefinition] = []