@ouro.bot/cli 0.1.0-alpha.1429 → 0.1.0-alpha.1430

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,12 @@
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.1430",
6
+ "changes": [
7
+ "Phone utterances in the cascade voice path (Twilio Media Stream and Twilio recordings) now end with a recorded outcome; the OpenAI Realtime and SIP engines are not covered yet. Each thing a caller says is recorded before its turn runs. Its speech, and any tool that messages a person, is noted before it goes out, and its turn records it as answered, silent (the agent had nothing to say) or failed. A reply counts as answered only once it could reach the caller: a Media Stream reply once some of its audio went down the call (so a hangup or talk-over after part of it played still counts as answered), a buffered recording's reply once its playback files are written, and a streamed recording's reply once its speech is made, before Twilio fetches the stream. A Media Stream reply cut off before any audio played is recorded as failed, saying why: the call ended, the caller spoke again, a tool's audio took its place, or the reply made no audio to send. Live audio is never replayed: an utterance a stopped process left is recorded as failed once the voice sense is listening again, and when it shuts down, and the record says what the caller had already heard. A bridge that cannot take its port leaves the running one's records alone. A recording callback Twilio sends twice runs one turn: a retry while the first is still being answered gets the same reply, a retry of a streamed reply gets the same play link while its stream is still served, and any other retry is sent on to listen. A record that cannot be written is logged and never costs the caller the answer or stops the voice sense."
8
+ ]
9
+ },
4
10
  {
5
11
  "version": "0.1.0-alpha.1429",
6
12
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1429",
2
+ "runtimeVersion": "0.1.0-alpha.1430",
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.1429</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1430</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -81,8 +81,9 @@ function readInboundOutcome(agentRoot, sense, id) {
81
81
  }
82
82
  function openInboundJournal(agentRoot, sense, options = {}) {
83
83
  const now = options.now ?? Date.now;
84
- const pendingDir = path.join(journalDir(agentRoot, sense), "pending-inbound");
85
- const outcomesDir = path.join(journalDir(agentRoot, sense), "inbound-outcomes");
84
+ const dir = options.dir ?? journalDir(agentRoot, sense);
85
+ const pendingDir = path.join(dir, "pending-inbound");
86
+ const outcomesDir = path.join(dir, "inbound-outcomes");
86
87
  fs.mkdirSync(pendingDir, { recursive: true });
87
88
  fs.mkdirSync(outcomesDir, { recursive: true });
88
89
  const cutoff = now() - exports.INBOUND_OUTCOME_RETENTION_MS;
@@ -139,6 +140,9 @@ function openInboundJournal(agentRoot, sense, options = {}) {
139
140
  return entry;
140
141
  },
141
142
  get,
143
+ outcome(id) {
144
+ return readJson(outcomePath(id));
145
+ },
142
146
  beginAttempt(id) {
143
147
  return update(id, (entry) => ({ ...entry, attempts: entry.attempts + 1 }))?.attempts ?? 0;
144
148
  },
@@ -4,6 +4,7 @@ exports.runVoiceLoopbackTurn = runVoiceLoopbackTurn;
4
4
  const runtime_1 = require("../../nerves/runtime");
5
5
  const shared_turn_1 = require("../shared-turn");
6
6
  const transcript_1 = require("./transcript");
7
+ const turn_attempts_1 = require("../turn-attempts");
7
8
  function deliveredTts(spoken) {
8
9
  return {
9
10
  status: "delivered",
@@ -32,7 +33,28 @@ function deliveryErrorMessage(error) {
32
33
  return error instanceof Error ? error.message : String(error);
33
34
  }
34
35
  async function runVoiceLoopbackTurn(options) {
36
+ const utterance = options.utterance;
37
+ utterance?.beginAttempt();
38
+ try {
39
+ const said = {};
40
+ const result = await runRecordedVoiceTurn(options, said);
41
+ if (said.nothing)
42
+ utterance?.settle("silent", "the agent had nothing to say");
43
+ else if (result.tts.status === "delivered")
44
+ utterance?.settle("answered");
45
+ else
46
+ utterance?.settle("failed", `the reply could not be spoken: ${result.tts.error}`);
47
+ return result;
48
+ }
49
+ catch (error) {
50
+ utterance?.settle("failed", `the turn failed: ${deliveryErrorMessage(error)}`);
51
+ throw error;
52
+ }
53
+ }
54
+ /** `said.nothing` is set when the turn ended with no speech, no failed speech and an empty reply. */
55
+ async function runRecordedVoiceTurn(options, said) {
35
56
  const runSenseTurn = options.runSenseTurn ?? shared_turn_1.runSenseTurn;
57
+ const utterance = options.utterance;
36
58
  let userMessage;
37
59
  try {
38
60
  userMessage = (0, transcript_1.transcriptToPromptText)(options.transcript);
@@ -64,6 +86,8 @@ async function runVoiceLoopbackTurn(options) {
64
86
  const synthesizeDelivery = async (delivery) => {
65
87
  deliveryIndex += 1;
66
88
  const segmentUtteranceId = `${options.transcript.utteranceId}-${deliveryIndex}-${delivery.kind}`;
89
+ // Noted before it can play, so a stopped call's record says what the caller heard.
90
+ utterance?.noteSpoke((0, turn_attempts_1.turnSpoke)(`speech:${delivery.kind}`, delivery.text));
67
91
  try {
68
92
  const spoken = await options.tts.synthesize({
69
93
  utteranceId: segmentUtteranceId,
@@ -96,6 +120,7 @@ async function runVoiceLoopbackTurn(options) {
96
120
  userMessage,
97
121
  latencyMode: "live",
98
122
  deliverySink: { onDelivery: synthesizeDelivery },
123
+ ...(utterance ? { onOutwardSend: (spoke) => utterance.noteSpoke(spoke) } : {}),
99
124
  ...(options.voiceCall ? { toolContext: { voiceCall: options.voiceCall } } : {}),
100
125
  });
101
126
  if (speechSegments.length > 0) {
@@ -142,6 +167,9 @@ async function runVoiceLoopbackTurn(options) {
142
167
  };
143
168
  }
144
169
  try {
170
+ said.nothing = !turn.response.trim();
171
+ if (!said.nothing)
172
+ utterance?.noteSpoke((0, turn_attempts_1.turnSpoke)("speech:text", turn.response));
145
173
  const spoken = await options.tts.synthesize({
146
174
  utteranceId: options.transcript.utteranceId,
147
175
  text: turn.response,
@@ -82,6 +82,7 @@ const realtime_tool_schema_1 = require("./realtime-tool-schema");
82
82
  const playback_1 = require("./playback");
83
83
  const transcript_1 = require("./transcript");
84
84
  const turn_1 = require("./turn");
85
+ const utterances_1 = require("./utterances");
85
86
  const phone_1 = require("./phone");
86
87
  const audio_playback_1 = require("./audio-playback");
87
88
  const floor_controller_1 = require("./floor-controller");
@@ -992,6 +993,19 @@ class TwilioMediaStreamSession {
992
993
  }
993
994
  /* v8 ignore stop */
994
995
  async processUtterance(utterance) {
996
+ // Recorded before anything can fail, so what the caller said ends in an outcome even if this process stops.
997
+ const record = (0, utterances_1.recordVoiceUtterance)(this.options.outputDir, utterance.utteranceId, {
998
+ callSid: this.callSid, friendId: this.friendId, sessionKey: this.sessionKey, transport: "media-stream",
999
+ });
1000
+ try {
1001
+ await this.answerUtterance(utterance, record);
1002
+ }
1003
+ catch (error) {
1004
+ record?.settle("failed", `the turn failed: ${errorMessage(error)}`);
1005
+ throw error;
1006
+ }
1007
+ }
1008
+ async answerUtterance(utterance, record) {
995
1009
  await fs.mkdir(this.callDir, { recursive: true });
996
1010
  const inputPath = path.join(this.callDir, `${safeSegment(utterance.utteranceId)}.wav`);
997
1011
  await fs.writeFile(inputPath, mulawFramesToPcm16Wav(utterance.frames));
@@ -1020,6 +1034,7 @@ class TwilioMediaStreamSession {
1020
1034
  outboundId: safeSegment(this.outboundId || "unknown"),
1021
1035
  },
1022
1036
  });
1037
+ record?.settle("silent", "a voicemail menu answered the call, so it was ended");
1023
1038
  this.socket.close();
1024
1039
  this.close();
1025
1040
  return;
@@ -1037,13 +1052,19 @@ class TwilioMediaStreamSession {
1037
1052
  source: transcript.source,
1038
1053
  })
1039
1054
  : transcript;
1040
- await this.runTranscriptTurn(turnTranscript, utterance.wasBargeIn);
1055
+ await this.runTranscriptTurn(turnTranscript, utterance.wasBargeIn, record);
1041
1056
  }
1042
- async runTranscriptTurn(transcript, wasBargeIn) {
1043
- if (this.closed || !this.streamSid)
1057
+ async runTranscriptTurn(transcript, wasBargeIn, record = null) {
1058
+ if (this.closed || !this.streamSid) {
1059
+ record?.settle("failed", "the call ended before this was answered");
1044
1060
  return;
1045
- const generation = this.startPlayback();
1061
+ }
1062
+ const generation = this.startPlayback("a later reply took its place before it was played");
1063
+ // The turn's outcome waits until the reply has gone down the call: one spoken after a hangup was never heard.
1064
+ // A turn that throws is recorded as failed by processUtterance.
1065
+ const hold = heldUtterance(record);
1046
1066
  const turn = await (0, turn_1.runVoiceLoopbackTurn)({
1067
+ utterance: hold.turn,
1047
1068
  agentName: this.options.agentName,
1048
1069
  friendId: this.friendId,
1049
1070
  sessionKey: this.sessionKey,
@@ -1057,14 +1078,25 @@ class TwilioMediaStreamSession {
1057
1078
  playAudio: (request) => this.playPreparedAudio(request),
1058
1079
  },
1059
1080
  });
1060
- if (generation !== this.playbackGeneration || this.closed)
1061
- return;
1081
+ const current = generation === this.playbackGeneration && !this.closed;
1062
1082
  const deliveries = deliveredSegments(turn);
1063
- if ((this.playbackBytesByGeneration.get(generation) ?? 0) === 0) {
1083
+ if (current && (this.playbackBytesByGeneration.get(generation) ?? 0) === 0) {
1064
1084
  for (const delivery of deliveries) {
1065
1085
  this.sendAudioChunk(delivery.audio, generation);
1066
1086
  }
1067
1087
  }
1088
+ // A turn with a record always reported its outcome; with none there is nothing to record.
1089
+ const played = (this.playbackBytesByGeneration.get(generation) ?? 0) > 0;
1090
+ if (hold.outcome()?.[0] === "answered" && !played) {
1091
+ record?.settle("failed", this.closed
1092
+ ? "the call ended before the reply was played"
1093
+ : this.playbackStartedBecause.get(generation + 1) ?? "the reply could not be sent down the call");
1094
+ }
1095
+ else {
1096
+ hold.release();
1097
+ }
1098
+ if (!current)
1099
+ return;
1068
1100
  /* v8 ignore start -- runVoiceLoopbackTurn always yields at least one delivered segment (it falls back to a whole-reply synthesis); kept as a guard @preserve */
1069
1101
  if (deliveries.length === 0) {
1070
1102
  this.playbackActive = false;
@@ -1092,7 +1124,7 @@ class TwilioMediaStreamSession {
1092
1124
  async streamGreetingJob(jobId, job) {
1093
1125
  if (this.closed || !this.streamSid)
1094
1126
  return;
1095
- const generation = this.startPlayback();
1127
+ const generation = this.startPlayback("the greeting played in its place before the reply was played");
1096
1128
  try {
1097
1129
  for await (const chunk of job.stream()) {
1098
1130
  if (generation !== this.playbackGeneration || this.closed)
@@ -1132,8 +1164,12 @@ class TwilioMediaStreamSession {
1132
1164
  });
1133
1165
  }
1134
1166
  /* v8 ignore stop */
1135
- startPlayback() {
1167
+ /** Why each playback round after the first began, so a reply it cut off before any audio played says why. */
1168
+ playbackStartedBecause = new Map();
1169
+ /** `supersedes` says, for a reply this new round cuts off before it played, what took its place. */
1170
+ startPlayback(supersedes) {
1136
1171
  this.playbackGeneration += 1;
1172
+ this.playbackStartedBecause.set(this.playbackGeneration, supersedes);
1137
1173
  this.playbackActive = true;
1138
1174
  this.clearHangupFallback();
1139
1175
  return this.playbackGeneration;
@@ -1162,7 +1198,7 @@ class TwilioMediaStreamSession {
1162
1198
  const prepared = await (0, audio_playback_1.prepareVoiceCallAudio)(request, {
1163
1199
  agentRoot: resolveTwilioPhoneAgentRoot(this.options),
1164
1200
  });
1165
- const generation = this.startPlayback();
1201
+ const generation = this.startPlayback("audio a tool played took its place before the reply was played");
1166
1202
  for (let offset = 0; offset < prepared.audio.byteLength; offset += 160) {
1167
1203
  if (this.closed || generation !== this.playbackGeneration)
1168
1204
  break;
@@ -1191,6 +1227,7 @@ class TwilioMediaStreamSession {
1191
1227
  return false;
1192
1228
  this.cancelPendingHangup("barge_in");
1193
1229
  this.playbackGeneration += 1;
1230
+ this.playbackStartedBecause.set(this.playbackGeneration, "the caller spoke again before the reply was played");
1194
1231
  this.playbackActive = false;
1195
1232
  this.socket.send(JSON.stringify({ event: "clear", streamSid: this.streamSid }));
1196
1233
  (0, runtime_1.emitNervesEvent)({
@@ -4073,6 +4110,10 @@ function playManyTwiml(urls) {
4073
4110
  function streamAudioUrl(options, basePath, safeCallSid, jobId) {
4074
4111
  return routeUrl(options.publicBaseUrl, `${basePath}/audio-stream/${encodeURIComponent(safeCallSid)}/${encodeURIComponent(`${jobId}.mp3`)}`);
4075
4112
  }
4113
+ /** The reply to a recording whose answer streams: play the stream, then listen again. */
4114
+ function streamedReplyTwiml(options, basePath, safeCallSid, jobId) {
4115
+ return `${playTwiml(streamAudioUrl(options, basePath, safeCallSid, jobId))}${redirectTwiml(options.publicBaseUrl, basePath)}`;
4116
+ }
4076
4117
  function scheduleJobCleanup(jobs, safeCallSid, jobId) {
4077
4118
  /* v8 ignore start -- stream job cleanup is delayed beyond request-scope tests @preserve */
4078
4119
  const cleanup = setTimeout(() => {
@@ -4147,6 +4188,8 @@ async function runPhonePromptTurn(options) {
4147
4188
  text: options.promptText,
4148
4189
  source: "loopback",
4149
4190
  });
4191
+ // The outcome waits for the playback files: a reply that could not be written never reached the caller.
4192
+ const hold = heldUtterance(options.utterance);
4150
4193
  const turn = await (0, turn_1.runVoiceLoopbackTurn)({
4151
4194
  agentName: options.bridgeOptions.agentName,
4152
4195
  friendId: options.friendId,
@@ -4154,9 +4197,11 @@ async function runPhonePromptTurn(options) {
4154
4197
  transcript,
4155
4198
  tts: options.bridgeOptions.tts,
4156
4199
  runSenseTurn: options.bridgeOptions.runSenseTurn,
4200
+ utterance: hold.turn,
4157
4201
  });
4158
4202
  const after = nextInputTwiml(options.bridgeOptions, options.basePath, options.afterPlayback);
4159
4203
  if (turn.tts.status !== "delivered") {
4204
+ hold.release();
4160
4205
  return xmlResponse(`${sayTwiml("voice output failed after the text response was captured.")}${after}`);
4161
4206
  }
4162
4207
  const audioUrls = await writeVoiceTurnPlaybackArtifacts({
@@ -4167,6 +4212,7 @@ async function runPhonePromptTurn(options) {
4167
4212
  baseUtteranceId: options.utteranceId,
4168
4213
  turn,
4169
4214
  });
4215
+ hold.release();
4170
4216
  return xmlResponse(`${playManyTwiml(audioUrls)}${after}`);
4171
4217
  }
4172
4218
  function computeTwilioSignature(input) {
@@ -4901,11 +4947,57 @@ async function handleRecording(options, basePath, params, jobs) {
4901
4947
  });
4902
4948
  return recordAgainResponse(options, basePath, "I did not receive audio. Please try again.");
4903
4949
  }
4950
+ const safeCallSid = safeSegment(recording.callSid);
4951
+ const safeRecordingSid = safeSegment(recording.recordingSid);
4952
+ const utteranceId = `twilio-${safeCallSid}-${safeRecordingSid}`;
4953
+ // Twilio retries a recording callback it did not hear back from. A retry while the first is still being answered
4954
+ // waits for it and gets the same reply; one after it has an outcome is sent on to listen again.
4955
+ const inFlightKey = `${options.outputDir}\0${utteranceId}`;
4956
+ const inFlight = recordingsInFlight.get(inFlightKey);
4957
+ if (inFlight || (0, utterances_1.seenVoiceUtterance)(options.outputDir, utteranceId)) {
4958
+ (0, runtime_1.emitNervesEvent)({
4959
+ level: "warn",
4960
+ component: "senses",
4961
+ event: "senses.voice_twilio_recording_duplicate",
4962
+ message: "Twilio sent a recording that already has a turn; it is not run again",
4963
+ meta: { agentName: options.agentName, callSid: safeCallSid, recordingSid: safeRecordingSid, inFlight: inFlight !== undefined },
4964
+ });
4965
+ if (inFlight)
4966
+ return inFlight;
4967
+ // A streamed reply's audio stays served for a while after the first reply, so a retry can still play it.
4968
+ const jobId = safeSegment(utteranceId);
4969
+ return xmlResponse(jobs.get(safeCallSid, jobId)
4970
+ ? streamedReplyTwiml(options, basePath, safeCallSid, jobId)
4971
+ : redirectTwiml(options.publicBaseUrl, basePath));
4972
+ }
4973
+ const answer = answerRecording(options, basePath, params, jobs, recording, utteranceId);
4974
+ recordingsInFlight.set(inFlightKey, answer);
4975
+ try {
4976
+ return await answer;
4977
+ }
4978
+ finally {
4979
+ recordingsInFlight.delete(inFlightKey);
4980
+ }
4981
+ }
4982
+ /**
4983
+ * Holds a turn's outcome until its reply is ready to reach the caller, so a reply that never did is not recorded as
4984
+ * answered. `release` records what the turn reported; it is called only after the turn returned, which always reports.
4985
+ */
4986
+ function heldUtterance(record) {
4987
+ const held = {};
4988
+ return {
4989
+ turn: record ? { ...record, settle: (...outcome) => { held.outcome = outcome; } } : null,
4990
+ outcome: () => held.outcome,
4991
+ release: () => { record?.settle(...held.outcome); },
4992
+ };
4993
+ }
4994
+ /** Replies to recording callbacks still being answered, so a retry Twilio sends meanwhile gets the same reply. */
4995
+ const recordingsInFlight = new Map();
4996
+ async function answerRecording(options, basePath, params, jobs, recording, utteranceId) {
4904
4997
  const safeCallSid = safeSegment(recording.callSid);
4905
4998
  const safeRecordingSid = safeSegment(recording.recordingSid);
4906
4999
  const callDir = path.join(options.outputDir, safeCallSid);
4907
5000
  const inputPath = path.join(callDir, `${safeRecordingSid}.wav`);
4908
- const utteranceId = `twilio-${safeCallSid}-${safeRecordingSid}`;
4909
5001
  const downloadRecording = options.downloadRecording ?? defaultTwilioRecordingDownloader;
4910
5002
  // Outbound calls are placed by us (defaultFriendId stays their fallback); inbound callers are
4911
5003
  // identified by the signed caller ID only.
@@ -4925,6 +5017,10 @@ async function handleRecording(options, basePath, params, jobs) {
4925
5017
  message: "starting Twilio voice turn",
4926
5018
  meta: { agentName: options.agentName, callSid: safeCallSid, recordingSid: safeRecordingSid, sessionKey },
4927
5019
  });
5020
+ const record = (0, utterances_1.recordVoiceUtterance)(options.outputDir, utteranceId, {
5021
+ callSid: safeCallSid, friendId, sessionKey, transport: "recording",
5022
+ });
5023
+ const failRecord = (error) => record?.settle("failed", `the turn failed: ${errorMessage(error)}`);
4928
5024
  try {
4929
5025
  if (normalizeTwilioPhonePlaybackMode(options.playbackMode) === "stream") {
4930
5026
  const jobId = safeSegment(utteranceId);
@@ -4937,32 +5033,39 @@ async function handleRecording(options, basePath, params, jobs) {
4937
5033
  jobId,
4938
5034
  baseUtteranceId: utteranceId,
4939
5035
  runTurn: async (onAudioChunk) => {
4940
- await fs.mkdir(callDir, { recursive: true });
4941
- const mediaUrl = twilioRecordingMediaUrl(recording.recordingUrl);
4942
- const audio = await downloadRecording({
4943
- recordingUrl: mediaUrl,
4944
- accountSid: options.twilioAccountSid?.trim() || undefined,
4945
- authToken: options.twilioAuthToken?.trim(),
4946
- });
4947
- await fs.writeFile(inputPath, audio);
4948
- const turnTranscript = await transcribeRecordingOrNoSpeech({
4949
- transcriber: options.transcriber,
4950
- utteranceId,
4951
- inputPath,
4952
- });
4953
- return (0, turn_1.runVoiceLoopbackTurn)({
4954
- agentName: options.agentName,
4955
- friendId,
4956
- sessionKey,
4957
- transcript: turnTranscript,
4958
- tts: options.tts,
4959
- runSenseTurn: options.runSenseTurn,
4960
- onAudioChunk,
4961
- });
5036
+ try {
5037
+ await fs.mkdir(callDir, { recursive: true });
5038
+ const mediaUrl = twilioRecordingMediaUrl(recording.recordingUrl);
5039
+ const audio = await downloadRecording({
5040
+ recordingUrl: mediaUrl,
5041
+ accountSid: options.twilioAccountSid?.trim() || undefined,
5042
+ authToken: options.twilioAuthToken?.trim(),
5043
+ });
5044
+ await fs.writeFile(inputPath, audio);
5045
+ const turnTranscript = await transcribeRecordingOrNoSpeech({
5046
+ transcriber: options.transcriber,
5047
+ utteranceId,
5048
+ inputPath,
5049
+ });
5050
+ return await (0, turn_1.runVoiceLoopbackTurn)({
5051
+ agentName: options.agentName,
5052
+ friendId,
5053
+ sessionKey,
5054
+ transcript: turnTranscript,
5055
+ tts: options.tts,
5056
+ runSenseTurn: options.runSenseTurn,
5057
+ onAudioChunk,
5058
+ utterance: record,
5059
+ });
5060
+ }
5061
+ catch (error) {
5062
+ failRecord(error);
5063
+ throw error;
5064
+ }
4962
5065
  },
4963
5066
  meta: { agentName: options.agentName, callSid: safeCallSid, recordingSid: safeRecordingSid, utteranceId },
4964
5067
  });
4965
- return xmlResponse(`${playTwiml(streamAudioUrl(options, basePath, safeCallSid, jobId))}${redirectTwiml(options.publicBaseUrl, basePath)}`);
5068
+ return xmlResponse(streamedReplyTwiml(options, basePath, safeCallSid, jobId));
4966
5069
  }
4967
5070
  await fs.mkdir(callDir, { recursive: true });
4968
5071
  const mediaUrl = twilioRecordingMediaUrl(recording.recordingUrl);
@@ -4988,8 +5091,11 @@ async function handleRecording(options, basePath, params, jobs) {
4988
5091
  sessionKey,
4989
5092
  promptText: noSpeechPrompt(),
4990
5093
  afterPlayback: "redirect",
5094
+ utterance: record,
4991
5095
  });
4992
5096
  }
5097
+ // The outcome waits for the playback files: a reply that could not be written never reached the caller.
5098
+ const hold = heldUtterance(record);
4993
5099
  const turn = await (0, turn_1.runVoiceLoopbackTurn)({
4994
5100
  agentName: options.agentName,
4995
5101
  friendId,
@@ -4997,8 +5103,10 @@ async function handleRecording(options, basePath, params, jobs) {
4997
5103
  transcript,
4998
5104
  tts: options.tts,
4999
5105
  runSenseTurn: options.runSenseTurn,
5106
+ utterance: hold.turn,
5000
5107
  });
5001
5108
  if (turn.tts.status !== "delivered") {
5109
+ hold.release();
5002
5110
  return xmlResponse(`${sayTwiml("voice output failed after the text response was captured.")}${redirectTwiml(options.publicBaseUrl, basePath)}`);
5003
5111
  }
5004
5112
  const audioUrls = await writeVoiceTurnPlaybackArtifacts({
@@ -5009,6 +5117,7 @@ async function handleRecording(options, basePath, params, jobs) {
5009
5117
  baseUtteranceId: utteranceId,
5010
5118
  turn,
5011
5119
  });
5120
+ hold.release();
5012
5121
  (0, runtime_1.emitNervesEvent)({
5013
5122
  component: "senses",
5014
5123
  event: "senses.voice_twilio_turn_end",
@@ -5018,6 +5127,7 @@ async function handleRecording(options, basePath, params, jobs) {
5018
5127
  return xmlResponse(`${playManyTwiml(audioUrls)}${redirectTwiml(options.publicBaseUrl, basePath)}`);
5019
5128
  }
5020
5129
  catch (error) {
5130
+ failRecord(error);
5021
5131
  (0, runtime_1.emitNervesEvent)({
5022
5132
  level: "error",
5023
5133
  component: "senses",
@@ -5298,6 +5408,7 @@ function createTwilioPhoneBridge(options) {
5298
5408
  return true;
5299
5409
  },
5300
5410
  close() {
5411
+ (0, utterances_1.failLeftoverVoiceUtterances)(options.outputDir, "shutdown");
5301
5412
  return new Promise((resolve, reject) => {
5302
5413
  mediaStreams.close((error) => error ? reject(error) : resolve());
5303
5414
  });
@@ -5440,6 +5551,9 @@ async function startTwilioPhoneBridgeServer(options) {
5440
5551
  server.once("listening", onListening);
5441
5552
  server.listen(port, host);
5442
5553
  });
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");
5443
5557
  (0, runtime_1.emitNervesEvent)({
5444
5558
  component: "senses",
5445
5559
  event: "senses.voice_twilio_server_start",
@@ -0,0 +1,167 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.voiceUtterances = voiceUtterances;
37
+ exports.seenVoiceUtterance = seenVoiceUtterance;
38
+ exports.recordVoiceUtterance = recordVoiceUtterance;
39
+ exports.failLeftoverVoiceUtterances = failLeftoverVoiceUtterances;
40
+ const path = __importStar(require("node:path"));
41
+ const runtime_1 = require("../../nerves/runtime");
42
+ const inbound_journal_1 = require("../inbound-journal");
43
+ const turn_attempts_1 = require("../turn-attempts");
44
+ const journals = new Map();
45
+ /** The utterance records of one voice output folder, kept in its `utterances` folder. */
46
+ function voiceUtterances(outputDir) {
47
+ let journal = journals.get(outputDir);
48
+ if (!journal) {
49
+ journal = (0, inbound_journal_1.openInboundJournal)(outputDir, "voice", { dir: path.join(outputDir, "utterances") });
50
+ journals.set(outputDir, journal);
51
+ }
52
+ return journal;
53
+ }
54
+ function recordFailed(outputDir, error) {
55
+ (0, runtime_1.emitNervesEvent)({
56
+ level: "error",
57
+ component: "senses",
58
+ event: "senses.voice_utterance_record_failed",
59
+ message: "could not open the voice utterance records; the call goes on without them",
60
+ meta: { outputDir, error: String(error) },
61
+ });
62
+ }
63
+ /** Whether this utterance already has a record, pending or settled, so a repeated webhook is not run twice. */
64
+ function seenVoiceUtterance(outputDir, id) {
65
+ try {
66
+ const journal = voiceUtterances(outputDir);
67
+ return journal.get(id) !== null || journal.outcome(id) !== null;
68
+ }
69
+ catch (error) {
70
+ recordFailed(outputDir, error);
71
+ return false;
72
+ }
73
+ }
74
+ /**
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.
77
+ */
78
+ function recordVoiceUtterance(outputDir, id, payload) {
79
+ let journal;
80
+ try {
81
+ journal = voiceUtterances(outputDir);
82
+ if (!journal.record(id, payload))
83
+ return null;
84
+ }
85
+ catch (error) {
86
+ recordFailed(outputDir, error);
87
+ return null;
88
+ }
89
+ const noteFailed = (note, error) => {
90
+ (0, runtime_1.emitNervesEvent)({
91
+ level: "error",
92
+ component: "senses",
93
+ event: "senses.voice_utterance_note_failed",
94
+ message: "could not note a voice utterance's progress; the call goes on",
95
+ meta: { id, note, error: String(error) },
96
+ });
97
+ };
98
+ return {
99
+ id,
100
+ beginAttempt() {
101
+ try {
102
+ journal.beginAttempt(id);
103
+ }
104
+ catch (error) {
105
+ noteFailed("attempt", error);
106
+ }
107
+ },
108
+ noteSpoke(spoke) {
109
+ try {
110
+ journal.markSpoke(id, spoke);
111
+ }
112
+ catch (error) {
113
+ noteFailed(spoke.kind, error);
114
+ }
115
+ },
116
+ settle: (outcome, detail) => { settleQuietly(journal, id, outcome, detail); },
117
+ };
118
+ }
119
+ /** Record an outcome, and log one that cannot be written instead of throwing into the call. True when it landed. */
120
+ function settleQuietly(journal, id, outcome, detail) {
121
+ try {
122
+ return journal.settle(id, outcome, detail);
123
+ }
124
+ catch (error) {
125
+ (0, runtime_1.emitNervesEvent)({
126
+ level: "error",
127
+ component: "senses",
128
+ event: "senses.voice_utterance_settle_failed",
129
+ message: "could not record a voice utterance's outcome; the next start records it as failed",
130
+ meta: { id, outcome, error: String(error) },
131
+ });
132
+ return false;
133
+ }
134
+ }
135
+ /**
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.
138
+ */
139
+ function failLeftoverVoiceUtterances(outputDir, when) {
140
+ let journal;
141
+ let leftover;
142
+ try {
143
+ journal = voiceUtterances(outputDir);
144
+ leftover = journal.pending();
145
+ }
146
+ catch (error) {
147
+ recordFailed(outputDir, error);
148
+ return 0;
149
+ }
150
+ const stopped = when === "start" ? "the voice sense restarted" : "the voice sense shut down";
151
+ let failed = 0;
152
+ for (const entry of leftover) {
153
+ const heard = entry.spoke ? `after ${(0, turn_attempts_1.describeTurnSpokes)(entry.spokeRecords)} went out` : "before this was answered";
154
+ if (settleQuietly(journal, entry.id, "failed", `${stopped} ${heard}; live audio is not replayed`))
155
+ failed += 1;
156
+ }
157
+ if (failed > 0) {
158
+ (0, runtime_1.emitNervesEvent)({
159
+ level: "warn",
160
+ component: "senses",
161
+ event: "senses.voice_utterances_left_failed",
162
+ message: "recorded voice utterances a stopped call left as failed; live audio is not replayed",
163
+ meta: { when, failed },
164
+ });
165
+ }
166
+ return failed;
167
+ }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1429",
3
+ "version": "0.1.0-alpha.1430",
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.1429",
9
+ "version": "0.1.0-alpha.1430",
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.1429",
3
+ "version": "0.1.0-alpha.1430",
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": {