Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180"""The composers offer skill completion exactly where the daemon reads a mention.
The daemon activates a skill named `$name` in prose(packages/albedo_sdk/src/albedo_sdk/skills/mentions.gleam). The TUI(cli/internal/tui/skill_mentions.go) and the web client(web/src/lib/skill-mentions.ts) each re-implement where a `$` starts amention, to offer completion while it is typed. A composer that disagreesoffers a name the daemon then ignores, or offers none where it would load one.The three are different languages, and Go counts runes where TypeScript countsUTF-16 units, so only running all three on the same drafts catches adisagreement.
Each generated draft ends where the cursor is. The oracle completes the typedname with a suffix no draft contains and asks the daemon's parser whether thecompleted name is a mention; both composers must offer completion exactlythen, with the typed prefix and the mention's span in their own units."""
from __future__ import annotations
import jsonimport osfrom pathlib import Pathimport subprocessimport sysimport tempfileimport unittest
HERE = Path(__file__).resolve().parentROOT = HERE.parents[1]sys.path.insert(0, str(HERE))sys.path.insert(0, str(HERE.parent))
import hypothesis_profiles # noqa: E402,F401from hypothesis import given, settings, strategies as st # noqa: E402
from support import GleamPeer # noqa: E402
# No piece contains these, so a completed name is new to every draft.COMPLETION = "QZ"NAME = frozenset("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-")
INLINE = [ "$", "$re", "$$", "\\", "\\$", "\\`", "`", "`", "``", "```", " ", " ", "re", "word", "price", '"', "*", "**", "_", "—", "(", "é", "e\u0301", "😀", "𝄞", "中",]INDENTS = ["", "", "", " ", " ", " ", "\t", " \t"]FENCES = ["```", "~~~", "````", "```py", "~~~ x", "``", "~~", "``` "]MENTIONS = ["$", "$r", "$re", "$r-e_1", " $re", "`$re", "\\$re", "$$re", "x$re"]
prose = st.lists(st.sampled_from(INLINE), max_size=6).map("".join)line = st.one_of( st.tuples(st.sampled_from(INDENTS), st.sampled_from(FENCES)).map("".join), st.tuples(st.sampled_from(INDENTS), prose).map("".join),)# Earlier lines, then the line the cursor ends: its indent, prose that may# open or close inline code, and a typed mention.drafts = st.tuples( st.lists(line, max_size=5), st.sampled_from(INDENTS), prose, st.sampled_from(MENTIONS),).map(lambda parts: "\n".join([*parts[0], parts[1] + parts[2] + parts[3]]))
class Helper: """A long-lived process answering one JSON batch per line."""
def __init__(self, args: list[str], cwd: Path) -> None: self._process = subprocess.Popen( args, cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True )
def call(self, cases: list[dict]) -> list: assert self._process.stdin is not None and self._process.stdout is not None self._process.stdin.write(json.dumps(cases) + "\n") self._process.stdin.flush() answer = json.loads(self._process.stdout.readline()) assert isinstance(answer, list) and len(answer) == len(cases) return answer
def close(self) -> None: assert self._process.stdin is not None self._process.stdin.close() self._process.wait(timeout=10)
def utf16(text: str) -> int: return len(text.encode("utf-16-le")) // 2
class SkillMentionsTest(unittest.TestCase): peer: GleamPeer tui: Helper web: Helper
@classmethod def setUpClass(cls) -> None: cls.peer = GleamPeer() binary = Path(tempfile.mkdtemp(prefix="mentioncheck-")) / "mentioncheck" subprocess.run( ["go", "build", "-o", str(binary), "./internal/tui/mentioncheck"], cwd=ROOT / "cli", check=True, env=dict(os.environ, CGO_ENABLED="0"), ) cls.tui = Helper([str(binary)], ROOT) cls.web = Helper(["node", "web/scripts/skill-mentions-check.mjs"], ROOT)
@classmethod def tearDownClass(cls) -> None: cls.peer.close() cls.tui.close() cls.web.close()
@settings(max_examples=hypothesis_profiles.cases(200)) @given(st.lists(drafts, min_size=1, max_size=40)) def test_composers_offer_completion_where_the_daemon_reads_a_mention( self, texts: list[str] ) -> None: names = self.peer.call( "skill_mentions", "names", [{"text": t + COMPLETION} for t in texts] ) tui = self.tui.call([{"text": t, "cursor": len(t)} for t in texts]) web = self.web.call([{"text": t, "cursor": utf16(t)} for t in texts]) for text, read, offered_tui, offered_web in zip(texts, names, tui, web): assert isinstance(read, list) typed = len(text) - len(text.rstrip("".join(NAME))) prefix = text[len(text) - typed :] dollar = len(text) - typed - 1 mention = ( dollar >= 0 and text[dollar] == "$" and prefix + COMPLETION in read ) if not mention: self.assertIsNone( offered_tui, f"TUI offered in {text!r}; daemon reads {read}" ) self.assertIsNone( offered_web, f"web offered in {text!r}; daemon reads {read}" ) continue self.assertEqual( offered_tui, {"prefix": prefix, "start": dollar, "end": len(text)}, f"TUI in {text!r}", ) self.assertEqual( offered_web, {"prefix": prefix, "start": utf16(text[:dollar]), "end": utf16(text)}, f"web in {text!r}", )
if __name__ == "__main__": unittest.main()