From 9a3d5979d1a593ae65645bce757ffbd7e52b6d05 Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Wed, 25 Nov 2026 16:18:53 -0500 Subject: [PATCH] feat(honcho): recall peer memories in enrolled sessions --- e2e/_honcho_support.py | 21 ++++++ e2e/areas.toml | 1 + e2e/honcho_test.py | 42 +++++++++-- extensions/honcho/src/albedo_ext_honcho.gleam | 72 ++++++++++++++++++- .../honcho/src/albedo_ext_honcho/client.gleam | 56 +++++++++++++++ .../src/albedo_ext_honcho/delivery.gleam | 52 ++++++++++++-- .../honcho/src/albedo_ext_honcho/ledger.gleam | 7 ++ python/albedo_plugins/honcho.py | 18 +++++ robot-docs/README.md | 2 +- robot-docs/honcho.md | 27 +++++-- robot-docs/hooks.md | 1 + 11 files changed, 283 insertions(+), 16 deletions(-) create mode 100644 python/albedo_plugins/honcho.py diff --git a/e2e/_honcho_support.py b/e2e/_honcho_support.py index 27cd19ce7..99abc5fc1 100644 --- a/e2e/_honcho_support.py +++ b/e2e/_honcho_support.py @@ -1,5 +1,6 @@ """The v3 endpoints used by the Honcho extension, served over loopback.""" +from datetime import datetime, timezone import json import re import threading @@ -13,7 +14,9 @@ class Honcho: self.offline = threading.Event() self.attempted = threading.Event() self._rows = {} + self._joined = {} self._peers = set() + self._representation = "" self.lose_next_receipt = False self._lock = threading.Lock() owner = self @@ -57,8 +60,19 @@ class Honcho: if path == f"{workspace}/sessions": if set(body["peers"]) != self._peers: return 422, {} + self._joined[body["id"]] = { + peer: datetime.fromisoformat(membership["joined_at"]) + if membership.get("joined_at") + else datetime.now(timezone.utc) + for peer, membership in body["peers"].items() + } self._rows.setdefault(body["id"], []) return 200, {"id": body["id"]} + if path == f"{workspace}/peers/person/representation" and body["search_query"]: + return 200, {"representation": self._representation} + if path == f"{workspace}/peers/person/chat" and body["query"]: + return 200, {"content": self._representation} + match = re.fullmatch( rf"{workspace}/sessions/([a-zA-Z0-9_-]+)/messages(/list)?", path ) @@ -87,6 +101,13 @@ class Honcho: rows.append(row) self.messages.append(row) posted.append(row) + if ( + row["peer_id"] == "person" + and row["content"] == "I prefer narrow diffs." + and datetime.fromisoformat(row["created_at"]) + >= self._joined[match[1]]["person"] + ): + self._representation = "Prefers narrow diffs." if self.lose_next_receipt: self.lose_next_receipt = False return 503, {} diff --git a/e2e/areas.toml b/e2e/areas.toml index f793c8e34..826baa20c 100644 --- a/e2e/areas.toml +++ b/e2e/areas.toml @@ -2,6 +2,7 @@ # An unmapped daemon change uses the smoke set in e2e/e2e_select.py. [areas] "extensions/honcho/*" = ["honcho_test.py"] +"python/albedo_plugins/honcho.py" = ["honcho_test.py"] "extensions/photon/*" = ["photon_test.py"] "tools/photon/*" = ["photon_test.py"] "e2e/fixtures/photon/*" = ["photon_test.py"] diff --git a/e2e/honcho_test.py b/e2e/honcho_test.py index 9a8bf4476..0ef0b3e21 100644 --- a/e2e/honcho_test.py +++ b/e2e/honcho_test.py @@ -1,10 +1,19 @@ -"""Exercise the selected Honcho extension through a daemon restart.""" +"""Exercise the selected Honcho extension through a restart and a second session.""" +import json import unittest from urllib.parse import urlsplit from _honcho_support import Honcho -from harness import Albedo, Provider, exclusive, text, wait_until +from harness import ( + Albedo, + Provider, + conversation, + exclusive, + python, + text, + wait_until, +) from network_support import TunnelProxy @@ -16,7 +25,10 @@ class HonchoTests(unittest.TestCase): port = urlsplit(self.honcho.url).port self.proxy = TunnelProxy(targets={"honcho.invalid": ("127.0.0.1", port)}) self.addCleanup(self.proxy.close) - self.provider = Provider(lambda _: text("Understood.")) + self.replies = [] + self.provider = Provider( + lambda _: self.replies.pop(0) if self.replies else text("Understood.") + ) self.addCleanup(self.provider.close) def configure(self, app): @@ -56,7 +68,7 @@ class HonchoTests(unittest.TestCase): app.api(f"/sessions/{session}/reload", {"target": "session"}).close() return session - def test_committed_conversation_survives_restart(self): + def test_committed_conversation_survives_restart_and_informs_another_session(self): self.honcho.offline.set() self.honcho.lose_next_receipt = True with Albedo(self.provider, prepare=self.configure, protocol="responses") as app: @@ -76,3 +88,25 @@ class HonchoTests(unittest.TestCase): [(m["peer_id"], m["content"]) for m in self.honcho.messages], [("person", "I prefer narrow diffs."), ("albedo", "Understood.")], ) + second = self.enroll(app) + before = len(self.provider.requests) + self.replies.append(python('print(await honcho.ask("What do I prefer?"))')) + app.prompt(second, "What kind of diffs do I prefer?").close() + app.idle(second) + request = self.provider.requests[before]["request"] + self.assertIn("Prefers narrow diffs.", json.dumps(conversation(request))) + tool_results = [ + entry + for entry in app.history(second)["items"] + if entry["kind"] == "tool_result" + ] + self.assertIn("Prefers narrow diffs.", json.dumps(tool_results)) + wait_until( + lambda: len(self.honcho.messages) >= 4, + 30, + "second session did not sync", + ) + self.assertEqual( + [m["content"] for m in self.honcho.messages[2:]], + ["What kind of diffs do I prefer?", "Understood."], + ) diff --git a/extensions/honcho/src/albedo_ext_honcho.gleam b/extensions/honcho/src/albedo_ext_honcho.gleam index bccf5ef15..fcdcdca14 100644 --- a/extensions/honcho/src/albedo_ext_honcho.gleam +++ b/extensions/honcho/src/albedo_ext_honcho.gleam @@ -1,20 +1,88 @@ //// Cross-session memory for conversations enrolled with Honcho. +import albedo_ext_honcho/client import albedo_ext_honcho/config import albedo_ext_honcho/delivery import albedo_sdk/capability import albedo_sdk/extension +import albedo_sdk/hook +import albedo_sdk/host +import gleam/dynamic +import gleam/dynamic/decode +import gleam/json +import gleam/list +import gleam/option.{Some} +import gleam/result +import gleam/string pub const uses = [capability.Selection, capability.History, capability.Sessions] pub fn extension() -> extension.Extension { extension.Extension( "honcho", - "Sync enrolled conversations with Honcho.", + "Recall and sync conversation memory with Honcho.", [], - [extension.SettingsPlugin(config.declaration()), ..delivery.plugins()], + list.append( + [ + extension.SettingsPlugin(config.declaration()), + extension.ToolPlugin( + "Use await honcho.ask(question) for questions about the user's remembered preferences or earlier conversations. Catch HonchoError if the lookup fails.", + [], + ["honcho"], + [#("honcho", ask)], + ), + ], + delivery.plugins(recall), + ), fn(setup) { delivery.initialise(setup.storage) }, tables: delivery.tables, uses:, ) } + +fn recall(context: hook.Context, event: hook.Event) -> hook.Verdict { + case event { + hook.Prompted(_, Some(query)) -> { + let answer = { + use #(destination, check) <- result.try(delivery.destination( + context.storage, + context.session, + )) + client.representation(destination, query, check) + |> result.map_error(client.describe) + } + case answer { + Ok(text) if text != "" -> hook.Verdict(..hook.proceed, context: [text]) + _ -> hook.proceed + } + } + _ -> hook.proceed + } +} + +fn ask( + context: host.Context, + method: String, + args: dynamic.Dynamic, +) -> Result(json.Json, #(String, String)) { + let answer = { + use query <- result.try( + decode.run(args, decode.field("question", decode.string, decode.success)) + |> result.replace_error("expected a question"), + ) + case method, string.trim(query) { + "honcho.ask", "" -> Error("expected a nonempty question") + "honcho.ask", question -> { + use #(destination, check) <- result.try(delivery.destination( + context.storage, + context.session, + )) + client.chat(destination, question, check) + |> result.map_error(client.describe) + |> result.map(json.string) + } + _, _ -> Error("unknown Honcho operation") + } + } + result.map_error(answer, fn(reason) { #("honcho", reason) }) +} diff --git a/extensions/honcho/src/albedo_ext_honcho/client.gleam b/extensions/honcho/src/albedo_ext_honcho/client.gleam index 1a34695ae..7c54c9c3a 100644 --- a/extensions/honcho/src/albedo_ext_honcho/client.gleam +++ b/extensions/honcho/src/albedo_ext_honcho/client.gleam @@ -2,6 +2,7 @@ //// metadata. A successful lookup can reconcile a lost write receipt; an //// empty lookup alone cannot prove an earlier request never committed. +import albedo_bytes/scalars import albedo_clock import albedo_ext_honcho/config.{type Destination} import albedo_http @@ -14,6 +15,7 @@ import gleam/json import gleam/list import gleam/option.{type Option, None, Some} import gleam/result +import gleam/string pub type Failure { Retry(String) @@ -21,6 +23,12 @@ pub type Failure { Unknown(String) } +pub fn describe(error: Failure) -> String { + case error { + Retry(reason) | Refused(reason) | Unknown(reason) -> reason + } +} + type Request { Query(check: fn() -> Result(Nil, String)) CreateMessage(claim: fn() -> Result(Nil, String)) @@ -144,6 +152,10 @@ fn session(dest: Destination, id: String) -> String { workspace(dest) <> "/sessions/" <> id } +fn human(dest: Destination) -> String { + workspace(dest) <> "/peers/" <> dest.human +} + fn id_body(id: String) -> json.Json { json.object([#("id", json.string(id))]) } @@ -225,6 +237,50 @@ pub fn ensure( } } +pub fn representation( + dest: Destination, + query: String, + check: fn() -> Result(Nil, String), +) -> Result(String, Failure) { + let body = + json.object([ + #("search_query", json.string(scalars.take(query, 10_000))), + #("max_conclusions", json.int(8)), + ]) + post( + dest, + human(dest) <> "/representation", + body, + decode.at(["representation"], decode.string), + Query(check), + 1500, + ) + |> result.map(scalars.take(_, 4000)) +} + +pub fn chat( + dest: Destination, + query: String, + check: fn() -> Result(Nil, String), +) -> Result(String, Failure) { + case string.trim(query) == "" || scalars.length(query) > 10_000 { + True -> + Error(Refused("Honcho chat requires a query of 1 to 10000 characters")) + False -> { + let body = json.object([#("query", json.string(query))]) + post( + dest, + human(dest) <> "/chat", + body, + decode.at(["content"], decode.string), + Query(check), + 60_000, + ) + |> result.map(scalars.take(_, 16_000)) + } + } +} + fn source_metadata(key: String) -> json.Json { json.object([#("albedo_source", json.string(key))]) } diff --git a/extensions/honcho/src/albedo_ext_honcho/delivery.gleam b/extensions/honcho/src/albedo_ext_honcho/delivery.gleam index 785d838e8..4075dac94 100644 --- a/extensions/honcho/src/albedo_ext_honcho/delivery.gleam +++ b/extensions/honcho/src/albedo_ext_honcho/delivery.gleam @@ -1,11 +1,15 @@ //// Honcho enrollment belongs to the local daemon. A move keeps the remote //// history and starts without a delivery grant on the receiving daemon. +import albedo_ext_honcho/config import albedo_ext_honcho/ledger import albedo_ext_honcho/operator import albedo_ext_honcho/transfer import albedo_ext_honcho/worker +import albedo_process/within import albedo_sdk/extension +import albedo_sdk/hook +import albedo_sdk/network_context import albedo_sdk/storage import albedo_sdk/supervisor_owner import gleam/option.{None, Some} @@ -20,18 +24,40 @@ pub fn initialise(db: storage.Storage) -> Result(Nil, String) { ledger.initialise(db) } -pub fn plugins() -> List(extension.Plugin) { +pub fn destination( + db: storage.Storage, + session: String, +) -> Result(#(config.Destination, fn() -> Result(Nil, String)), String) { + use row <- result.map(ledger.current(db, session)) + let check = fn() { + use current <- result.try(ledger.current(db, session)) + case + current.remote == row.remote && current.grant_token == row.grant_token + { + True -> Ok(Nil) + False -> Error("Honcho enrollment changed during the request") + } + } + #(ledger.dest(row), check) +} + +pub fn plugins( + recall: fn(hook.Context, hook.Event) -> hook.Verdict, +) -> List(extension.Plugin) { [ operator.commands(), operator.clients(), - extension.StartupPlugin(start), + extension.StartupPlugin(fn(host) { start(host, recall) }), extension.CleanPlugin(ledger.forget), extension.FollowPlugin(ledger.follow), extension.TransferPlugin(transfer.adapter()), ] } -fn start(host: extension.Startup) -> Result(List(extension.Started), String) { +fn start( + host: extension.Startup, + recall: fn(hook.Context, hook.Event) -> hook.Verdict, +) -> Result(List(extension.Started), String) { let manager = worker.new() use _ <- result.map( supervisor_owner.start( @@ -61,6 +87,17 @@ fn start(host: extension.Startup) -> Result(List(extension.Started), String) { _ -> Nil } } + let ask = fn(context: hook.Context, event) { + case event { + hook.Prompted(_, Some(_)) -> + within.run( + 2000, + network_context.carried(fn() { recall(context, event) }), + ) + |> result.unwrap(hook.proceed) + _ -> hook.proceed + } + } let published = case opening { Ok(o) -> Some(fn(db) { @@ -69,7 +106,14 @@ fn start(host: extension.Startup) -> Result(List(extension.Started), String) { }) Error(_) -> None } - Ok(extension.Managed(..extension.empty(), observe:, published:)) + Ok( + extension.Managed( + ..extension.empty(), + observe:, + hook: Some(ask), + published:, + ), + ) }), ] } diff --git a/extensions/honcho/src/albedo_ext_honcho/ledger.gleam b/extensions/honcho/src/albedo_ext_honcho/ledger.gleam index f07e2c08b..e1a7056e7 100644 --- a/extensions/honcho/src/albedo_ext_honcho/ledger.gleam +++ b/extensions/honcho/src/albedo_ext_honcho/ledger.gleam @@ -252,6 +252,13 @@ pub fn current_in( inspect_in(db, conn, session, config) |> result.try(required) } +pub fn current( + db: storage.Storage, + session: String, +) -> Result(sql.BindingRow, String) { + inspection(db, session) |> result.try(required) +} + /// Scan a bounded page outside the writer. A rewind or concurrent rebind /// invalidates the read before its messages or cursor can commit. pub fn capture( diff --git a/python/albedo_plugins/honcho.py b/python/albedo_plugins/honcho.py new file mode 100644 index 000000000..9ecbe9669 --- /dev/null +++ b/python/albedo_plugins/honcho.py @@ -0,0 +1,18 @@ +"""Query the human peer bound to this session's Honcho enrollment.""" + +from typing import cast + +from albedo_api import Host, PythonApi + + +class Honcho: + def __init__(self, host: Host) -> None: + self._host = host + + async def ask(self, question: str) -> str: + """Ask about remembered preferences or previous conversations.""" + return cast(str, await self._host("honcho.ask", {"question": question})) + + +def setup(api: PythonApi) -> dict[str, object]: + return {"honcho": Honcho(api.host), "HonchoError": api.HostError} diff --git a/robot-docs/README.md b/robot-docs/README.md index 597a97ede..75003c6b4 100644 --- a/robot-docs/README.md +++ b/robot-docs/README.md @@ -89,7 +89,7 @@ and the [repository agent instructions](../AGENTS.md). - [Web client](web.md): browser state and the local web server. - [ACP](acp.md): editor attachment, prompts, output, and MCP overlays. - [Webhooks](webhooks.md): signed intake and session delivery. -- [Honcho](honcho.md): conversation sync. +- [Honcho](honcho.md): conversation sync and cross-session recall. - [Photon iMessage](photon.md): direct texts, replies and recovery. - [Discord](discord.md): bot configuration, messages, and delivery. - [Computer use](cua.md): the CUA binding and driver lifecycle. diff --git a/robot-docs/honcho.md b/robot-docs/honcho.md index 031385ff4..5c34ce15d 100644 --- a/robot-docs/honcho.md +++ b/robot-docs/honcho.md @@ -1,8 +1,9 @@ # Honcho -The [Honcho extension](../extensions/honcho/src/albedo_ext_honcho.gleam) -delivers enrolled conversations to the configured Honcho workspace. Albedo -installs the extension with its default selection off. +The [Honcho extension](../extensions/honcho/src/albedo_ext_honcho.gleam) looks +up memories when a person prompts an enrolled Albedo session. It also delivers +the conversation to the configured Honcho workspace. Albedo installs the +extension with its default selection off. ## Configure the destination @@ -52,8 +53,8 @@ last delivery, next retry, and any reason delivery paused. Disabling the extension or returning its session choice to inheritance revokes the local grant. Requests already sent can still complete. Re-enabling starts from the new transcript boundary and drops any old pending deliveries. A destination change -pauses capture until you run `/honcho bind`. Binding the new destination starts -a fresh remote session. +pauses capture and recall until you run `/honcho bind`. Binding the new +destination starts a fresh remote session. ## Delivery and recovery @@ -81,8 +82,24 @@ queued data. Moving a session leaves its binding with the source daemon, which stops sending to it. Run `/honcho bind` on the target to enroll the moved session from its current position. +## Recall + +The [prompt hook](hooks.md) queries the human peer's representation using the +human submission from the opening turn inputs. A successful lookup adds up to +4,000 Unicode scalar values to the model's context. Albedo saves that text as a +note attributed to the extension. An empty or failed lookup lets the turn +continue. + +For a question about previous conversations, use +`await honcho.ask("What did we decide about tests?")` in a Python cell. The +[kernel binding](../python/albedo_plugins/honcho.py) calls the same session's +enrollment. The +[HTTP client](../extensions/honcho/src/albedo_ext_honcho/client.gleam) sends the +question to the human peer's chat endpoint. + ## Related pages - [Outbound network routes](network.md) +- [Hooks](hooks.md) - [Extensions](extensions.md) - [All topics](README.md) diff --git a/robot-docs/hooks.md b/robot-docs/hooks.md index 65fa85cfa..aae16f597 100644 --- a/robot-docs/hooks.md +++ b/robot-docs/hooks.md @@ -102,4 +102,5 @@ their registered process groups are outside this guarantee. - [All topics](README.md) - [Change guidance](contributing.md) - [Agents](agent-sessions.md) +- [Honcho](honcho.md) - [Plugins](plugins.md) -- knotmirror 0.0.1