#!/usr/bin/env bash # Grimoire — tell the server this session opened a record, or ran a search. # # WHAT THIS ANSWERS # # A hook puts records in front of a session (prior art, the notes menu); the # session also searches for records itself, and opens others it reached on # its own (an id in a task log, a record the operator named). The server # records what each hook pushed against the session. This reports the other # half, from the tool calls themselves: # # - `get_note`, `get_task`, `get_snippet`, `get_lesson`, `get_process` — the # record was opened. The server stamps the delivery it followed, or records # a direct open when nothing delivered it first. # - `search` — the session asked. The server reads what that call returned # from its own log and records those results against the session, so an # open that follows counts as one reached by asking. # # Together they say, per kind of record, how much a session is shown, how # much it asks for, how much it reaches on its own, and what it opens. # # A tool call happened or it did not, and the harness reports it either way: # this asks the session nothing. # # EXIT 0, ALWAYS, silent on outage. This is bookkeeping; a failure here must # never turn a successful tool call into a hook error. set -uo pipefail # shellcheck source=plugin/hooks/grimoire_defs.sh . "$(dirname "${BASH_SOURCE[0]}")/grimoire_defs.sh" event=$(cat 2>/dev/null || true) [ -n "$event" ] || exit 0 event_flat=$(printf '%s' "$event" | grimoire_json_flat) session_id=$(grimoire_json_pick "$event_flat" '.session_id') [ -n "$session_id" ] || exit 0 tool_name=$(grimoire_json_pick "$event_flat" '.tool_name') command -v curl >/dev/null 2>&1 || exit 0 grimoire_config || exit 0 sid_esc=$(printf '%s' "$session_id" | grimoire_json_escape) || exit 0 post() { printf '%s' "$2" | curl -fsS --max-time 3 \ -H "Authorization: Bearer ${token}" \ -H "X-Grimoire-Plugin: ${plugin_version:-}" \ -H "Content-Type: application/json" \ --data-binary @- \ "${url%/}/api/plugin/$1" >/dev/null 2>&1 || true } case "$tool_name" in *__search) q=$(grimoire_json_pick "$event_flat" '.tool_input.q') [ -n "$q" ] || exit 0 q_esc=$(printf '%s' "$q" | grimoire_json_escape) || exit 0 post record-searched "$(printf '{"session_id":"%s","q":"%s"}' "$sid_esc" "$q_esc")" ;; *) # Each getter names its id differently; read whichever is present. A # process opened by name rather than id is left unrecorded. note_id="" for field in note_id task_id snippet_id lesson_id name_or_id; do note_id=$(grimoire_json_pick "$event_flat" ".tool_input.${field}") [ -n "$note_id" ] && break done case "$note_id" in ''|*[!0-9]*) exit 0 ;; esac post record-opened "$(printf '{"session_id":"%s","note_id":%s}' "$sid_esc" "$note_id")" ;; esac exit 0