Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(skills): add background watch hook pattern
cyhd98af5dc5c14
diff --git a/docs/plans/background-watch-hook.md b/docs/plans/background-watch-hook.mdnew file mode 100644index 000000000..305240dae--- /dev/null+++ b/docs/plans/background-watch-hook.md@@ -0,0 +1,40 @@+# Background Watch Hook++## Background++We want a reusable pattern and bundled guide that teaches agents how to wait for an external condition in the background and automatically send a `vibe hook` back into the current IM session when the condition is met.++The user explicitly does not want a new event subsystem inside Vibe Remote. The solution should stay lightweight and be built from:++1. a blocking waiter script+2. a detached shell wrapper+3. `vibe hook send`++## Goal++Add a reusable guide under `skills/` that:++- explains the detached execution pattern as a generic technique+- provides a general wrapper script for `wait -> capture stdout -> vibe hook send`+- provides a GitHub PR activity waiter as a concrete example++## Design++- `skills/background-watch-hook/SKILL.md`+ - explains when to use the pattern+ - explains how to derive the current `session_key`+ - explains the detached-shell pattern, wrapper interface, and common pitfalls+- `skills/background-watch-hook/scripts/watch_then_hook.sh`+ - runs an arbitrary waiter command+ - captures stdout+ - builds a prompt file+ - invokes `vibe hook send`+- `skills/background-watch-hook/scripts/wait_for_github_pr_activity.py`+ - waits until a PR gets new review activity+ - prints a concise activity summary to stdout++## Validation++- `bash -n` on the shell script+- `python3 -m py_compile` on the Python waiter+- basic `--help` smoke checksdiff --git a/skills/background-watch-hook/SKILL.md b/skills/background-watch-hook/SKILL.mdnew file mode 100644index 000000000..e80f0b4af--- /dev/null+++ b/skills/background-watch-hook/SKILL.md@@ -0,0 +1,207 @@+---+name: background-watch-hook+slug: background-watch-hook+description: Run a blocking watcher in the background and send a `vibe hook` back to the current IM session when it finishes. Use for GitHub reviews, CI, file completion, log matches, and process-exit follow-ups.+version: 0.1.0+---++# Background Watch Hook++Use this skill when the user wants the agent to:++- wait for an external event in the background+- stop polling manually+- automatically wake up the current IM session when the event happens++This is a reusable pattern, not a product feature. Do not build a new scheduler or event subsystem when this pattern is enough.++## Core Idea++The pattern has three parts:++1. A blocking waiter command that exits only when the watched condition becomes true.+2. A detached shell wrapper that runs the waiter asynchronously.+3. A `vibe hook send` call that fires only after the waiter exits successfully.++The waiter prints its final event summary to `stdout`. The wrapper captures that output, builds a prompt file, and queues one hook back into the current session.++Use this pattern for any one-off "wait in the background, then come back here" task, for example:++- GitHub PR reviews or comments+- CI finishing+- a file or export being generated+- a log line appearing+- a long-running process exiting++## Hard Rules++1. Do not use `watcher & && vibe hook send ...`. That runs the hook immediately after background launch, not after the watcher finishes.+2. Put both the waiter and the hook inside the same detached shell.+3. Keep waiter `stdout` clean. Final event summary goes to `stdout`; debug logs go to `stderr`.+4. Prefer `--prompt-file` over inline `--prompt` for hook payloads.+5. Use a timeout-aware waiter. Infinite waits are fine only when the user explicitly wants them.++## Files In This Skill++- `scripts/watch_then_hook.sh`+ General wrapper. Runs a waiter command, captures `stdout`, then calls `vibe hook send`.+- `scripts/wait_for_github_pr_activity.py`+ Included example waiter. Polls a GitHub PR until new review activity appears, then prints a concise summary.++## Session Targeting++You usually already know the current delivery target from Vibe Remote's prompt context:++- use the current `session_key` if the follow-up should return to the same channel+- append `::thread::<thread_id>` when the follow-up must land in the current thread+- use `--post-to channel` only when the user wants to preserve thread context but publish in the parent channel++If the current turn does not expose a usable session key, stop and ask for the exact delivery target instead of guessing.++## Wrapper First++`scripts/watch_then_hook.sh` is the main reusable tool in this skill. Most of the time you do not need to invent a new shell pattern. You only need:++1. a correct `session_key`+2. a short action-oriented prefix+3. a waiter command that follows the contract below++The wrapper interface is:++```bash+scripts/watch_then_hook.sh \+ --session-key "<session-key>" \+ [--prefix "<hook prefix>"] \+ [--post-to channel] \+ [--deliver-key "<dedupe-key>"] \+ [--hook-bin vibe] \+ [--timeout-exit-code 124] \+ -- <waiter command ...>+```++- `--session-key`+ Required. Delivery target for the follow-up hook.+- `--prefix`+ Optional. Prepended to the waiter output inside the generated prompt file.+- `--post-to`+ Optional. Use only when the follow-up should post to the parent channel while keeping thread context.+- `--deliver-key`+ Optional. Pass through when the caller needs dedupe semantics.+- `--hook-bin`+ Optional. Override only for testing or unusual environments.+- `--timeout-exit-code`+ Optional. The wrapper treats this exit code as a silent timeout.++## Preferred Execution Pattern++Run the wrapper itself in the background with `nohup bash -lc '...'`:++```bash+nohup bash -lc '+ scripts/watch_then_hook.sh \+ --session-key "slack::channel::C123::thread::171717.123" \+ --prefix "GitHub PR #151 has new review activity. Fetch the latest review state, summarize unresolved items, and continue handling them if needed." \+ -- \+ scripts/wait_for_github_pr_activity.py \+ --repo cyhhao/vibe-remote \+ --pr 151 \+ --interval 45+' >/tmp/watch-pr-151.log 2>&1 &+```++That command returns immediately, leaves the watcher running, and sends the hook only after the waiter exits with success.++## Generic Workflow++### 1. Pick the waiter++For other use cases, either:++- write a new small waiter in the task workspace, or+- reuse another existing blocking command that prints a final summary to `stdout`++Use `scripts/wait_for_github_pr_activity.py` only when the thing being watched is GitHub PR review activity.++### 2. Decide the session target++Use the current thread when the user wants the result to continue in context.++### 3. Build a short hook prefix++The prefix should tell the next turn what to do with the watcher result. Good prefixes are action-oriented:++- `GitHub PR has new review activity. Fetch the latest comments and continue resolving them.`+- `CI finished. Inspect the failure and propose the next fix.`+- `The export completed. Summarize the result and share the artifact details.`++### 4. Start the detached wrapper++Run `nohup bash -lc 'scripts/watch_then_hook.sh ...' >/tmp/<name>.log 2>&1 &`.++### 5. Tell the user what was started++Report:++- what is being watched+- where the hook will be delivered+- where the background log is going++## Waiter Contract++Design waiters to follow this contract:++- `exit 0`: event detected; final summary printed to `stdout`+- `exit 124`: timeout; no hook should be sent+- any other non-zero exit: failure; wrapper should exit without sending a hook++Good waiter output is compact and already useful to the next turn, for example:++```text+GitHub PR activity detected for cyhhao/vibe-remote#151+- review_comment #3025433621 by chatgpt-codex-connector[bot] on modules/agents/opencode/server.py+ Avoid terminating active OpenCode server during auth refresh+ https://github.com/cyhhao/vibe-remote/pull/151#discussion_r3025433621+```++## Writing New Waiters++Keep new waiters small and boring. A good waiter:++- blocks until a single condition becomes true+- prints one final summary to `stdout`+- keeps polling logs and diagnostics on `stderr`+- exits with `124` on timeout when a timeout matters++The wrapper is the reusable part. Waiters should stay disposable and task-specific.++## Included Example: GitHub PR Activity++`scripts/wait_for_github_pr_activity.py` snapshots the current PR state on startup when no explicit cursor is provided, then blocks until something newer appears. Use it as:++```bash+nohup bash -lc '+ scripts/watch_then_hook.sh \+ --session-key "slack::channel::C123::thread::171717.123" \+ --prefix "PR review changed. Check the latest GitHub review results and continue the review loop." \+ -- \+ scripts/wait_for_github_pr_activity.py \+ --repo cyhhao/vibe-remote \+ --pr 151 \+ --interval 60 \+ --timeout 14400+' >/tmp/watch-pr-151.log 2>&1 &+```++## Failure Handling++- If the waiter requires credentials, verify them before starting the background process.+- If `vibe hook send` is not on `PATH`, stop and fix the environment instead of launching a broken watcher.+- If the user wants a durable recurring watch shared across sessions, this pattern is not enough by itself; explain that it is best for one-off background waiting tied to the current task.++## Common Mistakes++- launching the waiter in the background and the hook in the foreground+- letting the waiter print noisy polling logs to `stdout`+- hardcoding the wrong session target+- forgetting that a channel follow-up and a thread follow-up use different `session_key` values+- omitting a timeout when the user expects eventual cleanupdiff --git a/skills/background-watch-hook/scripts/wait_for_github_pr_activity.py b/skills/background-watch-hook/scripts/wait_for_github_pr_activity.pynew file mode 100755index 000000000..f044781a8--- /dev/null+++ b/skills/background-watch-hook/scripts/wait_for_github_pr_activity.py@@ -0,0 +1,224 @@+#!/usr/bin/env python3+"""Wait until a GitHub pull request receives new review activity."""++from __future__ import annotations++import argparse+import json+import os+import shutil+import subprocess+import sys+import time+import urllib.error+import urllib.parse+import urllib.request+from typing import Any+++def _get_token() -> str | None:+ for env_name in ("GITHUB_TOKEN", "GH_TOKEN"):+ value = os.environ.get(env_name)+ if value:+ return value++ gh_path = shutil.which("gh")+ if not gh_path:+ return None++ try:+ result = subprocess.run(+ [gh_path, "auth", "token"],+ check=True,+ capture_output=True,+ text=True,+ )+ except Exception:+ return None+ token = result.stdout.strip()+ return token or None+++def _github_get(url: str, token: str | None) -> Any:+ request = urllib.request.Request(url)+ request.add_header("Accept", "application/vnd.github+json")+ request.add_header("User-Agent", "background-watch-hook/0.1.0")+ if token:+ request.add_header("Authorization", f"Bearer {token}")++ with urllib.request.urlopen(request, timeout=30) as response:+ return json.loads(response.read().decode("utf-8"))+++def _list_paginated(base_url: str, token: str | None) -> list[dict[str, Any]]:+ items: list[dict[str, Any]] = []+ page = 1+ while True:+ separator = "&" if "?" in base_url else "?"+ url = f"{base_url}{separator}per_page=100&page={page}"+ payload = _github_get(url, token)+ if not isinstance(payload, list):+ raise RuntimeError(f"Expected a JSON list from {url}")+ if not payload:+ break+ items.extend(item for item in payload if isinstance(item, dict))+ if len(payload) < 100:+ break+ page += 1+ return items+++def _squash(text: str | None, *, limit: int = 140) -> str:+ compact = " ".join((text or "").split())+ if len(compact) <= limit:+ return compact+ return compact[: limit - 1].rstrip() + "…"+++def _max_id(items: list[dict[str, Any]]) -> int:+ values = [int(item["id"]) for item in items if isinstance(item.get("id"), int)]+ return max(values, default=0)+++def _filter_new(items: list[dict[str, Any]], since_id: int) -> list[dict[str, Any]]:+ return sorted(+ [item for item in items if isinstance(item.get("id"), int) and int(item["id"]) > since_id],+ key=lambda item: (str(item.get("created_at") or ""), int(item["id"])),+ )+++def _format_review(review: dict[str, Any]) -> str:+ review_id = review.get("id")+ author = ((review.get("user") or {}).get("login")) or "unknown"+ state = str(review.get("state") or "commented").lower()+ body = _squash(review.get("body") or state)+ url = review.get("html_url") or ""+ return f"- review #{review_id} by {author} ({state})\n {body}\n {url}"+++def _format_review_comment(comment: dict[str, Any]) -> str:+ comment_id = comment.get("id")+ author = ((comment.get("user") or {}).get("login")) or "unknown"+ path = comment.get("path") or "unknown-path"+ body = _squash(comment.get("body"))+ url = comment.get("html_url") or ""+ return f"- review_comment #{comment_id} by {author} on {path}\n {body}\n {url}"+++def _format_issue_comment(comment: dict[str, Any]) -> str:+ comment_id = comment.get("id")+ author = ((comment.get("user") or {}).get("login")) or "unknown"+ body = _squash(comment.get("body"))+ url = comment.get("html_url") or ""+ return f"- issue_comment #{comment_id} by {author}\n {body}\n {url}"+++def _fetch_state(repo: str, pr_number: int, token: str | None) -> dict[str, list[dict[str, Any]]]:+ encoded_repo = urllib.parse.quote(repo, safe="/")+ reviews = _list_paginated(f"https://api.github.com/repos/{encoded_repo}/pulls/{pr_number}/reviews", token)+ review_comments = _list_paginated(+ f"https://api.github.com/repos/{encoded_repo}/pulls/{pr_number}/comments",+ token,+ )+ issue_comments = _list_paginated(+ f"https://api.github.com/repos/{encoded_repo}/issues/{pr_number}/comments",+ token,+ )+ return {+ "reviews": reviews,+ "review_comments": review_comments,+ "issue_comments": issue_comments,+ }+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--repo", required=True, help="GitHub repo in owner/name form")+ parser.add_argument("--pr", required=True, type=int, help="Pull request number")+ parser.add_argument("--interval", type=float, default=45.0, help="Polling interval in seconds")+ parser.add_argument("--timeout", type=float, default=0.0, help="Overall timeout in seconds; 0 means forever")+ parser.add_argument("--since-review-id", type=int, default=None, help="Existing review cursor")+ parser.add_argument("--since-review-comment-id", type=int, default=None, help="Existing review comment cursor")+ parser.add_argument("--since-issue-comment-id", type=int, default=None, help="Existing PR conversation comment cursor")+ parser.add_argument("--event-limit", type=int, default=8, help="Maximum number of new events to include in stdout")+ args = parser.parse_args()++ token = _get_token()+ start = time.monotonic()++ try:+ state = _fetch_state(args.repo, args.pr, token)+ except urllib.error.HTTPError as err:+ print(f"GitHub API error: {err.code} {err.reason}", file=sys.stderr)+ return 1+ except Exception as err: # noqa: BLE001+ print(f"Failed to fetch initial PR state: {err}", file=sys.stderr)+ return 1++ review_cursor = args.since_review_id if args.since_review_id is not None else _max_id(state["reviews"])+ review_comment_cursor = (+ args.since_review_comment_id+ if args.since_review_comment_id is not None+ else _max_id(state["review_comments"])+ )+ issue_comment_cursor = (+ args.since_issue_comment_id+ if args.since_issue_comment_id is not None+ else _max_id(state["issue_comments"])+ )++ print(+ (+ "Watching GitHub PR %s#%s from cursors: review=%s review_comment=%s issue_comment=%s"+ % (args.repo, args.pr, review_cursor, review_comment_cursor, issue_comment_cursor)+ ),+ file=sys.stderr,+ )++ while True:+ if args.timeout > 0 and (time.monotonic() - start) >= args.timeout:+ print("Timed out while waiting for GitHub PR activity", file=sys.stderr)+ return 124++ time.sleep(max(args.interval, 1.0))++ try:+ state = _fetch_state(args.repo, args.pr, token)+ except urllib.error.HTTPError as err:+ print(f"GitHub API error during polling: {err.code} {err.reason}", file=sys.stderr)+ continue+ except Exception as err: # noqa: BLE001+ print(f"Polling failed: {err}", file=sys.stderr)+ continue++ new_reviews = _filter_new(state["reviews"], review_cursor)+ new_review_comments = _filter_new(state["review_comments"], review_comment_cursor)+ new_issue_comments = _filter_new(state["issue_comments"], issue_comment_cursor)++ if not (new_reviews or new_review_comments or new_issue_comments):+ continue++ review_cursor = max(review_cursor, _max_id(new_reviews))+ review_comment_cursor = max(review_comment_cursor, _max_id(new_review_comments))+ issue_comment_cursor = max(issue_comment_cursor, _max_id(new_issue_comments))++ lines = [f"GitHub PR activity detected for {args.repo}#{args.pr}"]+ rendered_events: list[str] = []+ rendered_events.extend(_format_review(review) for review in new_reviews)+ rendered_events.extend(_format_review_comment(comment) for comment in new_review_comments)+ rendered_events.extend(_format_issue_comment(comment) for comment in new_issue_comments)++ visible_limit = max(args.event_limit, 1)+ for entry in rendered_events[:visible_limit]:+ lines.append(entry)++ total_events = len(rendered_events)+ if total_events > visible_limit:+ lines.append(f"- {total_events - visible_limit} additional event(s) omitted")++ print("\n".join(lines))+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/background-watch-hook/scripts/watch_then_hook.sh b/skills/background-watch-hook/scripts/watch_then_hook.shnew file mode 100755index 000000000..697ce4f2b--- /dev/null+++ b/skills/background-watch-hook/scripts/watch_then_hook.sh@@ -0,0 +1,139 @@+#!/usr/bin/env bash+set -euo pipefail++usage() {+ cat <<'EOF'+Usage:+ watch_then_hook.sh --session-key <session_key> [options] -- <waiter command...>++Options:+ --session-key <value> Required. Target session key for vibe hook send.+ --prefix <value> Optional. Text prepended before waiter stdout.+ --post-to <value> Optional. Passed through to vibe hook send.+ --deliver-key <value> Optional. Passed through to vibe hook send.+ --hook-bin <value> Optional. Hook CLI binary. Default: vibe+ --timeout-exit-code <n> Optional. Silent exit code. Default: 124+ -h, --help Show this help.++Behavior:+ - Runs the waiter command synchronously.+ - Captures waiter stdout to a temporary file.+ - If the waiter exits 0, builds a prompt file and runs vibe hook send.+ - If the waiter exits with the timeout code, exits silently without sending a hook.+ - Any other non-zero exit is treated as failure and no hook is sent.+EOF+}++session_key=""+prefix=""+post_to=""+deliver_key=""+hook_bin="${VIBE_HOOK_BIN:-vibe}"+timeout_exit_code=124++while [[ $# -gt 0 ]]; do+ case "$1" in+ --session-key)+ session_key="${2:-}"+ shift 2+ ;;+ --prefix)+ prefix="${2:-}"+ shift 2+ ;;+ --post-to)+ post_to="${2:-}"+ shift 2+ ;;+ --deliver-key)+ deliver_key="${2:-}"+ shift 2+ ;;+ --hook-bin)+ hook_bin="${2:-}"+ shift 2+ ;;+ --timeout-exit-code)+ timeout_exit_code="${2:-124}"+ shift 2+ ;;+ -h|--help)+ usage+ exit 0+ ;;+ --)+ shift+ break+ ;;+ *)+ echo "Unknown option: $1" >&2+ usage >&2+ exit 2+ ;;+ esac+done++if [[ -z "$session_key" ]]; then+ echo "--session-key is required" >&2+ usage >&2+ exit 2+fi++if [[ $# -eq 0 ]]; then+ echo "A waiter command is required after --" >&2+ usage >&2+ exit 2+fi++if ! command -v "$hook_bin" >/dev/null 2>&1; then+ echo "Hook binary not found: $hook_bin" >&2+ exit 127+fi++output_file="$(mktemp)"+prompt_file="$(mktemp)"+cleanup() {+ rm -f "$output_file" "$prompt_file"+}+trap cleanup EXIT++set +e+"$@" >"$output_file"+waiter_status=$?+set -e++if [[ "$waiter_status" -eq "$timeout_exit_code" ]]; then+ exit 0+fi++if [[ "$waiter_status" -ne 0 ]]; then+ echo "Waiter exited with status $waiter_status" >&2+ exit "$waiter_status"+fi++if [[ ! -s "$output_file" && -z "$prefix" ]]; then+ echo "Waiter succeeded but produced no stdout; skipping hook" >&2+ exit 0+fi++{+ if [[ -n "$prefix" ]]; then+ printf '%s\n' "$prefix"+ if [[ -s "$output_file" ]]; then+ printf '\n'+ fi+ fi+ if [[ -s "$output_file" ]]; then+ cat "$output_file"+ fi+} >"$prompt_file"++hook_cmd=("$hook_bin" hook send --session-key "$session_key" --prompt-file "$prompt_file")+if [[ -n "$post_to" ]]; then+ hook_cmd+=(--post-to "$post_to")+fi+if [[ -n "$deliver_key" ]]; then+ hook_cmd+=(--deliver-key "$deliver_key")+fi++"${hook_cmd[@]}"