ouija 0.1.0-alpha.237

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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
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");
}

/// True when the installed opencode plugin or skill differs from the embedded
/// copy, i.e. when a running `opencode serve` would actually load something new.
///
/// Callers must check this *before* `install()` overwrites the files. Most
/// releases change only the daemon binary, so restarting `opencode serve`
/// aborts every in-flight worker turn for nothing.
pub(crate) fn installed_plugin_differs() -> bool {
    let Ok(home) = std::env::var("HOME") else {
        // Cannot tell — say nothing rather than prompt a needless restart.
        return false;
    };
    let config_dir = std::path::PathBuf::from(home).join(".config/opencode");
    let differs = |path: std::path::PathBuf, embedded: &str| {
        std::fs::read_to_string(path)
            .map(|on_disk| on_disk != embedded)
            .unwrap_or(true)
    };
    differs(config_dir.join("plugins/ouija.ts"), embedded::PLUGIN_TS)
        || differs(config_dir.join("skills/ouija/SKILL.md"), embedded::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 caller_session_id(&self) -> Option<String> {
        std::env::var("OPENCODE_SESSION_ID")
            .ok()
            .filter(|session_id| !session_id.is_empty())
    }

    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 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};
    use std::sync::{Mutex, MutexGuard};

    static CALLER_SESSION_ENV_LOCK: Mutex<()> = Mutex::new(());

    struct ScopedEnvVar {
        name: &'static str,
        previous: Option<std::ffi::OsString>,
        _lock: MutexGuard<'static, ()>,
    }

    impl ScopedEnvVar {
        fn set(name: &'static str, value: Option<&str>) -> Self {
            let lock = CALLER_SESSION_ENV_LOCK
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let previous = std::env::var_os(name);
            unsafe {
                match value {
                    Some(value) => std::env::set_var(name, value),
                    None => std::env::remove_var(name),
                }
            }
            Self {
                name,
                previous,
                _lock: lock,
            }
        }
    }

    impl Drop for ScopedEnvVar {
        fn drop(&mut self) {
            unsafe {
                match self.previous.take() {
                    Some(value) => std::env::set_var(self.name, value),
                    None => std::env::remove_var(self.name),
                }
            }
        }
    }

    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 caller_session_reads_only_nonempty_opencode_session_id() {
        let _missing = ScopedEnvVar::set("OPENCODE_SESSION_ID", None);
        assert_eq!(backend().caller_session_id(), None);
        drop(_missing);

        let _empty = ScopedEnvVar::set("OPENCODE_SESSION_ID", Some(""));
        assert_eq!(backend().caller_session_id(), None);
        drop(_empty);

        let _present = ScopedEnvVar::set("OPENCODE_SESSION_ID", Some("ses_exact"));
        assert_eq!(backend().caller_session_id().as_deref(), Some("ses_exact"));
    }

    #[test]
    fn caller_session_plugin_exports_exact_shell_identity() {
        assert!(
            embedded::PLUGIN_TS.contains("\"shell.env\": async (input, output) =>"),
            "OpenCode plugin must define the documented shell.env hook"
        );
        assert!(
            embedded::PLUGIN_TS.contains("output.env.OPENCODE_SESSION_ID = input.sessionID"),
            "tool shells must receive only their exact OpenCode session identity"
        );
    }

    #[test]
    fn caller_session_registry_rejects_two_positive_backend_signals() {
        let _opencode = ScopedEnvVar::set("OPENCODE_SESSION_ID", Some("ses_opencode"));
        // The environment helper intentionally serializes only this module's
        // mutations. Set the second signal within the same scope so the
        // registry observes both identities atomically from this test.
        let previous_codex = std::env::var_os("CODEX_THREAD_ID");
        unsafe {
            std::env::set_var("CODEX_THREAD_ID", "thread_codex");
        }
        let identity =
            crate::backend::BackendRegistry::default_registry().caller_session_identity();
        unsafe {
            match previous_codex {
                Some(value) => std::env::set_var("CODEX_THREAD_ID", value),
                None => std::env::remove_var("CODEX_THREAD_ID"),
            }
        }
        assert_eq!(
            identity, None,
            "ambiguous adapter evidence must fail closed"
        );
    }

    #[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 plugin_tracks_incarnation_per_backend_session() {
        assert!(
            embedded::PLUGIN_TS.contains("new Map<string, string>()"),
            "readiness state must be per OpenCode backend session"
        );
        assert!(
            embedded::PLUGIN_TS.contains("body.session_incarnation = incarnation"),
            "activity hooks must carry the exact ready incarnation"
        );
        assert!(
            embedded::PLUGIN_TS.contains("sessionIncarnations.set"),
            "ready responses must refresh exact backend-session authority"
        );
    }

    #[test]
    fn embedded_skill_distinguishes_public_session_id_from_opencode_backend_ids() {
        assert!(
            embedded::SKILL_MD.contains(
                "Public Ouija IDs and backend-native conversation IDs are different identities"
            ),
            "skill must distinguish public Ouija and backend-native identities"
        );
        assert!(
            embedded::SKILL_MD.contains("never use `opencode` or a backend session ID as `--from`"),
            "skill must warn against backend labels and opaque backend session ids"
        );
    }

    #[test]
    fn embedded_skill_teaches_opt_in_task_reminders_for_opencode() {
        crate::backend::assert_shared_task_reminder_guidance(embedded::SKILL_MD);
    }

    // --- 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"
        );
        assert!(
            embedded::PLUGIN_TS.contains("fail-closed"),
            "OpenCode prompt must preserve fail-closed implicit whoami guidance"
        );
        assert!(
            embedded::PLUGIN_TS
                .contains("exact injected or operator-provided public Local session id"),
            "OpenCode prompt must allow an authoritative explicit Local id even when implicit \
             whoami is unresolved"
        );
        assert!(
            !embedded::PLUGIN_TS.contains("even a correct hand-typed"),
            "OpenCode prompt must not claim authoritative explicit Local ids are refused"
        );
    }

    #[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 a sender from a project"),
            "skill must explicitly forbid guessing a sender id"
        );
        assert!(
            embedded::SKILL_MD.contains("project, branch, role, process, or `ouija ls`"),
            "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"
        );
        assert!(
            embedded::SKILL_MD.contains("trusted injected context or the operator"),
            "skill must distinguish authoritative explicit Local ids from guesses"
        );
        assert!(
            embedded::SKILL_MD.contains("Never run `ouija register` to repair caller identity"),
            "skill must reject duplicate registration as identity recovery"
        );
    }

    #[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:#}"
        );
    }
}