@ouro.bot/cli 0.1.0-alpha.1443 → 0.1.0-alpha.1445

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/changelog.json CHANGED
@@ -1,6 +1,16 @@
1
1
  {
2
2
  "_note": "Each pull request writes its own change note under changes/; the release job on main gives each landed change its version and adds the notes here (scripts/release-version.cjs). On main this file stops at the last version set by hand; the published package has every release. Agents read this file directly via read_file to understand what changed between versions.",
3
3
  "versions": [
4
+ {
5
+ "version": "0.1.0-alpha.1445",
6
+ "changes": [
7
+ "Phone calls on the OpenAI Realtime and SIP engines now record an outcome for each thing the caller says, as cascade calls already did. The earlier note said these engines were \"not covered yet\". Local audio rooms, which also run on the Realtime engine, are still not recorded. Each utterance is recorded once its transcript arrives, before a reply is asked for. The next reply the caller asked for answers everything they said since the last one. A greeting or a holding phrase answers nobody, and a reply that only called a tool hands what it answers on to the next one.",
8
+ "On those engines a reply counts as answered only once some of its audio played. On a Media Stream that means Twilio reported it played. On SIP it means OpenAI reported it started streaming the reply's audio to the caller. A reply's speech is noted before its audio goes out. A tool that may message a person is noted once its own checks pass, just before it runs, so a tool they refuse is not noted.",
9
+ "A reply whose audio was cleared before any played is recorded as failed, with the reason: the call ended, the caller talked over it, or a tool's audio took its place. If OpenAI keeps sending that reply's audio and some of it plays, it counts as answered. The call's opening audio plays after whatever is already playing, so it no longer stops a reply from counting. When the call hangs up through `voice_end_call` without speaking to what the caller said, that is recorded as silent. So is a Realtime or SIP outbound call answered by a voicemail or fax machine. Live audio is never replayed.",
10
+ "Each utterance record now names the process and bridge that made it. Once a bridge is listening, it records as failed only leftovers from a bridge that closed, a process that stopped, or an older build. It does the same for its own calls if it shuts down. Records of a bridge still open, in this process or another running one, are left for a later check, so a second bridge on another port with the same folder no longer fails a running call. Nothing in the daemon closes a voice bridge today, so in practice what a stopped process left is recorded as failed when the voice sense next starts.",
11
+ "Update the Ouro UI files to Ouro UI v1.3.473."
12
+ ]
13
+ },
4
14
  {
5
15
  "version": "0.1.0-alpha.1443",
6
16
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1443",
2
+ "runtimeVersion": "0.1.0-alpha.1445",
3
3
  "bundleSchemaVersion": 3,
4
4
  "lastUpdated": "2026-09-03T00:00:00.000Z"
5
5
  }
@@ -1,7 +1,7 @@
1
1
  <?xml version="1.0"?>
2
2
  <Container version="2">
3
3
  <Name>ouro-butler</Name>
4
- <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1443</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1445</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -0,0 +1,158 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.realtimeUtteranceLedger = realtimeUtteranceLedger;
4
+ exports.isAudioPart = isAudioPart;
5
+ exports.responseMadeAudio = responseMadeAudio;
6
+ const runtime_1 = require("../../nerves/runtime");
7
+ const turn_attempts_1 = require("../turn-attempts");
8
+ const utterances_1 = require("./utterances");
9
+ function segment(input) {
10
+ return input.trim().replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
11
+ }
12
+ /** Tool arguments as text: only text values can name who a send goes to or what it says. */
13
+ function textArgs(args) {
14
+ return Object.fromEntries(Object.entries(args).filter((entry) => typeof entry[1] === "string"));
15
+ }
16
+ function realtimeUtteranceLedger(call) {
17
+ const prefix = call.engine === "openai-sip" ? "sip" : "realtime";
18
+ let heardCount = 0;
19
+ let waiting = [];
20
+ const replies = new Map();
21
+ /** What the caller said before the call asked to hang up and no reply spoke to. */
22
+ const unansweredByChoice = new Set();
23
+ const settleAll = (utterances, ...outcome) => {
24
+ for (const utterance of utterances)
25
+ utterance.settle(...outcome);
26
+ };
27
+ return {
28
+ heard(itemId) {
29
+ heardCount += 1;
30
+ const id = `${prefix}-${segment(call.callSid)}-${segment(itemId) || `caller-${heardCount}`}`;
31
+ const record = (0, utterances_1.recordVoiceUtterance)(call.outputDir, id, {
32
+ callSid: call.callSid, friendId: call.friendId, sessionKey: call.sessionKey, transport: call.engine,
33
+ }, call.bridge);
34
+ if (!record)
35
+ return;
36
+ record.beginAttempt();
37
+ waiting.push(record);
38
+ },
39
+ replyStarted(responseId, answers) {
40
+ if (!answers || !responseId || waiting.length === 0)
41
+ return;
42
+ replies.set(responseId, { utterances: waiting, spoke: false, unheard: false, done: false, cut: null });
43
+ waiting = [];
44
+ },
45
+ speaking(responseId) {
46
+ const reply = replies.get(responseId);
47
+ if (!reply)
48
+ return;
49
+ reply.unheard = true;
50
+ if (reply.spoke)
51
+ return;
52
+ reply.spoke = true;
53
+ const spoke = (0, turn_attempts_1.turnSpoke)("speech:audio", null);
54
+ for (const utterance of reply.utterances)
55
+ utterance.noteSpoke(spoke);
56
+ },
57
+ played(responseId) {
58
+ const reply = replies.get(responseId);
59
+ if (!reply)
60
+ return;
61
+ replies.delete(responseId);
62
+ settleAll(reply.utterances, "answered");
63
+ },
64
+ replyDone(responseId, madeAudio = false) {
65
+ const reply = replies.get(responseId);
66
+ if (!reply)
67
+ return;
68
+ // Audio still on its way to the caller may yet play.
69
+ if (reply.unheard || (madeAudio && !reply.cut)) {
70
+ reply.done = true;
71
+ return;
72
+ }
73
+ replies.delete(responseId);
74
+ if (reply.cut)
75
+ settleAll(reply.utterances, "failed", reply.cut);
76
+ else
77
+ waiting = [...reply.utterances, ...waiting];
78
+ },
79
+ toolSending(name, args) {
80
+ const spoke = (0, turn_attempts_1.turnSpokeForTool)(name, textArgs(args));
81
+ if (!spoke)
82
+ return;
83
+ for (const reply of replies.values())
84
+ for (const utterance of reply.utterances)
85
+ utterance.noteSpoke(spoke);
86
+ for (const utterance of waiting)
87
+ utterance.noteSpoke(spoke);
88
+ },
89
+ hangingUp() {
90
+ for (const reply of replies.values())
91
+ if (!reply.spoke)
92
+ for (const utterance of reply.utterances)
93
+ unansweredByChoice.add(utterance);
94
+ for (const utterance of waiting)
95
+ unansweredByChoice.add(utterance);
96
+ },
97
+ cutOff(reason) {
98
+ for (const [responseId, reply] of replies) {
99
+ if (!reply.unheard)
100
+ continue;
101
+ reply.unheard = false;
102
+ reply.cut = reason;
103
+ if (!reply.done)
104
+ continue;
105
+ replies.delete(responseId);
106
+ settleAll(reply.utterances, "failed", reason);
107
+ }
108
+ },
109
+ ended(silent) {
110
+ const counts = { failed: 0, silent: 0 };
111
+ const settle = (utterances, spoke, failure) => {
112
+ for (const utterance of utterances) {
113
+ if (silent || (!spoke && unansweredByChoice.has(utterance))) {
114
+ utterance.settle("silent", silent ?? "the call was ended without a spoken reply");
115
+ counts.silent += 1;
116
+ }
117
+ else {
118
+ utterance.settle("failed", failure);
119
+ counts.failed += 1;
120
+ }
121
+ }
122
+ };
123
+ for (const reply of replies.values()) {
124
+ settle(reply.utterances, reply.spoke, reply.cut && !reply.unheard ? reply.cut : "the call ended before the reply was played");
125
+ }
126
+ replies.clear();
127
+ settle(waiting, false, "the call ended before this was answered");
128
+ waiting = [];
129
+ if (counts.failed + counts.silent === 0)
130
+ return;
131
+ (0, runtime_1.emitNervesEvent)({
132
+ level: counts.failed > 0 ? "warn" : "info",
133
+ component: "senses",
134
+ event: "senses.voice_realtime_utterances_unanswered",
135
+ message: "a phone call ended with things the caller said that no reply played to",
136
+ meta: { engine: call.engine, callSid: segment(call.callSid), ...counts },
137
+ });
138
+ },
139
+ };
140
+ }
141
+ /** Whether a response content part is audio, as in `response.content_part.added` or a finished response's output. */
142
+ function isAudioPart(part) {
143
+ const type = part && typeof part === "object" ? part.type : undefined;
144
+ return type === "output_audio" || type === "audio";
145
+ }
146
+ /** Whether a finished response's output held audio, from its `response.done` event. */
147
+ function responseMadeAudio(event) {
148
+ const response = event.response;
149
+ if (!response || typeof response !== "object" || Array.isArray(response))
150
+ return false;
151
+ const output = response.output;
152
+ if (!Array.isArray(output))
153
+ return false;
154
+ return output.some((item) => {
155
+ const content = item && typeof item === "object" ? item.content : undefined;
156
+ return Array.isArray(content) && content.some(isAudioPart);
157
+ });
158
+ }
@@ -83,6 +83,7 @@ const playback_1 = require("./playback");
83
83
  const transcript_1 = require("./transcript");
84
84
  const turn_1 = require("./turn");
85
85
  const utterances_1 = require("./utterances");
86
+ const realtime_utterances_1 = require("./realtime-utterances");
86
87
  const phone_1 = require("./phone");
87
88
  const audio_playback_1 = require("./audio-playback");
88
89
  const floor_controller_1 = require("./floor-controller");
@@ -682,6 +683,8 @@ async function transcribeRecordingOrNoSpeech(options) {
682
683
  throw error;
683
684
  }
684
685
  }
686
+ /** Why an outbound call a voicemail or fax machine answered was ended, as its utterances record it. */
687
+ const MACHINE_ANSWERED = "a voicemail or fax machine answered the call, so it was ended";
685
688
  class TwilioMediaStreamSession {
686
689
  socket;
687
690
  identity;
@@ -996,7 +999,7 @@ class TwilioMediaStreamSession {
996
999
  // Recorded before anything can fail, so what the caller said ends in an outcome even if this process stops.
997
1000
  const record = (0, utterances_1.recordVoiceUtterance)(this.options.outputDir, utterance.utteranceId, {
998
1001
  callSid: this.callSid, friendId: this.friendId, sessionKey: this.sessionKey, transport: "media-stream",
999
- });
1002
+ }, this.lifecycle?.utteranceBridge);
1000
1003
  try {
1001
1004
  await this.answerUtterance(utterance, record);
1002
1005
  }
@@ -1779,6 +1782,8 @@ class TwilioOpenAIRealtimeMediaStreamSession {
1779
1782
  callerTurnSequence = 0;
1780
1783
  gatedResponseRequestSequence = 0;
1781
1784
  pendingGatedResponseId = null;
1785
+ /** What the caller said and what became of it. Phone calls only: a local audio room has no phone caller. */
1786
+ utterances = null;
1782
1787
  constructor(socket, identity, options, lifecycle) {
1783
1788
  this.socket = socket;
1784
1789
  this.identity = identity;
@@ -1798,9 +1803,9 @@ class TwilioOpenAIRealtimeMediaStreamSession {
1798
1803
  });
1799
1804
  });
1800
1805
  }
1801
- end() {
1806
+ end(silent) {
1802
1807
  this.socket.close();
1803
- this.close();
1808
+ this.close(silent);
1804
1809
  }
1805
1810
  /** Feed a raw Twilio message that arrived before this session attached (the bridge holds the first `start`). */
1806
1811
  handleRawMessage(raw) {
@@ -1869,6 +1874,16 @@ class TwilioOpenAIRealtimeMediaStreamSession {
1869
1874
  callSid: this.callSid,
1870
1875
  });
1871
1876
  this.lifecycle?.onIdentityChange?.(this, { callSid: this.callSid, outboundId: this.outboundId });
1877
+ if (!local) {
1878
+ this.utterances = (0, realtime_utterances_1.realtimeUtteranceLedger)({
1879
+ outputDir: this.options.outputDir,
1880
+ bridge: this.lifecycle?.utteranceBridge,
1881
+ engine: "openai-realtime",
1882
+ callSid: this.callSid,
1883
+ friendId: this.friendId,
1884
+ sessionKey: this.sessionKey,
1885
+ });
1886
+ }
1872
1887
  this.floor = new floor_controller_1.VoiceFloorController({
1873
1888
  transport: "twilio-media-stream",
1874
1889
  agentName: this.options.agentName,
@@ -2108,6 +2123,7 @@ class TwilioOpenAIRealtimeMediaStreamSession {
2108
2123
  if (!this.hangupRequested) {
2109
2124
  this.floor.apply({ type: "hangup.requested", atMs: Date.now(), reason: "voice_end_call" });
2110
2125
  }
2126
+ this.utterances?.hangingUp();
2111
2127
  this.hangupRequested = true;
2112
2128
  setTimeout(() => this.completeHangupIfReady("tool_fallback"), 7_500).unref?.();
2113
2129
  }
@@ -2190,6 +2206,8 @@ class TwilioOpenAIRealtimeMediaStreamSession {
2190
2206
  if (!playback)
2191
2207
  return;
2192
2208
  this.playbackMarks.delete(name);
2209
+ // Twilio returns a mark once the audio before it has played, so the reply reached the caller.
2210
+ this.utterances?.played(playback.responseId);
2193
2211
  if (this.playbackState
2194
2212
  && this.playbackState.itemId === playback.itemId
2195
2213
  && this.playbackState.contentIndex === playback.contentIndex) {
@@ -2223,7 +2241,7 @@ class TwilioOpenAIRealtimeMediaStreamSession {
2223
2241
  return;
2224
2242
  }
2225
2243
  if (type === "conversation.item.input_audio_transcription.completed" && typeof event.transcript === "string") {
2226
- this.handleUserTranscript(event.transcript);
2244
+ this.handleUserTranscript(event.transcript, stringField(event.item_id));
2227
2245
  return;
2228
2246
  }
2229
2247
  if (type === "response.output_audio_transcript.done" && typeof event.transcript === "string") {
@@ -2236,6 +2254,7 @@ class TwilioOpenAIRealtimeMediaStreamSession {
2236
2254
  }
2237
2255
  if (type === "response.done") {
2238
2256
  const responseId = realtimeResponseId(event);
2257
+ this.utterances?.replyDone(responseId);
2239
2258
  this.noteRealtimeResponseDone(responseId);
2240
2259
  if (this.completeRealtimeToolResponse(responseId))
2241
2260
  return;
@@ -2263,10 +2282,12 @@ class TwilioOpenAIRealtimeMediaStreamSession {
2263
2282
  return;
2264
2283
  this.noteRealtimeResponseConflict();
2265
2284
  }
2266
- handleUserTranscript(transcript) {
2285
+ handleUserTranscript(transcript, itemId) {
2267
2286
  const content = transcript.trim();
2268
2287
  if (!content)
2269
2288
  return;
2289
+ // Recorded before a reply is asked for, so what the caller said ends in an outcome even if this process stops.
2290
+ this.utterances?.heard(itemId);
2270
2291
  this.appendTranscript("user", content);
2271
2292
  const turnId = this.activeCallerTurnId ?? `caller-turn-${++this.callerTurnSequence}`;
2272
2293
  this.activeCallerTurnId = undefined;
@@ -2314,6 +2335,9 @@ class TwilioOpenAIRealtimeMediaStreamSession {
2314
2335
  return;
2315
2336
  const itemId = stringField(event.item_id);
2316
2337
  const contentIndex = numberField(event.content_index) ?? 0;
2338
+ const responseId = stringField(event.response_id) || this.activeRealtimeResponseId || "";
2339
+ // Noted before it can play, so a stopped call's record says what the caller heard.
2340
+ this.utterances?.speaking(responseId);
2317
2341
  let audioEndMs;
2318
2342
  if (itemId) {
2319
2343
  let current = this.playbackState;
@@ -2326,7 +2350,7 @@ class TwilioOpenAIRealtimeMediaStreamSession {
2326
2350
  }
2327
2351
  this.sendTwilioMedia(payload);
2328
2352
  if (itemId && audioEndMs !== undefined)
2329
- this.sendTwilioMark({ itemId, contentIndex, audioEndMs });
2353
+ this.sendTwilioMark({ responseId, itemId, contentIndex, audioEndMs });
2330
2354
  }
2331
2355
  handleCallerSpeechStarted() {
2332
2356
  this.clearPendingUserTurnResponse();
@@ -2367,6 +2391,7 @@ class TwilioOpenAIRealtimeMediaStreamSession {
2367
2391
  this.pendingGatedResponseId = null;
2368
2392
  }
2369
2393
  this.playbackMarks.clear();
2394
+ this.utterances?.cutOff("the caller spoke again before the reply was played");
2370
2395
  this.sendTwilioClear();
2371
2396
  if (!playback?.itemId)
2372
2397
  return;
@@ -2510,8 +2535,7 @@ class TwilioOpenAIRealtimeMediaStreamSession {
2510
2535
  message: "OpenAI Realtime voice tool call started",
2511
2536
  meta: { agentName: this.options.agentName, callSid: safeSegment(this.callSid), tool: name },
2512
2537
  });
2513
- // A call has no one to approve a protected tool, so it never runs here.
2514
- output = await (0, tools_1.rejectionWithoutApprover)(name, args, this.toolContext) ?? await (0, tools_1.execTool)(name, args, this.toolContext);
2538
+ output = await this.execRealtimeTool(name, args);
2515
2539
  (0, runtime_1.emitNervesEvent)({
2516
2540
  component: "senses",
2517
2541
  event: "senses.voice_twilio_realtime_tool_end",
@@ -2547,8 +2571,19 @@ class TwilioOpenAIRealtimeMediaStreamSession {
2547
2571
  this.requestRealtimeResponse();
2548
2572
  }
2549
2573
  }
2550
- /* v8 ignore start -- unchanged response coordination transport @preserve */
2574
+ /**
2575
+ * A call has no one to approve a protected tool, so it never runs here. A send it makes is noted once the tool's own
2576
+ * checks passed, just before it runs: one they refuse sent nothing.
2577
+ */
2578
+ async execRealtimeTool(name, args) {
2579
+ const refused = await (0, tools_1.rejectionWithoutApprover)(name, args, this.toolContext);
2580
+ if (refused !== null)
2581
+ return refused;
2582
+ return (0, tools_1.execTool)(name, args, { ...this.toolContext, beforeHandler: () => this.utterances?.toolSending(name, args) });
2583
+ }
2551
2584
  noteRealtimeResponseCreated(event) {
2585
+ // A reply the call asked for itself carries its own instructions (the greeting, a holding phrase): it answers nobody.
2586
+ this.utterances?.replyStarted(realtimeResponseId(event), !this.realtimeResponseCreateInFlight?.response?.instructions);
2552
2587
  this.realtimeResponseCreateInFlight = null;
2553
2588
  this.untrackedActiveRealtimeResponse = false;
2554
2589
  this.clearUntrackedActiveRealtimeResponseTimer();
@@ -2556,6 +2591,7 @@ class TwilioOpenAIRealtimeMediaStreamSession {
2556
2591
  if (responseId)
2557
2592
  this.activeRealtimeResponseId = responseId;
2558
2593
  }
2594
+ /* v8 ignore start -- unchanged response coordination transport @preserve */
2559
2595
  noteRealtimeResponseDone(_responseId) {
2560
2596
  this.realtimeResponseCreateInFlight = null;
2561
2597
  this.untrackedActiveRealtimeResponse = false;
@@ -2733,10 +2769,13 @@ class TwilioOpenAIRealtimeMediaStreamSession {
2733
2769
  const prepared = await (0, audio_playback_1.prepareVoiceCallAudio)(request, {
2734
2770
  agentRoot: resolveTwilioPhoneAgentRoot(this.options),
2735
2771
  });
2736
- this.playbackMarks.clear();
2737
- this.playbackState = undefined;
2738
- if (playbackOptions.clearFirst ?? true)
2772
+ // Audio that goes after what is playing, like the call's opening audio, leaves its marks to count as it plays.
2773
+ if (playbackOptions.clearFirst ?? true) {
2774
+ this.playbackMarks.clear();
2775
+ this.playbackState = undefined;
2776
+ this.utterances?.cutOff("audio a tool played took its place before the reply was played");
2739
2777
  this.sendTwilioClear();
2778
+ }
2740
2779
  for (let offset = 0; offset < prepared.audio.byteLength; offset += 160) {
2741
2780
  if (this.closed || !this.socket.isOpen())
2742
2781
  break;
@@ -2819,10 +2858,11 @@ class TwilioOpenAIRealtimeMediaStreamSession {
2819
2858
  });
2820
2859
  this.end();
2821
2860
  }
2822
- close() {
2861
+ close(silent) {
2823
2862
  if (this.closed)
2824
2863
  return;
2825
2864
  this.closed = true;
2865
+ this.utterances?.ended(silent);
2826
2866
  this.disclosure?.stop();
2827
2867
  if (this.openaiWs && (this.openaiWs.readyState === ws_1.WebSocket.OPEN || this.openaiWs.readyState === ws_1.WebSocket.CONNECTING)) {
2828
2868
  this.openaiWs.close();
@@ -2892,6 +2932,8 @@ class OpenAISipPhoneSession {
2892
2932
  callerTurnSequence = 0;
2893
2933
  gatedResponseRequestSequence = 0;
2894
2934
  pendingGatedResponseId = null;
2935
+ /** What the caller said and what became of it. */
2936
+ utterances = null;
2895
2937
  constructor(options, metadata, registry) {
2896
2938
  this.options = options;
2897
2939
  this.metadata = metadata;
@@ -2926,6 +2968,14 @@ class OpenAISipPhoneSession {
2926
2968
  to: this.metadata.to,
2927
2969
  callSid: this.metadata.callId,
2928
2970
  });
2971
+ this.utterances = (0, realtime_utterances_1.realtimeUtteranceLedger)({
2972
+ outputDir: this.options.outputDir,
2973
+ bridge: this.registry?.utteranceBridge,
2974
+ engine: "openai-sip",
2975
+ callSid: this.metadata.callId,
2976
+ friendId: this.friendId,
2977
+ sessionKey: this.sessionKey,
2978
+ });
2929
2979
  this.floor = new floor_controller_1.VoiceFloorController({
2930
2980
  transport: "openai-sip",
2931
2981
  agentName: this.options.agentName,
@@ -3417,6 +3467,17 @@ class OpenAISipPhoneSession {
3417
3467
  this.noteRealtimeResponseCreated(event);
3418
3468
  return;
3419
3469
  }
3470
+ // OpenAI sends a reply's audio straight down the SIP call. Its audio part is added just before the audio starts,
3471
+ // so speech is noted then, and the audio buffer starting (or audio reflected here) means it reached the caller.
3472
+ if (type === "response.content_part.added") {
3473
+ if ((0, realtime_utterances_1.isAudioPart)(event.part))
3474
+ this.utterances?.speaking(realtimeResponseId(event));
3475
+ return;
3476
+ }
3477
+ if (type === "output_audio_buffer.started" || type === "response.output_audio.delta") {
3478
+ this.utterances?.played(realtimeResponseId(event));
3479
+ return;
3480
+ }
3420
3481
  if (type === "input_audio_buffer.speech_started") {
3421
3482
  this.clearPendingUserTurnResponse();
3422
3483
  return;
@@ -3427,7 +3488,7 @@ class OpenAISipPhoneSession {
3427
3488
  }
3428
3489
  if (type === "conversation.item.input_audio_transcription.completed" && typeof event.transcript === "string") {
3429
3490
  this.recordOutboundAmdTranscriptCandidate(event.transcript);
3430
- this.handleUserTranscript(event.transcript);
3491
+ this.handleUserTranscript(event.transcript, stringField(event.item_id));
3431
3492
  return;
3432
3493
  }
3433
3494
  if (type === "response.output_audio_transcript.done" && typeof event.transcript === "string") {
@@ -3440,6 +3501,7 @@ class OpenAISipPhoneSession {
3440
3501
  }
3441
3502
  if (type === "response.done") {
3442
3503
  const responseId = realtimeResponseId(event);
3504
+ this.utterances?.replyDone(responseId, (0, realtime_utterances_1.responseMadeAudio)(event));
3443
3505
  this.noteRealtimeResponseDone(responseId);
3444
3506
  if (this.completeRealtimeToolResponse(responseId))
3445
3507
  return;
@@ -3466,10 +3528,12 @@ class OpenAISipPhoneSession {
3466
3528
  return;
3467
3529
  this.noteRealtimeResponseConflict();
3468
3530
  }
3469
- handleUserTranscript(transcript) {
3531
+ handleUserTranscript(transcript, itemId) {
3470
3532
  const content = transcript.trim();
3471
3533
  if (!content)
3472
3534
  return;
3535
+ // Recorded before a reply is asked for, so what the caller said ends in an outcome even if this process stops.
3536
+ this.utterances?.heard(itemId);
3473
3537
  this.appendTranscript("user", content);
3474
3538
  const turnId = this.activeCallerTurnId ?? `caller-turn-${++this.callerTurnSequence}`;
3475
3539
  this.activeCallerTurnId = undefined;
@@ -3617,8 +3681,7 @@ class OpenAISipPhoneSession {
3617
3681
  message: "OpenAI SIP voice tool call started",
3618
3682
  meta: { agentName: this.options.agentName, callId: safeSegment(this.metadata.callId), tool: name },
3619
3683
  });
3620
- // A call has no one to approve a protected tool, so it never runs here.
3621
- output = await (0, tools_1.rejectionWithoutApprover)(name, args, this.toolContext) ?? await (0, tools_1.execTool)(name, args, this.toolContext);
3684
+ output = await this.execRealtimeTool(name, args);
3622
3685
  (0, runtime_1.emitNervesEvent)({
3623
3686
  component: "senses",
3624
3687
  event: "senses.voice_openai_sip_tool_end",
@@ -3654,15 +3717,27 @@ class OpenAISipPhoneSession {
3654
3717
  this.requestRealtimeResponse();
3655
3718
  }
3656
3719
  }
3657
- /* v8 ignore start -- unchanged SIP response coordination @preserve */
3720
+ /**
3721
+ * A call has no one to approve a protected tool, so it never runs here. A send it makes is noted once the tool's own
3722
+ * checks passed, just before it runs: one they refuse sent nothing.
3723
+ */
3724
+ async execRealtimeTool(name, args) {
3725
+ const refused = await (0, tools_1.rejectionWithoutApprover)(name, args, this.toolContext);
3726
+ if (refused !== null)
3727
+ return refused;
3728
+ return (0, tools_1.execTool)(name, args, { ...this.toolContext, beforeHandler: () => this.utterances?.toolSending(name, args) });
3729
+ }
3658
3730
  noteRealtimeResponseCreated(event) {
3731
+ const responseId = realtimeResponseId(event);
3732
+ // A reply the call asked for itself carries its own instructions (the greeting, a holding phrase): it answers nobody.
3733
+ this.utterances?.replyStarted(responseId, !this.realtimeResponseCreateInFlight?.response?.instructions);
3659
3734
  this.realtimeResponseCreateInFlight = null;
3660
3735
  this.untrackedActiveRealtimeResponse = false;
3661
3736
  this.clearUntrackedActiveRealtimeResponseTimer();
3662
- const responseId = realtimeResponseId(event);
3663
3737
  if (responseId)
3664
3738
  this.activeRealtimeResponseId = responseId;
3665
3739
  }
3740
+ /* v8 ignore start -- unchanged SIP response coordination @preserve */
3666
3741
  noteRealtimeResponseDone(_responseId) {
3667
3742
  this.realtimeResponseCreateInFlight = null;
3668
3743
  this.untrackedActiveRealtimeResponse = false;
@@ -3806,6 +3881,7 @@ class OpenAISipPhoneSession {
3806
3881
  requestHangupFromTool() {
3807
3882
  if (this.closed)
3808
3883
  return;
3884
+ this.utterances?.hangingUp();
3809
3885
  this.hangupRequested = true;
3810
3886
  setTimeout(() => this.completeHangupIfReady("tool_fallback"), 7_500).unref?.();
3811
3887
  }
@@ -3881,6 +3957,7 @@ class OpenAISipPhoneSession {
3881
3957
  if (this.closed)
3882
3958
  return;
3883
3959
  this.closed = true;
3960
+ this.utterances?.ended(trigger === "amd_nonhuman" ? MACHINE_ANSWERED : undefined);
3884
3961
  this.clearOutboundAmdGreetingTimeout();
3885
3962
  this.registry?.unregister(this);
3886
3963
  if (this.openaiWs && (this.openaiWs.readyState === ws_1.WebSocket.OPEN || this.openaiWs.readyState === ws_1.WebSocket.CONNECTING)) {
@@ -3908,6 +3985,10 @@ class OpenAISipPhoneSession {
3908
3985
  /* v8 ignore stop */
3909
3986
  /* v8 ignore start -- active SIP registry map edge permutations belong with the post-D-012 transport split; SIP call lifecycle is covered through bridge tests @preserve */
3910
3987
  class ActiveOpenAISipSessions {
3988
+ utteranceBridge;
3989
+ constructor(utteranceBridge) {
3990
+ this.utteranceBridge = utteranceBridge;
3991
+ }
3911
3992
  byCallId = new Map();
3912
3993
  byOutboundId = new Map();
3913
3994
  register(session) {
@@ -4895,7 +4976,7 @@ async function handleOutgoingAmdStatus(options, outboundId, params, activeMediaS
4895
4976
  if (nonHumanStatus) {
4896
4977
  const session = activeMediaStreams.byOutboundId.get(job.outboundId)
4897
4978
  ?? (callSid ? activeMediaStreams.byCallSid.get(callSid) : undefined);
4898
- session?.end();
4979
+ session?.end(MACHINE_ANSWERED);
4899
4980
  activeSipSessions.getByOutboundId(job.outboundId)?.handleAsyncAmd(answeredBy, nonHumanStatus);
4900
4981
  (0, runtime_1.emitNervesEvent)({
4901
4982
  component: "senses",
@@ -4935,7 +5016,7 @@ async function handleListen(options, basePath) {
4935
5016
  maxLengthSeconds: options.recordMaxLengthSeconds ?? exports.DEFAULT_TWILIO_RECORD_MAX_LENGTH_SECONDS,
4936
5017
  }));
4937
5018
  }
4938
- async function handleRecording(options, basePath, params, jobs) {
5019
+ async function handleRecording(options, basePath, params, jobs, utteranceBridge) {
4939
5020
  const recording = parseRecordingParams(params);
4940
5021
  if (!recording) {
4941
5022
  (0, runtime_1.emitNervesEvent)({
@@ -4970,7 +5051,7 @@ async function handleRecording(options, basePath, params, jobs) {
4970
5051
  ? streamedReplyTwiml(options, basePath, safeCallSid, jobId)
4971
5052
  : redirectTwiml(options.publicBaseUrl, basePath));
4972
5053
  }
4973
- const answer = answerRecording(options, basePath, params, jobs, recording, utteranceId);
5054
+ const answer = answerRecording(options, basePath, params, jobs, recording, utteranceId, utteranceBridge);
4974
5055
  recordingsInFlight.set(inFlightKey, answer);
4975
5056
  try {
4976
5057
  return await answer;
@@ -4993,7 +5074,7 @@ function heldUtterance(record) {
4993
5074
  }
4994
5075
  /** Replies to recording callbacks still being answered, so a retry Twilio sends meanwhile gets the same reply. */
4995
5076
  const recordingsInFlight = new Map();
4996
- async function answerRecording(options, basePath, params, jobs, recording, utteranceId) {
5077
+ async function answerRecording(options, basePath, params, jobs, recording, utteranceId, utteranceBridge) {
4997
5078
  const safeCallSid = safeSegment(recording.callSid);
4998
5079
  const safeRecordingSid = safeSegment(recording.recordingSid);
4999
5080
  const callDir = path.join(options.outputDir, safeCallSid);
@@ -5019,7 +5100,7 @@ async function answerRecording(options, basePath, params, jobs, recording, utter
5019
5100
  });
5020
5101
  const record = (0, utterances_1.recordVoiceUtterance)(options.outputDir, utteranceId, {
5021
5102
  callSid: safeCallSid, friendId, sessionKey, transport: "recording",
5022
- });
5103
+ }, utteranceBridge);
5023
5104
  const failRecord = (error) => record?.settle("failed", `the turn failed: ${errorMessage(error)}`);
5024
5105
  try {
5025
5106
  if (normalizeTwilioPhonePlaybackMode(options.playbackMode) === "stream") {
@@ -5239,8 +5320,12 @@ function admitMediaStreamStart(options, pending, activeMediaStreams, start) {
5239
5320
  activeMediaStreams.reserved.add(callSid);
5240
5321
  return identity;
5241
5322
  }
5323
+ /** The id each bridge's utterance records carry, so the server that listens for it sweeps as that bridge. */
5324
+ const bridgeUtteranceIds = new WeakMap();
5242
5325
  function createTwilioPhoneBridge(options) {
5243
5326
  new URL(options.publicBaseUrl);
5327
+ // The id this bridge's calls' utterance records carry, so another bridge's sweep leaves them alone while it is open.
5328
+ const utteranceBridge = (0, utterances_1.openVoiceUtteranceBridge)();
5244
5329
  const basePath = normalizeTwilioPhoneBasePath(options.basePath);
5245
5330
  const sipWebhookPath = normalizeTwilioPhoneBasePath(options.openaiSip?.webhookPath ?? openAISipWebhookPath(options.agentName));
5246
5331
  const jobs = new TwilioAudioStreamJobStore();
@@ -5250,7 +5335,7 @@ function createTwilioPhoneBridge(options) {
5250
5335
  byOutboundId: new Map(),
5251
5336
  reserved: new Set(),
5252
5337
  };
5253
- const activeSipSessions = new ActiveOpenAISipSessions();
5338
+ const activeSipSessions = new ActiveOpenAISipSessions(utteranceBridge);
5254
5339
  const pendingCalls = options.pendingVoiceCalls ?? new call_auth_1.PendingVoiceCalls();
5255
5340
  const recentSipWebhooks = new call_auth_1.RecentIds();
5256
5341
  mediaStreams.on("connection", (ws) => {
@@ -5267,6 +5352,7 @@ function createTwilioPhoneBridge(options) {
5267
5352
  });
5268
5353
  let reservedCallSid = "";
5269
5354
  const lifecycle = {
5355
+ utteranceBridge,
5270
5356
  onIdentityChange: (activeSession, identity) => {
5271
5357
  activeMediaStreams.byCallSid.set(identity.callSid, activeSession);
5272
5358
  if (identity.outboundId)
@@ -5320,7 +5406,7 @@ function createTwilioPhoneBridge(options) {
5320
5406
  };
5321
5407
  ws.on("message", gate);
5322
5408
  });
5323
- return {
5409
+ const bridge = {
5324
5410
  async handle(request) {
5325
5411
  const method = request.method.toUpperCase();
5326
5412
  const requestPath = request.path.startsWith("/") ? request.path : `/${request.path}`;
@@ -5386,7 +5472,7 @@ function createTwilioPhoneBridge(options) {
5386
5472
  if (routePath === `${basePath}/listen`)
5387
5473
  return handleListen(options, basePath);
5388
5474
  if (routePath === `${basePath}/recording`)
5389
- return handleRecording(options, basePath, params, jobs);
5475
+ return handleRecording(options, basePath, params, jobs, utteranceBridge);
5390
5476
  return textResponse(404, "not found");
5391
5477
  },
5392
5478
  handleUpgrade(request, socket, head) {
@@ -5408,12 +5494,16 @@ function createTwilioPhoneBridge(options) {
5408
5494
  return true;
5409
5495
  },
5410
5496
  close() {
5411
- (0, utterances_1.failLeftoverVoiceUtterances)(options.outputDir, "shutdown");
5497
+ // This bridge's calls stop here, so what they left unanswered is failed; another open bridge's is left to it.
5498
+ (0, utterances_1.failLeftoverVoiceUtterances)(options.outputDir, "shutdown", utteranceBridge);
5499
+ (0, utterances_1.closeVoiceUtteranceBridge)(utteranceBridge);
5412
5500
  return new Promise((resolve, reject) => {
5413
5501
  mediaStreams.close((error) => error ? reject(error) : resolve());
5414
5502
  });
5415
5503
  },
5416
5504
  };
5505
+ bridgeUtteranceIds.set(bridge, utteranceBridge);
5506
+ return bridge;
5417
5507
  }
5418
5508
  /* v8 ignore start -- HTTP server adapter behavior is covered through startTwilioPhoneBridgeServer smoke tests; low-level stream disconnect branches are platform-dependent @preserve */
5419
5509
  function readRequestBody(req, limitBytes = 1_000_000) {
@@ -5551,9 +5641,9 @@ async function startTwilioPhoneBridgeServer(options) {
5551
5641
  server.once("listening", onListening);
5552
5642
  server.listen(port, host);
5553
5643
  });
5554
- // Live audio is never replayed: whatever a stopped process left unanswered is recorded as failed. This waits until
5555
- // the port is ours, so a second bridge that cannot listen never fails the running one's calls.
5556
- (0, utterances_1.failLeftoverVoiceUtterances)(options.outputDir, "start");
5644
+ // Live audio is never replayed: whatever a stopped call left unanswered is recorded as failed. This waits until the
5645
+ // port is ours, and leaves the calls of any bridge still open, in this process or another live one.
5646
+ (0, utterances_1.failLeftoverVoiceUtterances)(options.outputDir, "start", bridgeUtteranceIds.get(bridge));
5557
5647
  (0, runtime_1.emitNervesEvent)({
5558
5648
  component: "senses",
5559
5649
  event: "senses.voice_twilio_server_start",
@@ -33,14 +33,50 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.openVoiceUtteranceBridge = openVoiceUtteranceBridge;
37
+ exports.closeVoiceUtteranceBridge = closeVoiceUtteranceBridge;
36
38
  exports.voiceUtterances = voiceUtterances;
37
39
  exports.seenVoiceUtterance = seenVoiceUtterance;
38
40
  exports.recordVoiceUtterance = recordVoiceUtterance;
39
41
  exports.failLeftoverVoiceUtterances = failLeftoverVoiceUtterances;
42
+ const crypto = __importStar(require("node:crypto"));
40
43
  const path = __importStar(require("node:path"));
41
44
  const runtime_1 = require("../../nerves/runtime");
42
45
  const inbound_journal_1 = require("../inbound-journal");
43
46
  const turn_attempts_1 = require("../turn-attempts");
47
+ /** The bridges open in this process. Their calls may still be running, so their utterances are left to them. */
48
+ const openBridges = new Set();
49
+ /** Open a bridge's claim on the utterances its calls record, and return the id they carry. */
50
+ function openVoiceUtteranceBridge() {
51
+ const bridge = crypto.randomUUID();
52
+ openBridges.add(bridge);
53
+ return bridge;
54
+ }
55
+ /** The bridge closed: what its calls left is anyone's to record as failed. */
56
+ function closeVoiceUtteranceBridge(bridge) {
57
+ openBridges.delete(bridge);
58
+ }
59
+ function processRunning(pid) {
60
+ try {
61
+ process.kill(pid, 0);
62
+ return true;
63
+ }
64
+ catch (error) {
65
+ // A process this user may not signal is still running.
66
+ return error.code === "EPERM";
67
+ }
68
+ }
69
+ /**
70
+ * Whether the call that recorded an utterance can no longer answer it, so a sweep may record it as failed: its bridge
71
+ * is the one sweeping, or closed, or its process stopped, or an older build wrote it without an owner.
72
+ */
73
+ function ownerStopped(owner, sweeper) {
74
+ if (!owner)
75
+ return true;
76
+ if (owner.pid !== process.pid)
77
+ return !processRunning(owner.pid);
78
+ return owner.bridge === undefined || owner.bridge === sweeper || !openBridges.has(owner.bridge);
79
+ }
44
80
  const journals = new Map();
45
81
  /** The utterance records of one voice output folder, kept in its `utterances` folder. */
46
82
  function voiceUtterances(outputDir) {
@@ -72,14 +108,14 @@ function seenVoiceUtterance(outputDir, id) {
72
108
  }
73
109
  }
74
110
  /**
75
- * Record an utterance before its turn runs. Null when it already has an outcome, or when its folder cannot be
76
- * written, in which case the turn still runs and only a crash during it goes unrecorded.
111
+ * Record an utterance before its turn runs, as this process's and `bridge`'s. Null when it already has an outcome, or
112
+ * when its folder cannot be written, in which case the turn still runs and only a crash during it goes unrecorded.
77
113
  */
78
- function recordVoiceUtterance(outputDir, id, payload) {
114
+ function recordVoiceUtterance(outputDir, id, payload, bridge) {
79
115
  let journal;
80
116
  try {
81
117
  journal = voiceUtterances(outputDir);
82
- if (!journal.record(id, payload))
118
+ if (!journal.record(id, { ...payload, owner: { pid: process.pid, ...(bridge ? { bridge } : {}) } }))
83
119
  return null;
84
120
  }
85
121
  catch (error) {
@@ -133,10 +169,12 @@ function settleQuietly(journal, id, outcome, detail) {
133
169
  }
134
170
  }
135
171
  /**
136
- * Record every utterance a stopped process left as failed, and return how many were recorded. Runs once the sense
137
- * is listening and when it shuts down. Never throws: one it cannot record stays pending for the next run.
172
+ * Record every utterance a stopped call left as failed, and return how many were recorded. Runs once a bridge is
173
+ * listening and when it shuts down, as `bridge`: it records its own and those whose bridge closed or whose process
174
+ * stopped, and leaves those of a bridge still open, here or in another live process, to the next sweep. Never throws:
175
+ * one it cannot record stays pending for the next sweep.
138
176
  */
139
- function failLeftoverVoiceUtterances(outputDir, when) {
177
+ function failLeftoverVoiceUtterances(outputDir, when, bridge) {
140
178
  let journal;
141
179
  let leftover;
142
180
  try {
@@ -150,6 +188,8 @@ function failLeftoverVoiceUtterances(outputDir, when) {
150
188
  const stopped = when === "start" ? "the voice sense restarted" : "the voice sense shut down";
151
189
  let failed = 0;
152
190
  for (const entry of leftover) {
191
+ if (!ownerStopped(entry.payload.owner, bridge))
192
+ continue;
153
193
  const heard = entry.spoke ? `after ${(0, turn_attempts_1.describeTurnSpokes)(entry.spokeRecords)} went out` : "before this was answered";
154
194
  if (settleQuietly(journal, entry.id, "failed", `${stopped} ${heard}; live audio is not replayed`))
155
195
  failed += 1;
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1443",
3
+ "version": "0.1.0-alpha.1445",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@ouro.bot/cli",
9
- "version": "0.1.0-alpha.1443",
9
+ "version": "0.1.0-alpha.1445",
10
10
  "bundleDependencies": [
11
11
  "@ouro.bot/friends"
12
12
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1443",
3
+ "version": "0.1.0-alpha.1445",
4
4
  "description": "Ouroboros, the agent harness: agents with durable memory that live where you talk (terminal, Teams, iMessage, mail, voice) and use real tools. Start with npx ouro.bot@latest.",
5
5
  "homepage": "https://ouroboros.bot/",
6
6
  "engines": {