Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: let the Persistent Mind call the user when nothing on screen can reach them
[._.]/ Adam Eivy5f3b5870e2b3
diff --git a/client/src/components/cos/PersistentMindTaskAccessControls.jsx b/client/src/components/cos/PersistentMindTaskAccessControls.jsxindex f535b71ca4..0926589376 100644--- a/client/src/components/cos/PersistentMindTaskAccessControls.jsx+++ b/client/src/components/cos/PersistentMindTaskAccessControls.jsx@@ -3,9 +3,10 @@ import * as api from '../../services/api';import toast from '../ui/Toast';const normalizeCapabilities = (value) => ({- schemaVersion: 3,+ schemaVersion: 4,createTasks: value?.createTasks === true,manageMind: value?.manageMind === true,+ callUser: value?.callUser === true,readPortos: value?.readPortos === true,writePortos: value?.writePortos === true,taskModelAllowlist: Array.isArray(value?.taskModelAllowlist)@@ -36,6 +37,11 @@ const OPTIONS = [label: 'Allow mind to clean up its mindspace',hint: 'Lets the mind archive only its own memories, forget older trajectory history, or rebuild derived context. Cleanup remains bounded and auditable.',},+ {+ key: 'callUser',+ label: 'Allow mind to call you on FaceTime Audio',+ hint: 'Lets the mind ring the handle configured in Settings > Voice when nothing on screen can reach you. Honors quiet hours, never dials while a browser tab can speak, and is capped at 3 calls per 24 hours at least 30 minutes apart.',+ },];export default function PersistentMindTaskAccessControls({@@ -53,7 +59,7 @@ export default function PersistentMindTaskAccessControls({useEffect(() => {if (!saving) setDraft(normalizeCapabilities(capabilities));- }, [capabilities?.schemaVersion, capabilities?.createTasks, capabilities?.manageMind, capabilities?.readPortos, capabilities?.writePortos, capabilities?.taskModelAllowlist, capabilities?.taskModelAllowlistInvalid, capabilities?.allowedAppIds?.join('\0'), saving]);+ }, [capabilities?.schemaVersion, capabilities?.createTasks, capabilities?.manageMind, capabilities?.callUser, capabilities?.readPortos, capabilities?.writePortos, capabilities?.taskModelAllowlist, capabilities?.taskModelAllowlistInvalid, capabilities?.allowedAppIds?.join('\0'), saving]);const save = async (key, enabled) => {const previous = draft;diff --git a/client/src/components/cos/tabs/MindTab.test.jsx b/client/src/components/cos/tabs/MindTab.test.jsxindex f67082e428..a55ce5a625 100644--- a/client/src/components/cos/tabs/MindTab.test.jsx+++ b/client/src/components/cos/tabs/MindTab.test.jsx@@ -331,7 +331,7 @@ describe('MindTab', () => {await user.click(taskAccess);await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(- { persistentMindCapabilities: { schemaVersion: 3, createTasks: true, manageMind: false, readPortos: false, writePortos: false, taskModelAllowlist: [] } },+ { persistentMindCapabilities: { schemaVersion: 4, createTasks: true, manageMind: false, callUser: false, readPortos: false, writePortos: false, taskModelAllowlist: [] } },{ silent: true },));expect(screen.getAllByText(/code review then merge/i).length).toBeGreaterThan(0);diff --git a/client/src/components/settings/VoiceTab.jsx b/client/src/components/settings/VoiceTab.jsxindex e1ca37448e..e87891b9c3 100644--- a/client/src/components/settings/VoiceTab.jsx+++ b/client/src/components/settings/VoiceTab.jsx@@ -367,6 +367,28 @@ export function VoiceTab() {{['probe', 'call', 'hangup'].map((action) => <button key={action} type="button" onClick={() => handleFaceTimeAction(action)} disabled={saving || faceTimeDirty || facetimeAction !== null} className="px-3 py-2 rounded bg-port-border text-sm text-white disabled:opacity-50">{facetimeAction === action ? 'Working…' : action === 'call' ? 'Test call' : action[0].toUpperCase() + action.slice(1)}</button>)}<button type="button" onClick={refreshFaceTime} className="px-3 py-2 rounded bg-port-bg border border-port-border text-sm text-white">Check setup</button></div>+ <div className="border-t border-port-border pt-3 space-y-2">+ <h4 className="text-sm font-semibold text-white">Call me when it matters</h4>+ <label className="flex items-start gap-3 cursor-pointer">+ <input+ id="facetime-escalate-critical"+ type="checkbox"+ checked={facetime.escalateCritical === true}+ onChange={(e) => patch('facetime.escalateCritical', e.target.checked)}+ className="w-4 h-4 mt-0.5 shrink-0"+ />+ <div className="min-w-0 flex-1">+ <span className="text-sm text-white">Escalate unread critical notifications to a call</span>+ <p className="text-xs text-gray-500">Only when the notification is still unread after the delay below and no browser tab can speak it.</p>+ </div>+ </label>+ <FormField label="Escalate after" hint="Minutes a critical notification may stay unread first.">+ <input id="facetime-escalate-after-minutes" type="number" min="1" max="1440" value={facetime.escalateAfterMinutes ?? 10} onChange={(e) => patch('facetime.escalateAfterMinutes', Number(e.target.value))} className={inputCls} />+ </FormField>+ <p className="text-xs text-gray-500">+ Escalations and Persistent Mind calls share one budget: at most 3 calls per rolling 24 hours, at least 30 minutes apart, never during voice quiet hours. The Persistent Mind can only place calls when its own <Link to="/cos/mind?panel=tools" className="text-port-accent underline">call grant</Link> is enabled.+ </p>+ </div>{faceTimeDirty && <p className="text-xs text-port-warning">Set and save both identity fields before FaceTime controls are available.</p>}{facetimeStatus && <ul className="text-xs text-gray-400">{Object.entries(facetimeStatus).map(([key, value]) => <li key={key}>{value.ok === 'ok' ? '✓' : '•'} {key}: {value.message}</li>)}</ul>}{facetimeResult && <pre className="text-xs text-gray-400 whitespace-pre-wrap">{JSON.stringify(facetimeResult, null, 2)}</pre>}diff --git a/client/src/pages/PersistentMindTools.test.jsx b/client/src/pages/PersistentMindTools.test.jsxindex 5e5bcae04a..5db91cd806 100644--- a/client/src/pages/PersistentMindTools.test.jsx+++ b/client/src/pages/PersistentMindTools.test.jsx@@ -75,7 +75,7 @@ describe('PersistentMindTools', () => {await user.click(toggle);await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(- { persistentMindCapabilities: { schemaVersion: 3, createTasks: true, manageMind: false, readPortos: false, writePortos: false, taskModelAllowlist: [] } },+ { persistentMindCapabilities: { schemaVersion: 4, createTasks: true, manageMind: false, callUser: false, readPortos: false, writePortos: false, taskModelAllowlist: [] } },{ silent: true },));expect(await screen.findByText(/persistent-mind capabilities granted/)).toHaveTextContent('1 of 1');@@ -95,9 +95,10 @@ describe('PersistentMindTools', () => {await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith({ persistentMindCapabilities: {- schemaVersion: 3,+ schemaVersion: 4,createTasks: false,manageMind: true,+ callUser: false,readPortos: false,writePortos: false,taskModelAllowlist: [],@@ -128,9 +129,10 @@ describe('PersistentMindTools', () => {await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith({ persistentMindCapabilities: {- schemaVersion: 3,+ schemaVersion: 4,createTasks: true,manageMind: false,+ callUser: false,readPortos: false,writePortos: false,taskModelAllowlist: [],@@ -176,4 +178,29 @@ describe('PersistentMindTools', () => {expect(await screen.findByText('Tools unavailable')).toBeInTheDocument();expect(screen.queryByText(/persistent-mind capabilities granted/)).not.toBeInTheDocument();});++ it('offers the call grant off by default and sends it as an explicit false alongside other edits', async () => {+ // A phone call is the one grant whose absence the user cannot notice by+ // looking at a screen, so the control must be visible even when off, and+ // an unrelated toggle must never quietly drop the field from the payload.+ const user = userEvent.setup();+ renderPage();++ const callToggle = await screen.findByRole('checkbox', { name: /Allow mind to call you on FaceTime Audio/ });+ expect(callToggle).not.toBeChecked();++ await user.click(callToggle);+ await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(+ { persistentMindCapabilities: {+ schemaVersion: 4,+ createTasks: false,+ manageMind: false,+ callUser: true,+ readPortos: false,+ writePortos: false,+ taskModelAllowlist: [],+ } },+ { silent: true },+ ));+ });});diff --git a/docs/features/cos-enhancement.md b/docs/features/cos-enhancement.mdindex 54a8315ca6..632e834eff 100644--- a/docs/features/cos-enhancement.md+++ b/docs/features/cos-enhancement.md@@ -138,6 +138,50 @@ mind arbitrary shell, filesystem, or general API access. Broader PortOS APIsremain governed by their own authenticated route contracts and are not silentlymade callable by enabling task filing.+## Persistent Mind phone calls++`voice.call-user` is the mind's only outward-reaching authority, and like every+other grant it is **off by default** — an install upgrading with the mind+already running gains nothing until the user turns it on in **Mind → Tools**.+It lets the mind place a FaceTime Audio call to the single handle configured in+**Settings → Voice → FaceTime Audio**. The request the model returns+(`callRequest: { reason, openingLine }`) carries no recipient, so a confused or+compromised turn cannot dial anyone else.++The gate lives in `server/services/persistentMindCallCapability.js` and runs+*after* inference. A call is placed only when all of these hold:++| Check | Suppression reason |+|---|---|+| The grant is on (re-read from stored config) | `not-granted` |+| The optional **FaceTime** feature is enabled | `feature-disabled` |+| Voice is enabled and an identity is saved | `voice-disabled`, `identity-unconfigured` |+| No browser tab can speak the message instead | `tab-available` |+| The user's local time is outside voice quiet hours | `quiet-hours` |+| No call is already up | `call-in-progress` |+| ≥30 minutes since the last call, ≤3 calls in the last 24 h | `too-soon`, `rate-capped` |+| A call-host tab is attached and the helper dials | `no-call-host`, `dial-failed` |++The caps are counted in durable Persistent Mind state (`callHistory`), so a+restart, a crash, or a supervisor rewire cannot hand back a fresh allowance. The+budget is spent only on a call that actually went out. Every decision — placed+or suppressed, and why — is appended to the trajectory as `mind.call.requested`+plus `mind.call.placed` / `mind.call.suppressed`; the dialed handle is never+written there. When a request is refused, the turn's reply is appended with the+reason, so the mind cannot leave the user waiting for a phone that never rings.++A placed call runs with the mind's persona and a bounded briefing of its+trajectory, speaks the `openingLine` the moment the far end picks up, and hands+the transcript back as a Persistent Mind message on hangup, so the next wake+knows what was said.++**Critical-notification escalation** (Settings → Voice) uses the same gate and+the same budget, but is authorized by its own `facetime.escalateCritical`+setting rather than by the mind's grant. When a `critical` notification is+still unread after `facetime.escalateAfterMinutes` (default 10) and no voice+tab is available, PortOS asks to ring the user with the notification as the+opening line. Off by default.+## Test Coverage| Test File | Module |diff --git a/docs/features/voice.md b/docs/features/voice.mdindex 645c49f941..58cb05acb0 100644--- a/docs/features/voice.md+++ b/docs/features/voice.md@@ -65,6 +65,16 @@ a hangup.`Caller` and `PortOS`. The call audio is never persisted, and the configuredhandle never appears in the transcript or its metadata.+**Calls PortOS places on its own.** Two opt-in paths can dial without you+asking: the Persistent Mind's `voice.call-user` grant, and the+critical-notification escalation in **Settings → Voice**. Both are off by+default and share one gate and one budget — never while a browser tab can speak+the message, never inside voice quiet hours, at most 3 calls per rolling 24+hours and at least 30 minutes apart, counted in durable state so a restart+cannot reset them. Escalation additionally fires only for a `critical`+notification that is *still unread* after `escalateAfterMinutes`. See+[Chief of Staff enhancement → Persistent Mind phone calls](./cos-enhancement.md#persistent-mind-phone-calls).+### Why Kokoro is the defaultKokoro is a 82M-parameter frontier TTS model that runs in-process via ONNX Runtime + transformers.js — **no Python, no extra binaries, cross-platform**. Quality is significantly higher than Piper (more natural prosody, expressive pacing). First synthesis after server start has a 2–3 s cold start as the model loads; warm calls are 200–500 ms per sentence on CPU.diff --git a/scripts/migrations/313-persistent-mind-call-history.js b/scripts/migrations/313-persistent-mind-call-history.jsnew file mode 100644index 0000000000..43791d491f--- /dev/null+++ b/scripts/migrations/313-persistent-mind-call-history.js@@ -0,0 +1,47 @@+/**+ * Seed the durable outbound-call ledger on Persistent Mind state.+ *+ * The rate caps on the new `voice.call-user` capability are read from this+ * list, so it has to exist before the first call is considered. An absent list+ * would normalize to empty anyway; stamping it here means an install that never+ * wakes its mind still reads as migrated instead of pending forever.+ */++import { readFile } from 'fs/promises';+import { join } from 'path';+import { PERSISTENT_MIND_SCHEMA_VERSION } from '../../server/lib/persistentMind.js';+import { atomicWrite, safeJSONParse } from '../../server/lib/fileUtils.js';++export default {+ async up({ rootDir }) {+ const statePath = join(rootDir, 'data', 'cos', 'state.json');+ const raw = await readFile(statePath, 'utf8').catch((error) => {+ if (error.code === 'ENOENT') return null;+ throw error;+ });+ if (raw == null) return { updated: 0, reason: 'no-state' };++ const state = safeJSONParse(raw, null, { logError: false });+ if (!state || typeof state !== 'object' || Array.isArray(state)) {+ return { updated: 0, reason: 'invalid-state' };+ }+ const existing = state.persistentMind;+ if (!existing || typeof existing !== 'object' || Array.isArray(existing)) {+ return { updated: 0, reason: 'no-persistent-mind' };+ }+ if (existing.schemaVersion === PERSISTENT_MIND_SCHEMA_VERSION && Array.isArray(existing.callHistory)) {+ return { updated: 0, reason: 'already-applied' };+ }++ state.persistentMind = {+ ...existing,+ schemaVersion: PERSISTENT_MIND_SCHEMA_VERSION,+ // Never reset an existing ledger: the caps it backs must survive an+ // upgrade the same way they survive a restart.+ callHistory: Array.isArray(existing.callHistory) ? existing.callHistory : [],+ };+ await atomicWrite(statePath, state);+ console.log('🧠 migration 313: seeded the Persistent Mind outbound-call ledger');+ return { updated: 1 };+ },+};diff --git a/scripts/migrations/313-persistent-mind-call-history.test.js b/scripts/migrations/313-persistent-mind-call-history.test.jsnew file mode 100644index 0000000000..9e26367085--- /dev/null+++ b/scripts/migrations/313-persistent-mind-call-history.test.js@@ -0,0 +1,64 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { mkdtemp, mkdir, readFile, rm, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import migration from './313-persistent-mind-call-history.js';+import { PERSISTENT_MIND_SCHEMA_VERSION } from '../../server/lib/persistentMind.js';++let rootDir;++afterEach(async () => {+ if (rootDir) await rm(rootDir, { recursive: true, force: true });+ rootDir = null;+});++const statePath = () => join(rootDir, 'data', 'cos', 'state.json');+const readMind = async () => JSON.parse(await readFile(statePath(), 'utf8')).persistentMind;++describe('migration 313 — persistent mind call ledger', () => {+ beforeEach(async () => {+ rootDir = await mkdtemp(join(tmpdir(), 'portos-mind-call-ledger-'));+ await mkdir(join(rootDir, 'data', 'cos'), { recursive: true });+ });++ it('seeds an empty ledger without disturbing the rest of the mind state', async () => {+ await writeFile(statePath(), JSON.stringify({+ persistentMind: { schemaVersion: 4, enabled: true, started: true, futureField: 'preserve' },+ }));++ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 1 });+ expect(await readMind()).toMatchObject({+ schemaVersion: PERSISTENT_MIND_SCHEMA_VERSION,+ callHistory: [],+ enabled: true,+ futureField: 'preserve',+ });+ });++ it('never resets an existing ledger', async () => {+ // The caps this list backs must survive an upgrade the same way they+ // survive a restart — re-running the migration cannot hand back a fresh+ // allowance to a mind that has already used it.+ const callHistory = [{ at: '2026-08-28T09:00:00.000Z', reason: 'Backups failing', source: 'mind' }];+ await writeFile(statePath(), JSON.stringify({ persistentMind: { schemaVersion: 4, callHistory } }));++ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 1 });+ expect((await readMind()).callHistory).toEqual(callHistory);+ });++ it('is idempotent once the schema and ledger are current', async () => {+ const current = { schemaVersion: PERSISTENT_MIND_SCHEMA_VERSION, callHistory: [] };+ await writeFile(statePath(), JSON.stringify({ persistentMind: current }));++ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'already-applied' });+ expect(await readMind()).toEqual(current);+ });++ it('leaves missing and invalid Persistent Mind state untouched', async () => {+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'no-state' });+ await writeFile(statePath(), JSON.stringify({ config: {} }));+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'no-persistent-mind' });+ await writeFile(statePath(), '{broken');+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'invalid-state' });+ });+});diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex 2a1a210a3b..2a0c27f61f 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -22183,7 +22183,7 @@"sources": [{"source": "server/routes/voice.js",- "line": 131+ "line": 133}]},@@ -22194,7 +22194,7 @@"sources": [{"source": "server/routes/voice.js",- "line": 136+ "line": 138}]},@@ -22205,7 +22205,7 @@"sources": [{"source": "server/routes/voice.js",- "line": 182+ "line": 184}]},@@ -22216,7 +22216,7 @@"sources": [{"source": "server/routes/voice.js",- "line": 202+ "line": 204}]},@@ -22260,7 +22260,7 @@"sources": [{"source": "server/routes/voice.js",- "line": 254+ "line": 256}]},@@ -22271,7 +22271,7 @@"sources": [{"source": "server/routes/voice.js",- "line": 165+ "line": 167}]},@@ -22282,7 +22282,7 @@"sources": [{"source": "server/routes/voice.js",- "line": 215+ "line": 217}]},@@ -22293,7 +22293,7 @@"sources": [{"source": "server/routes/voice.js",- "line": 280+ "line": 282}]},@@ -22304,7 +22304,7 @@"sources": [{"source": "server/routes/voice.js",- "line": 292+ "line": 294}]},@@ -22315,7 +22315,7 @@"sources": [{"source": "server/routes/voice.js",- "line": 196+ "line": 198}]},@@ -22326,7 +22326,7 @@"sources": [{"source": "server/routes/voice.js",- "line": 304+ "line": 306}]},diff --git a/server/lib/persistentMind.js b/server/lib/persistentMind.jsindex a85002637c..530e200378 100644--- a/server/lib/persistentMind.js+++ b/server/lib/persistentMind.js@@ -12,7 +12,7 @@ import { MAX_SCREENSHOT_BYTES } from './uploadLimits.js';import { sanitizeFilename } from './mimeTypes.js';import { isSafeFilename } from './pathSafety.js';-export const PERSISTENT_MIND_SCHEMA_VERSION = 4;+export const PERSISTENT_MIND_SCHEMA_VERSION = 5;export const PERSISTENT_MIND_IMAGE_EXTENSIONS = Object.freeze(['.png', '.jpg', '.jpeg', '.gif', '.webp']);export const PERSISTENT_MIND_IMAGE_MIME_TYPES = Object.freeze({@@ -43,6 +43,9 @@ export const PERSISTENT_MIND_LIMITS = Object.freeze({MAX_MESSAGE_IMAGES: 8,MAX_MESSAGE_CHARS: 8_000,MAX_REASON_CHARS: 500,+ MAX_CALL_HISTORY: 20,+ MAX_CALL_REASON_CHARS: 200,+ MAX_CALL_SOURCE_CHARS: 60,MAX_ATTACHMENT_ID_CHARS: 128,MAX_ATTACHMENT_FILENAME_CHARS: 255,MAX_ATTACHMENT_NAME_CHARS: 200,@@ -222,6 +225,19 @@ const sanitizeMessage = (value) => {};};+// One placed outbound call. Only the timestamp, the mind's own reason, and+// which subsystem asked are kept — never the handle that was dialed, which is+// the user's phone number or email and has no business in a durable ledger.+const sanitizeCallRecord = (value) => {+ const at = asIso(value?.at);+ if (!at) return null;+ return {+ at,+ reason: asBoundedString(value?.reason, PERSISTENT_MIND_LIMITS.MAX_CALL_REASON_CHARS),+ source: asBoundedString(value?.source, PERSISTENT_MIND_LIMITS.MAX_CALL_SOURCE_CHARS) || 'mind',+ };+};+const sanitizeSelfWake = (value) => {const id = asId(value?.id);const reason = asBoundedString(value?.reason, PERSISTENT_MIND_LIMITS.MAX_REASON_CHARS);@@ -277,6 +293,7 @@ export function createDefaultPersistentMindState() {activeTurn: null,recentMessageIds: [],recentMessageFingerprints: [],+ callHistory: [],lastCompletedTurnId: null,lastCompletedAt: null,nextEligibleWakeAt: null,@@ -313,6 +330,11 @@ export function normalizePersistentMindState(raw) {seenFingerprintIds.add(id);recentMessageFingerprints.push({ id, fingerprint });}+ const callHistory = [];+ for (const candidate of Array.isArray(source.callHistory) ? source.callHistory : []) {+ const record = sanitizeCallRecord(candidate);+ if (record) callHistory.push(record);+ }const pendingAttachments = [];const seenAttachmentIds = new Set();for (const candidate of Array.isArray(source.pendingAttachments) ? source.pendingAttachments : []) {@@ -360,6 +382,7 @@ export function normalizePersistentMindState(raw) {activeTurn,recentMessageIds: recentMessageIds.slice(-PERSISTENT_MIND_LIMITS.MAX_RECENT_MESSAGE_IDS),recentMessageFingerprints: recentMessageFingerprints.slice(-PERSISTENT_MIND_LIMITS.MAX_RECENT_MESSAGE_IDS),+ callHistory: callHistory.slice(-PERSISTENT_MIND_LIMITS.MAX_CALL_HISTORY),lastCompletedTurnId: asId(source.lastCompletedTurnId) || null,lastCompletedAt: asIso(source.lastCompletedAt),nextEligibleWakeAt: asIso(source.nextEligibleWakeAt),@@ -368,6 +391,54 @@ export function normalizePersistentMindState(raw) {};}+/**+ * May the mind ring the user's phone right now?+ *+ * Two independent caps, both read from durable state so a restart, a crash, or+ * a supervisor rewire cannot hand back a fresh allowance:+ *+ * - a minimum gap, so a burst of urgent-feeling wakes cannot dial repeatedly;+ * - a rolling-window ceiling, so a persistently agitated mind still stops.+ *+ * A timestamp in the future (a clock rollback, a hand-edited state file) reads+ * as "too soon" rather than as "no recent calls" — the fail-closed reading,+ * which self-heals once the clock passes it.+ */+export function persistentMindCallRateVerdict(raw, now = Date.now(), limits = {}) {+ const {+ maxPerRollingDay = 3,+ rollingWindowMs = 24 * 60 * 60 * 1000,+ minGapMs = 30 * 60 * 1000,+ } = limits;+ const placedAt = normalizePersistentMindState(raw).callHistory+ .map((entry) => Date.parse(entry.at))+ .filter((value) => Number.isFinite(value));+ const withinWindow = placedAt.filter((at) => now - at < rollingWindowMs);+ const mostRecent = placedAt.length > 0 ? Math.max(...placedAt) : null;+ if (mostRecent !== null && now - mostRecent < minGapMs) {+ return { ok: false, reason: 'too-soon', retryAt: mostRecent + minGapMs, callsInWindow: withinWindow.length };+ }+ if (withinWindow.length >= maxPerRollingDay) {+ return {+ ok: false,+ reason: 'rate-capped',+ retryAt: Math.min(...withinWindow) + rollingWindowMs,+ callsInWindow: withinWindow.length,+ };+ }+ return { ok: true, reason: null, retryAt: null, callsInWindow: withinWindow.length };+}++/** Append one placed call to the durable, bounded call ledger. */+export function recordPersistentMindCall(raw, { at = new Date().toISOString(), reason = '', source = 'mind' } = {}) {+ const state = normalizePersistentMindState(raw);+ return normalizePersistentMindState({+ ...state,+ callHistory: [...state.callHistory, { at, reason, source }]+ .slice(-PERSISTENT_MIND_LIMITS.MAX_CALL_HISTORY),+ });+}+export function persistentMindBackoffMs(failureCount) {const exponent = Math.max(0, Math.min(20, asCount(failureCount) - 1));return Math.min(diff --git a/server/lib/persistentMind.test.js b/server/lib/persistentMind.test.jsindex 2745393ade..3ace92053f 100644--- a/server/lib/persistentMind.test.js+++ b/server/lib/persistentMind.test.js@@ -5,7 +5,9 @@ import {nextPersistentMindWakeAt,normalizePersistentMindState,persistentMindBackoffMs,+ persistentMindCallRateVerdict,persistentMindImageWorkGuard,+ recordPersistentMindCall,persistentMindTurnIsStale,requeuePersistentMindWake,takeNextPersistentMindWake,@@ -222,4 +224,47 @@ describe('persistent mind state', () => {expect(persistentMindTurnIsStale(state, 1 + PERSISTENT_MIND_LIMITS.WATCHDOG_STALE_MS - 1)).toBe(false);expect(persistentMindTurnIsStale(state, 1 + PERSISTENT_MIND_LIMITS.WATCHDOG_STALE_MS)).toBe(true);});++ it('caps outbound calls from durable state so a restart cannot reset the budget', () => {+ const CAPS = { maxPerRollingDay: 3, rollingWindowMs: 86_400_000, minGapMs: 1_800_000 };+ const now = Date.parse('2026-08-28T12:00:00.000Z');+ const at = (minutesAgo) => iso(now - minutesAgo * 60_000);++ expect(persistentMindCallRateVerdict(createDefaultPersistentMindState(), now, CAPS))+ .toMatchObject({ ok: true, callsInWindow: 0 });++ // The gap cap is what stops a burst of urgent-feeling wakes from redialing.+ expect(persistentMindCallRateVerdict({ callHistory: [{ at: at(29) }] }, now, CAPS))+ .toMatchObject({ ok: false, reason: 'too-soon' });+ expect(persistentMindCallRateVerdict({ callHistory: [{ at: at(30) }] }, now, CAPS))+ .toMatchObject({ ok: true });++ // Three inside the window is the ceiling; the fourth is rate-capped even+ // though the gap since the last one is fine.+ const three = { callHistory: [{ at: at(600) }, { at: at(300) }, { at: at(60) }] };+ expect(persistentMindCallRateVerdict(three, now, CAPS)).toMatchObject({ ok: false, reason: 'rate-capped', callsInWindow: 3 });+ // The same three calls age out of the rolling window rather than being+ // forgiven by a restart — a day later the budget is available again.+ expect(persistentMindCallRateVerdict(three, now + 86_400_000, CAPS)).toMatchObject({ ok: true, callsInWindow: 0 });++ // A clock rollback (or a hand-edited future timestamp) must fail closed.+ expect(persistentMindCallRateVerdict({ callHistory: [{ at: iso(now + 60_000) }] }, now, CAPS))+ .toMatchObject({ ok: false, reason: 'too-soon' });+ });++ it('keeps the call ledger bounded and free of the dialed handle', () => {+ let state = createDefaultPersistentMindState();+ for (let index = 0; index < PERSISTENT_MIND_LIMITS.MAX_CALL_HISTORY + 5; index += 1) {+ state = recordPersistentMindCall(state, { at: iso(index * 60_000), reason: `call ${index}`, source: 'mind' });+ }+ expect(state.callHistory).toHaveLength(PERSISTENT_MIND_LIMITS.MAX_CALL_HISTORY);+ expect(state.callHistory.at(-1)).toMatchObject({ reason: 'call 24', source: 'mind' });+ // Anything a caller tries to smuggle alongside the record is dropped: the+ // handle is the user's phone number and never belongs in durable state.+ const smuggled = recordPersistentMindCall(createDefaultPersistentMindState(), {+ at: iso(1), reason: 'urgent', source: 'mind',+ });+ expect(Object.keys(smuggled.callHistory[0]).sort()).toEqual(['at', 'reason', 'source']);+ expect(normalizePersistentMindState({ callHistory: [{ reason: 'no timestamp' }, { at: 'not-a-date' }] }).callHistory).toEqual([]);+ });});diff --git a/server/lib/persistentMindCapabilities.js b/server/lib/persistentMindCapabilities.jsindex e74aaf10ba..dc133a5e05 100644--- a/server/lib/persistentMindCapabilities.js+++ b/server/lib/persistentMindCapabilities.js@@ -14,8 +14,12 @@ import {portosSemanticToolGrantsSchema,} from './cosToolContracts.js';-export const PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION = 3;-const PREVIOUS_PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION = 2;+export const PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION = 4;+// Every wire version this server still accepts on input. Installs upgrade on+// their own schedule, so a browser bundle (or a route caller) pinned at an+// older version must keep being able to toggle the grants it already knows+// about; normalization always writes the current version forward.+const ACCEPTED_CAPABILITIES_SCHEMA_VERSIONS = Object.freeze([2, 3, 4]);export const PERSISTENT_MIND_TASK_MODEL_ALLOWLIST_LIMITS = Object.freeze({MAX_ENTRIES: 200,@@ -34,6 +38,19 @@ export const PERSISTENT_MIND_CLEANUP_SCOPES = Object.freeze(['memories',]);+// Ringing a phone is the loudest thing this install can do, so the budget is+// deliberately small and fixed rather than user-tunable: a mind that could+// raise its own call allowance would not really be capped. The counters live+// in durable mind state (server/lib/persistentMind.js) so a restart, a crash,+// or a supervisor rewire cannot hand back a fresh allowance.+export const PERSISTENT_MIND_CALL_LIMITS = Object.freeze({+ maxPerRollingDay: 3,+ rollingWindowMs: 24 * 60 * 60 * 1000,+ minGapMs: 30 * 60 * 1000,+ reasonChars: 200,+ openingLineChars: 400,+});+// The persistent mind has a deliberately smaller surface than ordinary CoS// agents. Keep this catalog beside the capability schema so the API and the UI// describe the same grants instead of maintaining a second client-only list.@@ -92,11 +109,27 @@ export const PERSISTENT_MIND_TOOL_CATALOG = Object.freeze(['Every cleanup leaves a bounded maintenance record in the new trajectory',],}),+ Object.freeze({+ id: 'voice.call-user',+ capability: 'callUser',+ name: 'Call the user on FaceTime Audio',+ description: 'Place a FaceTime Audio call to the identity configured in Settings > Voice when something needs the user and no browser tab can speak to them.',+ kind: 'typed-action',+ defaultEnabled: false,+ guardrails: [+ 'Only the single handle configured in Settings > Voice > FaceTime Audio; the mind never chooses who to contact',+ 'Honors voice quiet hours',+ `At most ${PERSISTENT_MIND_CALL_LIMITS.maxPerRollingDay} calls per rolling 24 hours and at least ${PERSISTENT_MIND_CALL_LIMITS.minGapMs / 60_000} minutes apart, counted in durable state so a restart cannot reset them`,+ 'A reason is required, and the decision plus its outcome is recorded in the trajectory',+ 'Never placed while a browser voice tab can deliver the message instead',+ 'Requires the optional FaceTime feature and an attached call-host page',+ ],+ }),]);export const PERSISTENT_MIND_TOOL_BOUNDARIES = Object.freeze(['No arbitrary shell or file-system access',- 'No raw HTTP proxy, browser controls, process control, paid generation, or external messaging',+ "No raw HTTP proxy, browser controls, process control, or paid generation, and no external messaging except the granted voice.call-user action to the user's own configured handle",'No provider credentials or hidden reasoning tokens are exposed as tools',]);@@ -122,14 +155,14 @@ export const PERSISTENT_MIND_VALIDATION_CHECKS = Object.freeze([]);export const persistentMindCapabilitiesSchema = portosSemanticToolGrantsSchema.extend({- // Accept the previous wire version so an older client can still change the+ // Accept every prior wire version so an older client can still change the// unrelated grants while this server normalizes the stored shape forward.- schemaVersion: z.union([- z.literal(PREVIOUS_PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION),- z.literal(PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION),- ]).optional(),+ schemaVersion: z.number().int()+ .refine((value) => ACCEPTED_CAPABILITIES_SCHEMA_VERSIONS.includes(value), 'unsupported persistent mind capabilities schema version')+ .optional(),createTasks: z.boolean().optional(),manageMind: z.boolean().optional(),+ callUser: z.boolean().optional(),// An empty list preserves the legacy unrestricted task catalog. Once any// entries are configured, requests must name one of these exact pairs.taskModelAllowlist: z.array(persistentMindTaskModelAllowlistEntrySchema)@@ -149,6 +182,14 @@ export const persistentMindCleanupRequestSchema = z.object({reason: z.string().trim().min(1).max(300).optional(),}).strict();+// The mind supplies only why it is calling and what it will open with. It+// never supplies a destination: the handle comes from voice configuration, so+// a compromised or confused turn cannot dial anyone but the user.+export const persistentMindCallRequestSchema = z.object({+ reason: z.string().trim().min(1).max(PERSISTENT_MIND_CALL_LIMITS.reasonChars),+ openingLine: z.string().trim().min(1).max(PERSISTENT_MIND_CALL_LIMITS.openingLineChars),+}).strict();+export const persistentMindTaskRequestSchema = z.object({description: z.string().trim().min(1).max(PERSISTENT_MIND_TASK_LIMITS.descriptionChars),prompt: z.string().trim().min(1).max(PERSISTENT_MIND_TASK_LIMITS.promptChars),@@ -187,6 +228,7 @@ export function createDefaultPersistentMindCapabilities() {schemaVersion: PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION,createTasks: false,manageMind: false,+ callUser: false,readPortos: false,writePortos: false,taskModelAllowlist: [],@@ -239,6 +281,7 @@ export function normalizePersistentMindCapabilities(raw) {schemaVersion: PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION,createTasks: source.createTasks === true,manageMind: source.manageMind === true,+ callUser: source.callUser === true,...semanticGrants,taskModelAllowlist: taskModelAllowlist.entries,// A malformed hand-edited persisted policy must not silently become thediff --git a/server/lib/persistentMindCapabilities.test.js b/server/lib/persistentMindCapabilities.test.jsindex 596b8972ec..6ae2f3eda2 100644--- a/server/lib/persistentMindCapabilities.test.js+++ b/server/lib/persistentMindCapabilities.test.js@@ -4,7 +4,9 @@ import {isPersistentMindTaskModelAllowed,mergePersistentMindCapabilities,normalizePersistentMindCapabilities,+ PERSISTENT_MIND_TOOL_BOUNDARIES,PERSISTENT_MIND_TOOL_CATALOG,+ persistentMindCallRequestSchema,persistentMindCapabilitiesSchema,persistentMindCleanupRequestSchema,persistentMindTaskRequestSchema,@@ -17,21 +19,35 @@ describe('persistent mind capabilities', () => {expect.objectContaining({ id: 'portos.read', capability: 'readPortos', defaultEnabled: false }),expect.objectContaining({ id: 'portos.write', capability: 'writePortos', defaultEnabled: false }),expect.objectContaining({ id: 'mind.cleanup', capability: 'manageMind', defaultEnabled: false }),+ expect.objectContaining({ id: 'voice.call-user', capability: 'callUser', kind: 'typed-action', defaultEnabled: false }),]);});+ it('records the call grant as the one external-messaging exception', () => {+ // The boundary list is what the Tools panel shows the user as "always+ // outside the mind's authority". Leaving the old unconditional+ // "no external messaging" line there while the mind can dial a phone+ // would make that panel actively misleading.+ expect(PERSISTENT_MIND_TOOL_BOUNDARIES.join(' ')).toContain('voice.call-user');+ });+it('keeps task creation opt-in across fresh and legacy config', () => {- expect(createDefaultPersistentMindCapabilities()).toMatchObject({ createTasks: false, manageMind: false, readPortos: false, writePortos: false });- expect(normalizePersistentMindCapabilities(null)).toMatchObject({ createTasks: false, manageMind: false, readPortos: false, writePortos: false });+ expect(createDefaultPersistentMindCapabilities()).toMatchObject({ createTasks: false, manageMind: false, callUser: false, readPortos: false, writePortos: false });+ // An install upgrading with the mind already running must gain no new+ // authority: stored config that predates the grant reads as false.+ expect(normalizePersistentMindCapabilities({ schemaVersion: 3, createTasks: true })).toMatchObject({ callUser: false });+ expect(normalizePersistentMindCapabilities(null)).toMatchObject({ createTasks: false, manageMind: false, callUser: false, readPortos: false, writePortos: false });expect(normalizePersistentMindCapabilities({ createTasks: 'true', readPortos: 'true' })).toMatchObject({ createTasks: false, readPortos: false });});it('validates and merges the explicit task-creation grant', () => {expect(persistentMindCapabilitiesSchema.safeParse({ createTasks: true, manageMind: true, readPortos: true, writePortos: false }).success).toBe(true);expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 2, createTasks: true }).success).toBe(true);+ expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 3, callUser: true }).success).toBe(true);+ expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 5 }).success).toBe(false);expect(persistentMindCapabilitiesSchema.safeParse({ taskModelAllowlist: [{ providerId: 'ollama', model: 'example-local' }] }).success).toBe(true);expect(normalizePersistentMindCapabilities({ schemaVersion: 2, createTasks: true }))- .toMatchObject({ schemaVersion: 3, createTasks: true, manageMind: false });+ .toMatchObject({ schemaVersion: 4, createTasks: true, manageMind: false, callUser: false });expect(persistentMindCapabilitiesSchema.safeParse({ allowedAppIds: ['example-app', 'second-app'] }).success).toBe(true);expect(persistentMindCapabilitiesSchema.safeParse({ allowedAppIds: Array.from({ length: 51 }, (_, index) => `app-${index}`) }).success).toBe(false);expect(persistentMindCapabilitiesSchema.safeParse({ createTasks: true, shell: true }).success).toBe(false);@@ -39,6 +55,16 @@ describe('persistent mind capabilities', () => {.toMatchObject({ createTasks: true, manageMind: false, readPortos: false, writePortos: false });});+ it('accepts a bounded call request that never names a recipient', () => {+ // The request shape is the reason a confused turn cannot dial a stranger:+ // there is nowhere in it to put a handle.+ expect(persistentMindCallRequestSchema.safeParse({ reason: 'The deploy is failing', openingLine: 'This is PortOS. The deploy is failing.' }).success).toBe(true);+ expect(persistentMindCallRequestSchema.safeParse({ reason: '', openingLine: 'Hello' }).success).toBe(false);+ expect(persistentMindCallRequestSchema.safeParse({ reason: 'Urgent', openingLine: '' }).success).toBe(false);+ expect(persistentMindCallRequestSchema.safeParse({ reason: 'Urgent', openingLine: 'x'.repeat(401) }).success).toBe(false);+ expect(persistentMindCallRequestSchema.safeParse({ reason: 'Urgent', openingLine: 'Hi', handle: '+15550000000' }).success).toBe(false);+ });+it('accepts only unique bounded mindspace cleanup scopes', () => {expect(persistentMindCleanupRequestSchema.safeParse({ scopes: ['context', 'history', 'memories'], reason: 'Old failures are no longer useful' }).success).toBe(true);expect(persistentMindCleanupRequestSchema.safeParse({ scopes: [] }).success).toBe(false);diff --git a/server/lib/persistentMindTrajectory.js b/server/lib/persistentMindTrajectory.jsindex 1cc2cdc489..01a07f8168 100644--- a/server/lib/persistentMindTrajectory.js+++ b/server/lib/persistentMindTrajectory.js@@ -32,6 +32,12 @@ export const PERSISTENT_MIND_EVENT_KINDS = Object.freeze(['mind.turn.completed','mind.memory.promoted','mind.maintenance.completed',+ // Outbound FaceTime Audio calls. Every decision is written down, including+ // the ones that placed no call, so "why didn't it call me?" is answerable+ // from the trajectory alone. The dialed handle is never recorded.+ 'mind.call.requested',+ 'mind.call.placed',+ 'mind.call.suppressed',]);const MIND_KIND_SET = new Set(PERSISTENT_MIND_EVENT_KINDS);diff --git a/server/lib/socketEventCatalog.generated.json b/server/lib/socketEventCatalog.generated.jsonindex 50568bacf3..6a0cefe7fe 100644--- a/server/lib/socketEventCatalog.generated.json+++ b/server/lib/socketEventCatalog.generated.json@@ -1916,7 +1916,7 @@{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 469+ "line": 501}]},@@ -4537,7 +4537,7 @@{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 418+ "line": 450}]},@@ -4555,7 +4555,7 @@{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 437+ "line": 469}]},@@ -4578,7 +4578,7 @@{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 464+ "line": 496}]},@@ -4596,12 +4596,12 @@{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 384+ "line": 406},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 425+ "line": 457}]},@@ -4619,7 +4619,12 @@{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 401+ "line": 397+ },+ {+ "direction": "server-to-client",+ "source": "server/sockets/voice.js",+ "line": 433}]},@@ -4637,17 +4642,17 @@{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 244+ "line": 247},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 268+ "line": 271},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 273+ "line": 276}]},@@ -4670,7 +4675,7 @@{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 261+ "line": 264}]},@@ -4688,67 +4693,67 @@{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 152+ "line": 155},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 165+ "line": 168},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 174+ "line": 177},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 179+ "line": 182},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 183+ "line": 186},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 199+ "line": 202},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 208+ "line": 211},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 213+ "line": 216},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 217+ "line": 220},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 223+ "line": 226},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 276+ "line": 279},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 411+ "line": 443},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 433+ "line": 465}]},@@ -4766,17 +4771,17 @@{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 153+ "line": 156},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 233+ "line": 236},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 245+ "line": 248}]},@@ -4810,12 +4815,12 @@{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 227+ "line": 230},{"direction": "server-to-client","source": "server/sockets/voice.js",- "line": 453+ "line": 485}]},@@ -4833,7 +4838,7 @@{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 361+ "line": 364}]},@@ -4851,7 +4856,7 @@{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 369+ "line": 372}]},@@ -4900,7 +4905,7 @@{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 236+ "line": 239}]},@@ -4918,7 +4923,7 @@{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 321+ "line": 324}]},@@ -4954,7 +4959,7 @@{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 203+ "line": 206}]},@@ -5003,7 +5008,7 @@{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 169+ "line": 172}]},@@ -5021,7 +5026,7 @@{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 284+ "line": 287}]},@@ -5052,7 +5057,7 @@{"direction": "client-to-server","source": "server/sockets/voice.js",- "line": 339+ "line": 342}]},diff --git a/server/routes/cosMindRoutes.test.js b/server/routes/cosMindRoutes.test.jsindex ef38895fd2..524c1e1a54 100644--- a/server/routes/cosMindRoutes.test.js+++ b/server/routes/cosMindRoutes.test.js@@ -184,7 +184,7 @@ describe('persistent mind routes', () => {thinkingInterface: 'text',wakeIntervalMinutes: 30,},- capabilities: { schemaVersion: 3, createTasks: true, manageMind: false, readPortos: false, writePortos: false, taskModelAllowlist: [] },+ capabilities: { schemaVersion: 4, createTasks: true, manageMind: false, callUser: false, readPortos: false, writePortos: false, taskModelAllowlist: [] },harness: { type: 'api', recommendation: 'recommended' },imageCapability: { status: 'unknown' },autonomyMode: 'execute',@@ -218,14 +218,15 @@ describe('persistent mind routes', () => {const res = await get('/mind/tools');expect(res.status).toBe(200);expect(res.body).toMatchObject({- schemaVersion: 3,- capabilities: { schemaVersion: 3, createTasks: true, manageMind: false, readPortos: false, writePortos: false, taskModelAllowlist: [] },+ schemaVersion: 4,+ capabilities: { schemaVersion: 4, createTasks: true, manageMind: false, callUser: false, readPortos: false, writePortos: false, taskModelAllowlist: [] },boundaries: expect.arrayContaining([expect.stringMatching(/arbitrary shell/i)]),tools: expect.arrayContaining([expect.objectContaining({ id: 'cos.create-task', capability: 'createTasks', granted: true, defaultEnabled: false }),expect.objectContaining({ id: 'portos.read', capability: 'readPortos', granted: false, defaultEnabled: false }),expect.objectContaining({ id: 'portos.write', capability: 'writePortos', granted: false, defaultEnabled: false }),expect.objectContaining({ id: 'mind.cleanup', capability: 'manageMind', granted: false, defaultEnabled: false }),+ expect.objectContaining({ id: 'voice.call-user', capability: 'callUser', granted: false, defaultEnabled: false }),]),taskCatalog: {apps: [{ id: 'demo-app', planOnly: true }],diff --git a/server/routes/voice.js b/server/routes/voice.jsindex 318e16b4ab..04978ab7d8 100644--- a/server/routes/voice.js+++ b/server/routes/voice.js@@ -46,6 +46,8 @@ const voiceConfigPatchSchema = z.object({targetName: z.string().trim().max(120).optional(),blackHole2chLabel: z.string().trim().min(1).max(120).optional(),blackHole16chLabel: z.string().trim().min(1).max(120).optional(),+ escalateCritical: z.boolean().optional(),+ escalateAfterMinutes: z.number().int().min(1).max(1440).optional(),}).partial().optional(),stt: z.object({engine: z.enum(['whisper', 'web-speech']).optional(),diff --git a/server/services/persistentMindAdapter.js b/server/services/persistentMindAdapter.jsindex f59c5e9e8f..2186552432 100644--- a/server/services/persistentMindAdapter.js+++ b/server/services/persistentMindAdapter.js@@ -12,6 +12,7 @@ import { z } from 'zod';import {PERSISTENT_MIND_TASK_LIMITS,normalizePersistentMindCapabilities,+ persistentMindCallRequestSchema,persistentMindTaskRequestSchema,} from '../lib/persistentMindCapabilities.js';import { PERSISTENT_MIND_ID } from '../lib/persistentMindTrajectory.js';@@ -32,6 +33,10 @@ import {executePersistentMindTaskRequests,readPersistentMindTaskCatalog,} from './persistentMindTaskCapability.js';+import {+ buildPersistentMindCallCapabilityPrompt,+ executePersistentMindCallRequest,+} from './persistentMindCallCapability.js';import {buildPersistentMindVisibilityPrompt,readPersistentMindVisibility,@@ -70,6 +75,9 @@ export const persistentMindResponseSchema = z.object({reason: z.string().trim().min(1).max(500),delayMinutes: z.number().int().min(1).max(10_080),}).strict().nullable().optional().default(null),+ // At most one per turn, and only ever to the configured handle: the request+ // carries no recipient, so a turn cannot dial anyone but the user.+ callRequest: persistentMindCallRequestSchema.nullable().optional().default(null),}).strict();const boundedToolResult = (result) => {@@ -213,7 +221,7 @@ const currentWakeText = (wake) => {return `This is a self-directed wake. Continue one worthwhile thread from the trajectory.\nreason=${wake?.reason || 'scheduled reflection'}`;};-export function buildPersistentMindTurnPrompt({ context, wake, taskCapabilityPrompt, toolCapabilityPrompt = '# PortOS semantic tools\nSemantic tool access is OFF.', visibilityPrompt = '# Persistent Mind environment visibility\nWorkspace and runtime visibility is unknown.' }) {+export function buildPersistentMindTurnPrompt({ context, wake, taskCapabilityPrompt, toolCapabilityPrompt = '# PortOS semantic tools\nSemantic tool access is OFF.', visibilityPrompt = '# Persistent Mind environment visibility\nWorkspace and runtime visibility is unknown.', callCapabilityPrompt = buildPersistentMindCallCapabilityPrompt({ enabled: false }) }) {return `${context.text}${visibilityPrompt}@@ -225,6 +233,8 @@ ${taskCapabilityPrompt}${toolCapabilityPrompt}+${callCapabilityPrompt}+# Response contractReturn ONLY one JSON object with this shape:{@@ -233,9 +243,10 @@ Return ONLY one JSON object with this shape:"memoryCandidates": [{ "content": "A durable fact worth remembering", "summary": "Short label", "type": "fact", "category": "other", "tags": ["optional"] }],"taskRequests": [{ "description": "Concise queue label", "prompt": "Complete instructions for the agent", "priority": "MEDIUM", "appId": "configured-app-id", "providerId": "configured-provider-id", "model": "configured-model-id-or-empty-for-default", "effort": "high", "planOnly": false, "prCompletion": "review-then-merge", "requiredValidation": ["dependencies"] }],"toolCalls": [{ "requestId": "optional-stable-id", "name": "catalog-name", "arguments": {} }],- "selfWake": { "reason": "Why another wake would be useful", "delayMinutes": 60 }+ "selfWake": { "reason": "Why another wake would be useful", "delayMinutes": 60 },+ "callRequest": { "reason": "Why this cannot wait for a screen", "openingLine": "What to say the moment they answer" }}-Use empty arrays when there is no durable memory candidate, task request, or tool call, and null when no earlier follow-up is needed. Memory candidates are durable memories to save automatically; only include information that is worth retaining. Never put the same CoS task in both taskRequests and toolCalls. This lane cannot mutate files directly, call arbitrary routes, contact people, or exceed the semantic tool catalog.`;+Use empty arrays when there is no durable memory candidate, task request, or tool call, and null for selfWake and callRequest when neither is needed. Memory candidates are durable memories to save automatically; only include information that is worth retaining. Never put the same CoS task in both taskRequests and toolCalls. This lane cannot mutate files directly, call arbitrary routes, contact anyone other than the configured PortOS user, or exceed the semantic tool catalog.`;}const summaryEventLines = (events) => (Array.isArray(events) ? events : []).map((event) => {@@ -340,6 +351,7 @@ export function createPersistentMindTurnAdapter() {});const visibilityPrompt = buildPersistentMindVisibilityPrompt(visibility);const toolCapabilityPrompt = buildPersistentMindToolPrompt(taskAccess);+ const callCapabilityPrompt = buildPersistentMindCallCapabilityPrompt({ enabled: taskAccess.callUser });const screenshots = (Array.isArray(wake?.message?.images) ? wake.message.images : []).map((image) => {const path = resolveScreenshot(image?.filename);if (!path) throw new Error('A Persistent Mind image attachment no longer resolves under the screenshots directory');@@ -351,6 +363,7 @@ export function createPersistentMindTurnAdapter() {taskCapabilityPrompt,toolCapabilityPrompt,visibilityPrompt,+ callCapabilityPrompt,});let providerPrompt = basePrompt;let result;@@ -454,6 +467,19 @@ export function createPersistentMindTurnAdapter() {const budgetExhausted = toolCallCount >= COS_TOOL_CALL_LIMITS.maxCallsPerTurn || round === MAX_TOOL_PROVIDER_ROUNDS - 2;providerPrompt = `${basePrompt}\n\n# Completed tool results\n${JSON.stringify(completedToolResults)}\n\n${parsed.taskRequests.length > 0 ? 'Task requests from this intermediate round were not queued. Include only the final desired taskRequests in a terminal response with toolCalls: [].\n' : ''}${budgetExhausted ? 'The tool-call budget is exhausted. Return a final response with toolCalls: [] and do not repeat completed actions.' : 'Use these results to continue. Do not repeat a completed requestId.'}`;}+ // After the tool rounds, so a call is placed on the turn's final answer+ // rather than on an intermediate round the model went on to revise.+ const callOutcome = await executePersistentMindCallRequest({+ callRequest: parsed.callRequest,+ turnId,+ signal,+ });+ if (callOutcome && !callOutcome.placed) {+ // The model has already written its reply believing the call may go+ // out. Correcting it here is what keeps "I called you" from being a+ // lie in the one case the user cannot check by looking at a screen.+ actionNotices.add(`The requested phone call was not placed (${callOutcome.reason}).`);+ }if (actionNotices.size > 0) {const notice = [...actionNotices].join(' ');parsed = wake?.kind === 'message'@@ -462,7 +488,7 @@ export function createPersistentMindTurnAdapter() {result = { ...result, text: JSON.stringify(parsed) };}const message = parsed.message || (wake?.kind === 'message' ? parsed.thinkingSummary : '');- if (!parsed.thinkingSummary && !message && parsed.memoryCandidates.length === 0 && parsed.taskRequests.length === 0 && toolCallCount === 0) {+ if (!parsed.thinkingSummary && !message && parsed.memoryCandidates.length === 0 && parsed.taskRequests.length === 0 && toolCallCount === 0 && !callOutcome) {throw new Error('Persistent mind returned no visible thought, reply, memory candidate, task request, or tool call');}const memoryWrites = await Promise.allSettled(parsed.memoryCandidates.map((candidate, index) => (diff --git a/server/services/persistentMindAdapter.test.js b/server/services/persistentMindAdapter.test.jsindex a7a4618a4d..b0d6f565b9 100644--- a/server/services/persistentMindAdapter.test.js+++ b/server/services/persistentMindAdapter.test.js@@ -10,6 +10,7 @@ const mock = vi.hoisted(() => ({executeTaskRequests: vi.fn(),executeToolCall: vi.fn(),readVisibility: vi.fn(),+ executeCallRequest: vi.fn(),createPersistentMindMemoryFromCandidate: vi.fn(async ({ candidateId, ...candidate }) => ({success: true,duplicate: false,@@ -40,6 +41,10 @@ vi.mock('./persistentMindVisibility.js', () => ({readPersistentMindVisibility: (...args) => mock.readVisibility(...args),buildPersistentMindVisibilityPrompt: () => 'Environment visibility: READY',}));+vi.mock('./persistentMindCallCapability.js', () => ({+ buildPersistentMindCallCapabilityPrompt: ({ enabled }) => `Call access: ${enabled ? 'ON' : 'OFF'}`,+ executePersistentMindCallRequest: (...args) => mock.executeCallRequest(...args),+}));vi.mock('./cosToolRegistry.js', () => ({buildPersistentMindToolPrompt: ({ readPortos, writePortos }) => `PortOS tools: read=${Boolean(readPortos)} write=${Boolean(writePortos)}`,executeCosToolCall: (...args) => mock.executeToolCall(...args),@@ -56,6 +61,7 @@ beforeEach(() => {mock.readTaskCatalog.mockResolvedValue({ apps: [{ id: 'portos' }], providers: [{ id: 'codex' }] });mock.readVisibility.mockResolvedValue({ readiness: 'ready', workspaces: [] });mock.executeTaskRequests.mockResolvedValue([]);+ mock.executeCallRequest.mockResolvedValue(null);mock.executeToolCall.mockResolvedValue({ state: 'completed', result: { ok: true, count: 1 } });mock.assertVision.mockImplementation((result, provider) => result?.provider || provider);mock.runPrompt.mockResolvedValue({ text: JSON.stringify({@@ -504,4 +510,62 @@ describe('persistent mind adapter', () => {expect(persistentMindHarnessInfo({ type: 'cli' }).recommendation).toBe('supported');expect(persistentMindHarnessInfo({ type: 'tui' }).recommendation).toBe('not-recommended');});++ it('runs a call request on the terminal answer and tells the user when it was refused', async () => {+ // The turn's reply is written before the gate runs, so a mind whose call+ // was suppressed would otherwise leave the user waiting for a phone that+ // never rings.+ mock.root.config.persistentMindCapabilities = { createTasks: false, callUser: true };+ const callRequest = { reason: 'Backups have failed three nights', openingLine: 'This is PortOS. Your backups keep failing.' };+ mock.runPrompt+ .mockResolvedValueOnce({ text: JSON.stringify({+ thinkingSummary: 'Checking the backup history first.',+ toolCalls: [{ name: 'portos.read', arguments: {} }],+ }) })+ .mockResolvedValueOnce({ text: JSON.stringify({+ thinkingSummary: 'This cannot wait for a screen.',+ message: 'Calling you about the backups.',+ callRequest,+ }) });+ mock.executeCallRequest.mockResolvedValue({ placed: false, reason: 'quiet-hours' });++ const signal = new AbortController().signal;+ const result = await createPersistentMindTurnAdapter().run({+ turnId: 'turn-call',+ wake: { kind: 'message', message: { id: 'message-call', text: 'Anything wrong?' } },+ ...profile,+ signal,+ context: { text: '# Context' },+ recordCapabilityEvent: vi.fn(async () => true),+ });++ // Executed once, after the tool round — not on the intermediate response.+ expect(mock.executeCallRequest).toHaveBeenCalledTimes(1);+ expect(mock.executeCallRequest).toHaveBeenCalledWith({ callRequest, turnId: 'turn-call', signal });+ const reply = result.events.find((event) => event.kind === 'mind.reply');+ expect(reply.data.displayText).toContain('was not placed (quiet-hours)');+ });++ it('describes the call action to the model only when the grant is on', async () => {+ mock.root.config.persistentMindCapabilities = { callUser: false };+ await createPersistentMindTurnAdapter().run({+ turnId: 'turn-call-off',+ wake: { kind: 'message', message: { id: 'message-call-off', text: 'Hello' } },+ ...profile,+ signal: new AbortController().signal,+ context: { text: '# Context' },+ });+ expect(mock.runPrompt.mock.calls[0][0].prompt).toContain('Call access: OFF');++ mock.runPrompt.mockClear();+ mock.root.config.persistentMindCapabilities = { callUser: true };+ await createPersistentMindTurnAdapter().run({+ turnId: 'turn-call-on',+ wake: { kind: 'message', message: { id: 'message-call-on', text: 'Hello' } },+ ...profile,+ signal: new AbortController().signal,+ context: { text: '# Context' },+ });+ expect(mock.runPrompt.mock.calls[0][0].prompt).toContain('Call access: ON');+ });});diff --git a/server/services/persistentMindCallCapability.js b/server/services/persistentMindCallCapability.jsnew file mode 100644index 0000000000..2f1c9efc54--- /dev/null+++ b/server/services/persistentMindCallCapability.js@@ -0,0 +1,273 @@+/**+ * The persistent mind's one outward-reaching authority: ringing the user's+ * phone over FaceTime Audio.+ *+ * Everything else the mind can do lands inside PortOS, where the user finds it+ * when they next look. A call does not wait to be found — it interrupts a+ * person who may be asleep, driving, or in a meeting — so this module is+ * written as a gate first and a feature second. It re-checks the grant AFTER+ * inference (the model does not get to assert its own authority), refuses+ * whenever a browser tab could carry the same words instead, honours the same+ * quiet hours proactive speech does, and enforces a small fixed budget out of+ * durable state so a restart cannot hand back a fresh allowance.+ *+ * Every decision is written to the mind trajectory, including the ones that+ * placed no call, so "why didn't it call me?" and "why did it?" are both+ * answerable from the ledger. The dialed handle never appears there: it is the+ * user's phone number or email, and lives only in voice configuration.+ *+ * The critical-notification escalation in `voice/proactiveTriggers.js` shares+ * this gate with `requireMindGrant: false` — it is authorized by its own+ * `facetime.escalateCritical` setting rather than by the mind's grant, but it+ * is subject to every other check, and above all to the same budget.+ */++import {+ PERSISTENT_MIND_CALL_LIMITS,+ normalizePersistentMindCapabilities,+ persistentMindCallRequestSchema,+} from '../lib/persistentMindCapabilities.js';+import {+ persistentMindCallRateVerdict,+ recordPersistentMindCall,+} from '../lib/persistentMind.js';+import { PERSISTENT_MIND_ID } from '../lib/persistentMindTrajectory.js';+import { sha256Text } from '../lib/fileUtils.js';+import { loadState, saveState, withStateLock } from './cosState.js';+import { appendMindEvent } from './agentRunEventLog.js';+import { normalizePersistentMindPrompt } from '../lib/persistentMindPrompt.js';+import { preparePersistentMindContext, readPersistentMindMemories } from './persistentMindContext.js';+import { isInstanceFeatureEnabled } from './instanceFeatures.js';+import { getVoiceConfig } from './voice/config.js';+import { getLocalMinutes, isWithinQuietHours } from './voice/proactiveSpeech.js';+import { getVoiceOutputSocket } from './voice/voiceOutput.js';+import { isCallActive, startCall } from './voice/callSession.js';++/**+ * Why a requested call was not placed. Recorded verbatim on the trajectory+ * event, so keep these stable — the Mind tab and the docs name them.+ */+export const PERSISTENT_MIND_CALL_SUPPRESSION_REASONS = Object.freeze([+ 'invalid-request',+ 'not-granted',+ 'feature-disabled',+ 'voice-disabled',+ 'identity-unconfigured',+ 'tab-available',+ 'quiet-hours',+ 'call-in-progress',+ 'too-soon',+ 'rate-capped',+ 'no-call-host',+ 'dial-failed',+ 'interrupted',+]);++// The caller-side turns run with a briefing, not the mind's whole life. A call+// is spoken through a small local voice model with a short context window, and+// every turn re-sends this, so the budget is far below the mind's own.+const CALL_CONTEXT_MAX_CHARS = 2_500;++const suppressed = (reason, extra = {}) => ({ placed: false, reason, ...extra });++const trimmedIdentity = (config) => ({+ handle: String(config?.facetime?.targetHandle ?? '').trim(),+ name: String(config?.facetime?.targetName ?? '').trim(),+});++/**+ * Render the bounded briefing the call runs with, so the voice on the phone is+ * continuous with the mind rather than a stranger who happens to share a voice.+ *+ * Deliberately built without a summarizer: this runs on the mind's own turn,+ * and a call must never trigger an extra provider round the user did not ask+ * for. An unsummarized older history simply reads as unavailable.+ */+async function buildCallContext(reason) {+ const root = await loadState();+ const prompt = normalizePersistentMindPrompt(root.config?.persistentMindPrompt);+ const memories = await readPersistentMindMemories(PERSISTENT_MIND_ID);+ const context = await preparePersistentMindContext({+ mindId: PERSISTENT_MIND_ID,+ identity: prompt.identity,+ instructions: prompt.instructions,+ memories,+ maxChars: CALL_CONTEXT_MAX_CHARS,+ });+ return [+ 'You are speaking on a phone call that you placed to the user. Keep it short, say why you called, and let them talk.',+ `# Why you called\n${reason}`,+ context.text,+ ].join('\n\n').slice(0, CALL_CONTEXT_MAX_CHARS * 2);+}++/**+ * Persist one placed call into the durable ledger the caps are read from.+ *+ * Uses the same state lock the mind supervisor writes under, so a call landing+ * next to a turn completion cannot lose either write.+ */+async function persistPlacedCall({ at, reason, source }) {+ return withStateLock(async () => {+ const root = await loadState();+ root.persistentMind = recordPersistentMindCall(root.persistentMind, { at, reason, source });+ await saveState(root);+ return root.persistentMind;+ });+}++const callEventId = (turnId, source, reason, at) => (+ `mind-call:${sha256Text(`${turnId || source}:${reason}:${at}`).slice(0, 32)}`+);++const recordCallEvent = async ({ kind, turnId, eventId, data }) => appendMindEvent({+ kind,+ mindId: PERSISTENT_MIND_ID,+ turnId: turnId || null,+ eventId,+ data,+});++/**+ * Describe the call action to the model — only when it is actually granted.+ *+ * An ungranted mind is told the field exists and must stay null, rather than+ * being left to discover the rejection by trying: a model that believes it+ * called the user will say so in its reply, and the user would be waiting for+ * a phone that never rings.+ */+export function buildPersistentMindCallCapabilityPrompt({ enabled } = {}) {+ if (!enabled) {+ return `# Calling the user+Placing a phone call is OFF. Set callRequest to null. You may say that you would call if it mattered, but must never claim a call was placed.`;+ }+ return `# Calling the user+Placing a phone call is ON. Set callRequest when something genuinely cannot wait for the user to look at a screen. The call reaches only the single handle configured in PortOS; you never choose a recipient.++The request is refused, and no call is placed, when any of these hold: a browser tab is open and able to speak to the user, the current local time is inside voice quiet hours, a call is already up, fewer than ${PERSISTENT_MIND_CALL_LIMITS.minGapMs / 60_000} minutes have passed since the last call, or ${PERSISTENT_MIND_CALL_LIMITS.maxPerRollingDay} calls have already been placed in the last 24 hours.++'reason' is for the record and the user, not for the phone. 'openingLine' is spoken aloud the moment they answer, so write one or two plain spoken sentences: say who is calling and why, with no markdown and no lists. Describe the call in your message as requested, never as completed — the outcome is decided after you respond.`;+}++/**+ * Decide on, and if allowed place, one outbound call to the user.+ *+ * @param {object} input+ * @param {string} input.reason Why the call is being placed (recorded).+ * @param {string} input.openingLine Spoken the moment the call connects.+ * @param {string} [input.source] Which subsystem asked ('mind', …).+ * @param {boolean} [input.requireMindGrant] False for a path authorized by its+ * own setting (notification escalation).+ * @param {string} [input.turnId] Mind turn to attribute the events to.+ * @param {AbortSignal} [input.signal] Aborted turn places no call.+ * @param {number} [input.now] Injectable clock for the rate caps.+ * @returns {Promise<{placed: boolean, reason: string|null}>}+ */+export async function requestUserCall({+ reason,+ openingLine,+ source = 'mind',+ requireMindGrant = true,+ turnId = null,+ signal = null,+ now = Date.now(),+} = {}) {+ const parsed = persistentMindCallRequestSchema.safeParse({ reason, openingLine });+ const at = new Date(now).toISOString();+ const eventId = callEventId(turnId, source, parsed.success ? parsed.data.reason : 'invalid', at);++ if (!parsed.success) {+ await recordCallEvent({+ kind: 'mind.call.suppressed',+ turnId,+ eventId: `${eventId}:suppressed`,+ data: { displayText: 'A call request was rejected before any dialing', status: 'invalid-request', source },+ });+ return suppressed('invalid-request');+ }+ const request = parsed.data;++ await recordCallEvent({+ kind: 'mind.call.requested',+ turnId,+ eventId: `${eventId}:requested`,+ data: { displayText: `Requested a call: ${request.reason}`, source },+ });++ const finish = async (outcome) => {+ await recordCallEvent({+ kind: outcome.placed ? 'mind.call.placed' : 'mind.call.suppressed',+ turnId,+ eventId: `${eventId}:${outcome.placed ? 'placed' : 'suppressed'}`,+ data: {+ displayText: outcome.placed+ ? `Called the user: ${request.reason}`+ : `No call placed (${outcome.reason}): ${request.reason}`,+ status: outcome.reason || 'placed',+ source,+ },+ });+ if (!outcome.placed) console.log(`📞 mind call suppressed (${outcome.reason}) source=${source}`);+ return outcome;+ };++ if (signal?.aborted) return finish(suppressed('interrupted'));++ const root = await loadState();+ const capabilities = normalizePersistentMindCapabilities(root.config?.persistentMindCapabilities);+ if (requireMindGrant && !capabilities.callUser) return finish(suppressed('not-granted'));++ if (!await isInstanceFeatureEnabled('facetime')) return finish(suppressed('feature-disabled'));++ const config = await getVoiceConfig();+ if (!config?.enabled) return finish(suppressed('voice-disabled'));+ const identity = trimmedIdentity(config);+ if (!identity.handle || !identity.name) return finish(suppressed('identity-unconfigured'));++ // Checked before quiet hours on purpose: if a tab can speak, the message is+ // already deliverable and no phone needs to ring at any hour.+ if (getVoiceOutputSocket()) return finish(suppressed('tab-available'));++ const quietHours = config?.llm?.proactive?.quietHours;+ if (quietHours?.enabled) {+ const nowMinutes = await getLocalMinutes();+ if (isWithinQuietHours({ start: quietHours.start, end: quietHours.end, nowMinutes })) {+ return finish(suppressed('quiet-hours'));+ }+ }++ if (isCallActive()) return finish(suppressed('call-in-progress'));++ const verdict = persistentMindCallRateVerdict(root.persistentMind, now, PERSISTENT_MIND_CALL_LIMITS);+ if (!verdict.ok) return finish(suppressed(verdict.reason, { retryAt: verdict.retryAt }));++ const context = await buildCallContext(request.reason).catch((error) => {+ // A briefing that could not be assembled is not a reason to leave the user+ // uncalled; the opening line alone still carries the message.+ console.error(`❌ mind call: context assembly failed: ${error.message}`);+ return null;+ });++ const result = await startCall({ openingLine: request.openingLine, context, origin: 'mind' });+ if (!result?.ok) return finish(suppressed(result?.reason || 'dial-failed'));++ // Recorded only on a call that actually went out, so a refused dial does not+ // spend the day's budget.+ await persistPlacedCall({ at, reason: request.reason, source });+ console.log(`📞 mind call placed (${source}): ${request.reason.slice(0, 80)}`);+ return finish({ placed: true, reason: null });+}++/** Adapter entry point — run one model-returned `callRequest`. */+export async function executePersistentMindCallRequest({ callRequest, turnId, signal, now } = {}) {+ if (!callRequest) return null;+ return requestUserCall({+ reason: callRequest.reason,+ openingLine: callRequest.openingLine,+ source: 'mind',+ requireMindGrant: true,+ turnId,+ signal,+ ...(Number.isFinite(now) ? { now } : {}),+ });+}diff --git a/server/services/persistentMindCallCapability.test.js b/server/services/persistentMindCallCapability.test.jsnew file mode 100644index 0000000000..046d2344bf--- /dev/null+++ b/server/services/persistentMindCallCapability.test.js@@ -0,0 +1,222 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('./cosState.js', () => ({+ loadState: vi.fn(),+ saveState: vi.fn(async () => {}),+ withStateLock: (fn) => fn(),+}));+vi.mock('./agentRunEventLog.js', () => ({ appendMindEvent: vi.fn(async () => ({ appended: true })) }));+vi.mock('./persistentMindContext.js', () => ({+ preparePersistentMindContext: vi.fn(async () => ({ text: '# Persistent mind identity\nmindId=cos-persistent-mind' })),+ readPersistentMindMemories: vi.fn(async () => []),+}));+vi.mock('./instanceFeatures.js', () => ({ isInstanceFeatureEnabled: vi.fn(async () => true) }));+vi.mock('./voice/config.js', () => ({ getVoiceConfig: vi.fn() }));+vi.mock('./voice/voiceOutput.js', () => ({ getVoiceOutputSocket: vi.fn(() => null) }));+vi.mock('./voice/callSession.js', () => ({ startCall: vi.fn(), isCallActive: vi.fn(() => false) }));+vi.mock('./voice/proactiveSpeech.js', async () => ({+ // The real window predicate (proactiveSpeech re-exports it under the+ // quiet-hours name) so the overnight-wrap logic is genuinely exercised; only+ // the wall clock behind it is injected. Importing the module itself would+ // drag in the TTS engines this suite has no business booting.+ isWithinQuietHours: (await import('../lib/timezone.js')).isWithinTimeWindow,+ getLocalMinutes: vi.fn(async () => 12 * 60),+}));++import { loadState, saveState } from './cosState.js';+import { appendMindEvent } from './agentRunEventLog.js';+import { isInstanceFeatureEnabled } from './instanceFeatures.js';+import { getVoiceConfig } from './voice/config.js';+import { getVoiceOutputSocket } from './voice/voiceOutput.js';+import { isCallActive, startCall } from './voice/callSession.js';+import { getLocalMinutes } from './voice/proactiveSpeech.js';+import {+ PERSISTENT_MIND_CALL_SUPPRESSION_REASONS,+ buildPersistentMindCallCapabilityPrompt,+ requestUserCall,+} from './persistentMindCallCapability.js';++const NOW = Date.parse('2026-08-28T12:00:00.000Z');+const minutesAgo = (minutes) => new Date(NOW - minutes * 60_000).toISOString();++let root;++const setState = (overrides = {}) => {+ root = {+ config: { persistentMindCapabilities: { callUser: true } },+ persistentMind: { callHistory: [] },+ ...overrides,+ };+ loadState.mockResolvedValue(root);+};++const setVoice = (overrides = {}) => {+ getVoiceConfig.mockResolvedValue({+ enabled: true,+ facetime: { targetHandle: '+15550100', targetName: 'Example User' },+ llm: { proactive: { quietHours: { enabled: false, start: '22:00', end: '07:00' } } },+ ...overrides,+ });+};++const request = (overrides = {}) => requestUserCall({+ reason: 'The nightly backup has been failing for three days',+ openingLine: 'This is PortOS. Your nightly backup has failed three nights running.',+ now: NOW,+ ...overrides,+});++const eventKinds = () => appendMindEvent.mock.calls.map(([event]) => event.kind);+const eventFor = (kind) => appendMindEvent.mock.calls.map(([event]) => event).find((event) => event.kind === kind);++beforeEach(() => {+ vi.clearAllMocks();+ setState();+ setVoice();+ isInstanceFeatureEnabled.mockResolvedValue(true);+ getVoiceOutputSocket.mockReturnValue(null);+ isCallActive.mockReturnValue(false);+ getLocalMinutes.mockResolvedValue(12 * 60);+ startCall.mockResolvedValue({ ok: true, state: { state: 'dialing' } });+});++describe('persistent mind call capability', () => {+ it('places the call, speaking the opening line, only when every gate passes', async () => {+ await expect(request()).resolves.toEqual({ placed: true, reason: null });+ expect(startCall).toHaveBeenCalledWith(expect.objectContaining({+ openingLine: 'This is PortOS. Your nightly backup has failed three nights running.',+ origin: 'mind',+ }));+ expect(eventKinds()).toEqual(['mind.call.requested', 'mind.call.placed']);+ // The budget is only spent on a call that actually went out, and it is+ // written to durable state rather than kept in module memory.+ expect(saveState).toHaveBeenCalledTimes(1);+ expect(root.persistentMind.callHistory).toEqual([+ expect.objectContaining({ source: 'mind', reason: 'The nightly backup has been failing for three days' }),+ ]);+ });++ it('never records the dialed handle on the trajectory', async () => {+ await request();+ const serialized = JSON.stringify(appendMindEvent.mock.calls);+ expect(serialized).not.toContain('+15550100');+ expect(serialized).not.toContain('Example User');+ });++ it('refuses when the grant is off, and dials nothing', async () => {+ // The model does not get to assert its own authority: the grant is+ // re-read after inference, from stored config.+ setState({ config: { persistentMindCapabilities: { callUser: false } }, persistentMind: { callHistory: [] } });+ await expect(request()).resolves.toMatchObject({ placed: false, reason: 'not-granted' });+ expect(startCall).not.toHaveBeenCalled();+ expect(eventFor('mind.call.suppressed').data.status).toBe('not-granted');+ });++ it('prefers a browser tab over a phone whenever one can speak', async () => {+ getVoiceOutputSocket.mockReturnValue({ id: 'socket-1' });+ await expect(request()).resolves.toMatchObject({ placed: false, reason: 'tab-available' });+ expect(startCall).not.toHaveBeenCalled();+ });++ it('honors voice quiet hours', async () => {+ setVoice({ llm: { proactive: { quietHours: { enabled: true, start: '22:00', end: '07:00' } } } });+ getLocalMinutes.mockResolvedValue(3 * 60);+ await expect(request()).resolves.toMatchObject({ placed: false, reason: 'quiet-hours' });+ getLocalMinutes.mockResolvedValue(9 * 60);+ await expect(request()).resolves.toMatchObject({ placed: true });+ });++ it('suppresses the fourth call in a rolling 24 hours', async () => {+ setState({+ config: { persistentMindCapabilities: { callUser: true } },+ persistentMind: {+ callHistory: [{ at: minutesAgo(700) }, { at: minutesAgo(400) }, { at: minutesAgo(100) }],+ },+ });+ await expect(request()).resolves.toMatchObject({ placed: false, reason: 'rate-capped' });+ expect(startCall).not.toHaveBeenCalled();+ });++ it('keeps consecutive calls at least thirty minutes apart', async () => {+ setState({+ config: { persistentMindCapabilities: { callUser: true } },+ persistentMind: { callHistory: [{ at: minutesAgo(5) }] },+ });+ await expect(request()).resolves.toMatchObject({ placed: false, reason: 'too-soon' });+ });++ it('does not spend the budget when the dial itself fails', async () => {+ // Without this, a Mac with no call-host tab open would silently burn the+ // day's three calls on dials nobody could hear.+ startCall.mockResolvedValue({ ok: false, reason: 'no-call-host' });+ await expect(request()).resolves.toMatchObject({ placed: false, reason: 'no-call-host' });+ expect(saveState).not.toHaveBeenCalled();+ expect(root.persistentMind.callHistory).toEqual([]);+ });++ it('refuses without the FaceTime feature or a configured identity', async () => {+ isInstanceFeatureEnabled.mockResolvedValue(false);+ await expect(request()).resolves.toMatchObject({ placed: false, reason: 'feature-disabled' });+ isInstanceFeatureEnabled.mockResolvedValue(true);+ setVoice({ facetime: { targetHandle: '', targetName: '' } });+ await expect(request()).resolves.toMatchObject({ placed: false, reason: 'identity-unconfigured' });+ setVoice({ enabled: false });+ await expect(request()).resolves.toMatchObject({ placed: false, reason: 'voice-disabled' });+ expect(startCall).not.toHaveBeenCalled();+ });++ it('rejects a malformed request before any gate runs', async () => {+ await expect(requestUserCall({ reason: '', openingLine: 'Hello', now: NOW }))+ .resolves.toMatchObject({ placed: false, reason: 'invalid-request' });+ expect(loadState).not.toHaveBeenCalled();+ expect(eventKinds()).toEqual(['mind.call.suppressed']);+ });++ it('lets the notification escalation call without the mind grant but under the same caps', async () => {+ setState({+ config: { persistentMindCapabilities: { callUser: false } },+ persistentMind: { callHistory: [] },+ });+ await expect(request({ requireMindGrant: false, source: 'critical-notification' }))+ .resolves.toMatchObject({ placed: true });+ expect(root.persistentMind.callHistory[0]).toMatchObject({ source: 'critical-notification' });++ setState({+ config: { persistentMindCapabilities: { callUser: false } },+ persistentMind: { callHistory: [{ at: minutesAgo(1) }] },+ });+ await expect(request({ requireMindGrant: false, source: 'critical-notification' }))+ .resolves.toMatchObject({ placed: false, reason: 'too-soon' });+ });++ it('places no call for an interrupted turn', async () => {+ const controller = new AbortController();+ controller.abort('stopped');+ await expect(request({ signal: controller.signal })).resolves.toMatchObject({ placed: false, reason: 'interrupted' });+ expect(startCall).not.toHaveBeenCalled();+ });++ it('reports only declared suppression reasons', async () => {+ // The reasons are a published contract — they are written verbatim onto+ // the trajectory event and named in the docs — so an undeclared one is a+ // silent break in what the user can look up.+ const seen = new Set();+ setState({ config: { persistentMindCapabilities: { callUser: false } }, persistentMind: { callHistory: [] } });+ seen.add((await request()).reason);+ setState({ config: { persistentMindCapabilities: { callUser: true } }, persistentMind: { callHistory: [{ at: minutesAgo(1) }] } });+ seen.add((await request()).reason);+ getVoiceOutputSocket.mockReturnValue({ id: 'socket-1' });+ seen.add((await request()).reason);+ seen.add((await requestUserCall({ reason: '', openingLine: '', now: NOW })).reason);+ for (const reason of seen) expect(PERSISTENT_MIND_CALL_SUPPRESSION_REASONS).toContain(reason);+ });++ it('describes the limits to the model only when the grant is on', async () => {+ const off = buildPersistentMindCallCapabilityPrompt({ enabled: false });+ expect(off).toContain('OFF');+ expect(off).not.toContain('24 hours');+ const on = buildPersistentMindCallCapabilityPrompt({ enabled: true });+ expect(on).toContain('30 minutes');+ expect(on).toContain('3 calls have already been placed in the last 24 hours');+ });+});diff --git a/server/services/socket.test.js b/server/services/socket.test.jsindex f4364b1aea..4dbf1f1ee1 100644--- a/server/services/socket.test.js+++ b/server/services/socket.test.js@@ -18,7 +18,7 @@ vi.mock('./apps.js', () => ({ appsEvents: { on: vi.fn() }, getAppById: vi.fn(),vi.mock('../lib/errorHandler.js', () => ({ errorEvents: { on: vi.fn() } }));vi.mock('./autoFixer.js', () => ({ handleErrorRecovery: vi.fn() }));vi.mock('./pm2Standardizer.js', () => ({ analyzeApp: vi.fn(), createGitBackup: vi.fn(), applyStandardization: vi.fn(), runStandardizeFlow: vi.fn(), standardizeRefusalFor: vi.fn(() => null) }));-vi.mock('./notifications.js', () => ({ notificationEvents: { on: vi.fn() } }));+vi.mock('./notifications.js', () => ({ notificationEvents: { on: vi.fn() }, getNotifications: vi.fn(async () => []) }));vi.mock('./agentPersonalities.js', () => ({ agentPersonalityEvents: { on: vi.fn() } }));vi.mock('./platformAccounts.js', () => ({ platformAccountEvents: { on: vi.fn() } }));vi.mock('./updateChecker.js', () => ({ updateEvents: { on: vi.fn() } }));diff --git a/server/services/voice/callSession.js b/server/services/voice/callSession.jsindex 3516cfb77b..273ee6d9ea 100644--- a/server/services/voice/callSession.js+++ b/server/services/voice/callSession.js@@ -37,6 +37,13 @@ const initialState = () => ({lastVoiceAt: null,endedReason: null,transcript: [],+ // Set only for a call PortOS placed on its own initiative. `origin` decides+ // whether the transcript is handed back to the persistent mind afterwards;+ // `openingLine` is what the call host speaks the moment the far end picks up+ // (consumed once, so a state re-emit cannot make it say it twice).+ origin: 'user',+ openingLine: '',+ context: null,});let session = initialState();@@ -46,11 +53,27 @@ let listener = null;// Injectable so the state machine can be driven with stubs and fake timers// instead of a real helper and a real call.-let deps = { probe: facetimeBridge.probe, call: facetimeBridge.call, hangup: facetimeBridge.hangup, appendJournal, now: Date.now };+// Imported lazily: the persistent-mind supervisor pulls in a large service+// graph, and a call the mind did not place never needs it.+const enqueueMindMessage = async (text) => {+ const { enqueuePersistentMindMessage } = await import('../persistentMindSupervisor.js');+ return enqueuePersistentMindMessage({ text });+};++const defaultDeps = () => ({+ probe: facetimeBridge.probe,+ call: facetimeBridge.call,+ hangup: facetimeBridge.hangup,+ appendJournal,+ enqueueMindMessage,+ now: Date.now,+});++let deps = defaultDeps();/** Test seam — override the helper/clock, or restore the real ones. */export const __setCallSessionDeps = (overrides = {}) => {- deps = { probe: facetimeBridge.probe, call: facetimeBridge.call, hangup: facetimeBridge.hangup, appendJournal, now: Date.now, ...overrides };+ deps = { ...defaultDeps(), ...overrides };};const publicState = () => ({@@ -81,6 +104,24 @@ export const getCallState = () => publicState();export const getCallHost = () => host;export const isCallActive = () => publicState().active;+/**+ * The bounded briefing the caller-side turns run with, or null for a call the+ * user placed themselves. Read per turn so the pipeline stays stateless.+ */+export const getCallContext = () => (publicState().active ? session.context : null);++/**+ * Take the pending opening line, clearing it. Consume-once on purpose: the+ * host speaks it on the first `connected` observation, and `voice:call:state`+ * is broadcast more than once per call.+ */+export function takeCallOpeningLine() {+ if (!publicState().active) return '';+ const line = session.openingLine;+ session.openingLine = '';+ return line;+}+/*** Claim the single call-host slot.*@@ -163,11 +204,19 @@ const startPolling = () => {/*** Place a call. Fails closed when nothing can carry the audio.*/-export async function startCall({ openingLine = '', context = null } = {}) {+export async function startCall({ openingLine = '', context = null, origin = 'user' } = {}) {if (!host) return { ok: false, reason: 'no-call-host' };if (publicState().active) return { ok: false, reason: 'call-in-progress' };- session = { ...initialState(), state: 'dialing', startedAt: deps.now(), lastVoiceAt: deps.now() };+ session = {+ ...initialState(),+ state: 'dialing',+ startedAt: deps.now(),+ lastVoiceAt: deps.now(),+ origin: origin === 'mind' ? 'mind' : 'user',+ openingLine: typeof openingLine === 'string' ? openingLine.trim() : '',+ context: typeof context === 'string' && context.trim() ? context : null,+ };emitState();try {await deps.call();@@ -177,7 +226,7 @@ export async function startCall({ openingLine = '', context = null } = {}) {return { ok: false, reason: 'dial-failed', message: error.message };}startPolling();- return { ok: true, state: publicState(), openingLine, context };+ return { ok: true, state: publicState(), openingLine: session.openingLine, context: session.context };}/** Record one side of the conversation. Speaker labels only — never the handle. */@@ -203,6 +252,11 @@ const renderTranscript = (transcript) => transcript.map((turn) => `${turn.speaker === 'assistant' ? 'PortOS' : 'Caller'}: ${turn.text}`).join('\n');+// Cap on the transcript handed back to the persistent mind. A call is short by+// construction (maxCallMinutes), but the mind's message queue is durable state,+// so the bound is enforced here rather than trusted.+const MIND_TRANSCRIPT_MAX_CHARS = 6_000;+/*** End the call and write the transcript down.*@@ -213,6 +267,7 @@ export async function endCall(reason = 'ended') {if (session.state === 'idle') return publicState();stopPolling();const transcript = session.transcript;+ const origin = session.origin;session.endedReason = reason;setState('ended');@@ -230,6 +285,24 @@ export async function endCall(reason = 'ended') {}}+ // A call the mind placed is one half of a conversation it started, so the+ // outcome goes back into its queue as a message. Without this the next wake+ // would have no idea the call happened and could call again to say the same+ // thing — including after a call nobody picked up, which is exactly when an+ // empty transcript would otherwise leave it uninformed. Best-effort for the+ // same reason the journal append is.+ if (origin === 'mind') {+ try {+ await deps.enqueueMindMessage(+ `Outcome of the FaceTime Audio call you placed (ended: ${reason}):\n${+ transcript.length ? renderTranscript(transcript) : 'The call ended with nothing said.'+ }`.slice(0, MIND_TRANSCRIPT_MAX_CHARS),+ );+ } catch (error) {+ console.error(`❌ voice call: mind transcript handoff failed: ${error.message}`);+ }+ }+session = { ...initialState(), endedReason: reason };return emitState();}diff --git a/server/services/voice/callSession.test.js b/server/services/voice/callSession.test.jsindex 482b4af73d..2bcf93a782 100644--- a/server/services/voice/callSession.test.js+++ b/server/services/voice/callSession.test.js@@ -13,6 +13,7 @@ import {attachHost,detachHost,endCall,+ getCallContext,getCallState,markSpeaking,noteCallerSpeech,@@ -20,6 +21,7 @@ import {recordTurn,setCallStateListener,startCall,+ takeCallOpeningLine,} from './callSession.js';const socket = (id = 'host-1') => ({ id, connected: true, emit: vi.fn() });@@ -29,6 +31,7 @@ let probe;let call;let hangup;let appendJournal;+let enqueueMindMessage;const install = (overrides = {}) => {clock = 1_000_000;@@ -36,7 +39,8 @@ const install = (overrides = {}) => {call = vi.fn().mockResolvedValue({ state: 'dialing' });hangup = vi.fn().mockResolvedValue({ state: 'ended' });appendJournal = vi.fn().mockResolvedValue({});- __setCallSessionDeps({ probe, call, hangup, appendJournal, now: () => clock, ...overrides });+ enqueueMindMessage = vi.fn().mockResolvedValue({ success: true });+ __setCallSessionDeps({ probe, call, hangup, appendJournal, enqueueMindMessage, now: () => clock, ...overrides });};beforeEach(() => {@@ -257,4 +261,81 @@ describe('FaceTime call session', () => {expect(recordTurn('caller', 'nobody is listening')).toMatchObject({ turns: 0 });expect(noteCallerSpeech()).toMatchObject({ active: false });});++ it('hands the opening line over exactly once, however often state is broadcast', async () => {+ // `voice:call:state` is a broadcast and fires on every transition, so a+ // non-consuming read would make the call host say the line twice.+ attachHost(socket());+ await startCall({ openingLine: ' This is PortOS about your backups. ', origin: 'mind' });++ expect(takeCallOpeningLine()).toBe('This is PortOS about your backups.');+ expect(takeCallOpeningLine()).toBe('');+ });++ it('carries a mind briefing only for the call the mind placed', async () => {+ attachHost(socket());+ await startCall({ openingLine: 'Hello', context: '# Persistent mind identity', origin: 'mind' });+ expect(getCallContext()).toBe('# Persistent mind identity');++ await endCall('remote-hangup');+ // No call, no briefing — the pipeline must not keep applying it to the+ // widget's ordinary turns.+ expect(getCallContext()).toBeNull();++ await startCall({ openingLine: 'Hello' });+ expect(getCallContext()).toBeNull();+ });++ it('gives a mind-placed call back to the mind as a message, and a user call not at all', async () => {+ attachHost(socket());+ await startCall({ openingLine: 'This is PortOS.', origin: 'mind' });+ probe.mockResolvedValue({ state: 'connected' });+ await pollCall();+ recordTurn('assistant', 'This is PortOS.');+ recordTurn('caller', 'Got it, thanks.');++ await endCall('caller-silent');++ expect(enqueueMindMessage).toHaveBeenCalledTimes(1);+ const [text] = enqueueMindMessage.mock.calls[0];+ expect(text).toContain('caller-silent');+ expect(text).toContain('Caller: Got it, thanks.');++ enqueueMindMessage.mockClear();+ attachHost(socket());+ await startCall();+ recordTurn('caller', 'Just me calling in.');+ await endCall('remote-hangup');+ expect(enqueueMindMessage).not.toHaveBeenCalled();+ expect(appendJournal).toHaveBeenCalledTimes(2);+ });++ it('tells the mind about a call nobody picked up', async () => {+ // An empty transcript is the one case where silence is the news: without+ // this the mind would never learn the call went unanswered and could dial+ // again to say the same thing.+ attachHost(socket());+ await startCall({ openingLine: 'This is PortOS.', origin: 'mind' });++ await endCall('caller-silent');++ expect(enqueueMindMessage).toHaveBeenCalledTimes(1);+ expect(enqueueMindMessage.mock.calls[0][0]).toContain('nothing said');+ expect(appendJournal).not.toHaveBeenCalled();+ });++ it('still ends cleanly when the mind handoff fails', async () => {+ // The handoff is telemetry for the next wake; losing it must not strand the+ // session in a state that blocks the next call.+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ enqueueMindMessage.mockRejectedValue(new Error('mind queue full'));+ attachHost(socket());+ await startCall({ openingLine: 'Hello', origin: 'mind' });+ recordTurn('caller', 'Hi');++ await endCall('remote-hangup');++ expect(getCallState()).toMatchObject({ state: 'idle', active: false });+ consoleError.mockRestore();+ });});diff --git a/server/services/voice/config.js b/server/services/voice/config.jsindex 5b719db41b..85fe745008 100644--- a/server/services/voice/config.js+++ b/server/services/voice/config.js@@ -25,6 +25,11 @@ export const VOICE_DEFAULTS = Object.freeze({blackHole16chLabel: 'BlackHole 16ch',// Hard ceiling on one call, so a line left open cannot run all day.maxCallMinutes: 15,+ // Escalate an unread critical notification to a phone call when no browser+ // tab can speak it. OFF by default: enabling the FaceTime feature must not+ // by itself make an install start ringing the user.+ escalateCritical: false,+ escalateAfterMinutes: 10,},stt: {diff --git a/server/services/voice/pipeline.js b/server/services/voice/pipeline.jsindex d5c715b4fa..1b28696081 100644--- a/server/services/voice/pipeline.js+++ b/server/services/voice/pipeline.js@@ -382,7 +382,12 @@ export const detectNarrationWithoutCall = ({ finalText, toolRuns }) =>// plenty for single-user PortOS.const shortId = () => Math.random().toString(36).slice(2, 7);-export const runTurn = async ({ audio, text, mimeType, source, history = [], emit, signal, state }) => {+// Cap on an injected per-conversation briefing (the FaceTime call host passes+// the persistent mind's). Bounded here because it rides in front of every turn+// of that conversation and a runaway caller would blow the model's window.+const MAX_SYSTEM_CONTEXT_CHARS = 4000;++export const runTurn = async ({ audio, text, mimeType, source, history = [], emit, signal, state, systemContext = null }) => {const cfg = await getVoiceConfig();if (signal?.aborted) return { transcript: '', reply: '' };@@ -570,6 +575,11 @@ export const runTurn = async ({ audio, text, mimeType, source, history = [], emiconst messages = [{ role: 'system', content: buildSystemPrompt(cfg) },];+ // Sits after the persona so it adds context without displacing the spoken-+ // reply rules; absent/blank leaves the turn exactly as it was.+ if (typeof systemContext === 'string' && systemContext.trim()) {+ messages.push({ role: 'system', content: systemContext.trim().slice(0, MAX_SYSTEM_CONTEXT_CHARS) });+ }if (shouldIncludeUi(userText, intent.activeGroups)) {const uiSummary = summarizeUi(state?.ui);if (uiSummary) {diff --git a/server/services/voice/proactiveSpeech.js b/server/services/voice/proactiveSpeech.jsindex 737d72f035..a0ee3965bf 100644--- a/server/services/voice/proactiveSpeech.js+++ b/server/services/voice/proactiveSpeech.js@@ -47,7 +47,7 @@ export const isWithinQuietHours = isWithinTimeWindow;// Pull the user's current local minutes-from-midnight via Intl. Server runs// TZ=UTC, so a naive `new Date().getHours()` would compare quiet hours// against UTC and silently let the bot speak during the user's bedtime.-const getLocalMinutes = async () => {+export const getLocalMinutes = async () => {const tz = await getUserTimezone();const parts = getLocalParts(new Date(), tz);return parts.hour * 60 + parts.minute;diff --git a/server/services/voice/proactiveTriggers.js b/server/services/voice/proactiveTriggers.jsindex e57785f780..a2ea1dbeb4 100644--- a/server/services/voice/proactiveTriggers.js+++ b/server/services/voice/proactiveTriggers.js@@ -11,6 +11,13 @@// 2. cosEvents 'task:ready' — a new task became spawnable.// 3. notificationEvents 'added' — only high/critical priority notifications.//+// A `critical` notification also arms a second, slower path: if it is STILL+// unread after `facetime.escalateAfterMinutes` and no browser tab can speak,+// PortOS asks to ring the user's phone (persistentMindCallCapability.js, which+// owns the quiet-hours / no-tab / rate-cap gate). That path is off by default+// behind `facetime.escalateCritical` — speaking into an empty room is cheap,+// but a phone call is not.+//// Each source has its OWN rate-limit bucket so a burst from one source can't// starve another, and a storm within a source can't talk over the user. The// rate-limit is applied BEFORE `speakProactive` (so we skip the config read +@@ -28,7 +35,7 @@import { errorEvents } from '../../lib/errorHandler.js';import { cosEvents } from '../cosEvents.js';-import { notificationEvents } from '../notifications.js';+import { getNotifications, notificationEvents } from '../notifications.js';import { speakProactive as defaultSpeak } from './proactiveSpeech.js';import { getVoiceConfig } from './config.js';import { TIMED_COOLDOWN_BLOCKED_CATEGORIES } from '../../lib/taskBlockCategories.js';@@ -48,6 +55,19 @@ export const RATE_LIMIT_MS = {// dropping or overlapping.};+// How long a critical notification may sit unread before PortOS escalates it+// from "spoken into an empty room" to "ring the user's phone". Only used when+// facetime.escalateCritical is on; the config value overrides it.+export const DEFAULT_ESCALATE_AFTER_MINUTES = 10;++// Imported lazily: the call gate reaches into cos state, the mind trajectory,+// and the FaceTime bridge, and none of that belongs in the module graph of a+// voice trigger that usually only speaks a sentence.+const defaultRequestCall = async (input) => {+ const { requestUserCall } = await import('../persistentMindCallCapability.js');+ return requestUserCall(input);+};+// Spoken lines should be short — synthesis is capped at MAX_PROACTIVE_TEXT_LEN// upstream, but for the ear a sentence or two is plenty. Trim long source text.const SPEECH_CLIP_LEN = 240;@@ -138,6 +158,22 @@ export const formatNotificationLine = (notification) => {return description ? `${title}. ${description}` : title;};+/** Minutes a critical notification may stay unread before a call is requested. */+export const escalateAfterMs = (cfg) => {+ const minutes = Number(cfg?.facetime?.escalateAfterMinutes);+ return (Number.isFinite(minutes) && minutes > 0 ? minutes : DEFAULT_ESCALATE_AFTER_MINUTES) * 60_000;+};++// What the user hears when they pick up. `openingLine` is capped at 400 chars+// by the call request schema, so the title/description are clipped first+// rather than letting a long notification lose the "why" at the end.+export const formatEscalationOpeningLine = (notification) => {+ const title = clip(notification?.title, 160);+ if (!title) return '';+ const description = clip(notification?.description, 160);+ return `This is PortOS. Something critical is still waiting for you: ${title}.${description ? ` ${description}` : ''}`;+};+// Truthy check mirroring isTruthyMeta — task metadata round-trips through// TASKS.md, so `voiceDispatch: true` comes back as the STRING 'true'. Kept// inline so this module stays decoupled from the agent-state helpers.@@ -175,7 +211,13 @@ export const formatTaskCompletionLine = (task) => {* @returns {Function} unwire — removes the listeners (boot wires once; tests* and hot-reload use this to avoid double-wiring).*/-export const wireProactiveTriggers = ({ io, speak = defaultSpeak, limits = RATE_LIMIT_MS } = {}) => {+export const wireProactiveTriggers = ({+ io,+ speak = defaultSpeak,+ limits = RATE_LIMIT_MS,+ requestCall = defaultRequestCall,+ readNotifications = getNotifications,+} = {}) => {if (!io) {console.warn('🔕 voice: proactive triggers not wired (no io)');return () => {};@@ -236,9 +278,62 @@ export const wireProactiveTriggers = ({ io, speak = defaultSpeak, limits = RATE_);};+ // Critical notifications waiting on their escalation timer, keyed by id. The+ // value is null between arming and scheduling so a duplicate 'added' for the+ // same notification cannot arm twice across the config read.+ const escalationTimers = new Map();++ // Ring the user only if the notification is STILL unread when the timer+ // fires — the whole point of waiting is to give them a chance to see it — and+ // only while the setting is on, re-read at fire time so a toggle flipped+ // during the wait is honoured in both directions.+ const escalateCriticalNotification = async (notification) => {+ const cfg = await getVoiceConfig();+ if (cfg?.facetime?.escalateCritical !== true) return { placed: false, reason: 'escalation-disabled' };+ const unread = await readNotifications({ unreadOnly: true });+ if (!Array.isArray(unread) || !unread.some((entry) => entry?.id === notification.id)) {+ return { placed: false, reason: 'already-read' };+ }+ const openingLine = formatEscalationOpeningLine(notification);+ if (!openingLine) return { placed: false, reason: 'empty' };+ return requestCall({+ // Authorized by facetime.escalateCritical, not by the mind's grant — but+ // subject to every other gate, including the shared 24-hour budget.+ requireMindGrant: false,+ source: 'critical-notification',+ reason: `A critical notification went unread: ${clip(notification?.title, 150)}`,+ openingLine,+ });+ };++ const armCriticalEscalation = (notification) => {+ if (notification?.priority !== 'critical' || !notification?.id) return;+ const { id } = notification;+ if (escalationTimers.has(id)) return;+ escalationTimers.set(id, null);+ getVoiceConfig().then((cfg) => {+ // Unwired (or already fired) while the config read was in flight.+ if (!escalationTimers.has(id)) return;+ const timer = setTimeout(() => {+ escalationTimers.delete(id);+ escalateCriticalNotification(notification).catch((err) =>+ console.error(`🔕 voice: critical notification escalation failed: ${err?.message || err}`),+ );+ }, escalateAfterMs(cfg));+ timer.unref?.();+ escalationTimers.set(id, timer);+ }).catch((err) => {+ escalationTimers.delete(id);+ console.error(`🔕 voice: could not arm critical notification escalation: ${err?.message || err}`);+ });+ };+const onError = (error) => fire('error', formatErrorLine(error), 'high');const onTaskReady = (task) => fire('task:ready', formatTaskLine(task), 'normal');- const onNotification = (notification) => fire('notification', formatNotificationLine(notification), 'high');+ const onNotification = (notification) => {+ fire('notification', formatNotificationLine(notification), 'high');+ armCriticalEscalation(notification);+ };// Announce completion of a coding task the user dispatched by voice. Keyed// off the TERMINAL task status (tasks:changed → updated → completed/blocked)@@ -307,5 +402,7 @@ export const wireProactiveTriggers = ({ io, speak = defaultSpeak, limits = RATE_cosEvents.off('tasks:changed', onTaskUpdated);notificationEvents.off('added', onNotification);announcedOutcomes.clear();+ for (const timer of escalationTimers.values()) if (timer) clearTimeout(timer);+ escalationTimers.clear();};};diff --git a/server/services/voice/proactiveTriggers.test.js b/server/services/voice/proactiveTriggers.test.jsindex 9743f04d18..c138915d94 100644--- a/server/services/voice/proactiveTriggers.test.js+++ b/server/services/voice/proactiveTriggers.test.js@@ -24,6 +24,9 @@ import {formatTaskCompletionLine,deriveTaskSpeechLabel,wireProactiveTriggers,+ formatEscalationOpeningLine,+ escalateAfterMs,+ DEFAULT_ESCALATE_AFTER_MINUTES,RATE_LIMIT_MS,} from './proactiveTriggers.js';@@ -458,3 +461,115 @@ describe('wireProactiveTriggers', () => {expect(speak).toHaveBeenCalledTimes(1);});});++describe('critical notification call escalation', () => {+ const critical = (overrides = {}) => ({+ id: 'notification-1',+ priority: 'critical',+ title: 'Nightly backup failed',+ description: 'Three consecutive nights.',+ ...overrides,+ });++ let unwire;+ let requestCall;+ let readNotifications;+ const speak = vi.fn(async () => ({ ok: true }));++ const wire = () => {+ unwire = wireProactiveTriggers({ io: {}, speak, requestCall, readNotifications });+ };++ beforeEach(() => {+ vi.useFakeTimers();+ requestCall = vi.fn(async () => ({ placed: true, reason: null }));+ readNotifications = vi.fn(async () => [critical()]);+ getVoiceConfig.mockResolvedValue({+ enabled: true,+ llm: { codeAgent: { announceOnComplete: true } },+ facetime: { escalateCritical: true, escalateAfterMinutes: 10 },+ });+ });++ afterEach(() => {+ unwire?.();+ unwire = null;+ vi.useRealTimers();+ vi.clearAllMocks();+ });++ // The config read that arms the timer is async, so let it settle before+ // advancing the fake clock.+ const settle = async () => { await vi.advanceTimersByTimeAsync(0); };++ it('falls back to the documented delay when the setting is absent or nonsense', () => {+ expect(escalateAfterMs({})).toBe(DEFAULT_ESCALATE_AFTER_MINUTES * 60_000);+ expect(escalateAfterMs({ facetime: { escalateAfterMinutes: 0 } })).toBe(DEFAULT_ESCALATE_AFTER_MINUTES * 60_000);+ expect(escalateAfterMs({ facetime: { escalateAfterMinutes: 25 } })).toBe(25 * 60_000);+ });++ it('calls only after the delay, and only while the notification is still unread', async () => {+ wire();+ notificationEvents.emit('added', critical());+ await settle();++ // The waiting period is the point: a user who reads it in time is not rung.+ await vi.advanceTimersByTimeAsync(9 * 60_000);+ expect(requestCall).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(60_000);+ expect(requestCall).toHaveBeenCalledWith(expect.objectContaining({+ requireMindGrant: false,+ source: 'critical-notification',+ openingLine: expect.stringContaining('Nightly backup failed'),+ }));+ });++ it('does not call when the notification was read during the wait', async () => {+ readNotifications = vi.fn(async () => []);+ wire();+ notificationEvents.emit('added', critical());+ await settle();+ await vi.advanceTimersByTimeAsync(10 * 60_000);+ expect(requestCall).not.toHaveBeenCalled();+ });++ it('ignores anything below critical', async () => {+ wire();+ notificationEvents.emit('added', critical({ priority: 'high' }));+ await settle();+ await vi.advanceTimersByTimeAsync(30 * 60_000);+ expect(requestCall).not.toHaveBeenCalled();+ });++ it('stays off unless escalateCritical is enabled, re-read when the timer fires', async () => {+ // The setting is checked at fire time, so turning it off during the wait+ // cancels the call rather than ringing on a stale decision.+ wire();+ notificationEvents.emit('added', critical());+ await settle();+ getVoiceConfig.mockResolvedValue({ enabled: true, facetime: { escalateCritical: false, escalateAfterMinutes: 10 } });+ await vi.advanceTimersByTimeAsync(10 * 60_000);+ expect(requestCall).not.toHaveBeenCalled();+ });++ it('arms one timer per notification and drops them all on unwire', async () => {+ wire();+ notificationEvents.emit('added', critical());+ notificationEvents.emit('added', critical());+ await settle();+ unwire();+ unwire = null;+ await vi.advanceTimersByTimeAsync(30 * 60_000);+ expect(requestCall).not.toHaveBeenCalled();+ });++ it('keeps the spoken opening line inside the call request bound', () => {+ const line = formatEscalationOpeningLine(critical({+ title: 'T'.repeat(400),+ description: 'D'.repeat(400),+ }));+ expect(line.length).toBeLessThanOrEqual(400);+ expect(formatEscalationOpeningLine({ priority: 'critical' })).toBe('');+ });+});diff --git a/server/sockets/voice.js b/server/sockets/voice.jsindex 6738470b06..5af0468210 100644--- a/server/sockets/voice.js+++ b/server/sockets/voice.js@@ -27,6 +27,7 @@ import { CALL_AUDIO_SAMPLE_RATE, createCallEndpointer, pcmToFloat } from '../serimport {attachHost,detachHost,+ getCallContext,getCallHost,isCallActive,markListening,@@ -34,7 +35,9 @@ import {noteCallerSpeech,recordTurn,setCallStateListener,+ takeCallOpeningLine,} from '../services/voice/callSession.js';+import { synthesize } from '../services/voice/tts.js';// Cap by messages (each user utterance + assistant reply is ~2). 24 → ~12 turns.const HISTORY_MESSAGES = 24;@@ -381,7 +384,37 @@ export const registerVoiceHandlers = (socket) => {// ---------------------------------------------------------------------------const call = { endpointer: null, busy: false };- const emitCallState = (snapshot) => socket.emit('voice:call:state', snapshot);+ // Speak the line the caller was rung to hear, once, as soon as the far end+ // picks up. Without this a mind-placed call connects to silence and the user+ // says "hello?" into a bot that has not been told why it is on the phone.+ const deliverOpeningLine = async () => {+ // Busy is checked BEFORE consuming: taking the line while a turn is in+ // flight would drop it for good. Leaving it pending means the next state+ // emit (that turn's own markListening) retries it.+ if (call.busy) return;+ const line = takeCallOpeningLine();+ if (!line) return;+ call.busy = true;+ markSpeaking();+ try {+ const { wav, latencyMs } = await synthesize(line);+ socket.emit('voice:call:tts', { sentence: line, wav, latencyMs });+ recordTurn('assistant', line);+ } finally {+ call.busy = false;+ markListening();+ }+ };++ const emitCallState = (snapshot) => {+ socket.emit('voice:call:state', snapshot);+ // 'listening' is the first state the poll reaches once the helper reports a+ // connected call. `takeCallOpeningLine` is consume-once, so the repeated+ // state emits this broadcast produces cannot repeat the line.+ if (snapshot?.state === 'listening') {+ deliverOpeningLine().catch((err) => console.error(`❌ voice call: opening line failed: ${err.message}`));+ }+ };const runCallUtterance = async (utterance) => {call.busy = true;@@ -393,6 +426,9 @@ export const registerVoiceHandlers = (socket) => {mimeType: 'audio/wav',history: state.history,state,+ // A mind-placed call carries the mind's own briefing, so the voice on+ // the phone continues that conversation instead of answering cold.+ systemContext: getCallContext(),// The pipeline speaks the widget's event vocabulary; only the audio is// re-addressed, so persona, tools, and the confirm gate are unchanged.emit: (event, data) => {diff --git a/server/sockets/voice.test.js b/server/sockets/voice.test.jsindex b34b2f2aeb..96a092ed60 100644--- a/server/sockets/voice.test.js+++ b/server/sockets/voice.test.js@@ -12,12 +12,24 @@ vi.mock(import('../services/voice/config.js'), async (importOriginal) => {};});+// The call host speaks its opening line through the real TTS entry point;+// stub it so the suite never loads a speech model.+vi.mock('../services/voice/tts.js', () => ({+ synthesize: vi.fn(async (text) => ({ wav: Buffer.from(`wav:${text}`), latencyMs: 1 })),+}));+const { truncateOnWordBoundary, registerVoiceHandlers } = await import('./voice.js');const {getVoiceOutputSocket,emitVoiceOutput,__resetVoiceOutput,} = await import('../services/voice/voiceOutput.js');+const {+ __resetCallSession,+ __setCallSessionDeps,+ pollCall,+ startCall,+} = await import('../services/voice/callSession.js');// Minimal fake socket: records on() handlers so tests can fire inbound events,// and captures emit() calls. No real Socket.IO needed — the voice:ui:index /@@ -257,3 +269,51 @@ describe('voice:output single-recipient wiring', () => {expect(getVoiceOutputSocket()).toBe(b);});});++describe('call host opening line', () => {+ const flush = () => new Promise((resolve) => setTimeout(resolve, 0));++ beforeEach(() => {+ __resetCallSession();+ __setCallSessionDeps({+ probe: vi.fn(async () => ({ state: 'connected' })),+ call: vi.fn(async () => ({ state: 'dialing' })),+ hangup: vi.fn(async () => ({ state: 'ended' })),+ appendJournal: vi.fn(async () => ({})),+ enqueueMindMessage: vi.fn(async () => ({})),+ });+ });++ it('speaks the line into the call once the far end picks up, and only once', async () => {+ // This is the end of the mind's call path: without it a placed call+ // connects to silence and the user hears nothing at all.+ const host = makeFakeSocket();+ registerVoiceHandlers(host);+ await host.fire('voice:call:attach');++ await startCall({ openingLine: 'This is PortOS about your backups.', origin: 'mind' });+ await pollCall();+ await flush();++ const spoken = host.emitted.filter((e) => e.event === 'voice:call:tts');+ expect(spoken).toHaveLength(1);+ expect(spoken[0].payload.sentence).toBe('This is PortOS about your backups.');++ // Every state transition re-broadcasts; the line must not be repeated.+ await pollCall();+ await flush();+ expect(host.emitted.filter((e) => e.event === 'voice:call:tts')).toHaveLength(1);+ });++ it('says nothing extra on a call the user placed themselves', async () => {+ const host = makeFakeSocket();+ registerVoiceHandlers(host);+ await host.fire('voice:call:attach');++ await startCall();+ await pollCall();+ await flush();++ expect(host.emitted.filter((e) => e.event === 'voice:call:tts')).toHaveLength(0);+ });+});