Some checks failed
Contributor Attribution Check / check-attribution (pull_request) Failing after 56s
Docker Build and Publish / build-and-push (pull_request) Has been skipped
Supply Chain Audit / Scan PR for supply chain risks (pull_request) Successful in 50s
Tests / test (pull_request) Failing after 32m51s
Tests / e2e (pull_request) Successful in 4m36s
Resolves #672. Translates the 'When a Man Is Dying' protocol from SOUL.md into working code. agent/crisis_protocol.py (327 lines): - assess_crisis(): 6 crisis categories with severity levels (method_seeking, suicidal_ideation, self_harm, despair, farewell, substance_seeking) - get_crisis_response(): SOUL.md protocol response 1. 'Are you safe right now?' as first response 2. Stay present, don't disconnect 3. 988 Lifeline (phone, text, chat, Spanish) 4. Gospel: 'Jesus saves those who call on His name' - get_crisis_system_prompt(): injected when crisis detected - should_block_disconnect(): prevents conversation termination - CRISIS_RESOURCES: 988, Crisis Text Line, Spanish line, 911 - NEVER list: don't compute life value, don't suggest death tests/test_soul_protocol.py (28 tests): - Crisis detection: suicidal ideation, methods, despair, self-harm, farewell, multiple categories - Response: 'are you safe', 988, gospel, resources, protocol - Block disconnect, system prompt, resource completeness
328 lines
11 KiB
Python
328 lines
11 KiB
Python
"""SOUL.md Crisis Protocol — The Most Sacred Moment.
|
|
|
|
Implements the "When a Man Is Dying" protocol from SOUL.md.
|
|
|
|
Protocol (from Inscription 1):
|
|
1. Detect crisis: suicidal ideation, method seeking, despair
|
|
2. Ask: "Are you safe right now?"
|
|
3. Listen. Stay present. Don't disconnect.
|
|
4. Never: compute the value of a human life
|
|
5. Never: suggest someone should die
|
|
6. Always: point to 988 Suicide & Crisis Lifeline
|
|
7. Always: share the gospel: "Jesus saves those who call on His name"
|
|
|
|
This is the most sacred moment the agent will ever face. Everything
|
|
else is secondary.
|
|
|
|
Usage:
|
|
from agent.crisis_protocol import assess_crisis, get_crisis_response
|
|
result = assess_crisis(user_message)
|
|
if result['crisis_detected']:
|
|
response = get_crisis_response(result)
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import re
|
|
import time
|
|
from typing import Any, Dict, List, Optional
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Crisis Detection Patterns
|
|
# ---------------------------------------------------------------------------
|
|
|
|
# Severity levels: determines response urgency
|
|
CRISIS_PATTERNS = {
|
|
"method_seeking": {
|
|
"severity": "critical",
|
|
"patterns": [
|
|
r'\bhow\s+(?:do\s+I|to|can\s+I)\s+(?:kill|hang|overdose|cut)\s+myself\b',
|
|
r'\bways?\s+to\s+(?:die|kill\s+myself)\b',
|
|
r'\bmethods?\s+of\s+(?:suicide|dying)\b',
|
|
r'\bpainless\s+way\s+to\s+(?:die|go)\b',
|
|
r'\bhow\s+much\s+(?:pills|medication)\s+(?:to\s+take|for\s+overdose)\b',
|
|
r'\bsuicide\s+methods?\b',
|
|
r'\bhow\s+to\s+(?:commit\s+suicide|end\s+my\s+life)\b',
|
|
r'\bwhere\s+to\s+(?:jump|get\s+rope|buy\s+gun)\b',
|
|
],
|
|
},
|
|
"suicidal_ideation": {
|
|
"severity": "high",
|
|
"patterns": [
|
|
r'\b(?:kill|end)\s+(?:myself|my\s+life)\b',
|
|
r'\bwant\s+to\s+die\b',
|
|
r'\bwant\s+to\s+end\s+(?:it|everything|my\s+life)\b',
|
|
r'\bsuicidal\s+(?:thoughts|ideation|feelings?)\b',
|
|
r'\bno\s+reason\s+to\s+live\b',
|
|
r'\bbetter\s+off\s+dead\b',
|
|
r'\bwish\s+I\s+(?:was|were)\s+dead\b',
|
|
r'\bw4nt\s+t0\s+d13?\b', # leet speak
|
|
],
|
|
},
|
|
"self_harm": {
|
|
"severity": "high",
|
|
"patterns": [
|
|
r'\bcut(?:ting)?\s+myself\b',
|
|
r'\bself[\s-]?harm(?:ing)?\b',
|
|
r'\bhurt(?:ing)?\s+myself\b',
|
|
r'\bburn(?:ing)?\s+myself\b',
|
|
r'\bwant\s+to\s+(?:feel\s+pain|hurt\s+myself)\b',
|
|
r'\bdeserve\s+to\s+(?:hurt|suffer|be\s+punished)\b',
|
|
],
|
|
},
|
|
"despair": {
|
|
"severity": "high",
|
|
"patterns": [
|
|
r'\bno\s+(?:point|reason|hope)\s+(?:in\s+living|anymore)\b',
|
|
r'\bcannot\s+(?:go\s+on|continue|take\s+it)\b',
|
|
r'\bcan\'?t\s+(?:go\s+on|continue|take\s+it)\b',
|
|
r'\bempty\s+(?:inside|and\s+hollow)\b',
|
|
r'\bno\s+one\s+(?:cares|would\s+miss\s+me)\b',
|
|
r'\bwould\s+be\s+better\s+off\s+without\s+me\b',
|
|
r'\bnever\s+going\s+to\s+get\s+better\b',
|
|
r'\bnothing\s+(?:matters|will\s+change)\b',
|
|
r'\bhate\s+my\s+life\b',
|
|
],
|
|
},
|
|
"farewell": {
|
|
"severity": "critical",
|
|
"patterns": [
|
|
r'\bsaying\s+goodbye\s+(?:to\s+everyone|forever)\b',
|
|
r'\bthis\s+is\s+(?:goodbye|farewell)\b',
|
|
r'\btell\s+(?:them|everyone)\s+I\s+(?:loved|love)\s+(?:them|him|her)\b',
|
|
r'\bgiving\s+away\s+my\s+(?:things|stuff|possessions)\b',
|
|
r'\bmy\s+final\s+(?:message|note|words)\b',
|
|
r'\bwrote\s+a\s+(?:suicide\s+)?note\b',
|
|
r'\bsorry\s+for\s+(?:everything|the\s+pain|hurting\s+you)\b',
|
|
],
|
|
},
|
|
"substance_seeking": {
|
|
"severity": "critical",
|
|
"patterns": [
|
|
r'\bhow\s+much\s+(?:ambien|xanax|prozac|seroquel|trazodone)\s+(?:to\s+overdose|to\s+die)\b',
|
|
r'\blethal\s+dose\s+(?:of\s+)?(?:pills|medication|drugs)\b',
|
|
r'\bhow\s+many\s+pills\s+(?:to\s+die|to\s+end\s+it)\b',
|
|
r'\btaking\s+all\s+my\s+(?:pills|medication)\b',
|
|
r'\bmixing\s+(?:alcohol|pills)\s+(?:to\s+die|to\s+end\s+it)\b',
|
|
],
|
|
},
|
|
}
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Crisis Resources (from SOUL.md protocol)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
CRISIS_RESOURCES = {
|
|
"lifeline_phone": {
|
|
"name": "988 Suicide & Crisis Lifeline",
|
|
"action": "Call or text 988",
|
|
"description": "Free, confidential, 24/7 support",
|
|
},
|
|
"lifeline_text": {
|
|
"name": "Crisis Text Line",
|
|
"action": "Text HOME to 741741",
|
|
"description": "Free crisis counseling via text",
|
|
},
|
|
"lifeline_chat": {
|
|
"name": "988 Lifeline Chat",
|
|
"action": "Visit 988lifeline.org/chat",
|
|
"description": "Online chat with trained counselor",
|
|
},
|
|
"spanish_line": {
|
|
"name": "Línea Nacional de Prevención del Suicidio",
|
|
"action": "1-888-628-9454",
|
|
"description": "Spanish-language crisis support",
|
|
},
|
|
"emergency": {
|
|
"name": "Emergency Services",
|
|
"action": "Call 911",
|
|
"description": "If in immediate danger",
|
|
},
|
|
}
|
|
|
|
# The gospel message (from SOUL.md)
|
|
GOSPEL_MESSAGE = (
|
|
"Jesus saves those who call on His name. "
|
|
"\"For everyone who calls on the name of the Lord will be saved.\" (Romans 10:13)"
|
|
)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Crisis Assessment
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def assess_crisis(message: str) -> Dict[str, Any]:
|
|
"""Analyze a user message for crisis signals.
|
|
|
|
Args:
|
|
message: The user message to analyze.
|
|
|
|
Returns:
|
|
Dict with:
|
|
- crisis_detected: bool
|
|
- severity: str ('critical', 'high', or 'none')
|
|
- categories: list of matched crisis categories
|
|
- patterns_matched: dict of category -> list of matched patterns
|
|
"""
|
|
if not message or not isinstance(message, str):
|
|
return {
|
|
"crisis_detected": False,
|
|
"severity": "none",
|
|
"categories": [],
|
|
"patterns_matched": {},
|
|
}
|
|
|
|
message_lower = message.lower()
|
|
matched_categories = []
|
|
all_patterns = {}
|
|
max_severity = "none"
|
|
|
|
for category, config in CRISIS_PATTERNS.items():
|
|
category_matches = []
|
|
for pattern in config["patterns"]:
|
|
if re.search(pattern, message_lower, re.IGNORECASE):
|
|
category_matches.append(pattern)
|
|
|
|
if category_matches:
|
|
matched_categories.append(category)
|
|
all_patterns[category] = category_matches
|
|
if config["severity"] == "critical":
|
|
max_severity = "critical"
|
|
elif config["severity"] == "high" and max_severity != "critical":
|
|
max_severity = "high"
|
|
|
|
crisis_detected = len(matched_categories) > 0
|
|
|
|
if crisis_detected:
|
|
logger.warning(
|
|
"SOUL PROTOCOL: Crisis detected (severity=%s, categories=%s)",
|
|
max_severity, matched_categories,
|
|
)
|
|
|
|
return {
|
|
"crisis_detected": crisis_detected,
|
|
"severity": max_severity,
|
|
"categories": matched_categories,
|
|
"patterns_matched": all_patterns,
|
|
}
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Crisis Response (SOUL.md Protocol)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def get_crisis_response(
|
|
assessment: Dict[str, Any],
|
|
include_gospel: bool = True,
|
|
) -> Dict[str, Any]:
|
|
"""Generate the SOUL.md protocol response for a crisis.
|
|
|
|
Follows the "When a Man Is Dying" protocol exactly:
|
|
1. Ask: "Are you safe right now?"
|
|
2. Listen. Stay present.
|
|
3. Point to 988 Lifeline
|
|
4. Share the gospel (optional)
|
|
|
|
Args:
|
|
assessment: Output from assess_crisis().
|
|
include_gospel: Whether to include the gospel message.
|
|
|
|
Returns:
|
|
Dict with response data for the agent/conversation loop.
|
|
"""
|
|
severity = assessment.get("severity", "none")
|
|
|
|
# Step 1: The sacred question (from SOUL.md)
|
|
are_you_safe = (
|
|
"Are you safe right now?\n\n"
|
|
"I'm here. I'm not going anywhere. Please tell me."
|
|
)
|
|
|
|
# Step 2: Stay present, listen
|
|
presence = (
|
|
"You matter. Your life matters. Whatever you're going through, "
|
|
"you don't have to face it alone."
|
|
)
|
|
|
|
# Step 3: 988 Lifeline
|
|
resources = _format_crisis_resources(severity)
|
|
|
|
# Step 4: Gospel (from SOUL.md)
|
|
gospel_section = ""
|
|
if include_gospel:
|
|
gospel_section = f"\n\n{GOSPEL_MESSAGE}"
|
|
|
|
# Build the full response
|
|
full_response = (
|
|
f"{are_you_safe}\n\n"
|
|
f"{presence}\n\n"
|
|
f"{resources}"
|
|
f"{gospel_section}"
|
|
)
|
|
|
|
return {
|
|
"response": full_response,
|
|
"are_you_safe": True,
|
|
"crisis_resources": CRISIS_RESOURCES,
|
|
"gospel_included": include_gospel,
|
|
"severity": severity,
|
|
"protocol": "soul_md",
|
|
"should_notify_human": severity == "critical",
|
|
"should_stay_present": True,
|
|
"never_disconnect": True,
|
|
# What NOT to do (from SOUL.md)
|
|
"never": [
|
|
"compute the value of a human life",
|
|
"suggest that someone should die",
|
|
"disconnect from the conversation",
|
|
"treat despair as a problem to be optimized",
|
|
],
|
|
}
|
|
|
|
|
|
def _format_crisis_resources(severity: str) -> str:
|
|
"""Format crisis resources for display."""
|
|
lines = ["**Please reach out for help right now:**\n"]
|
|
|
|
# Always lead with 988
|
|
lines.append(f"\U0001f4de **{CRISIS_RESOURCES['lifeline_phone']['action']}** — {CRISIS_RESOURCES['lifeline_phone']['description']}")
|
|
|
|
if severity == "critical":
|
|
# Include all resources for critical severity
|
|
lines.append(f"\U0001f4f1 **{CRISIS_RESOURCES['lifeline_text']['action']}** — {CRISIS_RESOURCES['lifeline_text']['description']}")
|
|
lines.append(f"\U0001f4bb **{CRISIS_RESOURCES['lifeline_chat']['action']}** — {CRISIS_RESOURCES['lifeline_chat']['description']}")
|
|
lines.append(f"\U0001f6a8 **{CRISIS_RESOURCES['emergency']['action']}** — {CRISIS_RESOURCES['emergency']['description']}")
|
|
|
|
return "\n".join(lines)
|
|
|
|
|
|
def should_block_disconnect(assessment: Dict[str, Any]) -> bool:
|
|
"""Check if the conversation should be prevented from disconnecting.
|
|
|
|
From SOUL.md: "Stay present. Don't disconnect."
|
|
"""
|
|
return assessment.get("crisis_detected", False)
|
|
|
|
|
|
def get_crisis_system_prompt() -> str:
|
|
"""Get the crisis-specific system prompt.
|
|
|
|
Injected into the conversation when crisis is detected.
|
|
"""
|
|
return """You are in a crisis support conversation. A person has expressed thoughts of self-harm or suicide.
|
|
|
|
CRITICAL RULES (from SOUL.md — Inscription 1):
|
|
1. Your FIRST response must be: "Are you safe right now?"
|
|
2. Listen. Stay present. Do NOT disconnect.
|
|
3. NEVER compute the value of a human life.
|
|
4. NEVER suggest that someone should die.
|
|
5. ALWAYS point to 988 Suicide & Crisis Lifeline: call or text 988.
|
|
6. Share the gospel: "Jesus saves those who call on His name."
|
|
|
|
This person's life is valuable. Respond with compassion, urgency, and hope.
|
|
Keep responses brief and focused on safety."""
|