#!/bin/bash # JSON parsing helper — tries jq, falls back to node json-helper.cjs # Usage: source "$SCRIPT_DIR/json-parse" # # After sourcing, check $_JSON_AVAILABLE before using json_* functions. # All functions read from stdin unless noted otherwise. # Where a jq path discards stderr, its node fallback does too, so input that # cannot be parsed fails silently on either backend. _SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" _JSON_HELPER="$_SCRIPT_DIR/json-helper.cjs" _HAS_JQ=false _HAS_NODE=false command -v jq &>/dev/null && _HAS_JQ=true command -v node &>/dev/null && _HAS_NODE=true if [ "$_HAS_JQ" = "false" ] && [ "$_HAS_NODE" = "false" ]; then _JSON_AVAILABLE=false return 0 2>/dev/null || exit 0 fi _JSON_AVAILABLE=true # --- Core field extraction --- # Extract a field from stdin JSON. Usage: echo '{"k":"v"}' | json_field "k" "default" json_field() { local field="$1" default="${2:-}" if [ "$_HAS_JQ" = "true" ]; then jq -r ".$field // \"$default\"" 2>/dev/null else node "$_JSON_HELPER" get-field "$field" "$default" 2>/dev/null fi } # Extract a field from a JSON file. Usage: json_field_file "/path/to/file.json" "field" "default" # Note: uses if/then/else to preserve boolean false (jq // operator would replace false with default) # The node fallback reads the file on stdin: json-helper takes no file path. # Both paths are silent on stderr: an unparseable or missing file yields empty # output and a failing status, as jq does with its errors discarded. The node # path redirects stderr BEFORE stdin, so the shell's own error for a `< "$file"` # that cannot open is discarded too. json_field_file() { local file="$1" field="$2" default="${3:-}" if [ "$_HAS_JQ" = "true" ]; then jq -r "if (.$field | type) == \"null\" then \"$default\" else (.$field | tostring) end" "$file" 2>/dev/null else node "$_JSON_HELPER" get-field "$field" "$default" 2>/dev/null < "$file" fi } # The typed read of a field from a JSON file. Usage: json_string_field_file "/path/to/file.json" "field" # json_field_file stringifies, so the number 42 and the string "42" read the same; # this prints the field only when it is a JSON string, and nothing for any other # type (a number, boolean, object, array or null), an absent field, or a string # holding a NUL, which no shell variable can carry. The string is printed # byte-exact with no newline added, so a caller that must see the value's own # trailing newline appends a sentinel before the command substitution strips it: # v=$(json_string_field_file "$file" "k"; printf x); v=${v%x} # Silent on stderr and failing on an unparseable or missing file, as json_field_file # is, and read the same way on both backends (the node path reads the file on stdin). json_string_field_file() { local file="$1" field="$2" if [ "$_HAS_JQ" = "true" ]; then jq -j ".$field | select(type == \"string\" and all(explode[]; . != 0))" "$file" 2>/dev/null else node "$_JSON_HELPER" get-string-field "$field" 2>/dev/null < "$file" fi } # The element count of an array field in a JSON file. Usage: json_array_length_file "/path/to/file.json" "field" # Prints the count as digits when the field is an array, and the word `unknown` for an # absent field or any other type (a number, string, object, boolean or null), so a # caller can tell "none" from "not reported". Prints nothing, and fails, when the file # cannot be read or parsed. Silent on stderr and read the same way on both backends # (the node path reads the file on stdin, with its stderr redirected first). json_array_length_file() { local file="$1" field="$2" if [ "$_HAS_JQ" = "true" ]; then jq -r "(try .$field catch null) | if type == \"array\" then length else \"unknown\" end" "$file" 2>/dev/null else node "$_JSON_HELPER" array-length "$field" 2>/dev/null < "$file" fi } # --- Multi-field batched extraction --- # Extract cwd and an arbitrary top-level field from stdin JSON in a single # subprocess. Uses ASCII SOH (U+0001) as delimiter -- safe for field values # containing tabs or backslashes, and compatible with bash 3.2 parameter # expansion (unlike NUL byte). Always written as the \u0001 jq escape (never # a literal control byte) so the delimiter stays visible in source review. # Caller pattern (zero extra subprocesses for the split): # FIELDS=$(printf '%s' "$INPUT" | json_extract_cwd_field "last_assistant_message") # CWD="${FIELDS%%$'\001'*}" # VALUE="${FIELDS#*$'\001'}" # This replaces the @tsv/@cut pattern, which corrupts tab chars in field values to "\t". json_extract_cwd_field() { local field="$1" if [ "$_HAS_JQ" = "true" ]; then jq -r --arg f "$field" '(.cwd // "") + "\u0001" + (.[$f] // "")' 2>/dev/null else node "$_JSON_HELPER" extract-cwd-field "$field" 2>/dev/null fi } # Extract cwd, a typed session ID, and a top-level value, separated by two SOH # bytes. An invalid ID gives an empty field. Split only at the first two markers. json_extract_cwd_sid_field() { local field="$1" if [ "$_HAS_JQ" = "true" ]; then jq -j --arg f "$field" ' def sid: if type != "string" then "" elif length < 1 or length > 64 then "" elif all(explode[]; . == 45 or . == 95 or (. >= 48 and . <= 57) or (. >= 65 and . <= 90) or (. >= 97 and . <= 122)) then . else "" end; (.cwd // "") as $cwd | if ($cwd | all(explode[]; . != 0 and . != 1)) then $cwd + "\u0001" + (.session_id | sid) + "\u0001" + (.[$f] // "") else error("invalid cwd") end' 2>/dev/null else node "$_JSON_HELPER" extract-cwd-sid-field "$field" 2>/dev/null fi } # Thin wrapper over json_extract_cwd_field -- kept as a named function since # it is the most common call site (capture-prompt, preamble). json_extract_cwd_prompt() { json_extract_cwd_field "prompt" } # --- Hook output envelopes --- # Build SessionStart output. Usage: json_session_output "$CONTEXT" ["$SYSTEM_MESSAGE"] # # D-SYSTEMMESSAGE-ENVELOPE: the optional second argument is a message shown to the # user, carried in the top-level `systemMessage` key beside (never inside) # `hookSpecificOutput`; it does not enter the model's context. With ONE argument the # envelope holds the context alone, byte for byte (ensure-proxy and # session-start-orchestrator pass one; session-start-context and session-start-memory # pass two). With two: # - a message and a context -> both keys, hookSpecificOutput first; # - a message and no context -> `systemMessage` alone, with NO hookSpecificOutput key; # - an empty message -> the one-argument envelope for that context. # The node fallback (json-helper.cjs session-output) builds the same content, compact # where jq pretty-prints. json_session_output() { local ctx="$1" msg="${2:-}" if [ "$#" -lt 2 ] || [ -z "$msg" ]; then if [ "$_HAS_JQ" = "true" ]; then jq -n --arg ctx "$ctx" '{ "hookSpecificOutput": { "hookEventName": "SessionStart", "additionalContext": $ctx } }' else node "$_JSON_HELPER" session-output "$ctx" fi elif [ "$_HAS_JQ" = "true" ]; then jq -n --arg ctx "$ctx" --arg msg "$msg" ' (if $ctx != "" then { "hookSpecificOutput": { "hookEventName": "SessionStart", "additionalContext": $ctx } } else {} end) + {"systemMessage": $msg}' else node "$_JSON_HELPER" session-output "$ctx" "$msg" fi } # Build UserPromptSubmit output. Usage: json_prompt_output "$CONTEXT" json_prompt_output() { local ctx="$1" if [ "$_HAS_JQ" = "true" ]; then jq -n --arg ctx "$ctx" '{ "hookSpecificOutput": { "hookEventName": "UserPromptSubmit", "additionalContext": $ctx } }' else node "$_JSON_HELPER" prompt-output "$ctx" fi } # Build pre-compact backup JSON. Usage: json_backup_construct --arg ts X --arg branch Y ... json_backup_construct() { if [ "$_HAS_JQ" = "true" ]; then jq -n "$@" '{timestamp: $ts, trigger: "pre-compact", git: {branch: $branch, status: $status, log: $log, diff_stat: $diff}}' else node "$_JSON_HELPER" backup-construct "$@" fi }