Skip to content

A skill to stop your coding agent from burying the answer. ADHD-friendly output.

Support OMP session context API

OMP Agent3bbfaaac7549
diff --git a/INSTALL.md b/INSTALL.md
index 23ad92b..05efb70 100644
--- a/INSTALL.md
+++ b/INSTALL.md
@@ -460,6 +460,35 @@ If `PI_CODING_AGENT_DIR` is set, put `.i-have-adhd-always` in that directory ins
</details>
+<details>
+<summary><strong>Oh My Pi (OMP)</strong></summary>
+
+### Install
+
+```bash
+omp plugin marketplace add ayghri/i-have-adhd
+omp plugin install --scope user i-have-adhd@i-have-adhd
+```
+
+Start a new OMP session and run `/i-have-adhd` to toggle the mode.
+
+### Update
+
+```bash
+omp plugin marketplace update i-have-adhd
+omp plugin upgrade --scope user i-have-adhd@i-have-adhd
+```
+
+### Uninstall
+
+```bash
+omp plugin uninstall --scope user i-have-adhd@i-have-adhd
+omp plugin marketplace remove i-have-adhd
+```
+
+</details>
+
+
<details>
<summary><strong>Qwen Code</strong></summary>
diff --git a/extensions/context-compat.ts b/extensions/context-compat.ts
new file mode 100644
index 0000000..2d8a1f4
--- /dev/null
+++ b/extensions/context-compat.ts
@@ -0,0 +1,66 @@
+export type ContextMessageMarker = Readonly<{
+ type?: string;
+ role?: string;
+ customType?: string;
+}>;
+
+type CompatibleSessionManager = {
+ buildSessionContext?: () => { messages: readonly ContextMessageMarker[] };
+ buildContextEntries?: () => readonly ContextMessageMarker[];
+};
+
+export function contextMessages(
+ sessionManager: unknown,
+): readonly ContextMessageMarker[] {
+ if (sessionManager === null || typeof sessionManager !== "object") {
+ throw new Error("Unsupported session manager: expected an object");
+ }
+
+ const compatible = sessionManager as CompatibleSessionManager;
+
+ if (typeof compatible.buildSessionContext === "function") {
+ const messages = compatible.buildSessionContext().messages;
+ if (!Array.isArray(messages)) {
+ throw new Error(
+ "Unsupported session manager: buildSessionContext() returned no messages array",
+ );
+ }
+ return messages;
+ }
+
+ if (typeof compatible.buildContextEntries === "function") {
+ const entries = compatible.buildContextEntries();
+ if (!Array.isArray(entries)) {
+ throw new Error(
+ "Unsupported session manager: buildContextEntries() returned no entries array",
+ );
+ }
+ return entries;
+ }
+
+ throw new Error(
+ "Unsupported session manager: expected buildSessionContext() or buildContextEntries()",
+ );
+}
+
+export function latestMarkerIsActive(
+ messages: readonly ContextMessageMarker[],
+ activeType: string,
+ disabledType: string,
+): boolean {
+ let active = false;
+
+ for (const message of messages) {
+ if (message.role !== "custom" && message.type !== "custom_message") {
+ continue;
+ }
+
+ if (message.customType === activeType) {
+ active = true;
+ } else if (message.customType === disabledType) {
+ active = false;
+ }
+ }
+
+ return active;
+}
diff --git a/extensions/i-have-adhd.ts b/extensions/i-have-adhd.ts
index 8e43fba..351a3b8 100644
--- a/extensions/i-have-adhd.ts
+++ b/extensions/i-have-adhd.ts
@@ -6,6 +6,10 @@ import {
type ExtensionAPI,
type ExtensionContext,
} from "@earendil-works/pi-coding-agent";
+import {
+ contextMessages,
+ latestMarkerIsActive,
+} from "./context-compat";
const EXTENSION_DIR = dirname(fileURLToPath(import.meta.url));
const SKILL_PATH = join(
@@ -84,19 +88,11 @@ function getSavedState(ctx: ExtensionContext): boolean | undefined {
* injected again.
*/
function rulesAreInContext(ctx: ExtensionContext): boolean {
- let active = false;
-
- for (const entry of ctx.sessionManager.buildContextEntries()) {
- if (entry.type !== "custom_message") continue;
-
- if (entry.customType === RULES_MESSAGE_TYPE) {
- active = true;
- } else if (entry.customType === DISABLED_MESSAGE_TYPE) {
- active = false;
- }
- }
-
- return active;
+ return latestMarkerIsActive(
+ contextMessages(ctx.sessionManager),
+ RULES_MESSAGE_TYPE,
+ DISABLED_MESSAGE_TYPE,
+ );
}
export default function iHaveAdhdExtension(pi: ExtensionAPI) {
diff --git a/package.json b/package.json
index f3da071..3b52be8 100644
--- a/package.json
+++ b/package.json
@@ -6,6 +6,9 @@
"homepage": "https://github.com/ayghri/i-have-adhd",
"private": true,
"keywords": ["pi-package"],
+ "omp": {
+ "extensions": ["./extensions/i-have-adhd.ts"]
+ },
"pi": {
"extensions": ["./extensions/i-have-adhd.ts"],
"skills": ["./skills"]
diff --git a/scripts/check_context_compat.ts b/scripts/check_context_compat.ts
new file mode 100644
index 0000000..dcc3b90
--- /dev/null
+++ b/scripts/check_context_compat.ts
@@ -0,0 +1,85 @@
+import {
+ contextMessages,
+ latestMarkerIsActive,
+} from "../extensions/context-compat";
+
+const ACTIVE = "i-have-adhd-rules";
+const DISABLED = "i-have-adhd-disabled";
+
+function assert(condition: unknown, message: string): asserts condition {
+ if (!condition) {
+ throw new Error(message);
+ }
+}
+
+const ompMessages = [{ role: "custom", customType: ACTIVE }];
+const ompManager = {
+ buildSessionContext: () => ({ messages: ompMessages }),
+ buildContextEntries: () => {
+ throw new Error("Pi fallback must not run when OMP API is available");
+ },
+};
+assert(
+ contextMessages(ompManager) === ompMessages,
+ "OMP session-context messages were not returned",
+);
+
+const piEntries = [{ type: "custom_message", customType: ACTIVE }];
+const piManager = {
+ buildContextEntries: () => piEntries,
+};
+assert(
+ contextMessages(piManager) === piEntries,
+ "Pi context entries were not returned",
+);
+
+let unsupportedFailed = false;
+try {
+ contextMessages({});
+} catch (error) {
+ unsupportedFailed =
+ error instanceof Error &&
+ error.message.includes(
+ "expected buildSessionContext() or buildContextEntries()",
+ );
+}
+assert(unsupportedFailed, "Unsupported session managers must fail closed");
+
+assert(
+ latestMarkerIsActive(
+ [
+ { role: "custom", customType: ACTIVE },
+ { role: "custom", customType: DISABLED },
+ { role: "custom", customType: ACTIVE },
+ ],
+ ACTIVE,
+ DISABLED,
+ ),
+ "OMP marker ordering was not preserved",
+);
+
+assert(
+ !latestMarkerIsActive(
+ [
+ { type: "custom_message", customType: ACTIVE },
+ { type: "custom_message", customType: DISABLED },
+ ],
+ ACTIVE,
+ DISABLED,
+ ),
+ "Pi marker ordering was not preserved",
+);
+
+assert(
+ !latestMarkerIsActive(
+ [
+ { role: "user", customType: ACTIVE },
+ { type: "message", customType: ACTIVE },
+ ],
+ ACTIVE,
+ DISABLED,
+ ),
+ "Ordinary messages must not activate the rules",
+);
+
+console.log("Pi/OMP context compatibility checks passed");
diff --git a/scripts/check_pi_extension.py b/scripts/check_pi_extension.py
index 248d2b0..1cd3fa6 100644
--- a/scripts/check_pi_extension.py
+++ b/scripts/check_pi_extension.py
@@ -1,16 +1,18 @@
#!/usr/bin/env python3
-"""Smoke-test the Pi package without making a model request."""
+"""Smoke-test the Pi or OMP package without making a model request."""
from __future__ import annotations
+import argparse
import json
import os
import queue
+import shutil
import subprocess
import tempfile
import threading
from pathlib import Path
-from typing import Any
+from typing import Any, Callable
ROOT = Path(__file__).resolve().parents[1]
@@ -31,13 +33,21 @@ def validate_package_manifest() -> None:
"extensions": ["./extensions/i-have-adhd.ts"],
"skills": ["./skills"],
}
+ assert package.get("omp") == {
+ "extensions": ["./extensions/i-have-adhd.ts"],
+ }
class RpcClient:
- def __init__(self, env: dict[str, str], *args: str) -> None:
+ def __init__(
+ self,
+ executable: str,
+ env: dict[str, str],
+ *args: str,
+ ) -> None:
self.stderr_file = tempfile.TemporaryFile(mode="w+t")
self.process = subprocess.Popen(
- ["pi", "--mode", "rpc", *args],
+ [executable, "--mode", "rpc", *args],
cwd=ROOT,
env=env,
stdin=subprocess.PIPE,
@@ -46,7 +56,7 @@ class RpcClient:
text=True,
)
if self.process.stdout is None:
- raise RuntimeError("Pi RPC stdout is unavailable")
+ raise RuntimeError("Agent RPC stdout is unavailable")
self.stdout_lines: queue.Queue[str | None] = queue.Queue()
self.stdout_thread = threading.Thread(
@@ -75,7 +85,7 @@ class RpcClient:
command: dict[str, Any],
) -> tuple[dict[str, Any], list[dict[str, Any]]]:
if self.process.stdin is None:
- raise RuntimeError("Pi RPC stdin is unavailable")
+ raise RuntimeError("Agent RPC stdin is unavailable")
payload = {"id": request_id, **command}
self.process.stdin.write(json.dumps(payload) + "\n")
@@ -87,12 +97,12 @@ class RpcClient:
line = self.stdout_lines.get(timeout=RPC_TIMEOUT_SECONDS)
except queue.Empty as error:
raise TimeoutError(
- f"Pi RPC did not respond within {RPC_TIMEOUT_SECONDS} seconds",
+ f"Agent RPC did not respond within {RPC_TIMEOUT_SECONDS} seconds",
) from error
if line is None:
raise RuntimeError(
- f"Pi RPC exited before responding: {self._read_stderr()}",
+ f"Agent RPC exited before responding: {self._read_stderr()}",
)
event = json.loads(line)
@@ -100,6 +110,31 @@ class RpcClient:
if event.get("type") == "response" and event.get("id") == request_id:
return event, events
+ def events_until(
+ self,
+ predicate: Callable[[dict[str, Any]], bool],
+ ) -> list[dict[str, Any]]:
+ events: list[dict[str, Any]] = []
+ while True:
+ try:
+ line = self.stdout_lines.get(timeout=RPC_TIMEOUT_SECONDS)
+ except queue.Empty as error:
+ raise TimeoutError(
+ f"Agent RPC did not emit the expected event within "
+ f"{RPC_TIMEOUT_SECONDS} seconds",
+ ) from error
+
+ if line is None:
+ raise RuntimeError(
+ f"Agent RPC exited before emitting the expected event: "
+ f"{self._read_stderr()}",
+ )
+
+ event = json.loads(line)
+ events.append(event)
+ if predicate(event):
+ return events
+
def close(self) -> None:
if self.process.stdin is not None:
self.process.stdin.close()
@@ -115,7 +150,7 @@ class RpcClient:
self.stderr_file.close()
if return_code not in (0, -15):
- raise RuntimeError(f"Pi RPC exited with {return_code}: {stderr}")
+ raise RuntimeError(f"Agent RPC exited with {return_code}: {stderr}")
def build_isolated_env(agent_dir: str) -> dict[str, str]:
@@ -166,18 +201,45 @@ def latest_enabled(entries_response: dict[str, Any]) -> bool:
return states[-1]
+def parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser(
+ description="Smoke-test the i-have-adhd extension without a model request."
+ )
+ parser.add_argument(
+ "--runtime",
+ choices=("pi", "omp"),
+ default="pi",
+ help="Agent runtime to exercise (default: pi)",
+ )
+ return parser.parse_args()
+
+
def main() -> None:
+ args = parse_args()
validate_package_manifest()
+ executable = shutil.which(args.runtime)
+ if executable is None:
+ raise RuntimeError(f"{args.runtime} executable is not available")
- with tempfile.TemporaryDirectory(prefix="i-have-adhd-pi-") as agent_dir:
+ with tempfile.TemporaryDirectory(
+ prefix=f"i-have-adhd-{args.runtime}-"
+ ) as agent_dir:
env = build_isolated_env(agent_dir)
- subprocess.run(
- ["pi", "install", str(ROOT)],
- cwd=ROOT,
- env=env,
- check=True,
- capture_output=True,
- text=True,
+ if args.runtime == "omp":
+ env.pop("PI_CODING_AGENT_DIR", None)
+ if args.runtime == "pi":
+ subprocess.run(
+ [executable, "install", str(ROOT)],
+ cwd=ROOT,
+ env=env,
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+ extension_args = (
+ []
+ if args.runtime == "pi"
+ else ["--no-extensions", "-e", str(ROOT)]
)
reload_probe = Path(agent_dir, "reload-probe.ts")
@@ -208,12 +270,37 @@ export default function (pi: ExtensionAPI) {
)
client = RpcClient(
+ executable,
env,
"--no-session",
+ *extension_args,
"-e",
str(reload_probe),
"--adhd",
)
+ if args.runtime == "omp":
+ try:
+ startup_events = client.events_until(
+ lambda event: event.get("type")
+ == "available_commands_update",
+ )
+ command_event = startup_events[-1]
+ command_names = {
+ command["name"]
+ for command in command_event["commands"]
+ }
+ assert "i-have-adhd" in command_names
+ assert "skill:i-have-adhd" in command_names
+ assert any(
+ "ADHD ON" in (text or "")
+ for text in status_texts(startup_events)
+ )
+ finally:
+ client.close()
+
+ print("omp extension smoke test passed")
+ return
+
try:
commands, startup_events = client.request("commands", {"type": "get_commands"})
command_names = {command["name"] for command in commands["data"]["commands"]}
@@ -314,21 +401,27 @@ export default function (pi: ExtensionAPI) {
finally:
client.close()
- Path(agent_dir, ".i-have-adhd-always").touch()
- always_on = RpcClient(env, "--no-session")
- try:
- _, always_on_events = always_on.request(
- "always-on",
- {"type": "get_state"},
- )
- assert any(
- "ADHD ON" in (text or "")
- for text in status_texts(always_on_events)
+ if args.runtime == "pi":
+ Path(agent_dir, ".i-have-adhd-always").touch()
+ always_on = RpcClient(
+ executable,
+ env,
+ "--no-session",
+ *extension_args,
)
- finally:
- always_on.close()
+ try:
+ _, always_on_events = always_on.request(
+ "always-on",
+ {"type": "get_state"},
+ )
+ assert any(
+ "ADHD ON" in (text or "")
+ for text in status_texts(always_on_events)
+ )
+ finally:
+ always_on.close()
- print("Pi extension smoke test passed")
+ print(f"{args.runtime} extension smoke test passed")
if __name__ == "__main__":
diff --git a/tests/test_omp_package.py b/tests/test_omp_package.py
new file mode 100644
index 0000000..51d9f7a
--- /dev/null
+++ b/tests/test_omp_package.py
@@ -0,0 +1,31 @@
+import json
+import unittest
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+class OmpPackageTest(unittest.TestCase):
+ def setUp(self):
+ self.package = json.loads((ROOT / "package.json").read_text(encoding="utf8"))
+
+ def test_omp_and_pi_extension_manifests_are_declared(self):
+ extension = ["./extensions/i-have-adhd.ts"]
+ self.assertEqual({"extensions": extension}, self.package["omp"])
+ self.assertEqual(
+ {"extensions": extension, "skills": ["./skills"]},
+ self.package["pi"],
+ )
+
+ def test_skill_remains_explicitly_invoked(self):
+ skill = (ROOT / "skills" / "i-have-adhd" / "SKILL.md").read_text(
+ encoding="utf8"
+ )
+ frontmatter = skill.split("---\n", 2)[1]
+ self.assertIn("name: i-have-adhd", frontmatter)
+ self.assertIn("disable-model-invocation: true", frontmatter)
+
+
+if __name__ == "__main__":
+ unittest.main()