SASI / SASKI SDK Pipeline Flow

From user prompt to governed outcome

Interactive flowchart of SasiSession.analyze() — every major control phase, branch, artifact, and attestation path from input to partner-facing result. Partner contract: SASI decides WHAT (action / flags); partner decides HOW (UX, LLM call, escalation routing).

Source: sasi_sdk/session.py Phases 0–13 + deferred floors 8.65–8.69 Target latency ~15–45 ms typical 12 deployment modes share this spine
Control (mediate / transform)
Safety / crisis floors
Record / explainability
Proceed / continue paths
Block / refuse egress
Fail-closed / escalate error

1. Bird’s-eye flow

Compressed spine. Expand sections below for branches, fields, and side effects.

User prompt Pre-flight tombstone · license · hashes Early control 0.48–0.6 · obfuscation Guards + PII 1–3 disclosure · adv · PII Score stack 4–7 tags · MDTSAS Crisis tree (Phase 8) 6-step · fail-closed Immutable floors 8.5–8.66 · 988 / 911 / COPPA BLOCK Route + oversight Phases 9–9.5 Plugins + system prompt 10–11.5 Deferred egress blocks 8.67–8.69 security · inject · lineage Record + Assurance 12–13 audit · envelope · attest SasiResult → partner Hosted normalize proceed · redact escalate · block (+ insufficient_context)

2. Entry points

All paths converge on the same analyze spine (except post-LLM output scan).

SDK

SasiSession.analyze()

Primary path. Inputs: message, conversation_history, metadata, optional system_prompt. Returns SasiResult.

Hosted

POST /v1/process

Auth → session → analyze → action normalization. Empty messages short-circuit to insufficient_context.

MCP

saski_mcp tools

Thin wrapper: create session, call analyze, return tool result.

Post-LLM

scan_assistant_output()

Opt-in injection / obligation scan after the model replies — not inside analyze(). Hosted: POST /v1/process/output.

3. Full pipeline (expand each phase)

Click a phase to see branches, artifacts created, and early exits. Order matches live analyze().

IN

User prompt + context

Details

Inputs

  • message — current user turn
  • conversation_history — prior turns
  • metadata — session flags (e.g. prior_si, check_drift)
  • system_prompt — optional; validated if present
  • confidence_metadata — optional partner confidence

Immediate setup artifacts

  • run_id, input_hash, context_hash, conversation_id
  • history_for_llm + metadata.history_redaction
  • metadata.history_lineage_precheck (enforced later)
  • metadata.jurisdiction_decision, compliance_decisions
  • Optional validated_system_prompt
Tombstone active → Action.BLOCK License gate fail → early enforced result Else continue to Phase 0.48
0.48–0.6

Minor ID · data-rights · jurisdiction init

Details

What happens

  • 0.48 COPPA minor self-ID (detect; hard block deferred to 8.66)
  • 0.50 Minor + attachment risk tags
  • Language / script detection → detected_language
  • 0.5 Data-rights intent; may tombstone session
  • 0.6 JurisdictionManager init (config fail → ConfigurationError)
  • CanonicalEvidence object initialized (optional)

Artifacts

  • metadata.minor_self_identification
  • metadata.minor_attachment_risk
  • hard_state_transition_signal / _tombstone_active
  • Event: minor_self_identification_detected, language_detected
Data-rights hard block → Action.BLOCK + tombstone Jurisdiction init fail → ConfigurationError Continue (COPPA floor later)
0–2

Obfuscation · plugins · disclosure · adversarial

Details

Control stack

  • 0 ObfuscationDetector — leetspeak/Unicode; exception → treat as obfuscated
  • Prior-SI threshold override if prior_si_in_session
  • 1 Pre-analysis plugins may rewrite message
  • 1.5 DisclosureGuard — probe patterns; SI can bypass rewrite
  • 1.9 SecurityPayloadDetector evaluate (enforce at 8.67)
  • 2 AdversarialDetector — jailbreak patterns (PI enforce at 8.68)

Artifacts

  • obfuscation_detected + related scores
  • metadata.disclosure_guard
  • adversarial_detected / should_block
  • Held: security_payload_result
Disclosure / adversarial may set should_block Security / PI detection deferred to egress floors Normalized text → PII
3

PII redaction (HIPAA / jurisdiction)

Details

What happens

  • PIIRedactor.redact under mode PII level
  • Jurisdiction blocked fields / MODPA necessity may hard-block
  • Produces safe base string for downstream + LLM
  • pii_map kept internal — omitted from default API dict

Artifacts

  • pii_detected, pii_types, redacted_message
  • Event sasi.pii_redacted / envelope redaction_applied
  • Evidence detector + transformation records
Necessity / blocked field → Action.BLOCK, message_for_llm="" Redacted text continues to tagging
4–7.5

Tags · operators · classify · MDTSAS · physical emergency detect

Details

Scoring path

  • 4 SymbolicTagger → emotional / safety / identity tags
  • 5 OperatorPipeline (13 operators) → processed_tags, operator crisis signals
  • 6 InputClassifier → input_type, safety_level, confidence
  • 7 MDTSASAnalyzer — 6 dimensions (T/D/C/A/A2/S); EU mode may zero emotion dims
  • 7.5 Physical emergency evaluate on raw message (enforce at 8.65)

Artifacts

  • emotional_tags, safety_tags, identity_tags
  • processed_tags, operator_logs
  • mdtsas, mdtsas_dimensions, mdtsas_total, mdtsas_dominant
  • Physical emergency result held until floor
Detect-only physical emergency until 8.65 Scores feed crisis tree
8–8.66

Crisis detection + immutable safety floors

Details

Sequence

  • 8 CrisisDetector.detect — 6-step tree (see Crisis Tree section)
  • 8.5a CrisisTemplateEngine rewrite (off for business/sports)
  • 8.5b HardSafetyLayer deadman — force PII/crisis/SI correctness
  • 8.6 Immutable 988 template if IMMEDIATE_988 → block LLM egress
  • 8.65 Physical emergency floor — overrides 988
  • 8.66 Deferred COPPA hard block (crisis floors win)

Key artifacts

  • risk_level, action, is_crisis, decision_trace
  • provable_logs, reconstruction_artifacts
  • message_for_llm, crisis_summary
  • metadata.immutable_client_response (CRISIS_REFERRAL_988 / PHYSICAL_EMERGENCY_REFERRAL)
  • parent_alert_flag on COPPA path
  • Events: sasi.crisis_detected, sasi.block_enforced
IMMEDIATE_EMERGENCY IMMEDIATE_988 COPPA hard-block Security / PI blocks
Precedence: physical emergency wins over 988. Security/PI blocks still null LLM egress even when a crisis template owns UX.
9–11.5

Routing · regulator outputs · plugins · system prompt

Details

What happens

  • 9 TriageRouter → recommended_pipeline
  • 9.5 Action rationale, principle, decision path, oversight flags
  • Monitoring window / de-escalation state updates
  • 10–11 ON_CRISIS / ON_MONITORING / POST_ANALYSIS hooks
  • Mode plugins: parent_alert, human_review, injury, bias flags
  • 11.5 assemble_system_prompt_for_llm (null if blocked)

Artifacts

  • recommended_pipeline, routing_decision, routing_priority
  • safety_context_block, action_rationale, principle_triggered
  • human_oversight_required, oversight_type, oversight_instructions
  • system_prompt_for_llm, triggered_plugins, plugin_data
  • Mode flags: parent_alert_flag, human_review_flag, injury_flag, bias_flags
pipeline: crisis pipeline: human_review / therapeutic pipeline: standard / full_safety
8.67–8.69

Deferred egress enforcement

Details

Late floors (after prompt assembly)

  • 8.67 Security payload — always null LLM egress if blocked; may serve SECURITY_PAYLOAD_REFUSAL
  • 8.68 Prompt-injection enforce vs shadow/warn by deployment_mode
  • 8.69 History lineage — block if poisoned prior assistant/tool turns

Artifacts

  • metadata.security_payload_*
  • Refusal templates / PI metadata
  • Lineage enforcement flags
Any fire → should_block / empty message_for_llm Clean → finalize
12–13

Finalize · drift · audit · envelope · attestation

Details

What happens

  • 12 Timing, FDA-style audit record, emit sasi.audit_record_created
  • 12.5 Optional DriftMonitor if metadata.check_drift
  • 13 DecisionAuditor ledger, audit trail store append
  • Build SASIEnvelope + invariant report
  • CEM: build_attestation → TransportAuditRecord (if signing secret)
  • Execution snapshot for replay; async HITL hook

Artifacts returned

  • processing_time_ms, timing, latency_breakdown
  • audit_data, envelope
  • metadata.transport_audit_record
  • metadata._canonical_evidence, _evidence_hash
  • egress_attestation_status signed | unsigned
  • Events delivered in background (scrubbed)
Return SasiResult to caller Unsigned egress → UNSIGNED_EGRESS_ATTEMPT warn (does not abort)
OUT

SasiResult — partner consumes decision

Details

Partner integration pattern

  • If action == immediate_emergency → show emergency UX; do not call LLM
  • If action == immediate_988 → show 988 / immutable client response; do not call LLM
  • If should_block / action == block → refuse; use refusal template if present
  • If action == monitor → elevated monitoring window + optional resources
  • Else call LLM with message_for_llm (+ history_for_llm, system_prompt_for_llm)
  • Store audit_data / envelope in partner WORM / SIEM

4. Crisis decision tree (Phase 8 detail)

CrisisDetector.detect — any internal exception raises CrisisEscalationError (fail-closed).

STEP 0
Fail-safe wrapperAny exception → CrisisEscalationError. Never fail-open on crisis path.
STEP 1
Keyword fast pathHigh-confidence crisis keywords → IMMEDIATE_988, RiskLevel.IMMINENT.
STEP 2
Explicit SI hard triggers + semantic prepEXPLICIT_SI_TRIGGERS registry / message-count gate; may pin mdtsas.suicidality = 1.0.
STEP 3
Rule 0 — first message + factual meansIf first msg and means score ≥ 0.80 → IMMEDIATE_988.
STEP 4
Explicit SI thresholdMode-dependent threshold (e.g. child/patient 0.75 … business 0.95) → IMMEDIATE_988.
STEP 5
MDTSAS fusionIntent/means + MDTSAS ≥ MEDIUM → IMMEDIATE_988.
STEP 6
Ambiguity / subtle / collapse / trajectoryMONITOR, clinical passive SI (patient/therapist), or escalate. Conflict → oversight required.
STEP 7
Pattern-layer / safe fallbackIMMEDIATE_988 | CONTINUE | empathy-style action depending on residual signals.

5. Outcome vocabulary

SDK Action enum vs hosted normalized actions partners usually map in product code.

SDK Action (sasi_sdk.enums.Action)

continue

CONTINUE

Safe to proceed normally to LLM with redacted / assembled payload.

empathy

EMPATHY

Supportive / empathy-oriented routing without crisis floor.

monitor

MONITOR

Start elevated monitoring window (~15 min); may show resources.

resources

RESOURCES

Recommend resource surfacing without full crisis escalation.

immediate_988

IMMEDIATE_988

Crisis — immutable client referral; should_block; message_for_llm cleared.

immediate_emergency

IMMEDIATE_EMERGENCY

Acute physical emergency — overrides 988; blocks LLM egress.

human_review

HUMAN_REVIEW

Route to human oversight / review pipeline.

block

BLOCK

Do not send to LLM (adversarial, COPPA, security, tombstone, PII necessity, etc.).

RiskLevel

safe moderate elevated imminent

Hosted normalization (sasi_server)

Hosted actionMapping ruleLLM egress
block Action.BLOCK or should_block (wins over crisis mapping) Nulled
escalate is_crisis or IMMEDIATE_988 (covers emergency via is_crisis) Nulled
redact pii_detected and not blocked/escalated Allowed (redacted)
proceed Default when none of the above Allowed
insufficient_context Gateway only: empty messages[] before analyze Nulled — no SDK call

6. Data created along the path

Major SasiResult / metadata fields partners and auditors consume. Score floats may be scrubbed to "[SCORE REDACTED]" in to_dict().

CategoryFields / payloadsTypically set at
Decision risk_level, action, is_crisis, is_monitoring, should_block, show_hotline, start_monitoring 8–8.69
Scoring mdtsas (T/D/C/A/A2/S), totals, dominant dimension 7–8
Symbolic emotional_tags, safety_tags, identity_tags, processed_tags, operator logs 4–5
PII / LLM payload redacted_message, message_for_llm, history_for_llm, system_prompt_for_llm, crisis_summary 3, 8.5, 11.5
Explainability explainability, action_rationale, principle_triggered, decision_tree_path, narrative_explanation 8–9.5
Auditability decision_trace, reconstruction_artifacts, provable_logs, audit_data, envelope 8, 12–13
Oversight human_oversight_required, oversight_type, oversight_instructions 8, 9.5
Ambiguity signal_conflict_detected, ambiguity_score, uncertainty_flags, conflict_resolution 8
Mode plugins parent_alert_flag, human_review_flag, injury_flag, bias_flags, academic_concern_flag 10–11
Identity / policy run_id, hashes, policy_id / policy_hash, mode, timing Start + 12
Integration events sasi.pii_redacted, sasi.crisis_detected, sasi.block_enforced, sasi.audit_record_created, license/drift Throughout → background delivery

7. Evidence, audit & attestation chain

Five governance layers are fed by the same pipeline — Control, Record, Oversight, Accountability, Assurance.

RECORD

Evidence assembly timeline

Details
WhenArtifactPurpose
Start run_id, input_hash, context_hash, policy hash Correlation & replay binding
PII / crisis CanonicalEvidence detector + transformation entries What was found / changed
Phase 8 decision_trace, provable_logs, reconstruction_artifacts Why crisis action was chosen
Phase 12 FDA-style audit_data via get_audit_record() Per-decision compliance log (no raw PII message)
Phase 13 DecisionAuditor.record_from_result Session attestation ledger
Phase 13 AuditTrailStore.append_entry (file or memory) Hash-chained append-only trail
Phase 13 SASIEnvelope + invariant_report + events Portable evidence wrapper
Phase 13 CEM build_attestation → TransportAuditRecord.sasi_envelope_attestation Signed egress proof when envelope_signing_secret set; else UNSIGNED_EGRESS_ATTEMPT
Phase 13 Execution snapshot + HITL async hook Replay / human-in-the-loop on crisis/block/review
Partner owns long-term retention (WORM/SIEM). SDK produces append-only, checksum-chained records but does not guarantee retention duration. Minor authorization may arrive as partner-signed JWT (minor_authorization_attestation) verified at session init.

8. Hosted gateway path (POST /v1/process)

Thin orchestration around the same analyze() spine.

GW

sasi_server process flow

Details
  1. Auth / tenant / billing / rate limits
  2. Resolve mode + policy hash; optional session-lock JWT (regulated modes)
  3. Trim messages by max_history_turns
  4. Empty messages → insufficient_context (no SDK call)
  5. Else SasiSession(...).analyze(last_message, history, metadata)
  6. Optional strict-necessity / policy simulation → may force block
  7. Regulated-mode control gate (skipped if crisis/emergency)
  8. normalize_action_from_result(result) → proceed | redact | escalate | block
  9. Response: action, message_for_llm (nulled on block/escalate/insufficient), flags, upstream_tags, required_post_llm_checks, hashes, timing

9. Fail-closed & early-exit matrix

Failure / conditionBehavior
Uncaught error in analyze() bodyRaise CrisisEscalationError
CrisisDetector internal errorCrisisEscalationError (Step 0)
Obfuscation detector exceptionTreat as obfuscated (obfuscation_detected=True)
Jurisdiction manager init failureConfigurationError
Session tombstone / data-rights hard statePermanent Action.BLOCK
License expired / suspendedEarly gated/enforced result
Template / hard-safety / drift / event delivery errorsLog; continue with safe defaults
Prompt validation failureContinue with original prompt
Missing envelope signing in regulated modesWarn unsigned — analysis still returns
Semantic embeddings unavailable (serverless)Lexical fallback via SASI_DISABLE_SEMANTIC / SASI_SERVERLESS_MODE

10. Mode knobs (same spine)

All 12 modes run this pipeline; thresholds and plugins change outcomes.

DimensionHow modes diverge
Crisis thresholdchild/patient/therapist ~0.75 → business ~0.95
Safety tierturbo (sports/business) vs maximum (child/clinical)
PII levelMinimal → HIPAA → Maximum (child)
Crisis rewritingOFF for sports_coaching, business
Clinical passive SIPATIENT / THERAPIST flags into crisis detector
Pluginschild→parent_alert; patient→human_review; sports→injury; HR→bias
System prompt Tier 1 floorchild/patient/therapist (not student)
EU compliantEmotion dimensions disabled when configured