Craft Anything: understand how any software works, and craft your own.
Rust
Send DeepSeek Harness tasks through stdin (#1067)
gtxy27ab0d0cbda9f9
diff --git a/crates/ai/src/cli_agents/adapters/dsh.rs b/crates/ai/src/cli_agents/adapters/dsh.rsindex 26f57e98..b77a2ed7 100644--- a/crates/ai/src/cli_agents/adapters/dsh.rs+++ b/crates/ai/src/cli_agents/adapters/dsh.rs@@ -1,7 +1,9 @@-//! DeepSeek Harness (`dsh --profile headless "<task>"`).+//! DeepSeek Harness (`dsh --profile headless`, with the task on stdin).//!//! The harness answers one task, streams its reasoning to stderr and prints its last message on//! stdout, so its output is the answer text, not JSON lines.+//! This needs a headless profile that accepts piped input (verified with 0.2.2-rc.1); older+//! versions without it reject the missing task and must be updated.//!//! It has no flag for a tool server the way other agents do: servers come from the profile's patch//! layers. Our tool server therefore arrives as one generated `--patch` overlay for this run, which@@ -27,6 +29,16 @@ impl AgentAdapter for DeepSeekHarness {&["dsh", "deepseek-harness"]}+ /// Keep task text out of Windows batch arguments and their command-line length limit.+ fn prompt_on_stdin(&self) -> bool {+ true+ }++ /// The headless task includes the preamble, with no added or removed whitespace.+ fn stdin_text(&self, preamble: &str, prompt: &str) -> String {+ format!("{preamble}{prompt}")+ }+fn args(&self, cx: &ArgsCx) -> Vec<String> {let mut v = cx.options.args.clone();v.extend(["--profile".into(), "headless".into()]);@@ -34,7 +46,8 @@ impl AgentAdapter for DeepSeekHarness {if !cx.question {v.extend(["--patch".into(), tool_server_patch(cx.mcp)]);}- v.push(format!("{}{}", cx.preamble, cx.prompt));+ // No task positional means stdin. Unlike `-`, this fails as a missing task on older+ // Harness versions without stdin support, rather than submitting a literal dash.v}@@ -163,15 +176,16 @@ mod tests {(DeepSeekHarness.args(&cx), mcp.clone())}- /// The task goes last, after the profile and any extra arguments.+ /// Only options go in argv; the task arrives on stdin after the profile starts.#[test]- fn one_task_goes_to_the_headless_profile_last() {+ fn headless_argv_contains_only_profile_and_patch_options() {let (a, _) = args(&BackendOptions::default(), false);assert_eq!(a[0..2], ["--profile", "headless"], "{a:?}");- assert_eq!(a.last().map(String::as_str), Some("PRE make a game"), "{a:?}");+ assert_eq!(a.len(), 4, "only the profile and tool-server patch: {a:?}");let with_args = BackendOptions { args: vec!["--patch".into(), "extra.yml".into()], ..Default::default() };let (a, _) = args(&with_args, false);assert_eq!(a[0..4], ["--patch", "extra.yml", "--profile", "headless"], "{a:?}");+ assert_eq!(a.len(), 6, "custom options and the generated patch: {a:?}");}/// The run's tool server, as an overlay in a folder of its own that only its owner can read.@@ -223,7 +237,27 @@ mod tests {fn a_question_gets_no_tool_server() {let (a, _) = args(&BackendOptions::default(), true);assert!(!a.iter().any(|x| x == "--patch"), "{a:?}");- assert_eq!(a.last().map(String::as_str), Some("PRE make a game"), "{a:?}");+ assert_eq!(a, ["--profile", "headless"], "{a:?}");+ }++ /// Batch launchers cannot accept line breaks or long tasks in argv; stdin preserves the text.+ #[test]+ fn multiline_and_long_tasks_use_stdin_without_changing_their_bytes() {+ let preamble = "Instructions:\r\n";+ let tasks = ["-question?\r\n中文 %PATH% & ^ \"quoted\"\n\n".to_string(), format!("{}\nlast line\n", "x".repeat(40_831))];+ for id in ["dsh", "deepseek-harness"] {+ let adapter = AgentAdapters::built_in().for_agent(id);+ for task in &tasks {+ for access in [Access::Build, Access::Question] {+ let a = build_args(adapter.as_ref(), &BackendOptions::default(), task, preamble, &mcp(), None, access);+ assert!(adapter.prompt_on_stdin(), "{id} must send task text on stdin");+ assert_eq!(a.len(), if matches!(access, Access::Question) { 2 } else { 4 }, "only options: {a:?}");+ assert!(!a.iter().any(|arg| arg.contains(task) || arg.contains(preamble)), "{a:?}");+ assert!(a.iter().map(|arg| arg.len() + 1).sum::<usize>() < 8191, "the task must not grow argv");+ assert_eq!(adapter.stdin_text(preamble, task), format!("{preamble}{task}"), "{id}");+ }+ }+ }}/// The agent is registered under both ids, not handed to the plain adapter.diff --git a/crates/ai/src/cli_agents/mod.rs b/crates/ai/src/cli_agents/mod.rsindex 340330c2..edaa3ff1 100644--- a/crates/ai/src/cli_agents/mod.rs+++ b/crates/ai/src/cli_agents/mod.rs@@ -2255,6 +2255,58 @@ echo '{"type":"turn.completed","usage":{"input_tokens":1,"output_tokens":1}}'}}+ /// The desktop Harness uses a custom batch launcher rather than an npm shim. Exercise the+ /// real conversation runner through such a launcher, with no installed agent or network.+ #[cfg(windows)]+ #[test]+ fn dsh_cmd_receives_multiline_and_long_tasks_on_stdin() {+ let dir = tempfile::tempdir().unwrap();+ let program = dir.path().join("dsh.cmd");+ let exe = std::env::current_exe().unwrap().display().to_string().replace('%', "%%");+ let script = format!(+ "@echo off\r\nsetlocal DisableDelayedExpansion\r\n\+ if \"%~1\"==\"--help\" (echo --profile& exit /b 0)\r\n\+ if not \"%~5\"==\"\" exit /b 2\r\n\+ echo %*> \"%~dp0argv\"\r\n\+ set \"{STDIN_ECHO_ENV}=%~dp0stdin\"\r\n\+ \"{exe}\" --exact --test-threads=1 cli_agents::tests::stdin_echo_child >nul\r\n\+ if errorlevel 1 exit /b 1\r\n\+ echo DSH_STDIN_FIXTURE_OK\r\n"+ );+ std::fs::write(&program, script).unwrap();+ let cases = [+ ("Instructions:\r\n", "-question?\r\n中文 %PATH% & ^ \"quoted\"\n\n".to_string()),+ ("", "--not-a-flag\n".to_string()),+ ("Instructions:\n", format!("{}\nlast line\n", "x".repeat(40_831))),+ ];+ for (preamble, prompt) in cases {+ let _ = std::fs::remove_file(dir.path().join("stdin"));+ let config =+ BackendConfig { name: "DSH fixture".into(), kind: BackendKind::AgentCli, model: "dsh".into(), base_url: None, ssh_host: None, enabled: true };+ let options = BackendOptions { command: Some(program.display().to_string()), timeout_secs: Some(20), ..Default::default() };+ let mut spec = CliSpec::new(config, options, false, Some(dir.path().to_path_buf()));+ spec.preamble = Some(preamble.into());+ spec.builder = Some(Builder { investigation: None, inbox: dir.path().join("inbox") });+ let mut c = CliConversation::new(spec);+ c.send(&prompt);+ let deadline = std::time::Instant::now() + Duration::from_secs(30);+ let mut events = Vec::new();+ while std::time::Instant::now() < deadline && !events.iter().any(|e| matches!(e, AgentEvent::TurnDone { .. })) {+ events.extend(c.poll());+ std::thread::sleep(Duration::from_millis(10));+ }+ c.stop();+ assert!(events.iter().any(|e| matches!(e, AgentEvent::TurnDone { .. })), "{events:?}");+ assert!(!events.iter().any(|e| matches!(e, AgentEvent::Error { .. })), "{events:?}");+ assert!(events.iter().any(|e| matches!(e, AgentEvent::TextDelta { text } if text.contains("DSH_STDIN_FIXTURE_OK"))), "{events:?}");+ assert_eq!(std::fs::read(dir.path().join("stdin")).unwrap(), format!("{preamble}{prompt}").as_bytes());+ let argv = std::fs::read_to_string(dir.path().join("argv")).unwrap();+ assert!(argv.starts_with("--profile headless --patch "), "{argv}");+ assert!(!argv.trim_end().ends_with(" -"), "old Harness versions would run a literal dash: {argv}");+ assert!(!argv.contains(&prompt), "task text must not appear in argv");+ }+ }+const STDIN_ECHO_ENV: &str = "CRAFT_ANYTHING_TEST_STDIN_ECHO";/// Not a test on its own: when run as the child of the test above, writes its stdin to thediff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 2657164b..66c7a811 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -781,8 +781,11 @@ Owner: open · Status: in progressown profile is left untouched. Verified with adapter and overlay tests and a live follow-upwebsite build whose journal shows `rebuild_check`, `core_unknown_add` and `core_handoff_write`going through our server — claimed: 0231071, branch `feature/dsh-agent-adapter`-- [ ] DeepSeek Harness: no resume (its headless profile keeps no session), a build on the harness's- desktop profile is untried, and the task still goes over in argv (see the argv note above)+- [x] DeepSeek Harness: send tasks on stdin so multiline and long messages can start through the+ Windows desktop launcher (see the argv note above)+ — claimed: gtxy27, branch `bugfix/r2.2-dsh-stdin`+- [ ] DeepSeek Harness: no resume (its headless profile keeps no session), and a build on the harness's+ desktop profile is untried- [ ] `setup` writes the plain `mcp` command, so it drops an `--all-tools` an entry already has, and`doctor` then calls that entry "a different copy or shape of the command" and suggests the verycommand that breaks it. The installed skill now warns against running `setup` on such an entry;diff --git a/docs/STATUS.md b/docs/STATUS.mdindex 604dcfc8..a3f7fcaa 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -90,7 +90,7 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi| Auto mode | Settings → Safety, on by default. Builder actions go ahead without asking, except a fixed set that is never done unasked (deleting outside the project, system changes, publishing…); questions get "decide yourself"; asset spending stops at the budget. Each project can choose allow, ask or refuse per kind of action instead (`project_approvals_set`, the Approvals menu under the prompt box, or `/approvals publish ask`; read-only `gh … view`/`list` count as commands, not publishing) | Unit tests, UI tests; not tried in a live build || Generated assets | Off until the person turns them on for a game (the switch on Make and on the project, `project_assets_allow`, `rebuild --generate-assets`, saved in craft.json; turning it on without a fal.ai key asks for one); the brief and the asset tools need both that and a key. `assets_image_generate` (Nano Banana Pro by default) and `assets_model_generate` (picture → Tripo P1 low-poly GLB with a face limit) through the person's key for each asset provider (fal.ai today), with agent apps and API-key builds alike; per-project budget, $5 by default (`[assets] budget_usd` in config.toml); models and prices from the `assets.toml` table (picture model selectable: Nano Banana Pro, FLUX dev or schnell; priced per picture or per megapixel); every call reports its cost | Unit tests; a live 3D generation with a real key (picture, then model) with FLUX dev; Nano Banana Pro not yet run with a real key; an API-key build not yet run with one || Claude Code builder | Runs the person's own `claude` in headless mode (Opus 5.5, high effort unless configured) with our MCP server, a permission-prompt tool and `core_person_ask`; preflights for our CLI (a build stops plainly if it's missing or won't start) and sign-in | Argument and stream-parser tests; live preflight; live builder turns; see [claude-code.md](claude-code.md) |-| DeepSeek Harness builder | Runs the person's own `dsh --profile headless "<task>"`, which answers one task and prints its last message as text. The harness takes its tool servers from profile patch layers and has no per-run flag for one, so our tool server arrives as a generated `--patch` overlay for that run (the run's project, inbox and mode included); the person's own profile is untouched, a question gets no tool server, and its headless profile keeps no session to resume. An npm `.cmd` shim is unwrapped to its interpreter, so `dsh` found on PATH runs as `node …/dsh/lib/bin.js` | Adapter and YAML-overlay tests; live preflight (`ai test`); live builder turns on a website (follow-up build, 3 min 10 s, 100% alike at 1440/768/390 px, Ready) where the builder's own journal entries show `rebuild_check`, `core_unknown_add`, `core_plan_update` and `core_handoff_write` going through our tool server, and that server started with the run's `--project`/`--inbox`. Not checked: resume (none exists) and a build with the harness's desktop profile. Also verified on macOS arm64 (2026-11-07, DSH 0.2.2-rc.1, stored sign-in restored for the headless profile as its README describes): a static website reached Ready with one check pass, and the builder called our MCP tools |+| DeepSeek Harness builder | Runs the person's own `dsh --profile headless` with the preamble and task on stdin, which answers one task and prints its last message as text. The harness takes its tool servers from profile patch layers and has no per-run flag for one, so our tool server arrives as a generated `--patch` overlay for that run (the run's project, inbox and mode included); the person's own profile is untouched, a question gets no tool server, and its headless profile keeps no session to resume. Standard npm shims are unwrapped to their interpreter; the desktop app's custom `.cmd` launcher receives only options, avoiding batch newline and command-line length limits. Requires a headless profile with stdin support (0.2.2-rc.1 verified); older versions without it reject the missing task and need updating | Adapter and YAML-overlay tests; live preflight (`ai test`); live builder turns on a website (follow-up build, 3 min 10 s, 100% alike at 1440/768/390 px, Ready) where the builder's own journal entries show `rebuild_check`, `core_unknown_add`, `core_plan_update` and `core_handoff_write` going through our tool server, and that server started with the run's `--project`/`--inbox`. Not checked: resume (none exists) and a build with the harness's desktop profile. Also verified on macOS arm64 (2026-11-07, DSH 0.2.2-rc.1, stored sign-in restored for the headless profile as its README describes): a static website reached Ready with one check pass, and the builder called our MCP tools ; Windows (2026-11-07): the new batch-launch regression failed with the reported startup error before the fix and then passed, including exact UTF-8 and 40,831-character task delivery. A patched Craft CLI chat through the official desktop `dsh.cmd` returned the expected answer with a local authentication overlay; no new GUI or full rebuild run was performed || Agents over ACP | Opt-in per backend (`acp = true`): Gemini CLI, Qwen Code, opencode, goose, Hermes and Maki in their ACP mode, one agent process per chat or build with our MCP server; Maki's ACP mode takes the backend's model (`cli_model`). In chat, permission requests become consent questions; in builds they go through the same approval policy as Claude Code's (inbox, Auto mode). While a saved session loads, replayed updates are withheld from the new turn | Protocol unit tests against scripted agent messages and an approval-policy test. Run live with Maki 0.7.0 only (2026-11-02, Linux, headless CLI): a static page built to Ready in 38 s, a follow-up continued the same session with `session/load`, and with Auto mode off its command and tool requests were refused in an unattended run. Replay suppression passes scripted load-history, success/error and cancellation tests; this correction has not been rerun with a live agent. Turns report 0 tokens over ACP || GitHub Copilot | Installed `copilot` through ACP by default, with CLI-owned login (no credential import), explicit Craft Anything MCP tool allowlist, model selection and fresh read-only build questions. Target handoff retains the last 128 entries with the active target last; context discovery respects tool cancellation and shared picker warnings name the agent | Authenticated builds, model discovery and real-account session resume confirmed by the person using the app. Target-boundary, cancellation and agent-warning regressions supplement unit tests and an offline CLI 1.0.105 compatibility test covering all five access modes. See [copilot.md](copilot.md) || Grok Build | Installed `grok` through ACP by default (`grok agent --no-leader stdio`). Sign-in stays in `grok login`. An existing `auth.json` counts as signed in and is not read; a missing file is unknown, so the run itself reports an authentication problem. `XAI_API_KEY` is separate: detection reads it and the xAI API backend can use it; this adapter does not. Clean room, deep chat, and questions are refused, because Grok can read and edit without a permission request and `grok agent` has no flag that holds those modes. A deep build is allowed. The chosen model is applied with `session/set_config_option` after `session/new`, because the CLI `--model` flag does not survive that call. Reasoning effort is passed after `agent` and set again after the model. Our MCP server is attached on the session, and only this agent is sent `"type": "stdio"`. The person's own Grok MCP servers are not removed. Thinking uses the shared model picker; there is no context-window control. `acp = false` and SSH are refused | Scripted ACP tests for the argument order, `"type": "stdio"` on Grok's server only, and `session/set_config_option` before the prompt, including a value the session already has. `initialize`, `session/new` and `session/set_config_option` were checked against Grok 1.0.77. A live deep build on 2026-11-06 (Grok 1.0.77, temporary ask-mode home) finished, called the Craft Anything server, and answered one permission request. The person's own config was not changed. See [grok.md](grok.md) |diff --git a/docs/pitfalls.md b/docs/pitfalls.mdindex 67808e28..3d2c41d0 100644--- a/docs/pitfalls.md+++ b/docs/pitfalls.md@@ -375,6 +375,10 @@ And when the shim's Node couldn't be found (nvm for Windows with no version in u`C:\Program Files\nodejs` link was gone), we fell back to the `.cmd`, and Rust refused themulti-line prompt: "batch file arguments are invalid", which named neither Node nor nvm. Searchnvm's version folders too, and when a shim's interpreter is missing, say so (`interpreter_missing`).+The desktop DeepSeek Harness has a custom batch launcher, so npm-shim handling does not unwrap+it either. Send its task on stdin, with no task argument. A literal `-` is a stdin marker in newer+Harness versions but is the task itself in older ones; omitting the task makes those older versions+fail before a model runs. They need an update to a headless profile that supports stdin.**A first analysis that waited for a lock it could never take.** Ghidra's analysis lock is createdwith `create_new` in `ghidra-cache/`, which only existed on machines that had used it before; on a