ouija 0.1.0-alpha.217

Cross-machine AI session daemon — bridges Claude Code sessions via tmux injection and Nostr P2P
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
use std::path::Path;

use super::{CodingAssistant, DeliveryMode, InjectConfig, ResumeOpts, StartOpts};

mod embedded {
    pub const PLUGIN_TS: &str = include_str!("../../opencode-plugin/ouija.ts");
    pub const SKILL_MD: &str = include_str!("../../skills/ouija/SKILL.md");
}

/// The legacy MCP URL that older ouija installs wrote into opencode's
/// `mcp.ouija` config. The `/mcp` route was removed from the daemon in
/// commit 2878926 "drop MCP tools, skill-only HATEOAS interface", and
/// any session that still has this entry keeps seeing SSE 404s from
/// opencode. We recognize it so we can clean it up.
const STALE_MCP_URL_PREFIX: &str = "http://localhost:7880/mcp";

/// Remove the dead `mcp.ouija` entry from an opencode config.
///
/// Only prunes if the entry's `url` points at `localhost:7880/mcp` (the
/// daemon's removed endpoint). User-provided custom URLs are left alone.
/// If pruning empties the surrounding `mcp` block entirely, the block
/// is removed too so configs don't accumulate empty objects.
fn prune_stale_mcp_ouija(config: &mut serde_json::Value) {
    let Some(obj) = config.as_object_mut() else {
        return;
    };
    let Some(mcp) = obj.get_mut("mcp").and_then(|v| v.as_object_mut()) else {
        return;
    };
    let stale = mcp
        .get("ouija")
        .and_then(|v| v.get("url"))
        .and_then(|v| v.as_str())
        .is_some_and(|u| u.starts_with(STALE_MCP_URL_PREFIX));
    if stale {
        mcp.remove("ouija");
    }
    if mcp.is_empty() {
        obj.remove("mcp");
    }
}

#[derive(Debug)]
pub struct OpenCode;

impl CodingAssistant for OpenCode {
    fn name(&self) -> &str {
        "opencode"
    }

    fn cli_name(&self) -> &str {
        "opencode"
    }

    fn process_names(&self) -> &[&str] {
        &["opencode"]
    }

    fn delivery_mode(&self) -> DeliveryMode {
        DeliveryMode::HttpApi {
            serve_command: "opencode serve".into(),
            attach_command: "opencode attach".into(),
        }
    }

    fn build_start_command(&self, opts: &StartOpts) -> String {
        // Placeholder: HttpApi sessions use the shared serve, so this is
        // only called as a fallback. The actual attach command is built
        // by start_session/restart_session after creating the opencode session.
        let escaped_dir = crate::scheduler::shell_escape(&opts.project_dir);
        format!("cd {escaped_dir} && echo 'waiting for opencode attach...'")
    }

    fn build_resume_command(&self, opts: &ResumeOpts) -> Option<String> {
        // Resume is handled via HTTP API on the shared serve
        let escaped_dir = crate::scheduler::shell_escape(&opts.project_dir);
        Some(format!(
            "cd {escaped_dir} && echo 'waiting for opencode attach...'"
        ))
    }

    fn detect_session_id(&self, _project_dir: &str) -> Option<String> {
        None
    }

    fn tui_ready_pattern(&self) -> Option<&str> {
        None
    }

    fn inject_config(&self) -> InjectConfig {
        // Fallback values if tmux injection is ever used; HttpApi mode bypasses this.
        InjectConfig {
            paste_settle_ms: 100,
            use_inner_bracketed_paste: false,
            startup_inject_delay_secs: 0,
        }
    }

    fn config_dir_name(&self) -> &str {
        ".opencode"
    }

    fn resolve_project_root<'a>(&self, path: &'a str) -> &'a str {
        path
    }

    fn has_project_history(&self, dir: &Path) -> bool {
        dir.join(".opencode").is_dir()
    }

    fn exit_command(&self) -> Option<&str> {
        None
    }

    fn install(&self) -> anyhow::Result<()> {
        let home = std::env::var("HOME")
            .map(std::path::PathBuf::from)
            .map_err(|_| anyhow::anyhow!("HOME environment variable not set"))?;

        let config_dir = home.join(".config/opencode");
        let config_path = config_dir.join("opencode.json");

        // Write the plugin file
        let plugins_dir = config_dir.join("plugins");
        std::fs::create_dir_all(&plugins_dir)?;
        std::fs::write(plugins_dir.join("ouija.ts"), embedded::PLUGIN_TS)?;

        // Write the ouija skill for OpenCode's skill discovery
        let skills_dir = config_dir.join("skills/ouija");
        std::fs::create_dir_all(&skills_dir)?;
        std::fs::write(skills_dir.join("SKILL.md"), embedded::SKILL_MD)?;

        let mut config: serde_json::Value = match std::fs::read_to_string(&config_path) {
            Ok(content) => serde_json::from_str(&content).unwrap_or_else(|_| serde_json::json!({})),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                std::fs::create_dir_all(&config_dir)?;
                serde_json::json!({ "$schema": "https://opencode.ai/config.json" })
            }
            Err(e) => return Err(e.into()),
        };

        // The `/mcp` route was removed from the daemon in commit 2878926.
        // Older installs wrote `mcp.ouija → http://localhost:7880/mcp`
        // into opencode.json, which causes persistent SSE 404 errors in
        // opencode's MCP sidebar. Prune the stale entry if present and
        // do NOT write a new one — ouija is skill+REST only now.
        prune_stale_mcp_ouija(&mut config);

        let obj = config
            .as_object_mut()
            .ok_or_else(|| anyhow::anyhow!("opencode config is not a JSON object"))?;

        // Add plugin to the plugin array (merge, don't overwrite)
        let plugin_file = plugins_dir.join("ouija.ts");
        let plugin_path = format!("file://{}", plugin_file.display());
        let plugins = obj.entry("plugin").or_insert_with(|| serde_json::json!([]));
        if let Some(arr) = plugins.as_array_mut() {
            // Remove old relative-path entry if present
            arr.retain(|v| v.as_str() != Some("./plugins/ouija.ts"));
            if !arr.iter().any(|v| v.as_str() == Some(&plugin_path)) {
                arr.push(serde_json::json!(plugin_path));
            }
        }

        std::fs::write(&config_path, serde_json::to_string_pretty(&config)?)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::backend::{ResumeOpts, StartOpts};

    fn backend() -> OpenCode {
        OpenCode
    }

    #[test]
    fn start_command_basic() {
        let cmd = backend().build_start_command(&StartOpts {
            project_dir: "/home/user/myproject".to_string(),
            worktree: None,
            model: None,
            effort: None,
            permission_mode: None,
            codex_home: None,
        });
        // HttpApi backends use shared serve; start command is a placeholder
        assert!(cmd.contains("/home/user/myproject"));
    }

    #[test]
    fn resume_command_returns_some() {
        let cmd = backend().build_resume_command(&ResumeOpts {
            project_dir: "/home/user/myproject".to_string(),
            session_id: None,
            worktree: None,
            model: None,
            effort: None,
            permission_mode: None,
            codex_home: None,
        });
        assert!(cmd.is_some());
        assert!(cmd.unwrap().contains("/home/user/myproject"));
    }

    #[test]
    fn detect_session_id_always_none() {
        assert_eq!(backend().detect_session_id("/home/user/myproject"), None);
        assert_eq!(backend().detect_session_id("/some/other/path"), None);
    }

    #[test]
    fn plugin_prompt_uses_public_session_id_for_sender_examples() {
        assert!(
            embedded::PLUGIN_TS.contains("ouija ask TARGET \"question\" --from ${publicSessionId}"),
            "OpenCode prompt must teach non-tmux tools to send from the resolved public Ouija session id"
        );
        assert!(
            embedded::PLUGIN_TS.contains("ouija tell TARGET \"info\" --from ${publicSessionId}"),
            "OpenCode prompt must not imply the backend label is a valid sender id"
        );
        assert!(
            embedded::PLUGIN_TS
                .contains("ouija reply TARGET N \"result\" --from ${publicSessionId}"),
            "OpenCode prompt must use the public session id for replies"
        );
        assert!(
            embedded::PLUGIN_TS.contains(
                "ouija tell TARGET \"working on it\" --reply-to N --from ${publicSessionId}"
            ),
            "OpenCode prompt must use the public session id for progress updates"
        );
    }

    #[test]
    fn embedded_skill_distinguishes_public_session_id_from_opencode_backend_ids() {
        assert!(
            embedded::SKILL_MD.contains("ouija ask target-id \"question\" --from public-ouija-id"),
            "skill must show ask with the public Ouija sender id"
        );
        assert!(
            embedded::SKILL_MD
                .contains("Never use `opencode` or an OpenCode `backend_session_id` as `--from`"),
            "skill must warn against backend labels and opaque backend session ids"
        );
    }

    // --- anti-guessing sender guidance (task #1395) ---
    //
    // An opencode agent that could not resolve its identity guessed the
    // project basename as --from, which named a real sibling session and
    // misrouted the reply. Both the injected OpenCode prompt and the skill
    // must direct agents to `ouija whoami` and explicitly forbid inferring
    // a sender id from anything else.

    #[test]
    fn plugin_prompt_directs_unresolved_identity_to_whoami_not_guesses() {
        assert!(
            embedded::PLUGIN_TS.contains("ouija whoami"),
            "OpenCode prompt must name the whoami command for unresolved identities"
        );
        assert!(
            embedded::PLUGIN_TS.contains("Never guess"),
            "OpenCode prompt must explicitly forbid guessing a sender id"
        );
        assert!(
            !embedded::PLUGIN_TS.contains("<public-ouija-id>"),
            "bare placeholder invites substituting a guessed id; it must be gone"
        );
        // Fail-closed policy (#1395 review f0, option B): while the id is
        // unresolved the daemon rejects sends even with a correct hand-typed
        // --from, so the prompt must say the fix is the environment, not
        // retrying with another id.
        assert!(
            embedded::PLUGIN_TS.contains("fail-closed"),
            "OpenCode prompt must explain the daemon fail-closes sends while \
             the caller's identity is unresolved"
        );
        assert!(
            embedded::PLUGIN_TS.contains("even a correct"),
            "OpenCode prompt must warn that even a correct id is rejected \
             until identity resolves"
        );
    }

    #[test]
    fn embedded_skill_forbids_inferring_sender_from_project_basename() {
        assert!(
            embedded::SKILL_MD.contains("ouija whoami"),
            "skill section 7 must teach `ouija whoami` as the identity source"
        );
        assert!(
            embedded::SKILL_MD.contains("Never guess"),
            "skill must explicitly forbid guessing a sender id"
        );
        assert!(
            embedded::SKILL_MD.contains("project directory"),
            "skill must name the project-basename guess that caused the incident"
        );
        assert!(
            !embedded::SKILL_MD.contains("such as `hub` or `feat/123-worker`"),
            "the old example read as an invitation to invent a plausible-looking id"
        );
    }

    #[test]
    fn has_project_history_with_opencode_dir() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir(tmp.path().join(".opencode")).unwrap();
        assert!(backend().has_project_history(tmp.path()));
    }

    #[test]
    fn has_project_history_without_opencode_dir() {
        let tmp = tempfile::tempdir().unwrap();
        assert!(!backend().has_project_history(tmp.path()));
    }

    #[test]
    fn prune_stale_mcp_ouija_removes_legacy_url() {
        // Commit 2878926 dropped the /mcp route from the daemon, but the
        // install logic kept writing mcp.ouija. Anyone who ran an older
        // ouija still has this dead entry in their opencode.json.
        let mut config = serde_json::json!({
            "mcp": {
                "ouija": {
                    "type": "remote",
                    "url": "http://localhost:7880/mcp",
                    "oauth": false,
                },
                "other": { "type": "local", "command": ["echo"] },
            }
        });
        prune_stale_mcp_ouija(&mut config);
        assert!(
            config["mcp"].get("ouija").is_none(),
            "stale mcp.ouija should be removed, got {config:#}"
        );
        assert!(
            config["mcp"].get("other").is_some(),
            "unrelated mcp entries must be preserved, got {config:#}"
        );
    }

    #[test]
    fn prune_stale_mcp_ouija_leaves_non_default_url_alone() {
        // If a user has manually pointed mcp.ouija at some other URL
        // (e.g. a hand-rolled MCP bridge), don't clobber their config.
        let mut config = serde_json::json!({
            "mcp": {
                "ouija": {
                    "type": "remote",
                    "url": "https://example.internal/ouija-mcp",
                    "oauth": false,
                }
            }
        });
        prune_stale_mcp_ouija(&mut config);
        assert!(
            config["mcp"]["ouija"].is_object(),
            "custom mcp.ouija URL must be preserved, got {config:#}"
        );
    }

    #[test]
    fn prune_stale_mcp_ouija_tolerates_missing_mcp_block() {
        let mut config = serde_json::json!({ "plugin": [] });
        // Must not panic, must not inject an `mcp` block.
        prune_stale_mcp_ouija(&mut config);
        assert!(
            config.get("mcp").is_none(),
            "should not add an mcp block when none exists, got {config:#}"
        );
    }

    #[test]
    fn prune_stale_mcp_ouija_removes_empty_mcp_after_pruning() {
        // If mcp.ouija was the only entry, the whole mcp block becomes
        // empty — clean it up so the user's config doesn't accrue noise.
        let mut config = serde_json::json!({
            "mcp": {
                "ouija": {
                    "type": "remote",
                    "url": "http://localhost:7880/mcp",
                }
            }
        });
        prune_stale_mcp_ouija(&mut config);
        assert!(
            config.get("mcp").is_none() || config["mcp"].as_object().is_some_and(|m| m.is_empty()),
            "mcp block should be removed or empty after prune, got {config:#}"
        );
    }

    #[test]
    fn resolve_project_root_unchanged() {
        let b = backend();
        assert_eq!(
            b.resolve_project_root("/home/user/myproject"),
            "/home/user/myproject"
        );
        assert_eq!(
            b.resolve_project_root("/home/user/myproject/subdir"),
            "/home/user/myproject/subdir"
        );
    }
}