Files

78 lines
2.8 KiB
Python

"""A form's link, recovered from the conversation's own transcripts.
The hub's mirror reads a machine's forms through the sidecar's proxy, and the
admin API never returns a form's link (its token): only `ask-form create`
prints it, and the events webhook (`serve --events-url`) carries it. A
machine whose `ask-form serve` doesn't post to the hub — a guest's own
computer, where ask-form was installed by hand — would so be mirrored with no
link at all: the home card says "Open its card", the Forms card's *Answer*
opens nothing.
The agent has to show the link to the user, so it is in the conversation's
transcript: the `create` call's output, or its own words. `recover` reads the
transcripts of every conversation that has a form without a link (the thread's
own and its subagents' — they share the sessionId) and files what it finds
under that form (``AskFormStore.adopt_link``). The scan is incremental per
file, so a pass over unchanged transcripts is a ``stat`` each.
"""
from __future__ import annotations
import logging
import pathlib
from askform.service import link_of, _publish
from conversations import tree
from core.state import AppState
log = logging.getLogger("askform")
# sessionId → its transcripts (the thread and every subagent), kept until the
# summaries change.
_index: tuple[int, dict[str, list[str]]] | None = None
def _paths_by_session(deps: AppState) -> dict[str, list[str]]:
global _index
v = deps.store.summaries_version
if _index and _index[0] == v:
return _index[1]
out: dict[str, list[str]] = {}
for path, s in deps.store.all_summaries():
sid = s.get("sessionId")
if sid:
out.setdefault(sid, []).append(path)
_index = (v, out)
return out
def recover(deps: AppState) -> int:
"""Give every pending form that has no link the one its conversation printed.
Returns how many forms got one."""
iter_fn = getattr(deps.askform_store, "iter_shallow", None)
records = iter_fn() if iter_fn is not None else deps.askform_store.list()
todo: dict[str, list[dict]] = {}
for r in records:
if r.get("status") == "pending" and r.get("sessionId") and not link_of(r):
todo.setdefault(r["sessionId"], []).append(r)
if not todo:
return 0
paths = _paths_by_session(deps)
n = 0
for sid, recs in todo.items():
for path in paths.get(sid, ()):
links = tree.form_links(pathlib.Path(path))
if not links:
continue
for r in recs:
lk = links.get(r["id"])
if not lk:
continue
got = deps.askform_store.adopt_link(
r["id"], url=lk.get("url"), public_url=lk.get("publicUrl"),
session=sid)
if got:
n += 1
_publish(deps, got)
return n