Files
openhuman/scripts/debug-agent-prompts.sh
T
Steven EnamakelandGitHub 1cb70e3234 feat: P-Format tool calls, user memory injection, planner upgrades (#511)
* feat(agent): introduce debug agent prompts script and CLI for prompt inspection

- Added `scripts/debug-agent-prompts.sh` to dump system prompts for built-in agents, facilitating prompt engineering reviews.
- Implemented `openhuman agent` CLI commands for inspecting agent definitions and rendering prompts.
- Updated `.gitignore` to exclude local prompt dumps and added version bump for `openhuman` to 0.52.5.
- Introduced `debug_dump` module for shared prompt rendering logic, enhancing debugging capabilities across the application.

* feat(pformat): introduce P-Format tool calls for efficient parameter handling

- Added a new module `pformat` to implement P-Format ("Parameter-Format") tool calls, which significantly reduce token usage in tool invocations.
- Updated the agent module to include the new `pformat` module.
- Enhanced the context management by integrating user memory summaries from the tree summarizer, optimizing the prompt rendering process.
- Introduced constants for user memory character limits to ensure efficient memory usage across namespaces.
- Implemented a new `UserMemorySection` in the prompt to display distilled long-term context, improving the agent's ability to leverage learned information during interactions.
- Refactored the tree summarizer store to collect root-level summaries with character caps, ensuring manageable context sizes in prompts.

* feat(dispatch): implement PFormatToolDispatcher for efficient tool call handling

- Introduced `PFormatToolDispatcher`, a new dispatcher that utilizes P-Format for compact tool call syntax, significantly reducing token usage during interactions.
- Updated the agent's session builder to support the new dispatcher, allowing for a seamless transition to P-Format as the default for text-based providers.
- Enhanced the prompt rendering process to accommodate P-Format, ensuring backward compatibility with existing JSON tool calls.
- Modified the context management to reflect the new tool call format, improving the overall efficiency of prompt generation and tool interaction.
- Added tests to validate the correct rendering of tool signatures in P-Format, ensuring that the new format is correctly integrated into the system.

* feat(tests): add comprehensive tests for PFormatToolDispatcher functionality

- Introduced multiple tests for the `PFormatToolDispatcher`, validating its ability to parse tool calls from both P-Format and JSON formats.
- Implemented tests to ensure correct handling of multiple tool call tags and the dispatcher’s fallback behavior to JSON when P-Format is ignored.
- Enhanced the `render_main_agent_dump` function to include the dispatcher instructions, ensuring accurate context for tool usage in debug outputs.
- Updated the tree summarizer tests to verify namespace filtering and summary collection with respect to character limits, improving overall test coverage and reliability.

* feat(prompt): enhance tool signature rendering with P-Format support

- Introduced a new function `render_pformat_signature_for_box_tool` to generate P-Format signatures for tools, improving consistency in tool call formatting.
- Updated the `render_subagent_system_prompt` function to utilize the new P-Format signatures, ensuring alignment with the main agent's tool call protocol.
- Enhanced documentation to clarify the use of P-Format in tool calls, including detailed instructions for argument handling and formatting within the tool use protocol.

* feat(planner): update agent configuration and enhance planning context

- Revised the `when_to_use` description to emphasize the agent's ability to gather real context through memory recall and web searches.
- Increased `max_iterations` from 5 to 8 to allow for more complex planning scenarios.
- Changed `omit_memory_context` to false, enabling the agent to utilize memory context during planning.
- Updated the tools list to include `memory_recall`, `memory_store`, `memory_forget`, and `web_search_tool`, enhancing the agent's capabilities for context gathering.
- Expanded the prompt documentation to instruct users on gathering context before planning, ensuring more informed and effective task decomposition.

* style: apply cargo fmt to new and modified files

* feat(debug): enhance error handling and logging in debug-agent-prompts and tool dispatching

- Added error handling for missing output directory in `debug-agent-prompts.sh`, ensuring clearer feedback for users.
- Introduced a verbose flag in `agent_cli.rs` to control logging output, improving usability during debugging.
- Refactored tool response parsing in `dispatcher.rs` to prefer p-format calls while maintaining compatibility with JSON, enhancing response handling.
- Updated session builder in `builder.rs` to finalize dispatcher selection after tool list preparation, ensuring accurate tool handling.
- Improved debug dump functionality in `debug_dump.rs` to clarify the context of the dump process, ensuring better understanding of the output.
- Enhanced prompt rendering functions to support explicit tool call formats, improving flexibility in subagent interactions.

* feat(cli, prompt): enhance logging and tool call format handling

- Added debug logging for the agent subcommand in `cli.rs`, improving traceability during command execution.
- Updated the `render_subagent_system_prompt_with_format` function in `prompt.rs` to support multiple tool call formats (P-Format, JSON, Native), ensuring consistent output and flexibility for subagent interactions.
- Refactored tool call protocol documentation to clarify usage across different formats, enhancing user understanding and implementation.

* fix: address PR review — 8 findings

1. scripts/debug-agent-prompts.sh: validate --out argument exists
2. agent_cli.rs: silence logger in run_list before Config::load_or_init
3. dispatcher.rs: per-tag p-format/JSON selection (no all-or-nothing)
4. builder.rs: move pformat_registry build after orchestrator tools
5. debug_dump.rs: fall back to bundled prompt location for File sources
6. store.rs: fix char/byte mixing in total_cap computations
7. prompt.rs: thread ToolCallFormat into render_subagent_system_prompt
8. cli.rs: add debug trace on agent dispatch + lower dispatcher log
2026-04-12 00:08:36 -07:00

175 lines
6.3 KiB
Bash
Executable File

#!/usr/bin/env bash
#
# debug-agent-prompts.sh — Dump the exact system prompt the context engine
# would produce for every built-in agent (plus the main / orchestrator
# agent), so prompt-engineering changes can be reviewed in one place.
#
# Each prompt is written to a numbered file under the output directory
# along with a side-car `.meta.txt` containing the metadata banner
# (agent id, model, tool count, cache boundary, …) that the CLI prints
# to stderr. Useful workflow:
#
# bash scripts/debug-agent-prompts.sh
# diff -u prompts.before/skills_agent.md prompts.after/skills_agent.md
#
# When run with `--stub-composio` (the default) the dumper injects the
# five Composio meta-tools into the registry even on machines that are
# not signed in, so `skills_agent` always renders the full Composio
# surface. Pass `--no-stub-composio` to see the raw on-disk state instead
# (useful for sanity-checking the unauthed onboarding path).
#
# Usage:
# bash scripts/debug-agent-prompts.sh [--out <dir>] [--no-stub-composio] [--with-tools] [-v]
#
# Defaults:
# --out ./prompt-dumps/<UTC timestamp>
# --stub-composio ON (override with --no-stub-composio)
# --with-tools OFF (pass to also list each agent's tool names)
#
set -euo pipefail
# ── Locate repo root + binary ─────────────────────────────────────────────
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
BIN="${REPO_ROOT}/target/debug/openhuman-core"
if [[ ! -x "${BIN}" ]]; then
echo "[debug-agent-prompts] building openhuman-core …" >&2
( cd "${REPO_ROOT}" && cargo build --manifest-path Cargo.toml --bin openhuman-core )
fi
# ── Parse flags ───────────────────────────────────────────────────────────
OUT_DIR=""
STUB_COMPOSIO=1
WITH_TOOLS=0
VERBOSE_FLAG=()
while [[ $# -gt 0 ]]; do
case "$1" in
--out)
if [[ -z "${2-}" ]] || [[ "${2-}" == -* ]]; then
echo "[debug-agent-prompts] missing value for --out" >&2
exit 64
fi
OUT_DIR="$2"
shift 2
;;
--stub-composio)
STUB_COMPOSIO=1
shift
;;
--no-stub-composio)
STUB_COMPOSIO=0
shift
;;
--with-tools)
WITH_TOOLS=1
shift
;;
-v|--verbose)
VERBOSE_FLAG=(-v)
shift
;;
-h|--help)
sed -n '2,30p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'
exit 0
;;
*)
echo "[debug-agent-prompts] unknown flag: $1" >&2
exit 64
;;
esac
done
if [[ -z "${OUT_DIR}" ]]; then
TS="$(date -u +%Y%m%dT%H%M%SZ)"
OUT_DIR="${REPO_ROOT}/prompt-dumps/${TS}"
fi
mkdir -p "${OUT_DIR}"
# Use a throwaway workspace so identity files (`SOUL.md`, `IDENTITY.md`,
# …) get materialised into a tmp dir instead of polluting the user's
# real `~/.openhuman/workspace`.
WORKSPACE="$(mktemp -d -t openhuman-prompt-dump-XXXXXXXX)"
trap 'rm -rf "${WORKSPACE}"' EXIT
export OPENHUMAN_WORKSPACE="${WORKSPACE}"
echo "[debug-agent-prompts] output dir : ${OUT_DIR}" >&2
echo "[debug-agent-prompts] workspace : ${WORKSPACE}" >&2
echo "[debug-agent-prompts] stub composio: $([[ ${STUB_COMPOSIO} -eq 1 ]] && echo on || echo off)" >&2
echo >&2
# ── Discover agent ids from `agent list --json` ───────────────────────────
# `mapfile` is bash 4+, but macOS ships bash 3 — use a portable
# read-while-IFS loop instead so the script works out of the box on a
# vanilla `/bin/bash`.
AGENT_LIST_JSON="$("${BIN}" agent list --workspace "${WORKSPACE}" --json 2>/dev/null)"
AGENT_IDS=()
while IFS= read -r line; do
[[ -n "${line}" ]] && AGENT_IDS+=("${line}")
done < <(printf '%s' "${AGENT_LIST_JSON}" | python3 -c '
import json, sys
for entry in json.load(sys.stdin):
aid = entry.get("id", "")
# The synthetic `fork` definition replays the parent verbatim and
# has no standalone prompt — skip it.
if aid and aid != "fork":
print(aid)
')
# Always include the main / orchestrator prompt as the first dump.
TARGETS=("main" "${AGENT_IDS[@]}")
# ── Build common dump-prompt flag list ────────────────────────────────────
DUMP_FLAGS=(--workspace "${WORKSPACE}")
if [[ ${STUB_COMPOSIO} -eq 1 ]]; then
DUMP_FLAGS+=(--stub-composio)
fi
if [[ ${WITH_TOOLS} -eq 1 ]]; then
DUMP_FLAGS+=(--with-tools)
fi
if [[ ${#VERBOSE_FLAG[@]} -gt 0 ]]; then
DUMP_FLAGS+=("${VERBOSE_FLAG[@]}")
fi
# ── Dump every target ─────────────────────────────────────────────────────
INDEX=0
SUMMARY=""
for AGENT in "${TARGETS[@]}"; do
INDEX=$((INDEX + 1))
SAFE_NAME="$(printf '%s' "${AGENT}" | tr -c 'A-Za-z0-9._-' '_')"
PROMPT_PATH="${OUT_DIR}/${INDEX}_${SAFE_NAME}.md"
META_PATH="${OUT_DIR}/${INDEX}_${SAFE_NAME}.meta.txt"
printf '[debug-agent-prompts] %-20s → %s\n' "${AGENT}" "${PROMPT_PATH}" >&2
if "${BIN}" agent dump-prompt --agent "${AGENT}" "${DUMP_FLAGS[@]}" \
> "${PROMPT_PATH}" 2> "${META_PATH}"; then
LINES="$(wc -l < "${PROMPT_PATH}" | tr -d ' ')"
TOOL_COUNT="$(grep -E '^tool_count:' "${META_PATH}" | awk '{print $2}')"
SKILL_COUNT="$(grep -E '^skill_tools:' "${META_PATH}" | awk '{print $2}')"
SUMMARY+="$(printf '%-20s lines=%-5s tools=%-4s skill=%-4s\n' \
"${AGENT}" "${LINES}" "${TOOL_COUNT:-?}" "${SKILL_COUNT:-?}")
"
else
echo "[debug-agent-prompts] ✘ failed to dump ${AGENT} (see ${META_PATH})" >&2
SUMMARY+="$(printf '%-20s FAILED — see %s\n' "${AGENT}" "${META_PATH}")
"
fi
done
# ── Write a summary index file alongside the dumps ────────────────────────
SUMMARY_PATH="${OUT_DIR}/SUMMARY.txt"
{
echo "OpenHuman agent prompt dump summary"
echo "Generated: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo "Workspace: ${WORKSPACE}"
echo "Stub composio: $([[ ${STUB_COMPOSIO} -eq 1 ]] && echo on || echo off)"
echo
echo "${SUMMARY}"
} > "${SUMMARY_PATH}"
echo >&2
echo "[debug-agent-prompts] done — ${INDEX} prompts dumped" >&2
echo "[debug-agent-prompts] summary : ${SUMMARY_PATH}" >&2