# Yunke — the brain of each call (per-recipient instructions)

Part of the [AI Voice Agent](/docs/modules_handbook/shared/voice-agent/readMe.md).
Added 2026-10-31. This delivery uses synthetic HTTP responses and an isolated local test
database. No runtime controls were enabled, cloud content changed or phone tasks created.

## What it does

A Yunke App phone profile carries the **brain** of its calls in `provider_settings.scenario_prompt`
(up to 4,000 characters since 2026-11-11; 200 before). A funnel rule chooses its profile as
before, so separate welcome, reminder and missed-session rules use separate brains without
switching the account's script.

**The App's current script is a fixed shell** (owner, 2026-11-11): its prompt is the universal
rules (it is an AI, how it talks, what it never does) plus `{{客户备注}}`, and its personalised
opening greets `{{客户名称}}`. The brain arrives as that remark with every task, and the lead's
first name as the customer name, so a campaign is written in the CRM and never in the App. Only
the opening audio, voice and knowledge base still live there. Yunke's own summary is no longer
used: our AI reads the transcript (`ReadAiVoiceCall`) and fills the profile's extraction fields,
exactly as for a Retell profile on `analysis_mode = own`; a phone profile is always on that mode.

**Scene delivery defaults ON after deployment (owner request, 2026-11-01).** No extra
environment entry or sixth enablement step is required. The existing five console controls,
matching credentials, exact-number allowlist, active profile and funnel rule still govern
execution; this default does not enable calling or change saved controls. An explicit
`YUNKE_APP_SCENARIOS_ENABLED=false` remains an installation-level override and refuses
configured scenes with `yunke_scenario_unverified` before binding/HTTP.

The instructions supplement the existing cloud script. They do not replace its opening
audio, voice, knowledge base or model settings. The editor's three examples are editable
drafts, not approved business scripts. Choosing the missed-session example does not select
an audience: configure the funnel rule's attendance condition separately.

## How it works

- The platform Yunke console's profile editor saves the optional instructions locally and
  pauses the profile. Saving does not change any of the five runtime gates or call a vendor API.
  Omitted fields preserve an existing scenario; an explicitly blank field removes it.
- Assignment reuses Retell's existing `FunnelAutomationMessage.ai_call_profile_id` and
  `SendFunnelAiCall` path, not a second scene router. The shared picker/request contract
  `AiCallProfile::canAssignToFunnel()` lists published active Retell profiles and complete
  platform App-mode Yunke profiles, including paused Yunke drafts. It does not require
  Retell IDs or `synced_at` for Yunke. Incomplete/legacy/agency phone profiles are excluded.
  Published Retell options remain first, preserving the form's existing default selection.
  Saving a rule never enables the selected profile, sessions or runtime controls. At execution,
  the unchanged job requires `isCallable()` and passes that registration's original variables.
- Nonempty scenarios enter the profile's canonical settings as `yunke_scenario_prompt`.
  Existing Retell hashes and Yunke profiles without scenarios are unchanged. A call freezes
  the template, settings version/hash and original dynamic variables before submission.
- `YunkeConversationalCaller` renders that frozen template and sends the result as the
  single recipient's `execlDataList[0].otherInfo`, with the lead's first name (printable,
  40 characters at most) as `customerName` for the shell's opening. The ordinary App session
  builder reads both directly from the active task, without a phone-local import/cache write.
  It never calls `updatePrompt`
  or `script/changeEffective` and never sends a guessed task-level script ID.
- Supported placeholders are `name`, `lead_name`, `first_name`, `funnel`, `event_title`, `event_date`,
  `event_time`, `watched_minutes` and `completion_percent`, inside `{{...}}`.
  The existing funnel composer already supplies these; no changes to rule dispatch are needed.
  The shared job supplies `lead_name` as the same alias used by Retell's profile examples.
  Only referenced values enter the instructions. In particular, the full variable bag and
  magic login/ticket links are not copied to the vendor task.
- Missing/empty variables, unsupported placeholders, malformed UTF-8/control characters,
  and rendered instructions longer than **4,000 UTF-16 units** refuse before creating a binding
  or making HTTP requests (`invalid_yunke_scenario`). Never silently truncate instructions.
  This is petaV3's own bound, not a published server limit for `otherInfo`: the App's prompt
  field takes 12,000, the longest brain proven live is 150 characters (prod, 2026-11-10), and
  the first shell call records the next figure here. A task Yunke rejects as too long hands
  the call to the profile's Retell backup instead of ringing with a cut-off brain.
- The APK's customer-context reader queries its local cache by phone. A shared identity/phone
  lock serialises the ledger check and submission across profiles. An unsettled accepted/unknown
  binding for the same phone blocks a new scenario. An existing scene also blocks a new
  plain task for that phone (`yunke_scenario_pending`). A local timeout is not proof the
  vendor task stopped. Explicit operator closure follows the existing stop runbook.
- Replaying an already claimed call returns its original receipt and never sends a second
  task or substitutes the profile's newly edited scenario.

### API-to-session static trace

Source: the previously acquired **APK 2.0.20**, inspected offline on 2026-10-31 with the
existing REA/JADX toolchain and decoded DEX instructions. APK SHA-256:
`100ffdb27f72b96f82013314e2eb73fe8b4e0501746811c173eb41d3c1f36bc9`.
No App, phone, browser session or vendor API was operated during this analysis.

| Hop | Observed contract |
|---|---|
| Create task | `hm0` sends `PhoneCustomersBean` in `execlDataList` to `ApiService.saveTask` (`/phone-ai-call/app/aiCallOut/save`). Both `otherInfo` and `additionalNotes` are declared customer fields. |
| Server storage and echo | **Not observable from the APK.** Saving and returning this exact customer's `otherInfo` still needs vendor confirmation or a bounded live test. A fake response cannot prove it. |
| Scheduled execution | `mq3.z` launches `xp3`; `AITaskDetailActivity.onScheduledLoadAndDial` reaches `startAICallAfterPauseApi` and `f2.R`, then `f2.o` launches `z1`. |
| Phone fetch | `z1` calls `sd.u` → `ApiService.getOutPhoneList`, POST `/phone-ai-call/app/aiCallOut/taskDetailPageLight`, with `taskId`, `callStatus`, `pageNum=1`, `pageSize=50`. Returned `TaskDetailPageBean.data` contains `TaskDetailBean` objects. |
| Active task | `z1` → `f2.d` / `x1` → `f2.c` queues those objects; `f2.O` sets the scheduled slot through `g50.t`. `g50.j(phone)` selects the matching active/preserved task by normalized phone and call sequence. A mismatched task is not a valid scene source. |
| Context injection | `iv3.a` calls `g50.j(phone).getOtherInfo()`; nonempty text replaces the cached customer remark and is appended under customer context in `dialog.system_role`. This ordinary path does not need a placeholder in the base script or a local cache insert. |
| Send to AI | `rv0.b` sends `iv3.a` as a StartSession payload (event 100). `ay0.b` also starts from `iv3.a` and carries its `system_role` into an `instructions` envelope. These are inspected code paths, not an observation of the current phone's selected mode. |

This corrects the earlier `additionalNotes` candidate. `iv3` reads that field from
`CallTaskCustomerDbBean`, truncates it to 200 Kotlin characters and prepends it to the
base script. `bm0` populates it during **phone-local document import**; no API-to-cache
write was established. The corrected sender uses only `otherInfo`, not both fields.
Generic batch adapters still accept both native customer fields for their existing uses.

### Mode limits and remaining live acceptance

- Ordinary `iv3` calls retain the selected global script, opening and other context.
  Custom-task mode (`g50.l()` with a nonempty effective prompt) uses a pure custom prompt
  and skips customer-context injection. Remote overrides/task-ignore-common-prompt can also
  change the result. They are not certified for scene delivery.
- Other inspected socket paths (`qv0`, `fu4`) use `tg2.u` for base instructions rather than
  unconditionally appending task context. Its `rs3`/`qs3` customer-remark expansion resolves
  `task.otherInfo` through `tg2.b0`, but only if the selected script contains the corresponding
  customer-remark placeholder. Do not treat one successful engine as coverage of all modes.
- Cached `additionalNotes` can still be prepended by `iv3`, even though petaV3 no longer sends
  that field. The ledger lock prevents overlapping petaV3 tasks, not stale phone context or
  manual/external tasks. Verify the effective prompt has no conflicting old instructions.
- `ApiService.updatePrompt` / `ws3` carries `instructions` and `openHistoryMessage` without
  a task ID. It is account/user scope and is never a per-task fallback here.

The App-side **static** path is now traced without relying on local import. Cloud echo,
the current phone/mode and actual spoken behavior remain **unverified**. The owner-approved
deployment default is not evidence of live acceptance. A separately approved owner-number
test must correlate the exact task/subtask,
returned `otherInfo`, matching session prompt, distinctive scene response and result binding,
then replay collection to verify deduplication. Record unavailable evidence as unverified;
do not install hooks, elevate phone permissions or mutate global scripts to fill a gap.
Read the App's existing logs passively; do not add calls to its queue-fetch endpoints to
petaV3 as a presumed read-only probe. Do not overlap the test with external/manual tasks.

The corrected regression first failed because the sender still used `additionalNotes`.
It now asserts the exact recipient payload, frozen variables, no private-link leakage and
one HTTP request across replay. Existing no-scene, gate-off, invalid-variable and same-phone
lock cases remain in the caller suite. These are offline contract tests only.

## Related files

- `src/Common/VoiceAgent/YunkeApp/YunkeScenario.php` — pure bounded renderer.
- `src/Common/VoiceAgent/YunkeConversationalCaller.php` — frozen scenario to recipient payload.
- `src/VoiceAgent/AiCallProfile.php`, `AiVoiceCall.php`,
  `Repositories/AiCallProfileRepository.php` — versioning, refusal labels and local saves.
- `app/Http/Controllers/Manage/Calls/YunkeController.php`,
  `app/Http/Requests/Manage/Calls/Yunke/ProfileRequest.php` — platform-only form handling.
- `app/Http/Controllers/Manage/Events/FunnelsController.php`,
  `app/Http/Requests/Manage/Events/FunnelAutomation/StoreRequest.php` — shared profile assignment.
- `resources/js/Pages/Manage/Calls/Yunke/Partials/ProfileEditor.vue` — scenario draft editor.
- `config/services.php`, `.env.example`, `phpunit.xml` — separately default-off delivery gate.
- `tests/Unit/VoiceAgent/YunkeScenarioTest.php`,
  `tests/Feature/VoiceAgent/YunkeAppCallerTest.php`, `YunkeConsoleTest.php`,
  `resources/js/Pages/Manage/Calls/Yunke/console.test.js` — synthetic regressions.
- `tests/Feature/Event/FunnelAiCallAutomationTest.php` — paused draft assignment, runtime
  refusal while paused, and three rule-selected scenes with frozen registration variables.

## Reference usage

Once per account, in the App (模型管理 → 呼出 → 新建呼出话术): create the shell script —
name `petaV3-shell`, a generic default opening, the personalised opening with `{{客户名称}}`,
and a prompt that is the universal rules followed by `{{客户备注}}` — and tick **设为当前使用**.
Then, in **Phone Call → Yunke**, create or edit one profile per scene and write its brain:
who this call is for, the steps, the one question to ask, how to end (the welcome example in
the editor is the lecture registration). Add the extraction fields our AI should fill. Bind
each funnel rule to its profile. The existing funnel queue supplies the registration's
variables automatically.

Leave the field blank to preserve the existing task payload. Local editing needs no migration,
cloud prompt update or session refresh. Normal deployment refreshes config and long-running
workers, making configured scenes available by default without changing runtime controls.
If this installation already explicitly sets `YUNKE_APP_SCENARIOS_ENABLED=false`, that
operator override continues to win. Scene/mode acceptance remains unverified until tested;
do not record a deployment or a true configuration value as a successful propagation test.
