From 84821892bc752238320a7b29ab554f1b785e0c10 Mon Sep 17 00:00:00 2001 From: Eason WaveKat Date: Sat, 31 Oct 2026 18:33:03 +1300 Subject: [PATCH 1/4] feat: add flow schema v3 for screened transfer Version 3 adds optional whisper and timeout_secs to transfer. A reader that ignored whisper would hand the call over blind, so it is a new version rather than an additive field. assistant moves to version 4. --- README.md | 5 +- conformance/v3/valid/minimal.expected.json | 5 + conformance/v3/valid/minimal.yaml | 7 + crates/wavekat-flow/build.rs | 2 +- .../wavekat-flow/schema/flow.v3.schema.json | 276 ++++++++++ crates/wavekat-flow/src/canonical.rs | 4 +- crates/wavekat-flow/src/lib.rs | 13 +- crates/wavekat-flow/src/model_ext.rs | 48 +- crates/wavekat-flow/tests/conformance.rs | 5 + docs/ROADMAP.md | 3 +- packages/flow-schema/scripts/generate.mjs | 4 +- .../src/generated/flow.v3.schema.json | 276 ++++++++++ packages/flow-schema/src/generated/model.ts | 10 +- packages/flow-schema/src/generated/schema.ts | 514 +++++++++++++++++- packages/flow-schema/src/index.ts | 4 +- packages/flow-schema/src/model.ts | 9 +- packages/flow-schema/src/parse.ts | 23 +- packages/flow-schema/src/serialize.ts | 4 +- packages/flow-schema/src/structure.ts | 3 +- packages/flow-schema/test/conformance.test.ts | 2 + packages/flow-schema/test/parse.test.ts | 38 ++ schema/README.md | 5 + schema/flow.v3.schema.json | 276 ++++++++++ 23 files changed, 1501 insertions(+), 35 deletions(-) create mode 100644 conformance/v3/valid/minimal.expected.json create mode 100644 conformance/v3/valid/minimal.yaml create mode 100644 crates/wavekat-flow/schema/flow.v3.schema.json create mode 100644 packages/flow-schema/src/generated/flow.v3.schema.json create mode 100644 schema/flow.v3.schema.json diff --git a/README.md b/README.md index 1e52088..e67f0db 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ code per language — **pinned by the shared corpus**, not generated. See ## Versioning -- `schema_version` is a property of the **document** (currently `2`). Each +- `schema_version` is a property of the **document** (currently `3`). Each version gets its own `schema/flow.vN.schema.json` and its own frozen `conformance/vN/` corpus. Growth is additive; an unsupported version is rejected, never silently migrated. @@ -78,6 +78,9 @@ code per language — **pinned by the shared corpus**, not generated. See has to be able to say "I don't run that version" — which is what makes it safe for the platform to hold back a document rather than hand over one that would fail to parse. `book` is why version 2 exists. +- **A change in what a component does is a new version too.** A `transfer` + with a `whisper` is a screened transfer: an older build would ignore the + field and hand the call over blind. That is why version 3 exists. - The npm package and the Rust crate version **independently** of `schema_version` (they track implementation releases). A given package release advertises which `schema_version`s it understands via diff --git a/conformance/v3/valid/minimal.expected.json b/conformance/v3/valid/minimal.expected.json new file mode 100644 index 0000000..4373c2e --- /dev/null +++ b/conformance/v3/valid/minimal.expected.json @@ -0,0 +1,5 @@ +{ + "description": "Version 3 is version 2 plus optional `whisper` and `timeout_secs` on `transfer` and nothing else: a document that uses none of the new surface is the same document it was, and must still validate once its schema_version is bumped.", + "structurallyValid": true, + "semantic": { "ok": true, "errors": [] } +} diff --git a/conformance/v3/valid/minimal.yaml b/conformance/v3/valid/minimal.yaml new file mode 100644 index 0000000..33545e4 --- /dev/null +++ b/conformance/v3/valid/minimal.yaml @@ -0,0 +1,7 @@ +schema_version: 3 +id: flow_min3 +name: Minimal, version 3 +entry: bye +nodes: + bye: + kind: hangup diff --git a/crates/wavekat-flow/build.rs b/crates/wavekat-flow/build.rs index b513cec..ff26a94 100644 --- a/crates/wavekat-flow/build.rs +++ b/crates/wavekat-flow/build.rs @@ -20,7 +20,7 @@ use std::{env, fs, path::Path}; /// Oldest first; the last entry is the one the model is generated from. -const VERSIONS: &[u32] = &[1, 2]; +const VERSIONS: &[u32] = &[1, 2, 3]; fn main() { println!("cargo:rerun-if-changed=build.rs"); diff --git a/crates/wavekat-flow/schema/flow.v3.schema.json b/crates/wavekat-flow/schema/flow.v3.schema.json new file mode 100644 index 0000000..5005f37 --- /dev/null +++ b/crates/wavekat-flow/schema/flow.v3.schema.json @@ -0,0 +1,276 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://schema.wavekat.com/flow/v3.json", + "title": "Flow", + "description": "The WaveKat call-flow (\"Receptionist\") document, schema_version 3. Version 3 is version 2 plus the screened transfer: the `transfer` node gains `whisper` and `timeout_secs`. Every version-2 document is a valid version-3 document once its `schema_version` is bumped, and nothing else changed. This file is the single source of truth for the document SHAPE, and — being the newest version — it is also the file both consumers generate their model types from, so one model covers every supported version. Semantic rules that a JSON Schema cannot express (graph reachability, exit-set exactness, hours/timezone math, DTMF digit validity, prompt length, per-component numeric bounds, and which components a given schema_version may use) are NOT encoded here — they live in each language's validator and are pinned by the shared conformance corpus. Unknown fields are permitted structurally, matching both implementations (Rust serde ignores them; the TS parser surfaces a non-blocking warning).", + "type": "object", + "required": ["schema_version", "id", "name", "entry", "nodes"], + "properties": { + "schema_version": { + "description": "Document format version. This file describes version 3 only; a document declaring another version validates against that version's schema file, not this one. (The type generators relax this constant to a plain integer so the generated model can hold any supported version — see scripts/generate.mjs and build.rs.)", + "type": "integer", + "const": 3 + }, + "id": { + "description": "Opaque platform-assigned id (flow_…). Treated as a label; appears in traces.", + "type": "string" + }, + "name": { + "description": "Human name shown in the editor and the read-only viewer.", + "type": "string" + }, + "version": { + "description": "Platform-assigned publish counter, bumped on publish. Defaults to 1 for a hand-written or generated pre-publish document. Distinct from schema_version.", + "type": "integer", + "minimum": 0, + "default": 1 + }, + "note": { + "description": "The author's note about the whole flow: free text for people reading it, in place of a YAML comment. Never read by the engine.", + "type": "string" + }, + "entry": { + "description": "Node id where execution begins.", + "type": "string" + }, + "nodes": { + "description": "The flat node set, keyed by human-meaningful node id and string-referenced by exits. Order is irrelevant to execution, but it is the author's reading order and is kept on save.", + "type": "object", + "additionalProperties": { "$ref": "#/$defs/Node" } + }, + "ui": { + "description": "Presentation metadata (canvas positions, annotations). Preserved on round-trip, never read by the engine. Opaque by design so a canvas editor can add layout fields without a schema bump." + } + }, + "$defs": { + "Prompt": { + "description": "What a component speaks: TTS text (a bare string) or a reference to a pre-rendered audio asset shipped alongside the flow.", + "oneOf": [ + { "title": "Text", "type": "string" }, + { + "title": "Audio", + "type": "object", + "required": ["audio"], + "properties": { + "audio": { + "description": "Audio asset ref. A generated-clip ref is a voice_prompts id matching ^vprompt_[a-z0-9]+$.", + "type": "string" + }, + "transcript": { + "description": "The words this pre-rendered clip speaks — the text it was synthesized from — carried so a viewer can show what a caller hears, and for traces. Advisory only: playback always uses `audio`, never this. Optional and forward-added: absent on older documents and on refs the platform did not generate from text.", + "type": "string" + } + } + } + ] + }, + "MessageTone": { + "description": "The cue a message node plays between its prompt and the start of recording.", + "type": "string", + "enum": ["beep", "none"] + }, + "Exits": { + "description": "Wired exits: exit name → target node id. Which names are valid is a property of the node's kind and is checked by the validator, not by this schema.", + "type": "object", + "additionalProperties": { "type": "string" } + }, + "TimeRange": { + "description": "One open window: open–close as \"HH:MM\" (24-hour). Ordering and overnight rules are enforced by the validator.", + "type": "object", + "required": ["open", "close"], + "properties": { + "open": { "type": "string" }, + "close": { "type": "string" } + } + }, + "WeeklySchedule": { + "description": "Open ranges per weekday; a missing or empty day means closed all day.", + "type": "object", + "properties": { + "mon": { "type": "array", "items": { "$ref": "#/$defs/TimeRange" } }, + "tue": { "type": "array", "items": { "$ref": "#/$defs/TimeRange" } }, + "wed": { "type": "array", "items": { "$ref": "#/$defs/TimeRange" } }, + "thu": { "type": "array", "items": { "$ref": "#/$defs/TimeRange" } }, + "fri": { "type": "array", "items": { "$ref": "#/$defs/TimeRange" } }, + "sat": { "type": "array", "items": { "$ref": "#/$defs/TimeRange" } }, + "sun": { "type": "array", "items": { "$ref": "#/$defs/TimeRange" } } + } + }, + "HoursException": { + "description": "A single-date override of the weekly schedule (holiday / special hours).", + "type": "object", + "required": ["date"], + "properties": { + "date": { "description": "\"YYYY-MM-DD\" in the flow's timezone.", "type": "string" }, + "closed": { "description": "Closed all day regardless of ranges.", "type": "boolean", "default": false }, + "ranges": { "type": "array", "items": { "$ref": "#/$defs/TimeRange" } } + } + }, + "Node": { + "description": "One node: a component (kind + its config) plus its wired exits. An internally-tagged union on `kind`.", + "oneOf": [ + { "$ref": "#/$defs/GreetingNode" }, + { "$ref": "#/$defs/HoursNode" }, + { "$ref": "#/$defs/MenuNode" }, + { "$ref": "#/$defs/RingNode" }, + { "$ref": "#/$defs/MessageNode" }, + { "$ref": "#/$defs/TransferNode" }, + { "$ref": "#/$defs/HangupNode" }, + { "$ref": "#/$defs/BookNode" } + ] + }, + "GreetingNode": { + "description": "Speak a prompt, then continue. Exit: next.", + "type": "object", + "required": ["kind", "prompt"], + "properties": { + "kind": { "const": "greeting" }, + "note": { "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", "type": "string" }, + "prompt": { "$ref": "#/$defs/Prompt" }, + "exits": { "$ref": "#/$defs/Exits" } + } + }, + "HoursNode": { + "description": "Branch on the business's weekly schedule + holiday overrides. Exits: open, closed.", + "type": "object", + "required": ["kind", "schedule", "timezone"], + "properties": { + "kind": { "const": "hours" }, + "note": { "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", "type": "string" }, + "schedule": { "$ref": "#/$defs/WeeklySchedule" }, + "timezone": { "description": "IANA zone (America/New_York). Validated to resolve at load.", "type": "string" }, + "exceptions": { "type": "array", "items": { "$ref": "#/$defs/HoursException" } }, + "exits": { "$ref": "#/$defs/Exits" } + } + }, + "MenuNode": { + "description": "Speak a prompt and collect a DTMF choice. Exits: one per digit in options, plus no_input and invalid.", + "type": "object", + "required": ["kind", "prompt", "options"], + "properties": { + "kind": { "const": "menu" }, + "note": { "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", "type": "string" }, + "prompt": { "$ref": "#/$defs/Prompt" }, + "options": { + "description": "Digit key → human label. The exit for a digit is exits[digit]. Valid digit keys are enforced by the validator.", + "type": "object", + "additionalProperties": { "type": "string" } + }, + "retries": { "type": "integer", "minimum": 0, "default": 1 }, + "timeout_secs": { "type": "integer", "minimum": 0, "default": 5 }, + "exits": { "$ref": "#/$defs/Exits" } + } + }, + "RingNode": { + "description": "Ring the human for a window. answered is an implicit terminal; the only wired exit is no_answer.", + "type": "object", + "required": ["kind", "timeout_secs"], + "properties": { + "kind": { "const": "ring" }, + "note": { "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", "type": "string" }, + "timeout_secs": { "type": "integer", "minimum": 0 }, + "exits": { "$ref": "#/$defs/Exits" } + } + }, + "MessageNode": { + "description": "Voicemail: speak a prompt, record, transcribe, notify. Terminal.", + "type": "object", + "required": ["kind", "prompt"], + "properties": { + "kind": { "const": "message" }, + "note": { "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", "type": "string" }, + "prompt": { "$ref": "#/$defs/Prompt" }, + "max_secs": { "type": "integer", "minimum": 0, "default": 120 }, + "tone": { "allOf": [{ "$ref": "#/$defs/MessageTone" }], "default": "beep" }, + "exits": { "$ref": "#/$defs/Exits" } + } + }, + "TransferNode": { + "description": "Hand the call to an external number. With `whisper`, a screened transfer: call the target first, play the whisper, and connect only when they accept; otherwise take `no_answer`. Without it, a blind transfer (terminal). `whisper` is spoken to the person at the target before they are connected, and `timeout_secs` is how long to let the target ring or decide. Both apply only to a screened transfer.", + "type": "object", + "required": ["kind", "target"], + "properties": { + "kind": { "const": "transfer" }, + "note": { "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", "type": "string" }, + "target": { "type": "string" }, + "whisper": { "$ref": "#/$defs/Prompt" }, + "timeout_secs": { "type": "integer", "minimum": 5, "maximum": 120 }, + "exits": { "$ref": "#/$defs/Exits" } + } + }, + "HangupNode": { + "description": "Speak an optional goodbye and end the call. Terminal.", + "type": "object", + "required": ["kind"], + "properties": { + "kind": { "const": "hangup" }, + "note": { "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", "type": "string" }, + "prompt": { "$ref": "#/$defs/Prompt" }, + "exits": { "$ref": "#/$defs/Exits" } + } + }, + "BookNode": { + "description": "Offer the caller open appointment times and book the one they choose, before the call ends. New in schema_version 2. The bookable grid is described here (weekly schedule + timezone + how long an appointment is); which times are actually free comes from the connected calendar at call time, and the engine never sees a credential. Exits: booked, no_slots, no_input, unavailable. Three fields carry more meaning than their types show, and are described here because a `$ref` with a sibling description makes the type generators emit a duplicate type instead of reusing the named one. `prompt` is spoken once before the open times are offered (\"I can book you in — here are the next available times\"); the times themselves are never part of it, since they are not known until the call. `confirm_prompt` is spoken immediately after a successful booking and directly BEFORE the booked time (\"You're booked for\" → \"Tuesday\" → \"ten thirty a.m.\"); it deliberately takes no placeholder, because a prompt is frozen audio by the time a call runs and nothing can be interpolated into the middle of it — anything that should follow the time belongs on the booked exit. `schedule` is when this business takes appointments, the `hours` node's weekly shape reused verbatim; it is not the same question `hours` answers, because a business can answer the phone at times it will not book.", + "type": "object", + "required": ["kind", "prompt", "confirm_prompt", "schedule", "timezone", "duration_mins"], + "properties": { + "kind": { "const": "book" }, + "note": { "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", "type": "string" }, + "prompt": { "$ref": "#/$defs/Prompt" }, + "confirm_prompt": { "$ref": "#/$defs/Prompt" }, + "schedule": { "$ref": "#/$defs/WeeklySchedule" }, + "timezone": { + "description": "IANA zone (America/New_York) the schedule is written in. Validated to resolve at load.", + "type": "string" + }, + "exceptions": { + "description": "Single-date overrides of the weekly schedule (holidays, one-off clinics), as on `hours`.", + "type": "array", + "items": { "$ref": "#/$defs/HoursException" } + }, + "duration_mins": { + "description": "How long one appointment runs. Bounds are the validator's (see each language's validate module), not this schema's.", + "type": "integer", + "minimum": 0 + }, + "buffer_mins": { + "description": "Clear time kept on BOTH sides of an appointment, so a slot is not offered flush against a busy interval.", + "type": "integer", + "minimum": 0, + "default": 0 + }, + "lead_mins": { + "description": "Nothing sooner than this many minutes from now is offered — the caller cannot book the next five minutes.", + "type": "integer", + "minimum": 0, + "default": 120 + }, + "horizon_days": { + "description": "How far ahead to look for open times.", + "type": "integer", + "minimum": 0, + "default": 14 + }, + "max_offers": { + "description": "How many times to offer the caller. Each offered time gets one keypad digit, counting from 1.", + "type": "integer", + "minimum": 0, + "default": 3 + }, + "retries": { + "description": "Extra attempts to collect a keypress after the first, as on `menu`.", + "type": "integer", + "minimum": 0, + "default": 1 + }, + "timeout_secs": { + "description": "How long to wait for a keypress on each attempt, as on `menu`.", + "type": "integer", + "minimum": 0, + "default": 5 + }, + "exits": { "$ref": "#/$defs/Exits" } + } + } + } +} diff --git a/crates/wavekat-flow/src/canonical.rs b/crates/wavekat-flow/src/canonical.rs index 88e661e..769b369 100644 --- a/crates/wavekat-flow/src/canonical.rs +++ b/crates/wavekat-flow/src/canonical.rs @@ -12,12 +12,12 @@ use std::sync::OnceLock; use serde_json::{Map, Value}; -use crate::{Flow, FLOW_V2_SCHEMA}; +use crate::{Flow, FLOW_V3_SCHEMA}; /// The newest schema, which the model is generated from. pub(crate) fn schema() -> &'static Value { static SCHEMA: OnceLock = OnceLock::new(); - SCHEMA.get_or_init(|| serde_json::from_str(FLOW_V2_SCHEMA).expect("bundled schema is JSON")) + SCHEMA.get_or_init(|| serde_json::from_str(FLOW_V3_SCHEMA).expect("bundled schema is JSON")) } /// Follow `$ref` (and a single-entry `allOf`, the schema's way of putting a diff --git a/crates/wavekat-flow/src/lib.rs b/crates/wavekat-flow/src/lib.rs index feb7984..be38055 100644 --- a/crates/wavekat-flow/src/lib.rs +++ b/crates/wavekat-flow/src/lib.rs @@ -58,15 +58,20 @@ pub use model_ext::{ /// package). pub const FLOW_V1_SCHEMA: &str = include_str!("../schema/flow.v1.schema.json"); -/// Format version 2 — version 1 plus the `book` component. This is also -/// the file the model types are generated from, being the newest. +/// Format version 2 — version 1 plus the `book` component. pub const FLOW_V2_SCHEMA: &str = include_str!("../schema/flow.v2.schema.json"); +/// Format version 3 — version 2 plus the screened transfer (`transfer` +/// gains `whisper` and `timeout_secs`). This is also the file the model +/// types are generated from, being the newest. +pub const FLOW_V3_SCHEMA: &str = include_str!("../schema/flow.v3.schema.json"); + /// The schema for a declared version, or `None` if this build has none. pub fn flow_schema(version: u32) -> Option<&'static str> { match version { 1 => Some(FLOW_V1_SCHEMA), 2 => Some(FLOW_V2_SCHEMA), + 3 => Some(FLOW_V3_SCHEMA), _ => None, } } @@ -77,9 +82,9 @@ pub fn flow_schema(version: u32) -> Option<&'static str> { /// This is what a daemon advertises and the platform refuses to serve /// past: a device that only knows version 1 must never be handed a /// document that uses a component it has no code for. -pub const SUPPORTED_SCHEMA_VERSIONS: &[u32] = &[1, 2]; +pub const SUPPORTED_SCHEMA_VERSIONS: &[u32] = &[1, 2, 3]; /// The newest version this build authors. Reading stays broad /// ([`SUPPORTED_SCHEMA_VERSIONS`]); writing is deliberately one number. /// Twin: `model.ts` `CURRENT_SCHEMA_VERSION`. -pub const CURRENT_SCHEMA_VERSION: u32 = 2; +pub const CURRENT_SCHEMA_VERSION: u32 = 3; diff --git a/crates/wavekat-flow/src/model_ext.rs b/crates/wavekat-flow/src/model_ext.rs index 96129f7..248c7cd 100644 --- a/crates/wavekat-flow/src/model_ext.rs +++ b/crates/wavekat-flow/src/model_ext.rs @@ -91,7 +91,8 @@ impl Node { } /// The prompts this node speaks. Most kinds have one; `book` has two - /// (its intro and its confirmation) and `hangup`'s is optional. Twin: + /// (its intro and its confirmation), and a `hangup`'s prompt and a + /// `transfer`'s whisper are optional. Twin: /// `model.ts` `nodePrompts`. pub fn prompts(&self) -> Vec<&Prompt> { match self { @@ -99,12 +100,13 @@ impl Node { | Node::Menu { prompt, .. } | Node::Message { prompt, .. } => vec![prompt], Node::Hangup { prompt, .. } => prompt.iter().collect(), + Node::Transfer { whisper, .. } => whisper.iter().collect(), Node::Book { prompt, confirm_prompt, .. } => vec![prompt, confirm_prompt], - Node::Hours { .. } | Node::Ring { .. } | Node::Transfer { .. } => Vec::new(), + Node::Hours { .. } | Node::Ring { .. } => Vec::new(), } } @@ -127,21 +129,23 @@ impl Node { | Node::Menu { prompt, .. } | Node::Message { prompt, .. } => vec![prompt], Node::Hangup { prompt, .. } => prompt.iter_mut().collect(), + Node::Transfer { whisper, .. } => whisper.iter_mut().collect(), Node::Book { prompt, confirm_prompt, .. } => vec![prompt, confirm_prompt], - Node::Hours { .. } | Node::Ring { .. } | Node::Transfer { .. } => Vec::new(), + Node::Hours { .. } | Node::Ring { .. } => Vec::new(), }; names.into_iter().zip(prompts).collect() } /// The field names of the prompts this node has: all of `fields`, - /// except a `hangup` with no goodbye has none. + /// except a `hangup` with no goodbye, or a `transfer` with no whisper, + /// has none. fn slot_names(&self, fields: &'static [&'static str]) -> Vec<&'static str> { match self { - Node::Hangup { prompt: None, .. } => Vec::new(), + Node::Hangup { prompt: None, .. } | Node::Transfer { whisper: None, .. } => Vec::new(), _ => fields.to_vec(), } } @@ -170,7 +174,7 @@ pub fn required_assets(flow: &Flow) -> Vec { } /// Every node field that can hold a prompt, across all kinds. -pub const PROMPT_FIELDS: &[&str] = &["prompt", "confirm_prompt"]; +pub const PROMPT_FIELDS: &[&str] = &["prompt", "confirm_prompt", "whisper"]; /// The fields a node of `kind` speaks a prompt from, in the order /// [`Node::prompts`] returns them, or `None` for a kind this build doesn't @@ -180,8 +184,9 @@ pub const PROMPT_FIELDS: &[&str] = &["prompt", "confirm_prompt"]; pub fn prompt_fields(kind: &str) -> Option<&'static [&'static str]> { match kind { "greeting" | "menu" | "message" | "hangup" => Some(&PROMPT_FIELDS[..1]), - "book" => Some(PROMPT_FIELDS), - "hours" | "ring" | "transfer" => Some(&[]), + "book" => Some(&PROMPT_FIELDS[..2]), + "transfer" => Some(&PROMPT_FIELDS[2..]), + "hours" | "ring" => Some(&[]), _ => None, } } @@ -283,6 +288,33 @@ impl Flow { mod tests { use crate::model::Prompt; + #[test] + fn transfer_whisper_is_a_prompt_and_an_asset() { + let flow = crate::Flow::from_yaml( + r#" +schema_version: 3 +id: f +name: n +entry: t +nodes: + t: + kind: transfer + target: "+15551230100" + whisper: { audio: vprompt_whisper01 } + timeout_secs: 20 + u: + kind: transfer + target: "+15551230101" +"#, + ) + .unwrap(); + let t = &flow.nodes["t"]; + assert_eq!(t.prompt_slots().len(), 1); + assert_eq!(t.prompt_slots()[0].0, "whisper"); + assert!(flow.nodes["u"].prompt_slots().is_empty()); + assert_eq!(super::required_assets(&flow), vec!["vprompt_whisper01"]); + } + #[test] fn generated_clip_refs() { use super::is_generated_clip_ref as clip; diff --git a/crates/wavekat-flow/tests/conformance.rs b/crates/wavekat-flow/tests/conformance.rs index f87bacf..7345f36 100644 --- a/crates/wavekat-flow/tests/conformance.rs +++ b/crates/wavekat-flow/tests/conformance.rs @@ -64,6 +64,11 @@ fn yaml_cases(version: &str, bucket: &str) -> Vec<(String, PathBuf)> { fn yaml_cases_in(dir: &std::path::Path) -> Vec<(String, PathBuf)> { let mut out = Vec::new(); + // A version may have no cases in a bucket yet (v3 starts with `valid` + // only); a missing directory is an empty bucket, not an error. + if !dir.is_dir() { + return out; + } for entry in fs::read_dir(dir).expect("read corpus dir") { let path = entry.unwrap().path(); if path.extension().and_then(|e| e.to_str()) == Some("yaml") { diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index c27549a..d49d6fd 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -187,4 +187,5 @@ Trigger: the format is stable enough and the repo is ready to be public. validation dispatches on the document's declared version, and a per-kind minimum version in both validators is what tells an author "bump the version" instead of "fix the typo". `assistant` becomes - version 3. + version 4: version 3 went to the screened transfer (`transfer` gains + `whisper` and `timeout_secs`). diff --git a/packages/flow-schema/scripts/generate.mjs b/packages/flow-schema/scripts/generate.mjs index bc713b8..6134f17 100644 --- a/packages/flow-schema/scripts/generate.mjs +++ b/packages/flow-schema/scripts/generate.mjs @@ -8,7 +8,7 @@ // One model, many schemas. Each schema file describes exactly one // `schema_version` and is what a document of that version is validated // against (see src/structure.ts). The *types*, though, have to hold any -// supported version — a consumer reads v1 and v2 documents through one +// supported version — a consumer reads v1, v2 and v3 documents through one // `Flow` — so codegen runs on the NEWEST schema only, which is a // superset of its predecessors, with one mechanical relaxation applied // (below). The Rust twin does the same in crates/wavekat-flow/build.rs. @@ -24,7 +24,7 @@ const repoRoot = resolve(pkg, '..', '..'); const genDir = resolve(pkg, 'src', 'generated'); // Oldest first; the last entry is the one the model is generated from. -const VERSIONS = [1, 2]; +const VERSIONS = [1, 2, 3]; const schemaPathFor = (v) => resolve(repoRoot, 'schema', `flow.v${v}.schema.json`); await mkdir(genDir, { recursive: true }); diff --git a/packages/flow-schema/src/generated/flow.v3.schema.json b/packages/flow-schema/src/generated/flow.v3.schema.json new file mode 100644 index 0000000..5005f37 --- /dev/null +++ b/packages/flow-schema/src/generated/flow.v3.schema.json @@ -0,0 +1,276 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://schema.wavekat.com/flow/v3.json", + "title": "Flow", + "description": "The WaveKat call-flow (\"Receptionist\") document, schema_version 3. Version 3 is version 2 plus the screened transfer: the `transfer` node gains `whisper` and `timeout_secs`. Every version-2 document is a valid version-3 document once its `schema_version` is bumped, and nothing else changed. This file is the single source of truth for the document SHAPE, and — being the newest version — it is also the file both consumers generate their model types from, so one model covers every supported version. Semantic rules that a JSON Schema cannot express (graph reachability, exit-set exactness, hours/timezone math, DTMF digit validity, prompt length, per-component numeric bounds, and which components a given schema_version may use) are NOT encoded here — they live in each language's validator and are pinned by the shared conformance corpus. Unknown fields are permitted structurally, matching both implementations (Rust serde ignores them; the TS parser surfaces a non-blocking warning).", + "type": "object", + "required": ["schema_version", "id", "name", "entry", "nodes"], + "properties": { + "schema_version": { + "description": "Document format version. This file describes version 3 only; a document declaring another version validates against that version's schema file, not this one. (The type generators relax this constant to a plain integer so the generated model can hold any supported version — see scripts/generate.mjs and build.rs.)", + "type": "integer", + "const": 3 + }, + "id": { + "description": "Opaque platform-assigned id (flow_…). Treated as a label; appears in traces.", + "type": "string" + }, + "name": { + "description": "Human name shown in the editor and the read-only viewer.", + "type": "string" + }, + "version": { + "description": "Platform-assigned publish counter, bumped on publish. Defaults to 1 for a hand-written or generated pre-publish document. Distinct from schema_version.", + "type": "integer", + "minimum": 0, + "default": 1 + }, + "note": { + "description": "The author's note about the whole flow: free text for people reading it, in place of a YAML comment. Never read by the engine.", + "type": "string" + }, + "entry": { + "description": "Node id where execution begins.", + "type": "string" + }, + "nodes": { + "description": "The flat node set, keyed by human-meaningful node id and string-referenced by exits. Order is irrelevant to execution, but it is the author's reading order and is kept on save.", + "type": "object", + "additionalProperties": { "$ref": "#/$defs/Node" } + }, + "ui": { + "description": "Presentation metadata (canvas positions, annotations). Preserved on round-trip, never read by the engine. Opaque by design so a canvas editor can add layout fields without a schema bump." + } + }, + "$defs": { + "Prompt": { + "description": "What a component speaks: TTS text (a bare string) or a reference to a pre-rendered audio asset shipped alongside the flow.", + "oneOf": [ + { "title": "Text", "type": "string" }, + { + "title": "Audio", + "type": "object", + "required": ["audio"], + "properties": { + "audio": { + "description": "Audio asset ref. A generated-clip ref is a voice_prompts id matching ^vprompt_[a-z0-9]+$.", + "type": "string" + }, + "transcript": { + "description": "The words this pre-rendered clip speaks — the text it was synthesized from — carried so a viewer can show what a caller hears, and for traces. Advisory only: playback always uses `audio`, never this. Optional and forward-added: absent on older documents and on refs the platform did not generate from text.", + "type": "string" + } + } + } + ] + }, + "MessageTone": { + "description": "The cue a message node plays between its prompt and the start of recording.", + "type": "string", + "enum": ["beep", "none"] + }, + "Exits": { + "description": "Wired exits: exit name → target node id. Which names are valid is a property of the node's kind and is checked by the validator, not by this schema.", + "type": "object", + "additionalProperties": { "type": "string" } + }, + "TimeRange": { + "description": "One open window: open–close as \"HH:MM\" (24-hour). Ordering and overnight rules are enforced by the validator.", + "type": "object", + "required": ["open", "close"], + "properties": { + "open": { "type": "string" }, + "close": { "type": "string" } + } + }, + "WeeklySchedule": { + "description": "Open ranges per weekday; a missing or empty day means closed all day.", + "type": "object", + "properties": { + "mon": { "type": "array", "items": { "$ref": "#/$defs/TimeRange" } }, + "tue": { "type": "array", "items": { "$ref": "#/$defs/TimeRange" } }, + "wed": { "type": "array", "items": { "$ref": "#/$defs/TimeRange" } }, + "thu": { "type": "array", "items": { "$ref": "#/$defs/TimeRange" } }, + "fri": { "type": "array", "items": { "$ref": "#/$defs/TimeRange" } }, + "sat": { "type": "array", "items": { "$ref": "#/$defs/TimeRange" } }, + "sun": { "type": "array", "items": { "$ref": "#/$defs/TimeRange" } } + } + }, + "HoursException": { + "description": "A single-date override of the weekly schedule (holiday / special hours).", + "type": "object", + "required": ["date"], + "properties": { + "date": { "description": "\"YYYY-MM-DD\" in the flow's timezone.", "type": "string" }, + "closed": { "description": "Closed all day regardless of ranges.", "type": "boolean", "default": false }, + "ranges": { "type": "array", "items": { "$ref": "#/$defs/TimeRange" } } + } + }, + "Node": { + "description": "One node: a component (kind + its config) plus its wired exits. An internally-tagged union on `kind`.", + "oneOf": [ + { "$ref": "#/$defs/GreetingNode" }, + { "$ref": "#/$defs/HoursNode" }, + { "$ref": "#/$defs/MenuNode" }, + { "$ref": "#/$defs/RingNode" }, + { "$ref": "#/$defs/MessageNode" }, + { "$ref": "#/$defs/TransferNode" }, + { "$ref": "#/$defs/HangupNode" }, + { "$ref": "#/$defs/BookNode" } + ] + }, + "GreetingNode": { + "description": "Speak a prompt, then continue. Exit: next.", + "type": "object", + "required": ["kind", "prompt"], + "properties": { + "kind": { "const": "greeting" }, + "note": { "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", "type": "string" }, + "prompt": { "$ref": "#/$defs/Prompt" }, + "exits": { "$ref": "#/$defs/Exits" } + } + }, + "HoursNode": { + "description": "Branch on the business's weekly schedule + holiday overrides. Exits: open, closed.", + "type": "object", + "required": ["kind", "schedule", "timezone"], + "properties": { + "kind": { "const": "hours" }, + "note": { "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", "type": "string" }, + "schedule": { "$ref": "#/$defs/WeeklySchedule" }, + "timezone": { "description": "IANA zone (America/New_York). Validated to resolve at load.", "type": "string" }, + "exceptions": { "type": "array", "items": { "$ref": "#/$defs/HoursException" } }, + "exits": { "$ref": "#/$defs/Exits" } + } + }, + "MenuNode": { + "description": "Speak a prompt and collect a DTMF choice. Exits: one per digit in options, plus no_input and invalid.", + "type": "object", + "required": ["kind", "prompt", "options"], + "properties": { + "kind": { "const": "menu" }, + "note": { "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", "type": "string" }, + "prompt": { "$ref": "#/$defs/Prompt" }, + "options": { + "description": "Digit key → human label. The exit for a digit is exits[digit]. Valid digit keys are enforced by the validator.", + "type": "object", + "additionalProperties": { "type": "string" } + }, + "retries": { "type": "integer", "minimum": 0, "default": 1 }, + "timeout_secs": { "type": "integer", "minimum": 0, "default": 5 }, + "exits": { "$ref": "#/$defs/Exits" } + } + }, + "RingNode": { + "description": "Ring the human for a window. answered is an implicit terminal; the only wired exit is no_answer.", + "type": "object", + "required": ["kind", "timeout_secs"], + "properties": { + "kind": { "const": "ring" }, + "note": { "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", "type": "string" }, + "timeout_secs": { "type": "integer", "minimum": 0 }, + "exits": { "$ref": "#/$defs/Exits" } + } + }, + "MessageNode": { + "description": "Voicemail: speak a prompt, record, transcribe, notify. Terminal.", + "type": "object", + "required": ["kind", "prompt"], + "properties": { + "kind": { "const": "message" }, + "note": { "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", "type": "string" }, + "prompt": { "$ref": "#/$defs/Prompt" }, + "max_secs": { "type": "integer", "minimum": 0, "default": 120 }, + "tone": { "allOf": [{ "$ref": "#/$defs/MessageTone" }], "default": "beep" }, + "exits": { "$ref": "#/$defs/Exits" } + } + }, + "TransferNode": { + "description": "Hand the call to an external number. With `whisper`, a screened transfer: call the target first, play the whisper, and connect only when they accept; otherwise take `no_answer`. Without it, a blind transfer (terminal). `whisper` is spoken to the person at the target before they are connected, and `timeout_secs` is how long to let the target ring or decide. Both apply only to a screened transfer.", + "type": "object", + "required": ["kind", "target"], + "properties": { + "kind": { "const": "transfer" }, + "note": { "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", "type": "string" }, + "target": { "type": "string" }, + "whisper": { "$ref": "#/$defs/Prompt" }, + "timeout_secs": { "type": "integer", "minimum": 5, "maximum": 120 }, + "exits": { "$ref": "#/$defs/Exits" } + } + }, + "HangupNode": { + "description": "Speak an optional goodbye and end the call. Terminal.", + "type": "object", + "required": ["kind"], + "properties": { + "kind": { "const": "hangup" }, + "note": { "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", "type": "string" }, + "prompt": { "$ref": "#/$defs/Prompt" }, + "exits": { "$ref": "#/$defs/Exits" } + } + }, + "BookNode": { + "description": "Offer the caller open appointment times and book the one they choose, before the call ends. New in schema_version 2. The bookable grid is described here (weekly schedule + timezone + how long an appointment is); which times are actually free comes from the connected calendar at call time, and the engine never sees a credential. Exits: booked, no_slots, no_input, unavailable. Three fields carry more meaning than their types show, and are described here because a `$ref` with a sibling description makes the type generators emit a duplicate type instead of reusing the named one. `prompt` is spoken once before the open times are offered (\"I can book you in — here are the next available times\"); the times themselves are never part of it, since they are not known until the call. `confirm_prompt` is spoken immediately after a successful booking and directly BEFORE the booked time (\"You're booked for\" → \"Tuesday\" → \"ten thirty a.m.\"); it deliberately takes no placeholder, because a prompt is frozen audio by the time a call runs and nothing can be interpolated into the middle of it — anything that should follow the time belongs on the booked exit. `schedule` is when this business takes appointments, the `hours` node's weekly shape reused verbatim; it is not the same question `hours` answers, because a business can answer the phone at times it will not book.", + "type": "object", + "required": ["kind", "prompt", "confirm_prompt", "schedule", "timezone", "duration_mins"], + "properties": { + "kind": { "const": "book" }, + "note": { "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", "type": "string" }, + "prompt": { "$ref": "#/$defs/Prompt" }, + "confirm_prompt": { "$ref": "#/$defs/Prompt" }, + "schedule": { "$ref": "#/$defs/WeeklySchedule" }, + "timezone": { + "description": "IANA zone (America/New_York) the schedule is written in. Validated to resolve at load.", + "type": "string" + }, + "exceptions": { + "description": "Single-date overrides of the weekly schedule (holidays, one-off clinics), as on `hours`.", + "type": "array", + "items": { "$ref": "#/$defs/HoursException" } + }, + "duration_mins": { + "description": "How long one appointment runs. Bounds are the validator's (see each language's validate module), not this schema's.", + "type": "integer", + "minimum": 0 + }, + "buffer_mins": { + "description": "Clear time kept on BOTH sides of an appointment, so a slot is not offered flush against a busy interval.", + "type": "integer", + "minimum": 0, + "default": 0 + }, + "lead_mins": { + "description": "Nothing sooner than this many minutes from now is offered — the caller cannot book the next five minutes.", + "type": "integer", + "minimum": 0, + "default": 120 + }, + "horizon_days": { + "description": "How far ahead to look for open times.", + "type": "integer", + "minimum": 0, + "default": 14 + }, + "max_offers": { + "description": "How many times to offer the caller. Each offered time gets one keypad digit, counting from 1.", + "type": "integer", + "minimum": 0, + "default": 3 + }, + "retries": { + "description": "Extra attempts to collect a keypress after the first, as on `menu`.", + "type": "integer", + "minimum": 0, + "default": 1 + }, + "timeout_secs": { + "description": "How long to wait for a keypress on each attempt, as on `menu`.", + "type": "integer", + "minimum": 0, + "default": 5 + }, + "exits": { "$ref": "#/$defs/Exits" } + } + } + } +} diff --git a/packages/flow-schema/src/generated/model.ts b/packages/flow-schema/src/generated/model.ts index 08d9756..06966e4 100644 --- a/packages/flow-schema/src/generated/model.ts +++ b/packages/flow-schema/src/generated/model.ts @@ -1,4 +1,4 @@ -// GENERATED from schema/flow.v{1,2}.schema.json by scripts/generate.mjs — do not edit. +// GENERATED from schema/flow.v{1,2,3}.schema.json by scripts/generate.mjs — do not edit. // Run `pnpm gen` after changing a schema; CI fails on drift. /** @@ -16,11 +16,11 @@ export type Text = string; export type MessageTone = 'beep' | 'none'; /** - * The WaveKat call-flow ("Receptionist") document, schema_version 2. Version 2 is version 1 plus the `book` component (appointment booking over the phone); every version-1 document is a valid version-2 document once its `schema_version` is bumped, and nothing else changed. This file is the single source of truth for the document SHAPE, and — being the newest version — it is also the file both consumers generate their model types from, so one model covers every supported version. Semantic rules that a JSON Schema cannot express (graph reachability, exit-set exactness, hours/timezone math, DTMF digit validity, prompt length, per-component numeric bounds, and which components a given schema_version may use) are NOT encoded here — they live in each language's validator and are pinned by the shared conformance corpus. Unknown fields are permitted structurally, matching both implementations (Rust serde ignores them; the TS parser surfaces a non-blocking warning). + * The WaveKat call-flow ("Receptionist") document, schema_version 3. Version 3 is version 2 plus the screened transfer: the `transfer` node gains `whisper` and `timeout_secs`. Every version-2 document is a valid version-3 document once its `schema_version` is bumped, and nothing else changed. This file is the single source of truth for the document SHAPE, and — being the newest version — it is also the file both consumers generate their model types from, so one model covers every supported version. Semantic rules that a JSON Schema cannot express (graph reachability, exit-set exactness, hours/timezone math, DTMF digit validity, prompt length, per-component numeric bounds, and which components a given schema_version may use) are NOT encoded here — they live in each language's validator and are pinned by the shared conformance corpus. Unknown fields are permitted structurally, matching both implementations (Rust serde ignores them; the TS parser surfaces a non-blocking warning). */ export interface Flow { /** - * Document format version. This file describes version 2 only; a document declaring another version validates against that version's schema file, not this one. (The type generators relax this constant to a plain integer so the generated model can hold any supported version — see scripts/generate.mjs and build.rs.) (Relaxed from a constant to a plain integer for type generation: one model type covers every supported version.) + * Document format version. This file describes version 3 only; a document declaring another version validates against that version's schema file, not this one. (The type generators relax this constant to a plain integer so the generated model can hold any supported version — see scripts/generate.mjs and build.rs.) (Relaxed from a constant to a plain integer for type generation: one model type covers every supported version.) */ schema_version: number; /** @@ -191,7 +191,7 @@ export interface MessageNode { [k: string]: unknown; } /** - * Blind-transfer to an external number. Terminal. + * Hand the call to an external number. With `whisper`, a screened transfer: call the target first, play the whisper, and connect only when they accept; otherwise take `no_answer`. Without it, a blind transfer (terminal). `whisper` is spoken to the person at the target before they are connected, and `timeout_secs` is how long to let the target ring or decide. Both apply only to a screened transfer. */ export interface TransferNode { kind: 'transfer'; @@ -200,6 +200,8 @@ export interface TransferNode { */ note?: string; target: string; + whisper?: Prompt; + timeout_secs?: number; exits?: Exits; [k: string]: unknown; } diff --git a/packages/flow-schema/src/generated/schema.ts b/packages/flow-schema/src/generated/schema.ts index b64be65..9d804ae 100644 --- a/packages/flow-schema/src/generated/schema.ts +++ b/packages/flow-schema/src/generated/schema.ts @@ -1,4 +1,4 @@ -// GENERATED from schema/flow.v{1,2}.schema.json by scripts/generate.mjs — do not edit. +// GENERATED from schema/flow.v{1,2,3}.schema.json by scripts/generate.mjs — do not edit. // Run `pnpm gen` after changing a schema; CI fails on drift. export const flowV1Schema = { @@ -917,5 +917,515 @@ export const flowV2Schema = { } } as const; +export const flowV3Schema = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://schema.wavekat.com/flow/v3.json", + "title": "Flow", + "description": "The WaveKat call-flow (\"Receptionist\") document, schema_version 3. Version 3 is version 2 plus the screened transfer: the `transfer` node gains `whisper` and `timeout_secs`. Every version-2 document is a valid version-3 document once its `schema_version` is bumped, and nothing else changed. This file is the single source of truth for the document SHAPE, and — being the newest version — it is also the file both consumers generate their model types from, so one model covers every supported version. Semantic rules that a JSON Schema cannot express (graph reachability, exit-set exactness, hours/timezone math, DTMF digit validity, prompt length, per-component numeric bounds, and which components a given schema_version may use) are NOT encoded here — they live in each language's validator and are pinned by the shared conformance corpus. Unknown fields are permitted structurally, matching both implementations (Rust serde ignores them; the TS parser surfaces a non-blocking warning).", + "type": "object", + "required": [ + "schema_version", + "id", + "name", + "entry", + "nodes" + ], + "properties": { + "schema_version": { + "description": "Document format version. This file describes version 3 only; a document declaring another version validates against that version's schema file, not this one. (The type generators relax this constant to a plain integer so the generated model can hold any supported version — see scripts/generate.mjs and build.rs.)", + "type": "integer", + "const": 3 + }, + "id": { + "description": "Opaque platform-assigned id (flow_…). Treated as a label; appears in traces.", + "type": "string" + }, + "name": { + "description": "Human name shown in the editor and the read-only viewer.", + "type": "string" + }, + "version": { + "description": "Platform-assigned publish counter, bumped on publish. Defaults to 1 for a hand-written or generated pre-publish document. Distinct from schema_version.", + "type": "integer", + "minimum": 0, + "default": 1 + }, + "note": { + "description": "The author's note about the whole flow: free text for people reading it, in place of a YAML comment. Never read by the engine.", + "type": "string" + }, + "entry": { + "description": "Node id where execution begins.", + "type": "string" + }, + "nodes": { + "description": "The flat node set, keyed by human-meaningful node id and string-referenced by exits. Order is irrelevant to execution, but it is the author's reading order and is kept on save.", + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/Node" + } + }, + "ui": { + "description": "Presentation metadata (canvas positions, annotations). Preserved on round-trip, never read by the engine. Opaque by design so a canvas editor can add layout fields without a schema bump." + } + }, + "$defs": { + "Prompt": { + "description": "What a component speaks: TTS text (a bare string) or a reference to a pre-rendered audio asset shipped alongside the flow.", + "oneOf": [ + { + "title": "Text", + "type": "string" + }, + { + "title": "Audio", + "type": "object", + "required": [ + "audio" + ], + "properties": { + "audio": { + "description": "Audio asset ref. A generated-clip ref is a voice_prompts id matching ^vprompt_[a-z0-9]+$.", + "type": "string" + }, + "transcript": { + "description": "The words this pre-rendered clip speaks — the text it was synthesized from — carried so a viewer can show what a caller hears, and for traces. Advisory only: playback always uses `audio`, never this. Optional and forward-added: absent on older documents and on refs the platform did not generate from text.", + "type": "string" + } + } + } + ] + }, + "MessageTone": { + "description": "The cue a message node plays between its prompt and the start of recording.", + "type": "string", + "enum": [ + "beep", + "none" + ] + }, + "Exits": { + "description": "Wired exits: exit name → target node id. Which names are valid is a property of the node's kind and is checked by the validator, not by this schema.", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "TimeRange": { + "description": "One open window: open–close as \"HH:MM\" (24-hour). Ordering and overnight rules are enforced by the validator.", + "type": "object", + "required": [ + "open", + "close" + ], + "properties": { + "open": { + "type": "string" + }, + "close": { + "type": "string" + } + } + }, + "WeeklySchedule": { + "description": "Open ranges per weekday; a missing or empty day means closed all day.", + "type": "object", + "properties": { + "mon": { + "type": "array", + "items": { + "$ref": "#/$defs/TimeRange" + } + }, + "tue": { + "type": "array", + "items": { + "$ref": "#/$defs/TimeRange" + } + }, + "wed": { + "type": "array", + "items": { + "$ref": "#/$defs/TimeRange" + } + }, + "thu": { + "type": "array", + "items": { + "$ref": "#/$defs/TimeRange" + } + }, + "fri": { + "type": "array", + "items": { + "$ref": "#/$defs/TimeRange" + } + }, + "sat": { + "type": "array", + "items": { + "$ref": "#/$defs/TimeRange" + } + }, + "sun": { + "type": "array", + "items": { + "$ref": "#/$defs/TimeRange" + } + } + } + }, + "HoursException": { + "description": "A single-date override of the weekly schedule (holiday / special hours).", + "type": "object", + "required": [ + "date" + ], + "properties": { + "date": { + "description": "\"YYYY-MM-DD\" in the flow's timezone.", + "type": "string" + }, + "closed": { + "description": "Closed all day regardless of ranges.", + "type": "boolean", + "default": false + }, + "ranges": { + "type": "array", + "items": { + "$ref": "#/$defs/TimeRange" + } + } + } + }, + "Node": { + "description": "One node: a component (kind + its config) plus its wired exits. An internally-tagged union on `kind`.", + "oneOf": [ + { + "$ref": "#/$defs/GreetingNode" + }, + { + "$ref": "#/$defs/HoursNode" + }, + { + "$ref": "#/$defs/MenuNode" + }, + { + "$ref": "#/$defs/RingNode" + }, + { + "$ref": "#/$defs/MessageNode" + }, + { + "$ref": "#/$defs/TransferNode" + }, + { + "$ref": "#/$defs/HangupNode" + }, + { + "$ref": "#/$defs/BookNode" + } + ] + }, + "GreetingNode": { + "description": "Speak a prompt, then continue. Exit: next.", + "type": "object", + "required": [ + "kind", + "prompt" + ], + "properties": { + "kind": { + "const": "greeting" + }, + "note": { + "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", + "type": "string" + }, + "prompt": { + "$ref": "#/$defs/Prompt" + }, + "exits": { + "$ref": "#/$defs/Exits" + } + } + }, + "HoursNode": { + "description": "Branch on the business's weekly schedule + holiday overrides. Exits: open, closed.", + "type": "object", + "required": [ + "kind", + "schedule", + "timezone" + ], + "properties": { + "kind": { + "const": "hours" + }, + "note": { + "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", + "type": "string" + }, + "schedule": { + "$ref": "#/$defs/WeeklySchedule" + }, + "timezone": { + "description": "IANA zone (America/New_York). Validated to resolve at load.", + "type": "string" + }, + "exceptions": { + "type": "array", + "items": { + "$ref": "#/$defs/HoursException" + } + }, + "exits": { + "$ref": "#/$defs/Exits" + } + } + }, + "MenuNode": { + "description": "Speak a prompt and collect a DTMF choice. Exits: one per digit in options, plus no_input and invalid.", + "type": "object", + "required": [ + "kind", + "prompt", + "options" + ], + "properties": { + "kind": { + "const": "menu" + }, + "note": { + "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", + "type": "string" + }, + "prompt": { + "$ref": "#/$defs/Prompt" + }, + "options": { + "description": "Digit key → human label. The exit for a digit is exits[digit]. Valid digit keys are enforced by the validator.", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "retries": { + "type": "integer", + "minimum": 0, + "default": 1 + }, + "timeout_secs": { + "type": "integer", + "minimum": 0, + "default": 5 + }, + "exits": { + "$ref": "#/$defs/Exits" + } + } + }, + "RingNode": { + "description": "Ring the human for a window. answered is an implicit terminal; the only wired exit is no_answer.", + "type": "object", + "required": [ + "kind", + "timeout_secs" + ], + "properties": { + "kind": { + "const": "ring" + }, + "note": { + "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", + "type": "string" + }, + "timeout_secs": { + "type": "integer", + "minimum": 0 + }, + "exits": { + "$ref": "#/$defs/Exits" + } + } + }, + "MessageNode": { + "description": "Voicemail: speak a prompt, record, transcribe, notify. Terminal.", + "type": "object", + "required": [ + "kind", + "prompt" + ], + "properties": { + "kind": { + "const": "message" + }, + "note": { + "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", + "type": "string" + }, + "prompt": { + "$ref": "#/$defs/Prompt" + }, + "max_secs": { + "type": "integer", + "minimum": 0, + "default": 120 + }, + "tone": { + "allOf": [ + { + "$ref": "#/$defs/MessageTone" + } + ], + "default": "beep" + }, + "exits": { + "$ref": "#/$defs/Exits" + } + } + }, + "TransferNode": { + "description": "Hand the call to an external number. With `whisper`, a screened transfer: call the target first, play the whisper, and connect only when they accept; otherwise take `no_answer`. Without it, a blind transfer (terminal). `whisper` is spoken to the person at the target before they are connected, and `timeout_secs` is how long to let the target ring or decide. Both apply only to a screened transfer.", + "type": "object", + "required": [ + "kind", + "target" + ], + "properties": { + "kind": { + "const": "transfer" + }, + "note": { + "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", + "type": "string" + }, + "target": { + "type": "string" + }, + "whisper": { + "$ref": "#/$defs/Prompt" + }, + "timeout_secs": { + "type": "integer", + "minimum": 5, + "maximum": 120 + }, + "exits": { + "$ref": "#/$defs/Exits" + } + } + }, + "HangupNode": { + "description": "Speak an optional goodbye and end the call. Terminal.", + "type": "object", + "required": [ + "kind" + ], + "properties": { + "kind": { + "const": "hangup" + }, + "note": { + "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", + "type": "string" + }, + "prompt": { + "$ref": "#/$defs/Prompt" + }, + "exits": { + "$ref": "#/$defs/Exits" + } + } + }, + "BookNode": { + "description": "Offer the caller open appointment times and book the one they choose, before the call ends. New in schema_version 2. The bookable grid is described here (weekly schedule + timezone + how long an appointment is); which times are actually free comes from the connected calendar at call time, and the engine never sees a credential. Exits: booked, no_slots, no_input, unavailable. Three fields carry more meaning than their types show, and are described here because a `$ref` with a sibling description makes the type generators emit a duplicate type instead of reusing the named one. `prompt` is spoken once before the open times are offered (\"I can book you in — here are the next available times\"); the times themselves are never part of it, since they are not known until the call. `confirm_prompt` is spoken immediately after a successful booking and directly BEFORE the booked time (\"You're booked for\" → \"Tuesday\" → \"ten thirty a.m.\"); it deliberately takes no placeholder, because a prompt is frozen audio by the time a call runs and nothing can be interpolated into the middle of it — anything that should follow the time belongs on the booked exit. `schedule` is when this business takes appointments, the `hours` node's weekly shape reused verbatim; it is not the same question `hours` answers, because a business can answer the phone at times it will not book.", + "type": "object", + "required": [ + "kind", + "prompt", + "confirm_prompt", + "schedule", + "timezone", + "duration_mins" + ], + "properties": { + "kind": { + "const": "book" + }, + "note": { + "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", + "type": "string" + }, + "prompt": { + "$ref": "#/$defs/Prompt" + }, + "confirm_prompt": { + "$ref": "#/$defs/Prompt" + }, + "schedule": { + "$ref": "#/$defs/WeeklySchedule" + }, + "timezone": { + "description": "IANA zone (America/New_York) the schedule is written in. Validated to resolve at load.", + "type": "string" + }, + "exceptions": { + "description": "Single-date overrides of the weekly schedule (holidays, one-off clinics), as on `hours`.", + "type": "array", + "items": { + "$ref": "#/$defs/HoursException" + } + }, + "duration_mins": { + "description": "How long one appointment runs. Bounds are the validator's (see each language's validate module), not this schema's.", + "type": "integer", + "minimum": 0 + }, + "buffer_mins": { + "description": "Clear time kept on BOTH sides of an appointment, so a slot is not offered flush against a busy interval.", + "type": "integer", + "minimum": 0, + "default": 0 + }, + "lead_mins": { + "description": "Nothing sooner than this many minutes from now is offered — the caller cannot book the next five minutes.", + "type": "integer", + "minimum": 0, + "default": 120 + }, + "horizon_days": { + "description": "How far ahead to look for open times.", + "type": "integer", + "minimum": 0, + "default": 14 + }, + "max_offers": { + "description": "How many times to offer the caller. Each offered time gets one keypad digit, counting from 1.", + "type": "integer", + "minimum": 0, + "default": 3 + }, + "retries": { + "description": "Extra attempts to collect a keypress after the first, as on `menu`.", + "type": "integer", + "minimum": 0, + "default": 1 + }, + "timeout_secs": { + "description": "How long to wait for a keypress on each attempt, as on `menu`.", + "type": "integer", + "minimum": 0, + "default": 5 + }, + "exits": { + "$ref": "#/$defs/Exits" + } + } + } + } +} as const; + /** Newest supported version's schema. */ -export default flowV2Schema; +export default flowV3Schema; diff --git a/packages/flow-schema/src/index.ts b/packages/flow-schema/src/index.ts index 9d1e3ff..619e033 100644 --- a/packages/flow-schema/src/index.ts +++ b/packages/flow-schema/src/index.ts @@ -21,14 +21,14 @@ // which crashes code-gen-disallowed runtimes (Cloudflare Workers) at // import time. It lives behind the `@wavekat/flow-schema/structure` // subpath so this barrel stays Ajv-free and safe to bundle on the edge. -import { flowV1Schema, flowV2Schema } from './generated/schema.js'; +import { flowV1Schema, flowV2Schema, flowV3Schema } from './generated/schema.js'; // Model: generated types + hand-written constants & helpers. export * from './model.js'; // The `book` component: its bounds, and the vocabulary a frozen-audio // device speaks a time with. export * from './book.js'; -export { flowV1Schema, flowV2Schema }; +export { flowV1Schema, flowV2Schema, flowV3Schema }; // Structural diff between two flows (authoring-only, TS-only — like mutate.ts). export type { FieldChange, FlowDiff, FlowDiffStatus, NodeDiff } from './diff.js'; diff --git a/packages/flow-schema/src/model.ts b/packages/flow-schema/src/model.ts index 18efaca..c5826d6 100644 --- a/packages/flow-schema/src/model.ts +++ b/packages/flow-schema/src/model.ts @@ -52,13 +52,13 @@ export type Component = Node; /** Schema versions this validator understands. Twin: `lib.rs` * `SUPPORTED_SCHEMA_VERSIONS`. */ -export const SUPPORTED_SCHEMA_VERSIONS: readonly number[] = [1, 2]; +export const SUPPORTED_SCHEMA_VERSIONS: readonly number[] = [1, 2, 3]; /** The newest version this build authors — what a new document should * declare. Reading stays broad ({@link SUPPORTED_SCHEMA_VERSIONS}); * writing is deliberately one number. Twin: `lib.rs` * `CURRENT_SCHEMA_VERSION`. */ -export const CURRENT_SCHEMA_VERSION = 2; +export const CURRENT_SCHEMA_VERSION = 3; /** Longest a spoken (text) prompt may be — see `validate.ts`. Twin: * `validate.rs` `MAX_PROMPT_CHARS`. */ @@ -245,7 +245,8 @@ export function isGeneratedClipRef(ref: string): boolean { } /** The prompts a node speaks. Most kinds have one; `book` has two (its - * intro and its confirmation), and `hangup`'s is optional. */ + * intro and its confirmation), and the prompt of `hangup` and the + * `whisper` of `transfer` are optional. */ export function nodePrompts(node: Node): Prompt[] { switch (node.kind) { case 'greeting': @@ -256,6 +257,8 @@ export function nodePrompts(node: Node): Prompt[] { return node.prompt === undefined ? [] : [node.prompt]; case 'book': return [node.prompt, node.confirm_prompt]; + case 'transfer': + return node.whisper === undefined ? [] : [node.whisper]; default: return []; } diff --git a/packages/flow-schema/src/parse.ts b/packages/flow-schema/src/parse.ts index 011c2aa..ac8b787 100644 --- a/packages/flow-schema/src/parse.ts +++ b/packages/flow-schema/src/parse.ts @@ -310,7 +310,7 @@ const NODE_CONFIG_FIELDS: Record = { menu: ['prompt', 'options', 'retries', 'timeout_secs'], ring: ['timeout_secs'], message: ['prompt', 'max_secs', 'tone'], - transfer: ['target'], + transfer: ['target', 'whisper', 'timeout_secs'], hangup: ['prompt'], book: [ 'prompt', @@ -433,7 +433,26 @@ function decodeComponent( case 'transfer': { const targetField = required(fields, 'target', context, issues, at); const target = targetField && asString(targetField.value, `${context} target`, issues); - return target === undefined ? undefined : { kind, target }; + if (target === undefined) return undefined; + const whisperField = fields.get('whisper'); + const whisper = whisperField + ? decodePrompt(whisperField.value, `${context} whisper`, issues) + : undefined; + const timeoutField = fields.get('timeout_secs'); + const timeout = timeoutField + ? asU32(timeoutField.value, `${context} timeout_secs`, issues) + : undefined; + // A field that is present but malformed already reported its issue; + // drop the whole node rather than run it without the field. + if ((whisperField && whisper === undefined) || (timeoutField && timeout === undefined)) { + return undefined; + } + return { + kind, + target, + ...(whisper !== undefined ? { whisper } : {}), + ...(timeout !== undefined ? { timeout_secs: timeout } : {}), + }; } case 'hangup': { const promptField = fields.get('prompt'); diff --git a/packages/flow-schema/src/serialize.ts b/packages/flow-schema/src/serialize.ts index bd23955..2a3f6ef 100644 --- a/packages/flow-schema/src/serialize.ts +++ b/packages/flow-schema/src/serialize.ts @@ -8,13 +8,13 @@ // are required, and their defaults all come from there, so a schema change // needs no change here. -import { flowV2Schema } from './generated/schema.js'; +import { flowV3Schema } from './generated/schema.js'; import type { Flow } from './model.js'; type Json = null | boolean | number | string | Json[] | { [key: string]: Json }; type Schema = { [key: string]: unknown }; -const ROOT = flowV2Schema as unknown as Schema; +const ROOT = flowV3Schema as unknown as Schema; /** Follow `$ref` (and a single-entry `allOf`, the schema's way of putting * a default next to a ref) to the schema that describes a value. */ diff --git a/packages/flow-schema/src/structure.ts b/packages/flow-schema/src/structure.ts index ac3c20e..9c12d7f 100644 --- a/packages/flow-schema/src/structure.ts +++ b/packages/flow-schema/src/structure.ts @@ -18,7 +18,7 @@ import { Ajv2020 } from 'ajv/dist/2020.js'; import type { ErrorObject, ValidateFunction } from 'ajv'; -import { flowV1Schema, flowV2Schema } from './generated/schema.js'; +import { flowV1Schema, flowV2Schema, flowV3Schema } from './generated/schema.js'; const ajv = new Ajv2020({ allErrors: true, strict: false }); @@ -32,6 +32,7 @@ const ajv = new Ajv2020({ allErrors: true, strict: false }); const validators = new Map([ [1, ajv.compile(flowV1Schema)], [2, ajv.compile(flowV2Schema)], + [3, ajv.compile(flowV3Schema)], ]); export type StructuralResult = diff --git a/packages/flow-schema/test/conformance.test.ts b/packages/flow-schema/test/conformance.test.ts index 7a1eea6..2e135a0 100644 --- a/packages/flow-schema/test/conformance.test.ts +++ b/packages/flow-schema/test/conformance.test.ts @@ -46,6 +46,8 @@ type Expectation = { function casesIn(version: string, bucket: string): string[] { const dir = resolve(corpusRoot, version, bucket); + // A version may have no cases in a bucket yet; a missing directory is empty. + if (!existsSync(dir)) return []; return readdirSync(dir) .filter((f) => f.endsWith('.yaml')) .map((f) => f.slice(0, -'.yaml'.length)); diff --git a/packages/flow-schema/test/parse.test.ts b/packages/flow-schema/test/parse.test.ts index a63e71b..f66d4f8 100644 --- a/packages/flow-schema/test/parse.test.ts +++ b/packages/flow-schema/test/parse.test.ts @@ -142,6 +142,44 @@ nodes: expect(issues.filter((issue) => issue.code === 'unknown_field')).toHaveLength(0); }); + it('keeps a transfer whisper and timeout without warning, and counts the whisper clip', () => { + const { flow, issues } = parseFlow(` +schema_version: 3 +id: f +name: n +entry: t +nodes: + t: + kind: transfer + target: "+15551230100" + whisper: { audio: vprompt_whisper01, transcript: A caller wants a person. } + timeout_secs: 20 +`); + const node = flow?.nodes['t']; + expect(node?.kind === 'transfer' && node.whisper).toEqual({ + audio: 'vprompt_whisper01', + transcript: 'A caller wants a person.', + }); + expect(node?.kind === 'transfer' && node.timeout_secs).toBe(20); + expect(issues.filter((issue) => issue.code === 'unknown_field')).toHaveLength(0); + expect(flow ? requiredAssets(flow) : []).toEqual(['vprompt_whisper01']); + }); + + it('rejects a malformed transfer whisper or timeout', () => { + const { issues } = parseFlow(` +schema_version: 3 +id: f +name: n +entry: t +nodes: + t: + kind: transfer + target: "+15551230100" + timeout_secs: soon +`); + expect(issues.some((issue) => issue.severity === 'error')).toBe(true); + }); + it('rejects a non-string audio prompt transcript', () => { const { issues } = parseFlow(` schema_version: 1 diff --git a/schema/README.md b/schema/README.md index f611864..7ee4ef0 100644 --- a/schema/README.md +++ b/schema/README.md @@ -9,9 +9,14 @@ version it declares, and no other. |---|---|---| | `flow.v1.schema.json` | `schema_version: 1` | the original seven components | | `flow.v2.schema.json` | `schema_version: 2` | `book` — appointment booking over the phone | +| `flow.v3.schema.json` | `schema_version: 3` | `transfer` gains `whisper` and `timeout_secs` — a screened transfer | Version 2 is version 1 plus one component: every v1 document is a valid v2 document once its `schema_version` is bumped, and nothing else changed. +Version 3 is version 2 plus two optional fields on `transfer`: every v2 +document is a valid v3 document once its `schema_version` is bumped. The +bump is for what the fields do, not for their shape. A reader that ignored +`whisper` would hand the call over without calling the target first. Everything downstream is generated or checked against these files: diff --git a/schema/flow.v3.schema.json b/schema/flow.v3.schema.json new file mode 100644 index 0000000..5005f37 --- /dev/null +++ b/schema/flow.v3.schema.json @@ -0,0 +1,276 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://schema.wavekat.com/flow/v3.json", + "title": "Flow", + "description": "The WaveKat call-flow (\"Receptionist\") document, schema_version 3. Version 3 is version 2 plus the screened transfer: the `transfer` node gains `whisper` and `timeout_secs`. Every version-2 document is a valid version-3 document once its `schema_version` is bumped, and nothing else changed. This file is the single source of truth for the document SHAPE, and — being the newest version — it is also the file both consumers generate their model types from, so one model covers every supported version. Semantic rules that a JSON Schema cannot express (graph reachability, exit-set exactness, hours/timezone math, DTMF digit validity, prompt length, per-component numeric bounds, and which components a given schema_version may use) are NOT encoded here — they live in each language's validator and are pinned by the shared conformance corpus. Unknown fields are permitted structurally, matching both implementations (Rust serde ignores them; the TS parser surfaces a non-blocking warning).", + "type": "object", + "required": ["schema_version", "id", "name", "entry", "nodes"], + "properties": { + "schema_version": { + "description": "Document format version. This file describes version 3 only; a document declaring another version validates against that version's schema file, not this one. (The type generators relax this constant to a plain integer so the generated model can hold any supported version — see scripts/generate.mjs and build.rs.)", + "type": "integer", + "const": 3 + }, + "id": { + "description": "Opaque platform-assigned id (flow_…). Treated as a label; appears in traces.", + "type": "string" + }, + "name": { + "description": "Human name shown in the editor and the read-only viewer.", + "type": "string" + }, + "version": { + "description": "Platform-assigned publish counter, bumped on publish. Defaults to 1 for a hand-written or generated pre-publish document. Distinct from schema_version.", + "type": "integer", + "minimum": 0, + "default": 1 + }, + "note": { + "description": "The author's note about the whole flow: free text for people reading it, in place of a YAML comment. Never read by the engine.", + "type": "string" + }, + "entry": { + "description": "Node id where execution begins.", + "type": "string" + }, + "nodes": { + "description": "The flat node set, keyed by human-meaningful node id and string-referenced by exits. Order is irrelevant to execution, but it is the author's reading order and is kept on save.", + "type": "object", + "additionalProperties": { "$ref": "#/$defs/Node" } + }, + "ui": { + "description": "Presentation metadata (canvas positions, annotations). Preserved on round-trip, never read by the engine. Opaque by design so a canvas editor can add layout fields without a schema bump." + } + }, + "$defs": { + "Prompt": { + "description": "What a component speaks: TTS text (a bare string) or a reference to a pre-rendered audio asset shipped alongside the flow.", + "oneOf": [ + { "title": "Text", "type": "string" }, + { + "title": "Audio", + "type": "object", + "required": ["audio"], + "properties": { + "audio": { + "description": "Audio asset ref. A generated-clip ref is a voice_prompts id matching ^vprompt_[a-z0-9]+$.", + "type": "string" + }, + "transcript": { + "description": "The words this pre-rendered clip speaks — the text it was synthesized from — carried so a viewer can show what a caller hears, and for traces. Advisory only: playback always uses `audio`, never this. Optional and forward-added: absent on older documents and on refs the platform did not generate from text.", + "type": "string" + } + } + } + ] + }, + "MessageTone": { + "description": "The cue a message node plays between its prompt and the start of recording.", + "type": "string", + "enum": ["beep", "none"] + }, + "Exits": { + "description": "Wired exits: exit name → target node id. Which names are valid is a property of the node's kind and is checked by the validator, not by this schema.", + "type": "object", + "additionalProperties": { "type": "string" } + }, + "TimeRange": { + "description": "One open window: open–close as \"HH:MM\" (24-hour). Ordering and overnight rules are enforced by the validator.", + "type": "object", + "required": ["open", "close"], + "properties": { + "open": { "type": "string" }, + "close": { "type": "string" } + } + }, + "WeeklySchedule": { + "description": "Open ranges per weekday; a missing or empty day means closed all day.", + "type": "object", + "properties": { + "mon": { "type": "array", "items": { "$ref": "#/$defs/TimeRange" } }, + "tue": { "type": "array", "items": { "$ref": "#/$defs/TimeRange" } }, + "wed": { "type": "array", "items": { "$ref": "#/$defs/TimeRange" } }, + "thu": { "type": "array", "items": { "$ref": "#/$defs/TimeRange" } }, + "fri": { "type": "array", "items": { "$ref": "#/$defs/TimeRange" } }, + "sat": { "type": "array", "items": { "$ref": "#/$defs/TimeRange" } }, + "sun": { "type": "array", "items": { "$ref": "#/$defs/TimeRange" } } + } + }, + "HoursException": { + "description": "A single-date override of the weekly schedule (holiday / special hours).", + "type": "object", + "required": ["date"], + "properties": { + "date": { "description": "\"YYYY-MM-DD\" in the flow's timezone.", "type": "string" }, + "closed": { "description": "Closed all day regardless of ranges.", "type": "boolean", "default": false }, + "ranges": { "type": "array", "items": { "$ref": "#/$defs/TimeRange" } } + } + }, + "Node": { + "description": "One node: a component (kind + its config) plus its wired exits. An internally-tagged union on `kind`.", + "oneOf": [ + { "$ref": "#/$defs/GreetingNode" }, + { "$ref": "#/$defs/HoursNode" }, + { "$ref": "#/$defs/MenuNode" }, + { "$ref": "#/$defs/RingNode" }, + { "$ref": "#/$defs/MessageNode" }, + { "$ref": "#/$defs/TransferNode" }, + { "$ref": "#/$defs/HangupNode" }, + { "$ref": "#/$defs/BookNode" } + ] + }, + "GreetingNode": { + "description": "Speak a prompt, then continue. Exit: next.", + "type": "object", + "required": ["kind", "prompt"], + "properties": { + "kind": { "const": "greeting" }, + "note": { "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", "type": "string" }, + "prompt": { "$ref": "#/$defs/Prompt" }, + "exits": { "$ref": "#/$defs/Exits" } + } + }, + "HoursNode": { + "description": "Branch on the business's weekly schedule + holiday overrides. Exits: open, closed.", + "type": "object", + "required": ["kind", "schedule", "timezone"], + "properties": { + "kind": { "const": "hours" }, + "note": { "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", "type": "string" }, + "schedule": { "$ref": "#/$defs/WeeklySchedule" }, + "timezone": { "description": "IANA zone (America/New_York). Validated to resolve at load.", "type": "string" }, + "exceptions": { "type": "array", "items": { "$ref": "#/$defs/HoursException" } }, + "exits": { "$ref": "#/$defs/Exits" } + } + }, + "MenuNode": { + "description": "Speak a prompt and collect a DTMF choice. Exits: one per digit in options, plus no_input and invalid.", + "type": "object", + "required": ["kind", "prompt", "options"], + "properties": { + "kind": { "const": "menu" }, + "note": { "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", "type": "string" }, + "prompt": { "$ref": "#/$defs/Prompt" }, + "options": { + "description": "Digit key → human label. The exit for a digit is exits[digit]. Valid digit keys are enforced by the validator.", + "type": "object", + "additionalProperties": { "type": "string" } + }, + "retries": { "type": "integer", "minimum": 0, "default": 1 }, + "timeout_secs": { "type": "integer", "minimum": 0, "default": 5 }, + "exits": { "$ref": "#/$defs/Exits" } + } + }, + "RingNode": { + "description": "Ring the human for a window. answered is an implicit terminal; the only wired exit is no_answer.", + "type": "object", + "required": ["kind", "timeout_secs"], + "properties": { + "kind": { "const": "ring" }, + "note": { "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", "type": "string" }, + "timeout_secs": { "type": "integer", "minimum": 0 }, + "exits": { "$ref": "#/$defs/Exits" } + } + }, + "MessageNode": { + "description": "Voicemail: speak a prompt, record, transcribe, notify. Terminal.", + "type": "object", + "required": ["kind", "prompt"], + "properties": { + "kind": { "const": "message" }, + "note": { "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", "type": "string" }, + "prompt": { "$ref": "#/$defs/Prompt" }, + "max_secs": { "type": "integer", "minimum": 0, "default": 120 }, + "tone": { "allOf": [{ "$ref": "#/$defs/MessageTone" }], "default": "beep" }, + "exits": { "$ref": "#/$defs/Exits" } + } + }, + "TransferNode": { + "description": "Hand the call to an external number. With `whisper`, a screened transfer: call the target first, play the whisper, and connect only when they accept; otherwise take `no_answer`. Without it, a blind transfer (terminal). `whisper` is spoken to the person at the target before they are connected, and `timeout_secs` is how long to let the target ring or decide. Both apply only to a screened transfer.", + "type": "object", + "required": ["kind", "target"], + "properties": { + "kind": { "const": "transfer" }, + "note": { "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", "type": "string" }, + "target": { "type": "string" }, + "whisper": { "$ref": "#/$defs/Prompt" }, + "timeout_secs": { "type": "integer", "minimum": 5, "maximum": 120 }, + "exits": { "$ref": "#/$defs/Exits" } + } + }, + "HangupNode": { + "description": "Speak an optional goodbye and end the call. Terminal.", + "type": "object", + "required": ["kind"], + "properties": { + "kind": { "const": "hangup" }, + "note": { "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", "type": "string" }, + "prompt": { "$ref": "#/$defs/Prompt" }, + "exits": { "$ref": "#/$defs/Exits" } + } + }, + "BookNode": { + "description": "Offer the caller open appointment times and book the one they choose, before the call ends. New in schema_version 2. The bookable grid is described here (weekly schedule + timezone + how long an appointment is); which times are actually free comes from the connected calendar at call time, and the engine never sees a credential. Exits: booked, no_slots, no_input, unavailable. Three fields carry more meaning than their types show, and are described here because a `$ref` with a sibling description makes the type generators emit a duplicate type instead of reusing the named one. `prompt` is spoken once before the open times are offered (\"I can book you in — here are the next available times\"); the times themselves are never part of it, since they are not known until the call. `confirm_prompt` is spoken immediately after a successful booking and directly BEFORE the booked time (\"You're booked for\" → \"Tuesday\" → \"ten thirty a.m.\"); it deliberately takes no placeholder, because a prompt is frozen audio by the time a call runs and nothing can be interpolated into the middle of it — anything that should follow the time belongs on the booked exit. `schedule` is when this business takes appointments, the `hours` node's weekly shape reused verbatim; it is not the same question `hours` answers, because a business can answer the phone at times it will not book.", + "type": "object", + "required": ["kind", "prompt", "confirm_prompt", "schedule", "timezone", "duration_mins"], + "properties": { + "kind": { "const": "book" }, + "note": { "description": "The author's note about this step: free text for people reading the flow, in place of a YAML comment. Never read by the engine.", "type": "string" }, + "prompt": { "$ref": "#/$defs/Prompt" }, + "confirm_prompt": { "$ref": "#/$defs/Prompt" }, + "schedule": { "$ref": "#/$defs/WeeklySchedule" }, + "timezone": { + "description": "IANA zone (America/New_York) the schedule is written in. Validated to resolve at load.", + "type": "string" + }, + "exceptions": { + "description": "Single-date overrides of the weekly schedule (holidays, one-off clinics), as on `hours`.", + "type": "array", + "items": { "$ref": "#/$defs/HoursException" } + }, + "duration_mins": { + "description": "How long one appointment runs. Bounds are the validator's (see each language's validate module), not this schema's.", + "type": "integer", + "minimum": 0 + }, + "buffer_mins": { + "description": "Clear time kept on BOTH sides of an appointment, so a slot is not offered flush against a busy interval.", + "type": "integer", + "minimum": 0, + "default": 0 + }, + "lead_mins": { + "description": "Nothing sooner than this many minutes from now is offered — the caller cannot book the next five minutes.", + "type": "integer", + "minimum": 0, + "default": 120 + }, + "horizon_days": { + "description": "How far ahead to look for open times.", + "type": "integer", + "minimum": 0, + "default": 14 + }, + "max_offers": { + "description": "How many times to offer the caller. Each offered time gets one keypad digit, counting from 1.", + "type": "integer", + "minimum": 0, + "default": 3 + }, + "retries": { + "description": "Extra attempts to collect a keypress after the first, as on `menu`.", + "type": "integer", + "minimum": 0, + "default": 1 + }, + "timeout_secs": { + "description": "How long to wait for a keypress on each attempt, as on `menu`.", + "type": "integer", + "minimum": 0, + "default": 5 + }, + "exits": { "$ref": "#/$defs/Exits" } + } + } + } +} From 4c21ce8aae750d9cd038219e92b228798021de05 Mon Sep 17 00:00:00 2001 From: Eason WaveKat Date: Sat, 31 Oct 2026 18:42:19 +1300 Subject: [PATCH 2/4] feat: validate screened transfers and v3 outbound --- .../screened-transfer.canonical.yaml | 13 + .../canonical/screened-transfer.expected.json | 4 + .../canonical/screened-transfer.input.yaml | 15 + .../invalid/v2-whisper-refused.expected.json | 5 + .../v2/invalid/v2-whisper-refused.yaml | 12 + ...d-transfer-missing-no-answer.expected.json | 5 + .../screened-transfer-missing-no-answer.yaml | 9 + .../timeout-without-whisper.expected.json | 5 + .../v3/invalid/timeout-without-whisper.yaml | 9 + ...ransfer-timeout-out-of-range.expected.json | 5 + .../transfer-timeout-out-of-range.yaml | 13 + .../invalid/blind-transfer.expected.json | 5 + .../v3/outbound/invalid/blind-transfer.yaml | 12 + .../invalid/no-answer-loop.expected.json | 5 + .../v3/outbound/invalid/no-answer-loop.yaml | 13 + .../valid/interview-reminder.expected.json | 5 + .../v3/outbound/valid/interview-reminder.yaml | 32 ++ .../v3/valid/screened-transfer.expected.json | 6 + conformance/v3/valid/screened-transfer.yaml | 27 ++ .../compat-old-readers/tests/old_readers.rs | 19 + crates/wavekat-flow/src/model_ext.rs | 29 +- crates/wavekat-flow/src/validate.rs | 426 +++++++++++++++++- packages/flow-schema/src/index.ts | 2 +- packages/flow-schema/src/model.ts | 57 ++- packages/flow-schema/src/validate.ts | 105 ++++- packages/flow-schema/test/outbound.test.ts | 212 ++++++++- 26 files changed, 1015 insertions(+), 35 deletions(-) create mode 100644 conformance/canonical/screened-transfer.canonical.yaml create mode 100644 conformance/canonical/screened-transfer.expected.json create mode 100644 conformance/canonical/screened-transfer.input.yaml create mode 100644 conformance/v2/invalid/v2-whisper-refused.expected.json create mode 100644 conformance/v2/invalid/v2-whisper-refused.yaml create mode 100644 conformance/v3/invalid/screened-transfer-missing-no-answer.expected.json create mode 100644 conformance/v3/invalid/screened-transfer-missing-no-answer.yaml create mode 100644 conformance/v3/invalid/timeout-without-whisper.expected.json create mode 100644 conformance/v3/invalid/timeout-without-whisper.yaml create mode 100644 conformance/v3/invalid/transfer-timeout-out-of-range.expected.json create mode 100644 conformance/v3/invalid/transfer-timeout-out-of-range.yaml create mode 100644 conformance/v3/outbound/invalid/blind-transfer.expected.json create mode 100644 conformance/v3/outbound/invalid/blind-transfer.yaml create mode 100644 conformance/v3/outbound/invalid/no-answer-loop.expected.json create mode 100644 conformance/v3/outbound/invalid/no-answer-loop.yaml create mode 100644 conformance/v3/outbound/valid/interview-reminder.expected.json create mode 100644 conformance/v3/outbound/valid/interview-reminder.yaml create mode 100644 conformance/v3/valid/screened-transfer.expected.json create mode 100644 conformance/v3/valid/screened-transfer.yaml diff --git a/conformance/canonical/screened-transfer.canonical.yaml b/conformance/canonical/screened-transfer.canonical.yaml new file mode 100644 index 0000000..bd58519 --- /dev/null +++ b/conformance/canonical/screened-transfer.canonical.yaml @@ -0,0 +1,13 @@ +schema_version: 3 +id: flow_screened_canon +name: Hand the call to a person +entry: person +nodes: + person: + kind: transfer + target: "+15551230100" + whisper: { audio: vprompt_whisper01, transcript: A caller asked to talk to someone. } + timeout_secs: 20 + exits: { no_answer: bye } + bye: + kind: hangup diff --git a/conformance/canonical/screened-transfer.expected.json b/conformance/canonical/screened-transfer.expected.json new file mode 100644 index 0000000..84958c5 --- /dev/null +++ b/conformance/canonical/screened-transfer.expected.json @@ -0,0 +1,4 @@ +{ + "description": "A transfer carrying `whisper` and `timeout_secs` (schema_version 3) is written in schema property order (`target`, `whisper`, `timeout_secs`, `exits`), the whisper clip keeps its transcript, and the text is a fixed point. Neither field equals a default, so both are written.", + "comments": 2 +} diff --git a/conformance/canonical/screened-transfer.input.yaml b/conformance/canonical/screened-transfer.input.yaml new file mode 100644 index 0000000..83d51ad --- /dev/null +++ b/conformance/canonical/screened-transfer.input.yaml @@ -0,0 +1,15 @@ +# Screened transfer, written the way a person might: fields out of order, +# the whisper as a clip with its transcript, and a comment to drop. +schema_version: 3 +name: Hand the call to a person +id: flow_screened_canon +entry: person +nodes: + person: + exits: { no_answer: bye } + timeout_secs: 20 + whisper: { transcript: A caller asked to talk to someone., audio: vprompt_whisper01 } + target: "+15551230100" + kind: transfer + bye: + kind: hangup diff --git a/conformance/v2/invalid/v2-whisper-refused.expected.json b/conformance/v2/invalid/v2-whisper-refused.expected.json new file mode 100644 index 0000000..dc77c6b --- /dev/null +++ b/conformance/v2/invalid/v2-whisper-refused.expected.json @@ -0,0 +1,5 @@ +{ + "description": "A version 2 document may not use `whisper` (or `timeout_secs`) on a transfer: an engine that only knows version 2 would ignore the whisper and hand the call over blind, so the field needs the version that has it. Added with version 3; the v2 cases around it are untouched.", + "structurallyValid": true, + "semantic": { "ok": false, "errors": ["field_requires_newer_schema"] } +} diff --git a/conformance/v2/invalid/v2-whisper-refused.yaml b/conformance/v2/invalid/v2-whisper-refused.yaml new file mode 100644 index 0000000..48ac4a8 --- /dev/null +++ b/conformance/v2/invalid/v2-whisper-refused.yaml @@ -0,0 +1,12 @@ +schema_version: 2 +id: flow_v2_whisper +name: Whisper in a version 2 document +entry: person +nodes: + person: + kind: transfer + target: "+15551230100" + whisper: A caller asked to talk to someone. Press any key to accept. + exits: { no_answer: bye } + bye: + kind: hangup diff --git a/conformance/v3/invalid/screened-transfer-missing-no-answer.expected.json b/conformance/v3/invalid/screened-transfer-missing-no-answer.expected.json new file mode 100644 index 0000000..8c3b524 --- /dev/null +++ b/conformance/v3/invalid/screened-transfer-missing-no-answer.expected.json @@ -0,0 +1,5 @@ +{ + "description": "A screened transfer can fail to connect, so it must wire `no_answer`; without it a person who never picks up leaves the caller with nowhere to go. A blind transfer (no whisper) has no exits, which is why the shape alone cannot say so.", + "structurallyValid": true, + "semantic": { "ok": false, "errors": ["missing_exits"] } +} diff --git a/conformance/v3/invalid/screened-transfer-missing-no-answer.yaml b/conformance/v3/invalid/screened-transfer-missing-no-answer.yaml new file mode 100644 index 0000000..12f0619 --- /dev/null +++ b/conformance/v3/invalid/screened-transfer-missing-no-answer.yaml @@ -0,0 +1,9 @@ +schema_version: 3 +id: flow_screened_no_exit +name: Screened transfer with no way out +entry: person +nodes: + person: + kind: transfer + target: "+15551230100" + whisper: A caller asked to talk to someone. Press any key to accept. diff --git a/conformance/v3/invalid/timeout-without-whisper.expected.json b/conformance/v3/invalid/timeout-without-whisper.expected.json new file mode 100644 index 0000000..42a1012 --- /dev/null +++ b/conformance/v3/invalid/timeout-without-whisper.expected.json @@ -0,0 +1,5 @@ +{ + "description": "`timeout_secs` is how long a screened transfer waits for the person to accept. A transfer with no `whisper` is blind and never waits, so the field means nothing there and is refused rather than ignored.", + "structurallyValid": true, + "semantic": { "ok": false, "errors": ["timeout_without_whisper"] } +} diff --git a/conformance/v3/invalid/timeout-without-whisper.yaml b/conformance/v3/invalid/timeout-without-whisper.yaml new file mode 100644 index 0000000..fa4ac70 --- /dev/null +++ b/conformance/v3/invalid/timeout-without-whisper.yaml @@ -0,0 +1,9 @@ +schema_version: 3 +id: flow_timeout_no_whisper +name: Timeout with nothing to screen +entry: person +nodes: + person: + kind: transfer + target: "+15551230100" + timeout_secs: 20 diff --git a/conformance/v3/invalid/transfer-timeout-out-of-range.expected.json b/conformance/v3/invalid/transfer-timeout-out-of-range.expected.json new file mode 100644 index 0000000..414abe0 --- /dev/null +++ b/conformance/v3/invalid/transfer-timeout-out-of-range.expected.json @@ -0,0 +1,5 @@ +{ + "description": "`timeout_secs` on a transfer is 5 to 120. The schema says so, and the validator says so again, so a caller that skips the structural pass still cannot publish a transfer that waits five minutes.", + "structurallyValid": false, + "semantic": { "ok": false, "errors": ["transfer_timeout_out_of_range"] } +} diff --git a/conformance/v3/invalid/transfer-timeout-out-of-range.yaml b/conformance/v3/invalid/transfer-timeout-out-of-range.yaml new file mode 100644 index 0000000..e6fc6e7 --- /dev/null +++ b/conformance/v3/invalid/transfer-timeout-out-of-range.yaml @@ -0,0 +1,13 @@ +schema_version: 3 +id: flow_timeout_range +name: Waiting too long for a person +entry: person +nodes: + person: + kind: transfer + target: "+15551230100" + whisper: A caller asked to talk to someone. Press any key to accept. + timeout_secs: 300 + exits: { no_answer: bye } + bye: + kind: hangup diff --git a/conformance/v3/outbound/invalid/blind-transfer.expected.json b/conformance/v3/outbound/invalid/blind-transfer.expected.json new file mode 100644 index 0000000..a7337ab --- /dev/null +++ b/conformance/v3/outbound/invalid/blind-transfer.expected.json @@ -0,0 +1,5 @@ +{ + "description": "Outbound calls may transfer from version 3, but only a screened transfer: the person who picks up hears a whisper first. A blind transfer would drop the callee on someone who did not know a call was coming. The same document is a valid inbound flow.", + "structurallyValid": true, + "semantic": { "ok": false, "errors": ["outbound_blind_transfer"] } +} diff --git a/conformance/v3/outbound/invalid/blind-transfer.yaml b/conformance/v3/outbound/invalid/blind-transfer.yaml new file mode 100644 index 0000000..8ac243f --- /dev/null +++ b/conformance/v3/outbound/invalid/blind-transfer.yaml @@ -0,0 +1,12 @@ +schema_version: 3 +id: flow_outbound_blind +name: Outbound blind transfer +entry: hello +nodes: + hello: + kind: greeting + prompt: Connecting you now. + exits: { next: forward } + forward: + kind: transfer + target: "+15551230100" diff --git a/conformance/v3/outbound/invalid/no-answer-loop.expected.json b/conformance/v3/outbound/invalid/no-answer-loop.expected.json new file mode 100644 index 0000000..eeaa207 --- /dev/null +++ b/conformance/v3/outbound/invalid/no-answer-loop.expected.json @@ -0,0 +1,5 @@ +{ + "description": "`no_answer` happens without the callee, like a menu's `no_input`, so ring -> greeting -> ring never needs anyone to do anything and would redial for ever.", + "structurallyValid": true, + "semantic": { "ok": false, "errors": ["outbound_unbounded_loop"] } +} diff --git a/conformance/v3/outbound/invalid/no-answer-loop.yaml b/conformance/v3/outbound/invalid/no-answer-loop.yaml new file mode 100644 index 0000000..7e460af --- /dev/null +++ b/conformance/v3/outbound/invalid/no-answer-loop.yaml @@ -0,0 +1,13 @@ +schema_version: 3 +id: flow_outbound_no_answer_loop +name: Outbound ring that retries for ever +entry: front +nodes: + front: + kind: ring + timeout_secs: 20 + exits: { no_answer: again } + again: + kind: greeting + prompt: Nobody picked up, trying again. + exits: { next: front } diff --git a/conformance/v3/outbound/valid/interview-reminder.expected.json b/conformance/v3/outbound/valid/interview-reminder.expected.json new file mode 100644 index 0000000..16d8a82 --- /dev/null +++ b/conformance/v3/outbound/valid/interview-reminder.expected.json @@ -0,0 +1,5 @@ +{ + "description": "A reminder call that can hand the callee to a person: a menu, then a screened transfer, then a `ring` step as the second try, then a goodbye. Version 3 lets an outbound call use `ring` and a screened `transfer`; the loop back to the menu needs a key press, so it is bounded.", + "structurallyValid": true, + "semantic": { "ok": true, "errors": [] } +} diff --git a/conformance/v3/outbound/valid/interview-reminder.yaml b/conformance/v3/outbound/valid/interview-reminder.yaml new file mode 100644 index 0000000..58b4987 --- /dev/null +++ b/conformance/v3/outbound/valid/interview-reminder.yaml @@ -0,0 +1,32 @@ +schema_version: 3 +id: flow_interview_reminder +name: Interview reminder with a hand-off +entry: hello +nodes: + hello: + kind: greeting + prompt: This is a reminder about your interview tomorrow. + exits: { next: ask } + ask: + kind: menu + prompt: Press 1 to confirm, or 2 to speak to someone. + options: { "1": Confirm, "2": Speak to someone } + exits: { "1": thanks, "2": person, no_input: bye, invalid: ask } + person: + kind: transfer + target: "+15551230100" + whisper: A candidate asked to speak to someone about an interview. Press any key to accept. + timeout_secs: 20 + exits: { no_answer: desk } + desk: + kind: ring + timeout_secs: 20 + exits: { no_answer: sorry } + sorry: + kind: hangup + prompt: Sorry, nobody is free right now. We will call you back. + thanks: + kind: hangup + prompt: Thank you, see you tomorrow. + bye: + kind: hangup diff --git a/conformance/v3/valid/screened-transfer.expected.json b/conformance/v3/valid/screened-transfer.expected.json new file mode 100644 index 0000000..534b7f7 --- /dev/null +++ b/conformance/v3/valid/screened-transfer.expected.json @@ -0,0 +1,6 @@ +{ + "description": "A screened transfer: a `transfer` with a `whisper` calls the target first and connects only when they accept, so it needs a `no_answer` exit for the case where they don't. The whisper clip is part of the assets a daemon must have before it arms the flow.", + "structurallyValid": true, + "semantic": { "ok": true, "errors": [] }, + "requiredAssets": ["vprompt_whisper01"] +} diff --git a/conformance/v3/valid/screened-transfer.yaml b/conformance/v3/valid/screened-transfer.yaml new file mode 100644 index 0000000..f6cd6aa --- /dev/null +++ b/conformance/v3/valid/screened-transfer.yaml @@ -0,0 +1,27 @@ +schema_version: 3 +id: flow_screened_transfer +name: Hand the call to a person +version: 1 +entry: ask +nodes: + ask: + kind: menu + prompt: Press 1 to talk to a person. + options: + "1": A person + exits: + "1": person + no_input: goodbye + invalid: goodbye + person: + kind: transfer + target: "+15551230100" + whisper: + audio: vprompt_whisper01 + transcript: A caller asked to talk to someone. Press any key to accept. + timeout_secs: 20 + exits: + no_answer: goodbye + goodbye: + kind: hangup + prompt: Goodbye. diff --git a/crates/compat-old-readers/tests/old_readers.rs b/crates/compat-old-readers/tests/old_readers.rs index 310cfd3..41330a3 100644 --- a/crates/compat-old-readers/tests/old_readers.rs +++ b/crates/compat-old-readers/tests/old_readers.rs @@ -149,3 +149,22 @@ fn old_reader_refuses_versions_it_does_not_know() { let flow = old_flow::Flow::from_yaml(yaml).expect("parses; the version gate is validate"); assert!(old_validate(&flow).is_err()); } + +#[test] +fn old_reader_refuses_a_screened_transfer_rather_than_run_it_blind() { + // `whisper` is what makes a transfer screened. A reader that parses the + // document but does not know the field would drop it and hand the call + // over blind, so the document declares version 3 and the old reader must + // refuse that version. It parses (unknown keys are tolerated); the + // refusal is the validation gate. + let yaml = fs::read_to_string(corpus().join("v3/valid/screened-transfer.yaml")).unwrap(); + let old = old_flow::Flow::from_yaml(&yaml).expect("parses; unknown keys are tolerated"); + assert!( + !old_flow::SUPPORTED_SCHEMA_VERSIONS.contains(&schema_version(&yaml)), + "{OLDEST_READER} claims to read version 3" + ); + assert!(old_validate(&old).is_err()); + assert!( + wavekat_flow::validate::validate(&wavekat_flow::Flow::from_yaml(&yaml).unwrap()).is_ok() + ); +} diff --git a/crates/wavekat-flow/src/model_ext.rs b/crates/wavekat-flow/src/model_ext.rs index 248c7cd..63ffe08 100644 --- a/crates/wavekat-flow/src/model_ext.rs +++ b/crates/wavekat-flow/src/model_ext.rs @@ -34,16 +34,34 @@ impl Node { } } - /// Whether a caller who reaches this node can have the call *end* here. - /// `ring` counts — its implicit `answered` hands the call to a human, - /// which ends the flow. Used by the "no caller is ever trapped" check. - pub fn is_terminal(&self) -> bool { + /// Whether this is a *screened* transfer: one with a `whisper`, which + /// tells the person who picks up what the call is and waits for them + /// to accept it. It can fail to connect, so it has a `no_answer` exit + /// (a blind transfer hands the call over and is done). Twin: + /// `model.ts` `isScreenedTransfer`. + pub fn is_screened_transfer(&self) -> bool { matches!( self, - Node::Message { .. } | Node::Transfer { .. } | Node::Hangup { .. } | Node::Ring { .. } + Node::Transfer { + whisper: Some(_), + .. + } ) } + /// Whether a caller who reaches this node can have the call *end* here. + /// `ring` counts — its implicit `answered` hands the call to a human, + /// which ends the flow. A blind `transfer` ends it too; a screened one + /// may fall out of its `no_answer` exit instead, so it does not count + /// and the "no caller is ever trapped" check follows that exit. + pub fn is_terminal(&self) -> bool { + match self { + Node::Transfer { .. } => !self.is_screened_transfer(), + Node::Message { .. } | Node::Hangup { .. } | Node::Ring { .. } => true, + _ => false, + } + } + /// The exit names this node **must** wire, given its config. Validation /// checks the node's `exits` keys are exactly this set — no missing exit /// (a dead choice) and no stray exit (a typo the engine would never @@ -69,6 +87,7 @@ impl Node { "no_input".into(), "unavailable".into(), ], + Node::Transfer { .. } if self.is_screened_transfer() => vec!["no_answer".into()], Node::Message { .. } | Node::Transfer { .. } | Node::Hangup { .. } => Vec::new(), } } diff --git a/crates/wavekat-flow/src/validate.rs b/crates/wavekat-flow/src/validate.rs index d72e5e4..563af81 100644 --- a/crates/wavekat-flow/src/validate.rs +++ b/crates/wavekat-flow/src/validate.rs @@ -30,6 +30,16 @@ const MAX_PROMPT_CHARS: usize = 2000; /// `packages/flow-schema/src/model.ts` `VALID_DIGITS`. const VALID_DIGITS: &[&str] = &["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "*", "#"]; +/// The shortest and longest a screened transfer may ring the person's +/// phone, in seconds. Twin: `model.ts` `MIN_TRANSFER_TIMEOUT_SECS` / +/// `MAX_TRANSFER_TIMEOUT_SECS`; the schema carries the same bounds. +const MIN_TRANSFER_TIMEOUT_SECS: i64 = 5; +const MAX_TRANSFER_TIMEOUT_SECS: i64 = 120; + +/// The oldest `schema_version` that may put `whisper` or `timeout_secs` +/// on a `transfer`. Twin: `model.ts` `TRANSFER_FIELDS_MIN_SCHEMA_VERSION`. +const TRANSFER_FIELDS_MIN_SCHEMA_VERSION: u32 = 3; + /// One thing wrong with a flow document. Carries enough context (node id, /// exit name, offending value) for the editor to point at it. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] @@ -109,9 +119,35 @@ pub enum ValidationError { declared: i64, }, + #[error( + "transfer node {node:?} sets {field}, which needs schema_version {required} (this document declares {declared})" + )] + FieldRequiresNewerSchema { + node: NodeId, + field: &'static str, + required: u32, + declared: i64, + }, + + #[error("transfer node {node:?} sets timeout_secs but has no whisper to screen with")] + TimeoutWithoutWhisper { node: NodeId }, + + #[error("transfer node {node:?} timeout_secs is {value} (allowed: {min}–{max})")] + TransferTimeoutOutOfRange { + node: NodeId, + value: i64, + min: i64, + max: i64, + }, + #[error("node {node:?} is a {kind} step, which an outbound call cannot run")] OutboundNodeNotAllowed { node: NodeId, kind: &'static str }, + #[error( + "transfer node {node:?} has no whisper: an outbound call must screen the person it hands the callee to" + )] + OutboundBlindTransfer { node: NodeId }, + #[error( "node {node:?} is on a loop that never waits for the callee, so an outbound call could repeat it forever" )] @@ -144,7 +180,11 @@ impl ValidationError { ValidationError::BookOutOfRange { .. } => "book_out_of_range", ValidationError::BookNeverOpen { .. } => "book_never_open", ValidationError::KindRequiresNewerSchema { .. } => "kind_requires_newer_schema", + ValidationError::FieldRequiresNewerSchema { .. } => "field_requires_newer_schema", + ValidationError::TimeoutWithoutWhisper { .. } => "timeout_without_whisper", + ValidationError::TransferTimeoutOutOfRange { .. } => "transfer_timeout_out_of_range", ValidationError::OutboundNodeNotAllowed { .. } => "outbound_node_not_allowed", + ValidationError::OutboundBlindTransfer { .. } => "outbound_blind_transfer", ValidationError::OutboundUnboundedLoop { .. } => "outbound_unbounded_loop", } } @@ -175,7 +215,19 @@ fn kind_min_schema_version(kind: &str) -> i64 { pub fn required_schema_version(flow: &Flow) -> i64 { flow.nodes .values() - .map(|node| kind_min_schema_version(node.kind())) + .map(|node| { + let fields = match node { + Node::Transfer { + whisper, + timeout_secs, + .. + } if whisper.is_some() || timeout_secs.is_some() => { + i64::from(TRANSFER_FIELDS_MIN_SCHEMA_VERSION) + } + _ => 1, + }; + kind_min_schema_version(node.kind()).max(fields) + }) .max() .unwrap_or(1) } @@ -207,6 +259,7 @@ pub fn validate(flow: &Flow) -> Result<(), Vec> { for (id, node) in &flow.nodes { check_exits(id, node, flow, &mut errs); check_node(id, node, &mut errs); + check_transfer_fields_version(id, node, flow.schema_version, &mut errs); // A component the document's own version doesn't have. Checked // per node rather than once per flow so the editor points at the @@ -237,14 +290,71 @@ pub fn validate(flow: &Flow) -> Result<(), Vec> { } } -/// The kinds a flow may use when it runs on a call the app *places*, with -/// no person standing by. Twin: `validate.ts` `OUTBOUND_KINDS`. +/// `whisper` and `timeout_secs` on a document older than the version that +/// has them. Reported per field, so the editor can say which one to drop +/// or which version to raise. +fn check_transfer_fields_version( + id: &NodeId, + node: &Node, + declared: i64, + errs: &mut Vec, +) { + let Node::Transfer { + whisper, + timeout_secs, + .. + } = node + else { + return; + }; + if declared >= i64::from(TRANSFER_FIELDS_MIN_SCHEMA_VERSION) { + return; + } + for (field, present) in [ + ("whisper", whisper.is_some()), + ("timeout_secs", timeout_secs.is_some()), + ] { + if present { + errs.push(ValidationError::FieldRequiresNewerSchema { + node: id.clone(), + field, + required: TRANSFER_FIELDS_MIN_SCHEMA_VERSION, + declared, + }); + } + } +} + +/// The kinds a flow may use on a call the app *places*, as of +/// `schema_version` 2 and earlier: no person is standing by. Kept for +/// compatibility; [`outbound_kinds`] is the version-aware list. Twin: +/// `validate.ts` `OUTBOUND_KINDS`. /// /// Left out: `ring` (there is nobody to hand the call to), `book` (it /// books against the number that called in, which an outbound call does -/// not have), and `transfer` (not offered on outbound calls yet). +/// not have), and `transfer` (not offered on outbound calls before +/// version 3). pub const OUTBOUND_KINDS: &[&str] = &["greeting", "menu", "message", "hangup", "hours"]; +/// [`OUTBOUND_KINDS`] plus what version 3 adds: `ring` and `transfer`, +/// because a person can now be reached on purpose. `transfer` must be +/// screened (see [`validate_outbound`]). +const OUTBOUND_KINDS_V3: &[&str] = &[ + "greeting", "menu", "message", "hangup", "hours", "ring", "transfer", +]; + +/// The kinds a flow declaring `schema_version` may use on an outbound +/// call. Version 2 and earlier get [`OUTBOUND_KINDS`], so a frozen +/// document keeps its verdict; version 3 adds `ring` and `transfer`. +/// Twin: `validate.ts` `outboundKinds`. +pub fn outbound_kinds(schema_version: u32) -> &'static [&'static str] { + if schema_version >= 3 { + OUTBOUND_KINDS_V3 + } else { + OUTBOUND_KINDS + } +} + /// Validate a flow for an **outbound** call: everything [`validate`] checks, /// plus the rules for a call the app places itself. /// @@ -254,10 +364,14 @@ pub const OUTBOUND_KINDS: &[&str] = &["greeting", "menu", "message", "hangup", " /// /// The outbound rules: /// -/// - every node is one of [`OUTBOUND_KINDS`] (`outbound_node_not_allowed`); +/// - every node is one of [`outbound_kinds`] for the document's version +/// (`outbound_node_not_allowed`); +/// - a `transfer` must be screened, i.e. carry a `whisper` +/// (`outbound_blind_transfer`) — the callee never lands on a person who +/// did not know a call was coming; /// - no loop reachable from `entry` is made only of moves that happen -/// without the callee — any exit of a `greeting` or `hours` step, or a -/// `menu`'s `no_input` exit. Such a loop, played into voicemail or to a +/// without the callee — any exit of a `greeting`, `hours` or `ring` step +/// or a screened `transfer`, or a `menu`'s `no_input` exit. Such a loop, played into voicemail or to a /// callee who stays silent, would never end (`outbound_unbounded_loop`). /// A loop through a menu's digit or `invalid` exits is fine: only a /// callee pressing keys can take it. @@ -265,16 +379,19 @@ pub const OUTBOUND_KINDS: &[&str] = &["greeting", "menu", "message", "hangup", " /// Twin: `validate.ts` `validateOutbound`. pub fn validate_outbound(flow: &Flow) -> Result<(), Vec> { let mut errs = validate(flow).err().unwrap_or_default(); + let allowed = outbound_kinds(flow.schema_version.clamp(0, i64::from(u32::MAX)) as u32); // In id order, so the errors come out the same every time. let mut nodes: Vec<(&NodeId, &Node)> = flow.nodes.iter().collect(); nodes.sort_by_key(|(id, _)| *id); for (id, node) in nodes { - if !OUTBOUND_KINDS.contains(&node.kind()) { + if !allowed.contains(&node.kind()) { errs.push(ValidationError::OutboundNodeNotAllowed { node: id.clone(), kind: node.kind(), }); + } else if matches!(node, Node::Transfer { .. }) && !node.is_screened_transfer() { + errs.push(ValidationError::OutboundBlindTransfer { node: id.clone() }); } } @@ -292,12 +409,18 @@ pub fn validate_outbound(flow: &Flow) -> Result<(), Vec> { } /// The exits a node takes without the callee doing anything: every exit of -/// a `greeting` (always `next`) or `hours` step (picked by the clock), and a +/// a `greeting` (always `next`), `hours` (picked by the clock), `ring` or +/// screened `transfer` step (`no_answer`: nobody picked up), and a /// `menu`'s `no_input` (taken when nobody presses a key — voicemail, say). fn silent_exits(node: &Node) -> Vec<&str> { let exits = node.exits().into_iter().flatten(); match node { - Node::Greeting { .. } | Node::Hours { .. } => exits.map(|(_, t)| t.as_str()).collect(), + Node::Greeting { .. } | Node::Hours { .. } | Node::Ring { .. } => { + exits.map(|(_, t)| t.as_str()).collect() + } + Node::Transfer { .. } if node.is_screened_transfer() => { + exits.map(|(_, t)| t.as_str()).collect() + } Node::Menu { .. } => exits .filter(|(key, _)| key.as_str() == "no_input") .map(|(_, t)| t.as_str()) @@ -438,10 +561,31 @@ fn check_node(id: &NodeId, node: &Node, errs: &mut Vec) { } Node::Ring { .. } => {} Node::Message { prompt, .. } => check_prompt(id, prompt, errs), - Node::Transfer { target, .. } => { + Node::Transfer { + target, + whisper, + timeout_secs, + .. + } => { if target.trim().is_empty() { errs.push(ValidationError::EmptyTransferTarget { node: id.clone() }); } + if let Some(p) = whisper { + check_prompt(id, p, errs); + } + if let Some(value) = *timeout_secs { + if whisper.is_none() { + errs.push(ValidationError::TimeoutWithoutWhisper { node: id.clone() }); + } + if !(MIN_TRANSFER_TIMEOUT_SECS..=MAX_TRANSFER_TIMEOUT_SECS).contains(&value) { + errs.push(ValidationError::TransferTimeoutOutOfRange { + node: id.clone(), + value, + min: MIN_TRANSFER_TIMEOUT_SECS, + max: MAX_TRANSFER_TIMEOUT_SECS, + }); + } + } } Node::Hangup { prompt, .. } => { if let Some(p) = prompt { @@ -1119,4 +1263,264 @@ nodes: assert!(codes.contains(&"unreachable"), "{codes:?}"); assert!(!codes.contains(&"outbound_unbounded_loop"), "{codes:?}"); } + + // ── screened transfer (schema_version 3) ───────────────────────────── + + const SCREENED: &str = r#" +schema_version: 3 +id: f +name: n +entry: t +nodes: + t: + kind: transfer + target: "+15551234567" + whisper: Press 1 to accept this call. + timeout_secs: 20 + exits: { no_answer: bye } + bye: + kind: hangup +"#; + + fn codes(src: &str) -> Vec<&'static str> { + validate(&parse(src)) + .err() + .unwrap_or_default() + .iter() + .map(ValidationError::code) + .collect() + } + + #[test] + fn a_screened_transfer_validates() { + assert_eq!(validate(&parse(SCREENED)), Ok(())); + } + + #[test] + fn screened_transfer_requires_no_answer() { + let src = SCREENED.replace(" exits: { no_answer: bye }\n", ""); + assert!(codes(&src).contains(&"missing_exits"), "{:?}", codes(&src)); + } + + #[test] + fn blind_transfer_has_no_exits_in_v3() { + let src = SCREENED + .replace(" whisper: Press 1 to accept this call.\n", "") + .replace(" timeout_secs: 20\n", ""); + assert_eq!(codes(&src), vec!["unexpected_exits"]); + let blind = src.replace(" exits: { no_answer: bye }\n", ""); + assert!(!codes(&blind).contains(&"unexpected_exits")); + } + + #[test] + fn whisper_in_v2_needs_v3() { + let src = SCREENED + .replace("schema_version: 3", "schema_version: 2") + .replace(" timeout_secs: 20\n", ""); + let errs = validate(&parse(&src)).unwrap_err(); + assert!(errs.contains(&ValidationError::FieldRequiresNewerSchema { + node: "t".into(), + field: "whisper", + required: 3, + declared: 2, + })); + assert_eq!(errs[0].code(), "field_requires_newer_schema"); + } + + #[test] + fn timeout_in_v2_needs_v3() { + let src = SCREENED + .replace("schema_version: 3", "schema_version: 1") + .replace(" whisper: Press 1 to accept this call.\n", "") + .replace(" exits: { no_answer: bye }\n", ""); + let errs = validate(&parse(&src)).unwrap_err(); + assert!(errs.contains(&ValidationError::FieldRequiresNewerSchema { + node: "t".into(), + field: "timeout_secs", + required: 3, + declared: 1, + })); + assert!(errs.contains(&ValidationError::TimeoutWithoutWhisper { node: "t".into() })); + } + + #[test] + fn timeout_without_whisper_refused() { + let src = SCREENED + .replace(" whisper: Press 1 to accept this call.\n", "") + .replace(" exits: { no_answer: bye }\n", ""); + assert!(codes(&src).contains(&"timeout_without_whisper")); + } + + #[test] + fn transfer_timeout_is_bounded() { + for (value, ok) in [ + (4, false), + (5, true), + (120, true), + (121, false), + (-1, false), + ] { + let src = SCREENED.replace("timeout_secs: 20", &format!("timeout_secs: {value}")); + let errs = validate(&parse(&src)).err().unwrap_or_default(); + assert_eq!(errs.is_empty(), ok, "timeout_secs {value}: {errs:?}"); + if !ok { + assert_eq!( + errs, + vec![ValidationError::TransferTimeoutOutOfRange { + node: "t".into(), + value, + min: 5, + max: 120, + }] + ); + assert_eq!(errs[0].code(), "transfer_timeout_out_of_range"); + } + } + } + + #[test] + fn an_overlong_whisper_is_refused() { + let src = SCREENED.replace( + "Press 1 to accept this call.", + &"a".repeat(MAX_PROMPT_CHARS + 1), + ); + assert_eq!(codes(&src), vec!["prompt_too_long"]); + } + + #[test] + fn a_screened_transfer_needs_v3() { + assert_eq!(required_schema_version(&parse(SCREENED)), 3); + let timeout_only = SCREENED.replace(" whisper: Press 1 to accept this call.\n", ""); + assert_eq!(required_schema_version(&parse(&timeout_only)), 3); + let blind = timeout_only.replace(" timeout_secs: 20\n", ""); + assert_eq!(required_schema_version(&parse(&blind)), 1); + } + + #[test] + fn a_screened_transfer_that_only_loops_traps_the_caller() { + // The hand-over can succeed, but a callee who never gets picked up + // must still reach an end. + let src = SCREENED.replace("no_answer: bye", "no_answer: t"); + assert!(codes(&src).contains(&"trapped"), "{:?}", codes(&src)); + } + + #[test] + fn outbound_kinds_by_version() { + assert_eq!(outbound_kinds(1), OUTBOUND_KINDS); + assert_eq!(outbound_kinds(2), OUTBOUND_KINDS); + assert_eq!( + outbound_kinds(3), + ["greeting", "menu", "message", "hangup", "hours", "ring", "transfer"] + ); + } + + const HANDOFF: &str = r#" +schema_version: 3 +id: f +name: n +entry: hello +nodes: + hello: + kind: greeting + prompt: This is a reminder about your appointment. + exits: { next: ask } + ask: + kind: menu + prompt: Press 1 to talk to someone, or 2 to confirm. + options: { "1": Talk, "2": Confirm } + exits: { "1": connect, "2": thanks, no_input: bye, invalid: ask } + connect: + kind: transfer + target: "+15551234567" + whisper: Press 1 to accept this call. + exits: { no_answer: sorry } + sorry: + kind: message + prompt: Nobody is free right now. Leave a message. + thanks: + kind: hangup + prompt: Thanks. + bye: + kind: hangup +"#; + + #[test] + fn v3_outbound_allows_ring_and_screened_transfer() { + assert_eq!(validate_outbound(&parse(HANDOFF)), Ok(())); + let with_ring = HANDOFF.replace( + " exits: { no_answer: sorry }\n", + " exits: { no_answer: desk }\n desk:\n kind: ring\n timeout_secs: 20\n exits: { no_answer: sorry }\n", + ); + assert_eq!(validate_outbound(&parse(&with_ring)), Ok(())); + } + + #[test] + fn v3_outbound_refuses_blind_transfer() { + let src = HANDOFF + .replace(" whisper: Press 1 to accept this call.\n", "") + .replace(" exits: { no_answer: sorry }\n", ""); + let errs = validate_outbound(&parse(&src)).unwrap_err(); + assert!(errs.contains(&ValidationError::OutboundBlindTransfer { + node: "connect".into() + })); + assert!(!outbound_codes(&src).contains(&"outbound_node_not_allowed")); + } + + #[test] + fn no_answer_loop_is_unbounded() { + // ring -> greeting -> ring, with no key press anywhere in between. + let src = r#" +schema_version: 3 +id: f +name: n +entry: r +nodes: + r: + kind: ring + timeout_secs: 20 + exits: { no_answer: again } + again: + kind: greeting + prompt: Trying again. + exits: { next: r } + bye: + kind: hangup +"#; + let codes = outbound_codes(src); + assert!(codes.contains(&"outbound_unbounded_loop"), "{codes:?}"); + } + + #[test] + fn a_screened_transfer_retrying_without_a_keypress_is_unbounded() { + // hello -> ask -(no_input)-> connect -(no_answer)-> hello: voicemail + // would pick up, ring out, and go round again for ever. + let src = HANDOFF + .replace("no_answer: sorry", "no_answer: hello") + .replace( + "no_input: bye, invalid: ask", + "no_input: connect, invalid: sorry", + ) + .replace(" bye:\n kind: hangup\n", ""); + assert_eq!(validate(&parse(&src)), Ok(())); + assert_eq!( + outbound_codes(&src), + vec![ + "outbound_unbounded_loop", + "outbound_unbounded_loop", + "outbound_unbounded_loop" + ] + ); + } + + #[test] + fn a_loop_that_needs_a_keypress_is_bounded() { + // hello -> ask -(1)-> connect -(no_answer)-> hello: only a callee + // pressing 1 can take the menu's digit exit. + let src = HANDOFF + .replace("no_answer: sorry", "no_answer: hello") + .replace("no_input: bye", "no_input: sorry") + .replace(" bye:\n kind: hangup\n", ""); + assert_eq!(validate(&parse(&src)), Ok(())); + assert_eq!(validate_outbound(&parse(&src)), Ok(())); + } } diff --git a/packages/flow-schema/src/index.ts b/packages/flow-schema/src/index.ts index 619e033..4c7e3dd 100644 --- a/packages/flow-schema/src/index.ts +++ b/packages/flow-schema/src/index.ts @@ -41,7 +41,7 @@ export type { ParseResult } from './parse.js'; export type { Comment } from './parse.js'; export { findComments, parseFlow } from './parse.js'; export { serializeFlow } from './serialize.js'; -export { OUTBOUND_KINDS, validateFlow, validateOutbound } from './validate.js'; +export { OUTBOUND_KINDS, outboundKinds, validateFlow, validateOutbound } from './validate.js'; export type { FlowCheck } from './check.js'; export { checkFlow } from './check.js'; export { isValidDate, isValidTimezone, parseTimeMinutes, validateHours } from './hours.js'; diff --git a/packages/flow-schema/src/model.ts b/packages/flow-schema/src/model.ts index c5826d6..fa417a2 100644 --- a/packages/flow-schema/src/model.ts +++ b/packages/flow-schema/src/model.ts @@ -60,6 +60,16 @@ export const SUPPORTED_SCHEMA_VERSIONS: readonly number[] = [1, 2, 3]; * `CURRENT_SCHEMA_VERSION`. */ export const CURRENT_SCHEMA_VERSION = 3; +/** The shortest and longest a screened transfer may ring the person's + * phone, in seconds. Twin: `validate.rs` `MIN_TRANSFER_TIMEOUT_SECS` / + * `MAX_TRANSFER_TIMEOUT_SECS`; the schema carries the same bounds. */ +export const MIN_TRANSFER_TIMEOUT_SECS = 5; +export const MAX_TRANSFER_TIMEOUT_SECS = 120; + +/** The oldest `schema_version` that may put `whisper` or `timeout_secs` on + * a `transfer`. Twin: `validate.rs` `TRANSFER_FIELDS_MIN_SCHEMA_VERSION`. */ +export const TRANSFER_FIELDS_MIN_SCHEMA_VERSION = 3; + /** Longest a spoken (text) prompt may be — see `validate.ts`. Twin: * `validate.rs` `MAX_PROMPT_CHARS`. */ export const MAX_PROMPT_CHARS = 2000; @@ -140,7 +150,17 @@ export const KIND_MIN_SCHEMA_VERSION: Record = { * Twin: `validate.rs` `required_schema_version`. */ export function requiredSchemaVersion(flow: Flow): number { - return Math.max(1, ...Object.values(flow.nodes).map((node) => KIND_MIN_SCHEMA_VERSION[node.kind])); + return Math.max( + 1, + ...Object.values(flow.nodes).map((node) => + Math.max( + KIND_MIN_SCHEMA_VERSION[node.kind], + node.kind === 'transfer' && (node.whisper !== undefined || node.timeout_secs !== undefined) + ? TRANSFER_FIELDS_MIN_SCHEMA_VERSION + : 1, + ), + ), + ); } /** @@ -163,12 +183,34 @@ export const DEFAULT_MESSAGE_TONE: MessageTone = 'beep'; // ── Helpers (logic layered on the generated types) ─────────────────────── /** - * Whether a caller who reaches this component can have the call *end* - * here. `ring` counts — its implicit `answered` hands the call to a - * human, which ends the flow. + * Whether this is a *screened* transfer: one with a `whisper`, which tells + * the person who picks up what the call is and waits for them to accept + * it. It can fail to connect, so it has a `no_answer` exit (a blind + * transfer hands the call over and is done). Twin: `model_ext.rs` + * `Node::is_screened_transfer`. */ -export function isTerminal(kind: string): boolean { - return kind === 'message' || kind === 'transfer' || kind === 'hangup' || kind === 'ring'; +export function isScreenedTransfer(node: Node): boolean { + return node.kind === 'transfer' && node.whisper !== undefined; +} + +/** + * Whether a caller who reaches this node can have the call *end* here. + * `ring` counts — its implicit `answered` hands the call to a human, + * which ends the flow. A blind `transfer` ends it too; a screened one may + * fall out of its `no_answer` exit instead, so it does not count and the + * "no caller is ever trapped" check follows that exit. + */ +export function isTerminal(node: Node): boolean { + switch (node.kind) { + case 'message': + case 'hangup': + case 'ring': + return true; + case 'transfer': + return !isScreenedTransfer(node); + default: + return false; + } } /** @@ -192,8 +234,9 @@ export function requiredExits(node: Node): string[] { // the day Google has an outage. case 'book': return ['booked', 'no_slots', 'no_input', 'unavailable']; - case 'message': case 'transfer': + return isScreenedTransfer(node) ? ['no_answer'] : []; + case 'message': case 'hangup': return []; default: diff --git a/packages/flow-schema/src/validate.ts b/packages/flow-schema/src/validate.ts index 2176e85..65e5681 100644 --- a/packages/flow-schema/src/validate.ts +++ b/packages/flow-schema/src/validate.ts @@ -12,12 +12,16 @@ // and menu/hours sanity caps. All problems are collected (not // fail-fast) so the editor can show every one at once. -import type { BookNode, ComponentKind, Flow, Prompt } from './model.js'; +import type { BookNode, ComponentKind, Flow, Prompt, TransferNode } from './model.js'; import { KIND_MIN_SCHEMA_VERSION, MAX_PROMPT_CHARS, + MAX_TRANSFER_TIMEOUT_SECS, + MIN_TRANSFER_TIMEOUT_SECS, SUPPORTED_SCHEMA_VERSIONS, + TRANSFER_FIELDS_MIN_SCHEMA_VERSION, VALID_DIGITS, + isScreenedTransfer, isTerminal, promptText, requiredExits, @@ -162,6 +166,7 @@ export function validateFlow(flow: Flow, nodeRanges: NodeRanges = {}): Issue[] { message: `transfer node "${id}" has an empty target`, }); } + checkTransferFields(id, node, flow.schema_version, issues, at); break; case 'hangup': if (node.prompt !== undefined) checkPrompt(id, node.prompt, issues, at); @@ -203,6 +208,54 @@ export function validateFlow(flow: Flow, nodeRanges: NodeRanges = {}): Issue[] { return issues; } +/** + * What a `transfer` may say about screening: the whisper is a prompt like + * any other, `timeout_secs` means nothing without one and is bounded, and + * both need a document that declares a version that has them. + */ +function checkTransferFields( + id: string, + node: TransferNode, + declared: number, + issues: Issue[], + at: (node: string) => Pick, +): void { + if (node.whisper !== undefined) checkPrompt(id, node.whisper, issues, at); + const timeout = node.timeout_secs; + if (timeout !== undefined) { + if (node.whisper === undefined) { + issues.push({ + ...at(id), + code: 'timeout_without_whisper', + message: `transfer node "${id}" sets timeout_secs but has no whisper to screen with`, + }); + } + if (timeout < MIN_TRANSFER_TIMEOUT_SECS || timeout > MAX_TRANSFER_TIMEOUT_SECS) { + issues.push({ + ...at(id), + code: 'transfer_timeout_out_of_range', + message: `transfer node "${id}" timeout_secs is ${timeout} (allowed: ${MIN_TRANSFER_TIMEOUT_SECS}–${MAX_TRANSFER_TIMEOUT_SECS})`, + params: { + value: timeout, + min: MIN_TRANSFER_TIMEOUT_SECS, + max: MAX_TRANSFER_TIMEOUT_SECS, + }, + }); + } + } + if (declared < TRANSFER_FIELDS_MIN_SCHEMA_VERSION) { + for (const field of ['whisper', 'timeout_secs'] as const) { + if (node[field] === undefined) continue; + issues.push({ + ...at(id), + code: 'field_requires_newer_schema', + message: `transfer node "${id}" sets ${field}, which needs schema_version ${TRANSFER_FIELDS_MIN_SCHEMA_VERSION} (this document declares ${declared})`, + params: { field, required: TRANSFER_FIELDS_MIN_SCHEMA_VERSION, declared }, + }); + } + } +} + /** * The `book` node's numeric bounds, and the one structural question a * schedule can fail: whether it leaves room for a single appointment. @@ -292,7 +345,7 @@ function checkGraph( // target qualifies. const canEnd = new Set(); for (const [id, node] of Object.entries(flow.nodes)) { - if (isTerminal(node.kind)) canEnd.add(id); + if (isTerminal(node)) canEnd.add(id); } let grew = true; while (grew) { @@ -345,12 +398,15 @@ function reachableFromEntry(flow: Flow): Set { // ── Outbound profile ───────────────────────────────────────────────────── /** - * The kinds a flow may use when it runs on a call the app *places*, with - * no person standing by. Twin: `validate.rs` `OUTBOUND_KINDS`. + * The kinds a flow may use on a call the app *places*, as of + * `schema_version` 2 and earlier: no person is standing by. Kept for + * compatibility; {@link outboundKinds} is the version-aware list. Twin: + * `validate.rs` `OUTBOUND_KINDS`. * * Left out: `ring` (there is nobody to hand the call to), `book` (it * books against the number that called in, which an outbound call does - * not have), and `transfer` (not offered on outbound calls yet). + * not have), and `transfer` (not offered on outbound calls before + * version 3). */ export const OUTBOUND_KINDS: readonly ComponentKind[] = [ 'greeting', @@ -360,6 +416,19 @@ export const OUTBOUND_KINDS: readonly ComponentKind[] = [ 'hours', ]; +const OUTBOUND_KINDS_V3: readonly ComponentKind[] = [...OUTBOUND_KINDS, 'ring', 'transfer']; + +/** + * The kinds a flow declaring `schemaVersion` may use on an outbound call. + * Version 2 and earlier get {@link OUTBOUND_KINDS}, so a frozen document + * keeps its verdict; version 3 adds `ring` and `transfer`, because a + * person can now be reached on purpose. `transfer` must be screened (see + * {@link validateOutbound}). Twin: `validate.rs` `outbound_kinds`. + */ +export function outboundKinds(schemaVersion: number): readonly ComponentKind[] { + return schemaVersion >= 3 ? OUTBOUND_KINDS_V3 : OUTBOUND_KINDS; +} + /** * Validate a flow for an **outbound** call: everything `validateFlow` * checks, plus the rules for a call the app places itself. @@ -369,10 +438,14 @@ export const OUTBOUND_KINDS: readonly ComponentKind[] = [ * * The outbound rules: * - * - every node is one of `OUTBOUND_KINDS` (`outbound_node_not_allowed`); + * - every node is one of `outboundKinds` for the document's version + * (`outbound_node_not_allowed`); + * - a `transfer` must be screened, i.e. carry a `whisper` + * (`outbound_blind_transfer`) — the callee never lands on a person who + * did not know a call was coming; * - no loop reachable from `entry` is made only of moves that happen - * without the callee — any exit of a `greeting` or `hours` step, or a - * `menu`'s `no_input` exit. Such a loop, played into voicemail or to a + * without the callee — any exit of a `greeting`, `hours` or `ring` step + * or a screened `transfer`, or a `menu`'s `no_input` exit. Such a loop, played into voicemail or to a * callee who stays silent, would never end (`outbound_unbounded_loop`). * A loop through a menu's digit or `invalid` exits is fine: only a * callee pressing keys can take it. @@ -387,15 +460,23 @@ export function validateOutbound(flow: Flow, nodeRanges: NodeRanges = {}): Issue range: nodeRanges[node], }); + const allowed = outboundKinds(flow.schema_version); for (const id of Object.keys(flow.nodes).sort()) { const node = flow.nodes[id]; - if (node && !OUTBOUND_KINDS.includes(node.kind as ComponentKind)) { + if (!node) continue; + if (!allowed.includes(node.kind as ComponentKind)) { issues.push({ ...at(id), code: 'outbound_node_not_allowed', message: `node "${id}" is a ${node.kind} step, which an outbound call cannot run`, params: { kind: node.kind }, }); + } else if (node.kind === 'transfer' && !isScreenedTransfer(node)) { + issues.push({ + ...at(id), + code: 'outbound_blind_transfer', + message: `transfer node "${id}" has no whisper: an outbound call must screen the person it hands the callee to`, + }); } } @@ -411,7 +492,8 @@ export function validateOutbound(flow: Flow, nodeRanges: NodeRanges = {}): Issue } /** The exits a node takes without the callee doing anything: every exit of - * a `greeting` (always `next`) or `hours` step (picked by the clock), and a + * a `greeting` (always `next`), `hours` (picked by the clock), `ring` or + * screened `transfer` step (`no_answer`: nobody picked up), and a * `menu`'s `no_input` (taken when nobody presses a key — voicemail, say). */ function silentExits(node: Flow['nodes'][string] | undefined): string[] { if (!node) return []; @@ -419,7 +501,10 @@ function silentExits(node: Flow['nodes'][string] | undefined): string[] { switch (node.kind) { case 'greeting': case 'hours': + case 'ring': return exits.map(([, target]) => target); + case 'transfer': + return isScreenedTransfer(node) ? exits.map(([, target]) => target) : []; case 'menu': return exits.filter(([key]) => key === 'no_input').map(([, target]) => target); default: diff --git a/packages/flow-schema/test/outbound.test.ts b/packages/flow-schema/test/outbound.test.ts index 5e265a1..1cc7c50 100644 --- a/packages/flow-schema/test/outbound.test.ts +++ b/packages/flow-schema/test/outbound.test.ts @@ -4,8 +4,9 @@ import { describe, expect, it } from 'vitest'; +import { requiredExits, requiredSchemaVersion } from '../src/model.js'; import { parseFlow } from '../src/parse.js'; -import { validateFlow, validateOutbound } from '../src/validate.js'; +import { outboundKinds, OUTBOUND_KINDS, validateFlow, validateOutbound } from '../src/validate.js'; function flowOf(source: string) { const parsed = parseFlow(source); @@ -163,3 +164,212 @@ nodes: expect(codes).not.toContain('outbound_unbounded_loop'); }); }); + +// ── screened transfer (schema_version 3) ───────────────────────────────── +// Twins of the screened-transfer tests in `validate.rs`. + +const SCREENED = ` +schema_version: 3 +id: f +name: n +entry: t +nodes: + t: + kind: transfer + target: "+15551234567" + whisper: Press 1 to accept this call. + timeout_secs: 20 + exits: { no_answer: bye } + bye: + kind: hangup +`; + +const codes = (source: string): string[] => validateFlow(flowOf(source)).map((i) => i.code); +const without = (source: string, ...lines: string[]): string => + lines.reduce((acc, line) => acc.replace(line, ''), source); +const WHISPER = ' whisper: Press 1 to accept this call.\n'; +const TIMEOUT = ' timeout_secs: 20\n'; +const NO_ANSWER = ' exits: { no_answer: bye }\n'; + +describe('screened transfer', () => { + it('validates', () => { + expect(validateFlow(flowOf(SCREENED))).toEqual([]); + }); + + it('requires no_answer', () => { + expect(codes(without(SCREENED, NO_ANSWER))).toContain('missing_exits'); + }); + + it('has no exits when blind, in v3', () => { + const blind = without(SCREENED, WHISPER, TIMEOUT); + expect(codes(blind)).toEqual(['unexpected_exits']); + expect(codes(without(blind, NO_ANSWER))).not.toContain('unexpected_exits'); + }); + + it('needs v3 for whisper', () => { + const issues = validateFlow( + flowOf(without(SCREENED, TIMEOUT).replace('schema_version: 3', 'schema_version: 2')), + ).filter((i) => i.code === 'field_requires_newer_schema'); + expect(issues.map((i) => i.params)).toEqual([{ field: 'whisper', required: 3, declared: 2 }]); + }); + + it('needs v3 for timeout_secs', () => { + const v1 = without(SCREENED, WHISPER, NO_ANSWER).replace('schema_version: 3', 'schema_version: 1'); + const found = codes(v1); + expect(found).toContain('field_requires_newer_schema'); + expect(found).toContain('timeout_without_whisper'); + }); + + it('refuses timeout_secs without whisper', () => { + expect(codes(without(SCREENED, WHISPER, NO_ANSWER))).toContain('timeout_without_whisper'); + }); + + it('bounds timeout_secs to 5..120', () => { + for (const [value, ok] of [ + [4, false], + [5, true], + [120, true], + [121, false], + ] as const) { + const issues = validateFlow( + flowOf(SCREENED.replace('timeout_secs: 20', `timeout_secs: ${value}`)), + ); + expect(issues.length === 0, `timeout_secs ${value}`).toBe(ok); + if (!ok) { + expect(issues.map((i) => [i.code, i.params])).toEqual([ + ['transfer_timeout_out_of_range', { value, min: 5, max: 120 }], + ]); + } + } + }); + + it('applies the prompt-length cap to the whisper', () => { + const long = SCREENED.replace('Press 1 to accept this call.', 'a'.repeat(2001)); + expect(codes(long)).toEqual(['prompt_too_long']); + }); + + it('needs schema_version 3 only when it uses the new fields', () => { + expect(requiredSchemaVersion(flowOf(SCREENED))).toBe(3); + const timeoutOnly = without(SCREENED, WHISPER); + expect(requiredSchemaVersion(flowOf(timeoutOnly))).toBe(3); + expect(requiredSchemaVersion(flowOf(without(timeoutOnly, TIMEOUT)))).toBe(1); + }); + + it('does not count as a way to end the call', () => { + expect(codes(SCREENED.replace('no_answer: bye', 'no_answer: t'))).toContain('trapped'); + }); + + it('wires no_answer in requiredExits', () => { + const flow = flowOf(SCREENED); + expect(requiredExits(flow.nodes.t as never)).toEqual(['no_answer']); + }); +}); + +const HANDOFF = ` +schema_version: 3 +id: f +name: n +entry: hello +nodes: + hello: + kind: greeting + prompt: This is a reminder about your appointment. + exits: { next: ask } + ask: + kind: menu + prompt: Press 1 to talk to someone, or 2 to confirm. + options: { "1": Talk, "2": Confirm } + exits: { "1": connect, "2": thanks, no_input: bye, invalid: ask } + connect: + kind: transfer + target: "+15551234567" + whisper: Press 1 to accept this call. + exits: { no_answer: sorry } + sorry: + kind: message + prompt: Nobody is free right now. Leave a message. + thanks: + kind: hangup + prompt: Thanks. + bye: + kind: hangup +`; + +describe('validateOutbound, version 3', () => { + it('lists the kinds by version', () => { + expect(outboundKinds(1)).toEqual(OUTBOUND_KINDS); + expect(outboundKinds(2)).toEqual(OUTBOUND_KINDS); + expect(outboundKinds(3)).toEqual([ + 'greeting', + 'menu', + 'message', + 'hangup', + 'hours', + 'ring', + 'transfer', + ]); + }); + + it('allows ring and a screened transfer', () => { + expect(validateOutbound(flowOf(HANDOFF))).toEqual([]); + const withRing = HANDOFF.replace( + ' exits: { no_answer: sorry }\n', + ' exits: { no_answer: desk }\n desk:\n kind: ring\n timeout_secs: 20\n exits: { no_answer: sorry }\n', + ); + expect(validateOutbound(flowOf(withRing))).toEqual([]); + }); + + it('refuses a blind transfer', () => { + const blind = without( + HANDOFF, + ' whisper: Press 1 to accept this call.\n', + ' exits: { no_answer: sorry }\n', + ); + const found = outboundCodes(blind); + expect(found).toContain('outbound_blind_transfer'); + expect(found).not.toContain('outbound_node_not_allowed'); + }); + + it('still refuses ring and transfer in version 2', () => { + const v2 = HANDOFF.replace('schema_version: 3', 'schema_version: 2'); + expect(outboundCodes(v2)).toContain('outbound_node_not_allowed'); + }); + + it('treats a no_answer loop as unbounded', () => { + const loop = ` +schema_version: 3 +id: f +name: n +entry: r +nodes: + r: + kind: ring + timeout_secs: 20 + exits: { no_answer: again } + again: + kind: greeting + prompt: Trying again. + exits: { next: r } + bye: + kind: hangup +`; + expect(outboundCodes(loop)).toContain('outbound_unbounded_loop'); + + const viaMenu = HANDOFF.replace('no_answer: sorry', 'no_answer: hello') + .replace('no_input: bye, invalid: ask', 'no_input: connect, invalid: sorry') + .replace(' bye:\n kind: hangup\n', ''); + expect(validateFlow(flowOf(viaMenu))).toEqual([]); + expect(outboundCodes(viaMenu)).toEqual([ + 'outbound_unbounded_loop', + 'outbound_unbounded_loop', + 'outbound_unbounded_loop', + ]); + }); + + it('treats a loop that needs a keypress as bounded', () => { + const src = HANDOFF.replace('no_answer: sorry', 'no_answer: hello') + .replace('no_input: bye', 'no_input: sorry') + .replace(' bye:\n kind: hangup\n', ''); + expect(validateOutbound(flowOf(src))).toEqual([]); + }); +}); From 23d8d70fcadee92f380a404e0d744f2cf77d3297 Mon Sep 17 00:00:00 2001 From: Eason WaveKat Date: Sat, 31 Oct 2026 18:45:26 +1300 Subject: [PATCH 3/4] feat: add screened transfer engine effect --- crates/wavekat-flow/src/engine.rs | 257 ++++++++++++++++++++++++++++++ crates/wavekat-flow/src/trace.rs | 3 + 2 files changed, 260 insertions(+) diff --git a/crates/wavekat-flow/src/engine.rs b/crates/wavekat-flow/src/engine.rs index a6efbd6..dd1d234 100644 --- a/crates/wavekat-flow/src/engine.rs +++ b/crates/wavekat-flow/src/engine.rs @@ -133,6 +133,22 @@ pub enum RingOutcome { NoAnswer, } +/// Result of a screened `transfer`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ScreenOutcome { + /// The person picked up, heard the whisper and accepted — they own the + /// call now and the engine steps out. + Connected, + /// Nobody picked up, or they declined, within the window. + NoAnswer, + /// The attempt could not be made or broke down (the reason is for logs). + Failed(String), +} + +/// How long a screened transfer waits for the person when the node sets no +/// `timeout_secs`. +pub const DEFAULT_SCREEN_TIMEOUT_SECS: u64 = 25; + /// The side effects the components need. The engine calls these; the impl /// performs the telephony/audio. `&mut self` because a real impl holds the /// live call. Methods return `anyhow::Result` so the daemon impl can surface @@ -160,6 +176,23 @@ pub trait FlowEffects: Send { /// Blind-transfer the call to `target`. async fn transfer(&mut self, target: &str) -> anyhow::Result<()>; + /// Screened transfer: ring `target`, play `whisper` to whoever picks up, + /// and connect the caller only once they accept. `NoAnswer` and `Failed` + /// leave the caller on the line, so the flow continues from the node's + /// `no_answer` exit. + /// + /// The default reports `Failed`, so an implementor that cannot screen + /// (and predates this method) still compiles and the flow falls through + /// to its `no_answer` exit instead of aborting. + async fn screened_transfer( + &mut self, + _target: &str, + _whisper: &Prompt, + _timeout: Duration, + ) -> anyhow::Result { + Ok(ScreenOutcome::Failed("not available on this call".into())) + } + /// Speak an optional goodbye and end the call. async fn hangup(&mut self, prompt: Option<&Prompt>) -> anyhow::Result<()>; @@ -359,6 +392,41 @@ async fn run_node( Ok(Step::End(FlowOutcome::MessageLeft)) } + Node::Transfer { + target, + whisper: Some(whisper), + timeout_secs, + .. + } => { + let timeout = Duration::from_secs( + timeout_secs + .map(|s| s.max(0) as u64) + .unwrap_or(DEFAULT_SCREEN_TIMEOUT_SECS), + ); + let outcome = fx + .screened_transfer(target, whisper, timeout) + .await + .map_err(EngineError::Effect)?; + let (label, connected) = match outcome { + ScreenOutcome::Connected => ("connected", true), + ScreenOutcome::NoAnswer => ("no_answer", false), + ScreenOutcome::Failed(_) => ("failed", false), + }; + trace.push( + id, + kind, + StepDetail::Screened { + target: target.clone(), + outcome: label.into(), + }, + ); + if connected { + Ok(Step::End(FlowOutcome::Transferred)) + } else { + goto(id, node, "no_answer") + } + } + Node::Transfer { target, .. } => { fx.transfer(target).await.map_err(EngineError::Effect)?; trace.push( @@ -678,8 +746,10 @@ mod tests { now: OffsetDateTime, digits: VecDeque>, ring: RingOutcome, + screen: ScreenOutcome, message_secs: u32, // observed: + screened: Option<(String, Duration)>, spoken: Vec, transferred: Option, recorded: bool, @@ -706,6 +776,8 @@ mod tests { now, digits: VecDeque::new(), ring: RingOutcome::NoAnswer, + screen: ScreenOutcome::NoAnswer, + screened: None, message_secs: 0, spoken: Vec::new(), transferred: None, @@ -742,6 +814,10 @@ mod tests { self.ring = r; self } + fn screen(mut self, o: ScreenOutcome) -> Self { + self.screen = o; + self + } fn message_secs(mut self, s: u32) -> Self { self.message_secs = s; self @@ -787,6 +863,15 @@ mod tests { self.transferred = Some(target.to_string()); Ok(()) } + async fn screened_transfer( + &mut self, + target: &str, + _whisper: &Prompt, + timeout: Duration, + ) -> anyhow::Result { + self.screened = Some((target.to_string(), timeout)); + Ok(self.screen.clone()) + } async fn hangup(&mut self, prompt: Option<&Prompt>) -> anyhow::Result<()> { if let Some(p) = prompt { self.spoken.push(prompt_label(p)); @@ -1313,4 +1398,176 @@ nodes: assert_eq!(trace.outcome, FlowOutcome::Transferred); assert_eq!(fx.transferred.as_deref(), Some("sip:desk@example.com")); } + + const SCREENED: &str = r#" +schema_version: 3 +id: f +name: n +entry: t +nodes: + t: + kind: transfer + target: sip:desk@example.com + whisper: Outbound call for you + exits: { no_answer: bye } + bye: + kind: hangup +"#; + + const SCREENED_TIMEOUT: &str = r#" +schema_version: 3 +id: f +name: n +entry: t +nodes: + t: + kind: transfer + target: sip:desk@example.com + whisper: Outbound call for you + timeout_secs: 40 + exits: { no_answer: bye } + bye: + kind: hangup +"#; + + async fn run_screened(src: &str, fx: &mut MockEffects) -> Trace { + let flow = Flow::from_yaml(src).unwrap(); + validate(&flow).unwrap(); + run_trace(&flow, fx).await + } + + fn screened_step(trace: &Trace) -> &StepDetail { + &trace + .steps + .iter() + .find(|s| matches!(s.detail, StepDetail::Screened { .. })) + .expect("a Screened step") + .detail + } + + #[tokio::test] + async fn screened_transfer_connected_ends_transferred() { + let mut fx = MockEffects::new(open_time()).screen(ScreenOutcome::Connected); + let trace = run_screened(SCREENED, &mut fx).await; + assert_eq!(trace.outcome, FlowOutcome::Transferred); + assert_eq!( + trace.steps.last().unwrap().detail, + StepDetail::Screened { + target: "sip:desk@example.com".into(), + outcome: "connected".into() + } + ); + assert!(!fx.hung_up); + } + + #[tokio::test] + async fn screened_transfer_no_answer_takes_exit() { + let mut fx = MockEffects::new(open_time()).screen(ScreenOutcome::NoAnswer); + let trace = run_screened(SCREENED, &mut fx).await; + assert_eq!( + screened_step(&trace), + &StepDetail::Screened { + target: "sip:desk@example.com".into(), + outcome: "no_answer".into() + } + ); + assert_eq!(trace.steps.last().unwrap().detail, StepDetail::HungUp); + assert!(fx.hung_up); + assert!(fx.transferred.is_none()); + } + + #[tokio::test] + async fn screened_transfer_failed_takes_exit() { + let mut fx = MockEffects::new(open_time()).screen(ScreenOutcome::Failed("boom".into())); + let trace = run_screened(SCREENED, &mut fx).await; + assert_eq!( + screened_step(&trace), + &StepDetail::Screened { + target: "sip:desk@example.com".into(), + outcome: "failed".into() + } + ); + assert_eq!(trace.steps.last().unwrap().detail, StepDetail::HungUp); + assert!(fx.hung_up); + } + + #[tokio::test] + async fn screened_transfer_default_timeout_is_25s() { + let mut fx = MockEffects::new(open_time()); + run_screened(SCREENED, &mut fx).await; + assert_eq!( + fx.screened, + Some(("sip:desk@example.com".into(), Duration::from_secs(25))) + ); + } + + #[tokio::test] + async fn screened_transfer_uses_node_timeout() { + let mut fx = MockEffects::new(open_time()); + run_screened(SCREENED_TIMEOUT, &mut fx).await; + assert_eq!( + fx.screened, + Some(("sip:desk@example.com".into(), Duration::from_secs(40))) + ); + } + + /// An effects impl written before `screened_transfer` existed: the + /// default must not abort the call. + struct LegacyEffects { + hung_up: bool, + } + + #[async_trait] + impl FlowEffects for LegacyEffects { + async fn speak(&mut self, _p: &Prompt) -> anyhow::Result<()> { + Ok(()) + } + async fn collect_digit(&mut self, _t: Duration) -> anyhow::Result> { + Ok(None) + } + async fn ring_human(&mut self, _t: Duration) -> anyhow::Result { + Ok(RingOutcome::NoAnswer) + } + async fn record_message( + &mut self, + _tone: MessageTone, + _m: Duration, + ) -> anyhow::Result { + Ok(0) + } + async fn transfer(&mut self, _t: &str) -> anyhow::Result<()> { + Ok(()) + } + async fn hangup(&mut self, _p: Option<&Prompt>) -> anyhow::Result<()> { + self.hung_up = true; + Ok(()) + } + async fn fetch_slots(&mut self, _q: &SlotQuery<'_>) -> anyhow::Result { + anyhow::bail!("unused") + } + async fn book_slot(&mut self, _s: &Slot) -> anyhow::Result { + anyhow::bail!("unused") + } + fn now(&self) -> OffsetDateTime { + open_time() + } + } + + #[tokio::test] + async fn default_screened_transfer_impl_fails_gracefully() { + let flow = Flow::from_yaml(SCREENED).unwrap(); + validate(&flow).unwrap(); + let mut fx = LegacyEffects { hung_up: false }; + let mut trace = Trace::new(&flow.id, flow.version); + run(&flow, &mut fx, &mut trace).await; + assert_eq!( + screened_step(&trace), + &StepDetail::Screened { + target: "sip:desk@example.com".into(), + outcome: "failed".into() + } + ); + assert!(fx.hung_up); + assert_ne!(trace.outcome, FlowOutcome::Aborted); + } } diff --git a/crates/wavekat-flow/src/trace.rs b/crates/wavekat-flow/src/trace.rs index b67b37f..2e878ee 100644 --- a/crates/wavekat-flow/src/trace.rs +++ b/crates/wavekat-flow/src/trace.rs @@ -107,6 +107,9 @@ pub enum StepDetail { MessageRecorded { secs: u32 }, /// A blind transfer was placed. Transferred { target: String }, + /// A screened transfer was attempted. `outcome` is `connected`, + /// `no_answer` or `failed`. + Screened { target: String, outcome: String }, /// The flow spoke an optional goodbye and hung up. HungUp, /// A `book` node read the calendar and offered this many times. From 7fba8a584042d1f4d3f47db0f15406846784a306 Mon Sep 17 00:00:00 2001 From: Eason WaveKat Date: Sat, 31 Oct 2026 20:15:50 +1300 Subject: [PATCH 4/4] test: drop accept prompt from v3 whispers --- conformance/v3/invalid/screened-transfer-missing-no-answer.yaml | 2 +- conformance/v3/invalid/transfer-timeout-out-of-range.yaml | 2 +- conformance/v3/outbound/valid/interview-reminder.yaml | 2 +- conformance/v3/valid/screened-transfer.yaml | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/conformance/v3/invalid/screened-transfer-missing-no-answer.yaml b/conformance/v3/invalid/screened-transfer-missing-no-answer.yaml index 12f0619..7e1e44c 100644 --- a/conformance/v3/invalid/screened-transfer-missing-no-answer.yaml +++ b/conformance/v3/invalid/screened-transfer-missing-no-answer.yaml @@ -6,4 +6,4 @@ nodes: person: kind: transfer target: "+15551230100" - whisper: A caller asked to talk to someone. Press any key to accept. + whisper: A caller asked to talk to someone. diff --git a/conformance/v3/invalid/transfer-timeout-out-of-range.yaml b/conformance/v3/invalid/transfer-timeout-out-of-range.yaml index e6fc6e7..30222c5 100644 --- a/conformance/v3/invalid/transfer-timeout-out-of-range.yaml +++ b/conformance/v3/invalid/transfer-timeout-out-of-range.yaml @@ -6,7 +6,7 @@ nodes: person: kind: transfer target: "+15551230100" - whisper: A caller asked to talk to someone. Press any key to accept. + whisper: A caller asked to talk to someone. timeout_secs: 300 exits: { no_answer: bye } bye: diff --git a/conformance/v3/outbound/valid/interview-reminder.yaml b/conformance/v3/outbound/valid/interview-reminder.yaml index 58b4987..bbe7459 100644 --- a/conformance/v3/outbound/valid/interview-reminder.yaml +++ b/conformance/v3/outbound/valid/interview-reminder.yaml @@ -15,7 +15,7 @@ nodes: person: kind: transfer target: "+15551230100" - whisper: A candidate asked to speak to someone about an interview. Press any key to accept. + whisper: Interview reminder call. The candidate asked to talk to someone. timeout_secs: 20 exits: { no_answer: desk } desk: diff --git a/conformance/v3/valid/screened-transfer.yaml b/conformance/v3/valid/screened-transfer.yaml index f6cd6aa..1c89de7 100644 --- a/conformance/v3/valid/screened-transfer.yaml +++ b/conformance/v3/valid/screened-transfer.yaml @@ -18,7 +18,7 @@ nodes: target: "+15551230100" whisper: audio: vprompt_whisper01 - transcript: A caller asked to talk to someone. Press any key to accept. + transcript: A caller asked to talk to someone. timeout_secs: 20 exits: no_answer: goodbye