@memberjunction/ai-agents 6.2.0-edge.3 → 6.2.0-edge.5

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.
Files changed (182) hide show
  1. package/README.md +100 -7
  2. package/dist/AgentRunner.d.ts +55 -5
  3. package/dist/AgentRunner.d.ts.map +1 -1
  4. package/dist/AgentRunner.js +277 -59
  5. package/dist/AgentRunner.js.map +1 -1
  6. package/dist/ArtifactToolManager.d.ts +11 -3
  7. package/dist/ArtifactToolManager.d.ts.map +1 -1
  8. package/dist/ArtifactToolManager.js +72 -6
  9. package/dist/ArtifactToolManager.js.map +1 -1
  10. package/dist/ClientToolRequestManager.d.ts +11 -1
  11. package/dist/ClientToolRequestManager.d.ts.map +1 -1
  12. package/dist/ClientToolRequestManager.js +19 -6
  13. package/dist/ClientToolRequestManager.js.map +1 -1
  14. package/dist/ConversationCompactionManager.d.ts +2 -0
  15. package/dist/ConversationCompactionManager.d.ts.map +1 -1
  16. package/dist/ConversationCompactionManager.js +2 -2
  17. package/dist/ConversationCompactionManager.js.map +1 -1
  18. package/dist/ConversationToolManager.d.ts +13 -2
  19. package/dist/ConversationToolManager.d.ts.map +1 -1
  20. package/dist/ConversationToolManager.js +19 -3
  21. package/dist/ConversationToolManager.js.map +1 -1
  22. package/dist/KnowledgeAgent.d.ts.map +1 -1
  23. package/dist/KnowledgeAgent.js +6 -1
  24. package/dist/KnowledgeAgent.js.map +1 -1
  25. package/dist/MJAIAgentRequestEntityServer.d.ts +6 -0
  26. package/dist/MJAIAgentRequestEntityServer.d.ts.map +1 -1
  27. package/dist/MJAIAgentRequestEntityServer.js +26 -1
  28. package/dist/MJAIAgentRequestEntityServer.js.map +1 -1
  29. package/dist/PayloadChangeAnalyzer.d.ts.map +1 -1
  30. package/dist/PayloadChangeAnalyzer.js +53 -30
  31. package/dist/PayloadChangeAnalyzer.js.map +1 -1
  32. package/dist/PayloadManager.d.ts +35 -2
  33. package/dist/PayloadManager.d.ts.map +1 -1
  34. package/dist/PayloadManager.js +250 -149
  35. package/dist/PayloadManager.js.map +1 -1
  36. package/dist/ScratchpadManager.d.ts +18 -0
  37. package/dist/ScratchpadManager.d.ts.map +1 -1
  38. package/dist/ScratchpadManager.js +61 -0
  39. package/dist/ScratchpadManager.js.map +1 -1
  40. package/dist/agent-audience.d.ts +38 -0
  41. package/dist/agent-audience.d.ts.map +1 -0
  42. package/dist/agent-audience.js +99 -0
  43. package/dist/agent-audience.js.map +1 -0
  44. package/dist/agent-context-injector.d.ts +17 -2
  45. package/dist/agent-context-injector.d.ts.map +1 -1
  46. package/dist/agent-context-injector.js +23 -7
  47. package/dist/agent-context-injector.js.map +1 -1
  48. package/dist/agent-memory-context-builder.d.ts +7 -2
  49. package/dist/agent-memory-context-builder.d.ts.map +1 -1
  50. package/dist/agent-memory-context-builder.js +12 -3
  51. package/dist/agent-memory-context-builder.js.map +1 -1
  52. package/dist/agent-pre-execution-rag.d.ts +101 -9
  53. package/dist/agent-pre-execution-rag.d.ts.map +1 -1
  54. package/dist/agent-pre-execution-rag.js +224 -23
  55. package/dist/agent-pre-execution-rag.js.map +1 -1
  56. package/dist/agent-run-watchdog.d.ts +65 -5
  57. package/dist/agent-run-watchdog.d.ts.map +1 -1
  58. package/dist/agent-run-watchdog.js +143 -28
  59. package/dist/agent-run-watchdog.js.map +1 -1
  60. package/dist/agent-types/flow-agent-type.d.ts +8 -0
  61. package/dist/agent-types/flow-agent-type.d.ts.map +1 -1
  62. package/dist/agent-types/flow-agent-type.js +48 -6
  63. package/dist/agent-types/flow-agent-type.js.map +1 -1
  64. package/dist/agent-types/loop-agent-prompt-params.d.ts +7 -0
  65. package/dist/agent-types/loop-agent-prompt-params.d.ts.map +1 -1
  66. package/dist/agent-types/loop-agent-prompt-params.js +1 -0
  67. package/dist/agent-types/loop-agent-prompt-params.js.map +1 -1
  68. package/dist/agent-types/loop-agent-response-type.d.ts +8 -2
  69. package/dist/agent-types/loop-agent-response-type.d.ts.map +1 -1
  70. package/dist/agent-types/loop-agent-response-type.js.map +1 -1
  71. package/dist/agent-types/loop-agent-type.d.ts +9 -2
  72. package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
  73. package/dist/agent-types/loop-agent-type.js +60 -16
  74. package/dist/agent-types/loop-agent-type.js.map +1 -1
  75. package/dist/artifact-tools/SearchResultSetToolLibrary.js +4 -4
  76. package/dist/artifact-tools/SearchResultSetToolLibrary.js.map +1 -1
  77. package/dist/base-agent.d.ts +837 -43
  78. package/dist/base-agent.d.ts.map +1 -1
  79. package/dist/base-agent.js +3081 -663
  80. package/dist/base-agent.js.map +1 -1
  81. package/dist/client-tool-results.d.ts +45 -0
  82. package/dist/client-tool-results.d.ts.map +1 -0
  83. package/dist/client-tool-results.js +94 -0
  84. package/dist/client-tool-results.js.map +1 -0
  85. package/dist/index.d.ts +9 -0
  86. package/dist/index.d.ts.map +1 -1
  87. package/dist/index.js +9 -0
  88. package/dist/index.js.map +1 -1
  89. package/dist/memory-manager-agent.d.ts.map +1 -1
  90. package/dist/memory-manager-agent.js +46 -34
  91. package/dist/memory-manager-agent.js.map +1 -1
  92. package/dist/native-tools/action-param-schema.d.ts +57 -0
  93. package/dist/native-tools/action-param-schema.d.ts.map +1 -0
  94. package/dist/native-tools/action-param-schema.js +238 -0
  95. package/dist/native-tools/action-param-schema.js.map +1 -0
  96. package/dist/native-tools/action-tool-builder.d.ts +5 -4
  97. package/dist/native-tools/action-tool-builder.d.ts.map +1 -1
  98. package/dist/native-tools/action-tool-builder.js +29 -71
  99. package/dist/native-tools/action-tool-builder.js.map +1 -1
  100. package/dist/native-tools/json-argument.d.ts +41 -0
  101. package/dist/native-tools/json-argument.d.ts.map +1 -0
  102. package/dist/native-tools/json-argument.js +79 -0
  103. package/dist/native-tools/json-argument.js.map +1 -0
  104. package/dist/prior-turn-tool-result-cache.d.ts +31 -12
  105. package/dist/prior-turn-tool-result-cache.d.ts.map +1 -1
  106. package/dist/prior-turn-tool-result-cache.js +59 -16
  107. package/dist/prior-turn-tool-result-cache.js.map +1 -1
  108. package/dist/query-builder-agent.d.ts +13 -4
  109. package/dist/query-builder-agent.d.ts.map +1 -1
  110. package/dist/query-builder-agent.js +102 -27
  111. package/dist/query-builder-agent.js.map +1 -1
  112. package/dist/realtime/bridge-realtime-session-factory.d.ts +44 -2
  113. package/dist/realtime/bridge-realtime-session-factory.d.ts.map +1 -1
  114. package/dist/realtime/bridge-realtime-session-factory.js +68 -20
  115. package/dist/realtime/bridge-realtime-session-factory.js.map +1 -1
  116. package/dist/realtime/bridge-realtime-usage-recorder.d.ts +81 -0
  117. package/dist/realtime/bridge-realtime-usage-recorder.d.ts.map +1 -0
  118. package/dist/realtime/bridge-realtime-usage-recorder.js +194 -0
  119. package/dist/realtime/bridge-realtime-usage-recorder.js.map +1 -0
  120. package/dist/realtime/client-only-channel-server.d.ts +83 -0
  121. package/dist/realtime/client-only-channel-server.d.ts.map +1 -0
  122. package/dist/realtime/client-only-channel-server.js +107 -0
  123. package/dist/realtime/client-only-channel-server.js.map +1 -0
  124. package/dist/realtime/identity-verification-channel-server.d.ts +50 -0
  125. package/dist/realtime/identity-verification-channel-server.d.ts.map +1 -0
  126. package/dist/realtime/identity-verification-channel-server.js +66 -0
  127. package/dist/realtime/identity-verification-channel-server.js.map +1 -0
  128. package/dist/realtime/interactive-component-channel-server.d.ts +39 -0
  129. package/dist/realtime/interactive-component-channel-server.d.ts.map +1 -0
  130. package/dist/realtime/interactive-component-channel-server.js +55 -0
  131. package/dist/realtime/interactive-component-channel-server.js.map +1 -0
  132. package/dist/realtime/realtime-avatar-resolution.d.ts +194 -0
  133. package/dist/realtime/realtime-avatar-resolution.d.ts.map +1 -0
  134. package/dist/realtime/realtime-avatar-resolution.js +208 -0
  135. package/dist/realtime/realtime-avatar-resolution.js.map +1 -0
  136. package/dist/realtime/realtime-channel-policy.d.ts +81 -0
  137. package/dist/realtime/realtime-channel-policy.d.ts.map +1 -0
  138. package/dist/realtime/realtime-channel-policy.js +91 -0
  139. package/dist/realtime/realtime-channel-policy.js.map +1 -0
  140. package/dist/realtime/realtime-channel-server-host.d.ts +14 -0
  141. package/dist/realtime/realtime-channel-server-host.d.ts.map +1 -1
  142. package/dist/realtime/realtime-channel-server-host.js +35 -0
  143. package/dist/realtime/realtime-channel-server-host.js.map +1 -1
  144. package/dist/realtime/realtime-client-session-service.d.ts +435 -34
  145. package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
  146. package/dist/realtime/realtime-client-session-service.js +806 -139
  147. package/dist/realtime/realtime-client-session-service.js.map +1 -1
  148. package/dist/realtime/realtime-coagent-config.d.ts +102 -16
  149. package/dist/realtime/realtime-coagent-config.d.ts.map +1 -1
  150. package/dist/realtime/realtime-coagent-config.js +126 -5
  151. package/dist/realtime/realtime-coagent-config.js.map +1 -1
  152. package/dist/realtime/realtime-recording-ledger.d.ts +130 -0
  153. package/dist/realtime/realtime-recording-ledger.d.ts.map +1 -0
  154. package/dist/realtime/realtime-recording-ledger.js +190 -0
  155. package/dist/realtime/realtime-recording-ledger.js.map +1 -0
  156. package/dist/realtime/realtime-recording-opus-assembly.d.ts +211 -0
  157. package/dist/realtime/realtime-recording-opus-assembly.d.ts.map +1 -0
  158. package/dist/realtime/realtime-recording-opus-assembly.js +706 -0
  159. package/dist/realtime/realtime-recording-opus-assembly.js.map +1 -0
  160. package/dist/realtime/realtime-recording-store.d.ts +174 -17
  161. package/dist/realtime/realtime-recording-store.d.ts.map +1 -1
  162. package/dist/realtime/realtime-recording-store.js +552 -58
  163. package/dist/realtime/realtime-recording-store.js.map +1 -1
  164. package/dist/realtime/realtime-session-runner.js +4 -4
  165. package/dist/realtime/realtime-session-runner.js.map +1 -1
  166. package/dist/realtime/realtime-turn-moderator.d.ts +2 -1
  167. package/dist/realtime/realtime-turn-moderator.d.ts.map +1 -1
  168. package/dist/realtime/realtime-turn-moderator.js +7 -1
  169. package/dist/realtime/realtime-turn-moderator.js.map +1 -1
  170. package/dist/realtime/realtime-vendor-resolution.d.ts +9 -0
  171. package/dist/realtime/realtime-vendor-resolution.d.ts.map +1 -1
  172. package/dist/realtime/realtime-vendor-resolution.js +16 -5
  173. package/dist/realtime/realtime-vendor-resolution.js.map +1 -1
  174. package/dist/realtime/realtime-video-output-gate.d.ts +83 -0
  175. package/dist/realtime/realtime-video-output-gate.d.ts.map +1 -0
  176. package/dist/realtime/realtime-video-output-gate.js +79 -0
  177. package/dist/realtime/realtime-video-output-gate.js.map +1 -0
  178. package/dist/tool-result-format.d.ts +14 -0
  179. package/dist/tool-result-format.d.ts.map +1 -1
  180. package/dist/tool-result-format.js.map +1 -1
  181. package/dist/volatile-child-prompt.js +3 -3
  182. package/package.json +21 -19
@@ -5,9 +5,16 @@
5
5
  * recording storage account, upload the audio, link it to the `AIAgentSession`, and stamp the session's
6
6
  * recording fields. Keeps the storage policy in one place rather than duplicated per topology.
7
7
  *
8
+ * Also hosts server-side recovery ({@link RecoverRealtimeRecordingFromSegments}): rebuilding a recording
9
+ * from its crash-recovery shards when the end-of-call upload never arrived. Recovery defers to a
10
+ * recording that already exists on a best-effort basis: it re-checks the session immediately before
11
+ * its stamp, but `BaseEntity` has no compare-and-set, so a writer landing inside that one load -> save
12
+ * window can still be overwritten.
13
+ *
8
14
  * @module @memberjunction/ai-agents
9
15
  */
10
- import { LogError } from '@memberjunction/core';
16
+ import { randomBytes } from 'crypto';
17
+ import { LogError, LogStatus } from '@memberjunction/core';
11
18
  import { FileStorageEngine } from '@memberjunction/storage';
12
19
  /**
13
20
  * Resolves the storage account a session recording should be written to: the agent's
@@ -23,6 +30,15 @@ export async function ResolveRecordingStorageAccountID(agent, contextUser, provi
23
30
  if (!providerID) {
24
31
  return null;
25
32
  }
33
+ return ResolveStorageAccountIDForProvider(providerID, contextUser, provider);
34
+ }
35
+ /**
36
+ * The first storage account of a storage provider (the account a recording stored under that provider
37
+ * is read and written through), or `null` when the provider has none.
38
+ *
39
+ * @param providerID The `MJ: File Storage Providers` id (e.g. an `MJ: Files` row's `ProviderID`).
40
+ */
41
+ export async function ResolveStorageAccountIDForProvider(providerID, contextUser, provider) {
26
42
  // Ensure the storage engine has loaded its accounts before reading them. The engine may be
27
43
  // unconfigured in this process, or configured BEFORE this storage account was provisioned (a stale
28
44
  // cache). Try the loaded cache first; if the provider's account isn't found, force a one-time refresh
@@ -30,7 +46,7 @@ export async function ResolveRecordingStorageAccountID(agent, contextUser, provi
30
46
  await FileStorageEngine.Instance.Config(false, contextUser, provider);
31
47
  let accounts = FileStorageEngine.Instance.GetAccountsByProviderID(providerID);
32
48
  if (accounts.length === 0) {
33
- await FileStorageEngine.Instance.Config(true, contextUser, provider);
49
+ await FileStorageEngine.Instance.RefreshAfterMiss(provider);
34
50
  accounts = FileStorageEngine.Instance.GetAccountsByProviderID(providerID);
35
51
  }
36
52
  return accounts[0]?.ID ?? null;
@@ -39,22 +55,47 @@ export async function ResolveRecordingStorageAccountID(agent, contextUser, provi
39
55
  export async function resolveRecordingStorageAccountID(agent, contextUser, provider) {
40
56
  return ResolveRecordingStorageAccountID(agent, contextUser, provider);
41
57
  }
42
- /** A short, stable file extension for the recording's MIME type. */
58
+ /** A short, stable file extension for the recording's MIME type (MIME types are case-insensitive). */
43
59
  function extensionForMime(mimeType) {
44
- if (mimeType.includes('webm'))
60
+ const type = mimeType.toLowerCase();
61
+ if (type.includes('webm'))
45
62
  return 'webm';
46
- if (mimeType.includes('ogg'))
63
+ if (type.includes('ogg'))
47
64
  return 'ogg';
48
- if (mimeType.includes('mp4') || mimeType.includes('m4a'))
65
+ if (type.includes('mp4') || type.includes('m4a'))
49
66
  return 'm4a';
50
67
  // Header-less raw PCM crash-recovery shards (audio/L16 / audio/pcm) — NOT individually playable;
51
68
  // recovery concatenates them in order and WAV-wraps. The consolidated file is always WAV.
52
- if (mimeType.includes('L16') || mimeType.includes('pcm'))
69
+ if (type.includes('l16') || type.includes('pcm'))
53
70
  return 'pcm';
54
71
  return 'wav';
55
72
  }
56
- /** The per-session folder all of a session's recording artifacts live in (shards + final file). */
57
- function recordingFolder(sessionID) {
73
+ /**
74
+ * Sample rate (Hz) carried by a raw-PCM MIME type such as `audio/L16;rate=48000`. Case-insensitive on
75
+ * the type and parameter name; whitespace and extra parameters are tolerated. Returns `null` for any
76
+ * other type, a missing `rate`, or a rate that is not a positive integer. Shared by the shard-key
77
+ * writer and the recovery's content-type fallback so the two cannot disagree on what counts as a rate.
78
+ */
79
+ function parsePcmRate(mimeType) {
80
+ const [type, ...params] = mimeType.split(';').map(part => part.trim());
81
+ if (!/^audio\/(l16|pcm)$/i.test(type)) {
82
+ return null;
83
+ }
84
+ for (const param of params) {
85
+ const match = /^rate\s*=\s*(\d+)$/i.exec(param);
86
+ const rate = match ? Number(match[1]) : 0;
87
+ if (Number.isSafeInteger(rate) && rate > 0) {
88
+ return rate;
89
+ }
90
+ }
91
+ return null;
92
+ }
93
+ /**
94
+ * The per-session storage folder all of a session's recording artifacts live in (legacy `seg-*` shards,
95
+ * the final `recording.*` file and `peaks.json`). Every writer derives the folder from here so the path
96
+ * convention lives in one place.
97
+ */
98
+ export function RecordingFolder(sessionID) {
58
99
  return `realtime-recordings/${sessionID}`;
59
100
  }
60
101
  /**
@@ -62,8 +103,12 @@ function recordingFolder(sessionID) {
62
103
  * the file's own provider/account) — NOT a public pre-signed link. Used to stream a recording to an
63
104
  * authorized browser securely. Never throws.
64
105
  *
106
+ * Gated for `contextUser` twice over: the `MJ: Files` row is loaded as the caller, and the storage gate
107
+ * (`FileStorageEngine.ResolveFileObject`) then requires Read on the account the row's provider resolves to and refuses
108
+ * an object another row tracks when the caller cannot read that row. A refusal is logged and returns `null`.
109
+ *
65
110
  * @param fileID The `MJ: Files` id of the recording.
66
- * @returns `{ Bytes, MimeType }` or `null` when the file/account/object can't be resolved.
111
+ * @returns `{ Bytes, MimeType }` or `null` when the file/account/object can't be resolved or the caller is refused.
67
112
  */
68
113
  export async function ReadRealtimeRecordingFile(fileID, contextUser, provider) {
69
114
  try {
@@ -71,19 +116,12 @@ export async function ReadRealtimeRecordingFile(fileID, contextUser, provider) {
71
116
  if (!await file.Load(fileID) || !file.ProviderKey) {
72
117
  return null;
73
118
  }
74
- // Ensure the engine knows this provider's accounts (idempotent; force-refresh if missing).
75
- await FileStorageEngine.Instance.Config(false, contextUser, provider);
76
- let accounts = FileStorageEngine.Instance.GetAccountsByProviderID(file.ProviderID);
77
- if (accounts.length === 0) {
78
- await FileStorageEngine.Instance.Config(true, contextUser, provider);
79
- accounts = FileStorageEngine.Instance.GetAccountsByProviderID(file.ProviderID);
80
- }
81
- const account = accounts[0];
82
- if (!account) {
119
+ // Resolve the provider's account and driver through the storage gate (throws on refusal — logged below).
120
+ const resolved = await FileStorageEngine.Instance.ResolveFileObject(file, contextUser, 'Read', provider);
121
+ if (!resolved) {
83
122
  return null;
84
123
  }
85
- const driver = await FileStorageEngine.Instance.GetDriver(account.ID, contextUser);
86
- const bytes = await driver.GetObject({ fullPath: file.ProviderKey });
124
+ const bytes = await resolved.Driver.GetObject({ fullPath: resolved.ObjectKey });
87
125
  if (!bytes || bytes.length === 0) {
88
126
  return null;
89
127
  }
@@ -99,12 +137,24 @@ export async function readRealtimeRecordingFile(fileID, contextUser, provider) {
99
137
  return ReadRealtimeRecordingFile(fileID, contextUser, provider);
100
138
  }
101
139
  /**
102
- * Writes ONE crash-recovery segment shard (`seg-NNNN.<ext>`) into the session's folder as a RAW
140
+ * `seg-NNNN.<ext>`, or `seg-NNNN.r<rate>.pcm` for a PCM shard whose MIME carries a rate. Header-less
141
+ * PCM has no way to say how fast to play it back, and recovery runs after the browser (and its
142
+ * `RecordingStartedAt`/rate bookkeeping) is gone, so the rate travels in the key itself.
143
+ */
144
+ function segmentFileName(segmentIndex, mimeType) {
145
+ const index = String(segmentIndex).padStart(4, '0');
146
+ const extension = extensionForMime(mimeType);
147
+ const rate = extension === 'pcm' ? parsePcmRate(mimeType) : null;
148
+ return rate === null ? `seg-${index}.${extension}` : `seg-${index}.r${rate}.${extension}`;
149
+ }
150
+ /**
151
+ * Writes ONE crash-recovery segment shard (`seg-NNNN[.r<rate>].<ext>`) into the session's folder as a RAW
103
152
  * storage object — no `MJ: Files` row, no session stamping. Shards are durability insurance during a
104
153
  * live call (so a browser/tab death loses at most the last window); they are byte-slices of one
105
154
  * continuous stream (only the first carries the container header), so they are NOT individually
106
- * playable — recovery is "concatenate the folder's shards in order". They are deleted once the
107
- * canonical consolidated file lands ({@link deleteRealtimeRecordingSegments}). Never throws.
155
+ * playable — recovery (see {@link RecoverRealtimeRecordingFromSegments}) concatenates them in index order,
156
+ * filling absent indexes with silence. They are deleted once the canonical consolidated file lands
157
+ * ({@link DeleteRealtimeRecordingSegments}), or by the recovery path once it has stamped its own file. Never throws.
108
158
  *
109
159
  * @returns `true` on success.
110
160
  */
@@ -112,8 +162,8 @@ export async function WriteRealtimeRecordingSegment(input) {
112
162
  const { SessionID, SegmentIndex, Audio, MimeType, StorageAccountID, ContextUser } = input;
113
163
  try {
114
164
  const driver = await FileStorageEngine.Instance.GetDriver(StorageAccountID, ContextUser);
115
- const name = `seg-${String(SegmentIndex).padStart(4, '0')}.${extensionForMime(MimeType)}`;
116
- return await driver.PutObject(`${recordingFolder(SessionID)}/${name}`, Audio, MimeType);
165
+ const name = segmentFileName(SegmentIndex, MimeType);
166
+ return await driver.PutObject(`${RecordingFolder(SessionID)}/${name}`, Audio, MimeType);
117
167
  }
118
168
  catch (error) {
119
169
  LogError(`writeRealtimeRecordingSegment failed (session ${SessionID}, seg ${SegmentIndex}): ${error instanceof Error ? error.message : String(error)}`);
@@ -139,7 +189,7 @@ export async function WriteRecordingPeaksSidecar(sessionID, storageAccountID, pe
139
189
  try {
140
190
  const driver = await FileStorageEngine.Instance.GetDriver(storageAccountID, contextUser);
141
191
  const payload = Buffer.from(JSON.stringify(peaks), 'utf8');
142
- return await driver.PutObject(`${recordingFolder(sessionID)}/peaks.json`, payload, 'application/json');
192
+ return await driver.PutObject(`${RecordingFolder(sessionID)}/peaks.json`, payload, 'application/json');
143
193
  }
144
194
  catch (error) {
145
195
  LogError(`writeRecordingPeaksSidecar failed (session ${sessionID}): ${error instanceof Error ? error.message : String(error)}`);
@@ -151,16 +201,20 @@ export async function writeRecordingPeaksSidecar(sessionID, storageAccountID, pe
151
201
  return WriteRecordingPeaksSidecar(sessionID, storageAccountID, peaks, contextUser);
152
202
  }
153
203
  /**
154
- * Deletes the `seg-*` shards in a session's folder, leaving the consolidated `recording.*` file. Called
155
- * after {@link storeRealtimeRecording} writes the canonical file at end of call. Never throws.
204
+ * Deletes every `seg-*` shard in a session's folder, leaving the consolidated `recording.*` file. Called
205
+ * after {@link StoreRealtimeRecording} writes the canonical file at end of call. The recovery path
206
+ * ({@link RecoverRealtimeRecordingFromSegments}) does not use this: it deletes only the shards it listed
207
+ * and assembled, so a shard written after its listing is not lost. Never throws.
156
208
  *
157
209
  * @returns The number of shards deleted.
158
210
  */
159
211
  export async function DeleteRealtimeRecordingSegments(sessionID, storageAccountID, contextUser) {
160
212
  try {
161
213
  const driver = await FileStorageEngine.Instance.GetDriver(storageAccountID, contextUser);
162
- const folder = recordingFolder(sessionID);
163
- const listed = await driver.ListObjects(folder);
214
+ const folder = RecordingFolder(sessionID);
215
+ // List the folder's CONTENTS: without the trailing slash, delimiter-based drivers (S3, GCS)
216
+ // return the folder itself as a common prefix and no objects, so no shard was ever deleted.
217
+ const listed = await driver.ListObjects(`${folder}/`);
164
218
  let deleted = 0;
165
219
  for (const obj of listed.objects ?? []) {
166
220
  const base = (obj.name.split('/').pop() ?? obj.name);
@@ -190,53 +244,493 @@ export async function deleteRealtimeRecordingSegments(sessionID, storageAccountI
190
244
  * @returns The created `MJ: Files` id, or the failure reason.
191
245
  */
192
246
  export async function StoreRealtimeRecording(input) {
193
- const { Audio, MimeType, Media, StartedAt, StorageAccountID, SessionID, ContextUser, Provider, Peaks } = input;
247
+ const { Audio, MimeType, StorageAccountID, SessionID, ContextUser, Provider, Peaks } = input;
194
248
  try {
195
249
  // Canonical consolidated file in the session's own folder, alongside (then replacing) its shards.
196
250
  const uploaded = await FileStorageEngine.Instance.UploadFile({
197
251
  content: Audio,
198
- fileName: `recording.${extensionForMime(MimeType)}`,
252
+ fileName: input.FileName ?? `recording.${extensionForMime(MimeType)}`,
199
253
  mimeType: MimeType,
254
+ description: input.Description,
200
255
  contextUser: ContextUser,
201
256
  storageAccountId: StorageAccountID,
202
257
  provider: Provider,
203
- pathPrefix: recordingFolder(SessionID)
258
+ pathPrefix: RecordingFolder(SessionID)
204
259
  });
205
260
  // Best-effort waveform-peaks sidecar (peaks.json) next to the recording, for fast waveform
206
261
  // rendering without re-decoding the audio. A sidecar failure never fails the recording itself.
207
262
  await WriteRecordingPeaksSidecar(SessionID, StorageAccountID, Peaks, ContextUser);
208
- // Link the file to the session record so it's discoverable via MJ: File Entity Record Links.
209
- const sessionEntityID = Provider.EntityByName('MJ: AI Agent Sessions')?.ID;
210
- if (sessionEntityID) {
211
- const link = await Provider.GetEntityObject('MJ: File Entity Record Links', ContextUser);
212
- link.NewRecord();
213
- link.FileID = uploaded.FileID;
214
- link.EntityID = sessionEntityID;
215
- link.RecordID = SessionID;
216
- if (!await link.Save()) {
217
- LogError(`storeRealtimeRecording: failed to link recording to session ${SessionID}: ${link.LatestResult?.CompleteMessage ?? 'unknown error'}`);
218
- }
219
- }
220
- // Stamp the recording fields on the session (file + media kind + t0).
221
- const session = await Provider.GetEntityObject('MJ: AI Agent Sessions', ContextUser);
222
- if (await session.Load(SessionID)) {
223
- session.RecordingFileID = uploaded.FileID;
224
- session.RecordingMedia = Media;
225
- session.RecordingStartedAt = StartedAt;
226
- if (!await session.Save()) {
227
- LogError(`storeRealtimeRecording: failed to stamp recording fields on session ${SessionID}: ${session.LatestResult?.CompleteMessage ?? 'unknown error'}`);
228
- }
229
- }
230
- return { FileID: uploaded.FileID, ErrorMessage: null };
263
+ return input.PreserveExistingRecording
264
+ ? await stampPreservingExisting(input, uploaded.FileID)
265
+ : await linkAndStamp(input, uploaded.FileID);
231
266
  }
232
267
  catch (error) {
233
268
  const message = error instanceof Error ? error.message : String(error);
234
269
  LogError(`storeRealtimeRecording failed for session ${SessionID}: ${message}`);
235
- return { FileID: null, ErrorMessage: message };
270
+ return { FileID: null, ErrorMessage: message, Superseded: false };
271
+ }
272
+ }
273
+ /**
274
+ * End-of-call path: link, then stamp unconditionally, so the browser's own recording replaces whatever
275
+ * the session pointed at. A session that cannot be loaded is still linked but not stamped (unchanged
276
+ * long-standing behaviour; the upload is reported as stored).
277
+ */
278
+ async function linkAndStamp(input, fileID) {
279
+ const { Media, StartedAt, SessionID, ContextUser, Provider } = input;
280
+ const session = await Provider.GetEntityObject('MJ: AI Agent Sessions', ContextUser);
281
+ const sessionLoaded = await session.Load(SessionID);
282
+ await LinkRecordingToSession(fileID, SessionID, ContextUser, Provider);
283
+ if (sessionLoaded) {
284
+ await stampRecordingOnSession(session, fileID, Media, StartedAt);
285
+ }
286
+ return { FileID: fileID, ErrorMessage: null, Superseded: false };
287
+ }
288
+ /**
289
+ * Recovery path: re-check -> stamp -> link. The re-check is the last read before the stamp, so the
290
+ * window in which a late recording can still be overwritten is one load -> save. The link is written
291
+ * only once the stamp saved, so a `Superseded` or failed result never leaves a link row behind.
292
+ */
293
+ async function stampPreservingExisting(input, fileID) {
294
+ const { Media, StartedAt, SessionID, ContextUser, Provider } = input;
295
+ const session = await Provider.GetEntityObject('MJ: AI Agent Sessions', ContextUser);
296
+ if (!await session.Load(SessionID)) {
297
+ const message = `could not re-read session ${SessionID} before stamping; file ${fileID} is orphaned and was not linked or stamped`;
298
+ LogError(`storeRealtimeRecording: ${message}`);
299
+ return { FileID: fileID, ErrorMessage: message, Superseded: false };
300
+ }
301
+ if (session.RecordingFileID) {
302
+ LogStatus(`storeRealtimeRecording: session ${SessionID} already has recording file ${session.RecordingFileID}; the just-uploaded file ${fileID} is orphaned and was not linked or stamped`);
303
+ return { FileID: fileID, ErrorMessage: null, Superseded: true };
304
+ }
305
+ if (!await stampRecordingOnSession(session, fileID, Media, StartedAt)) {
306
+ const reason = session.LatestResult?.CompleteMessage ?? 'unknown error';
307
+ return { FileID: fileID, ErrorMessage: `could not stamp file ${fileID} on session ${SessionID} (file orphaned, not linked): ${reason}`, Superseded: false };
308
+ }
309
+ await LinkRecordingToSession(fileID, SessionID, ContextUser, Provider);
310
+ return { FileID: fileID, ErrorMessage: null, Superseded: false };
311
+ }
312
+ /**
313
+ * Links a recording file to its session record so it's discoverable via `MJ: File Entity Record Links`.
314
+ * Failures are logged with the session and file ids; the link is discoverability only (the session's
315
+ * `RecordingFileID` is what playback uses), so callers do not fail the recording over it.
316
+ *
317
+ * @returns `true` when the link row was saved.
318
+ */
319
+ export async function LinkRecordingToSession(fileID, sessionID, contextUser, provider) {
320
+ const sessionEntityID = provider.EntityByName('MJ: AI Agent Sessions')?.ID;
321
+ if (!sessionEntityID) {
322
+ LogError(`LinkRecordingToSession: entity 'MJ: AI Agent Sessions' is not in metadata; recording file ${fileID} not linked to session ${sessionID}`);
323
+ return false;
236
324
  }
325
+ const link = await provider.GetEntityObject('MJ: File Entity Record Links', contextUser);
326
+ link.NewRecord();
327
+ link.FileID = fileID;
328
+ link.EntityID = sessionEntityID;
329
+ link.RecordID = sessionID;
330
+ if (!await link.Save()) {
331
+ LogError(`LinkRecordingToSession: failed to link recording file ${fileID} to session ${sessionID}: ${link.LatestResult?.CompleteMessage ?? 'unknown error'}`);
332
+ return false;
333
+ }
334
+ return true;
335
+ }
336
+ /** Stamps the recording fields on an already-loaded session (file + media kind + t0). Logs and returns false on a failed save. */
337
+ async function stampRecordingOnSession(session, fileID, media, startedAt) {
338
+ session.RecordingFileID = fileID;
339
+ session.RecordingMedia = media;
340
+ session.RecordingStartedAt = startedAt;
341
+ if (!await session.Save()) {
342
+ LogError(`storeRealtimeRecording: failed to stamp recording fields on session ${session.ID}: ${session.LatestResult?.CompleteMessage ?? 'unknown error'}`);
343
+ return false;
344
+ }
345
+ return true;
237
346
  }
238
347
  /** @deprecated Use {@link StoreRealtimeRecording}. */
239
348
  export async function storeRealtimeRecording(input) {
240
349
  return StoreRealtimeRecording(input);
241
350
  }
351
+ /** Size of the canonical mono PCM16 WAV header {@link WriteRecordingWavHeader} writes. */
352
+ export const RECORDING_WAV_HEADER_BYTES = 44;
353
+ const RECORDING_BYTES_PER_SAMPLE = 2; // mono, 16-bit PCM
354
+ /** WAV stores sizes as uint32; the RIFF chunk size is `36 + dataSize`, so data tops out 36 bytes short of the max. */
355
+ const RECORDING_MAX_DATA_BYTES = 0xFFFFFFFF - 36;
356
+ /**
357
+ * Assembles recovered recording shards into one WAV, in index order, filling every absent index with
358
+ * silence. Silence (rather than skipping the gap) keeps all later audio at its true time offset, so it
359
+ * stays aligned with transcript cues, which are offsets from the session's `RecordingStartedAt`.
360
+ *
361
+ * The gap length is the median length of the present shards excluding the highest present index (that
362
+ * one is normally a partial window); with a single shard, that shard's length. It is rounded down to
363
+ * an even byte count (whole 16-bit samples), minimum 2.
364
+ *
365
+ * The byte ceiling does not bound the index range on its own: under the default ceiling a single shard
366
+ * at index ~10^9 still fits, and the missing-index list grows with the highest index. Callers handling
367
+ * untrusted shards must cap the shard count and highest index themselves (recovery does, via
368
+ * {@link MAX_RECOVERY_SEGMENTS}) and pass a smaller `maxDataBytes`.
369
+ *
370
+ * @param segments Recovered shards; any order, unique non-negative integer indexes starting from 0.
371
+ * @param sampleRate Sample rate of the PCM data, in Hz.
372
+ * @param maxDataBytes Ceiling on the PCM data size (shards plus gap fill), checked before anything is
373
+ * allocated. Defaults to the WAV format's own limit; callers handling untrusted shards pass less.
374
+ * @throws Error on no segments, an invalid sample rate or index, a duplicate index, an empty or
375
+ * odd-length shard, or a result too large for a WAV.
376
+ */
377
+ export function BuildRecordingFromSegments(segments, sampleRate, maxDataBytes = RECORDING_MAX_DATA_BYTES) {
378
+ validateRecordingInputs(segments, sampleRate);
379
+ const ordered = [...segments].sort((a, b) => a.Index - b.Index);
380
+ const gapBytes = computeRecordingGapBytes(ordered);
381
+ // Count gaps arithmetically (indexes are unique and non-negative) so an absurd index fails the size
382
+ // check below instead of first enumerating billions of missing indexes.
383
+ const missingCount = ordered[ordered.length - 1].Index - (ordered.length - 1);
384
+ const dataSize = ordered.reduce((sum, s) => sum + s.Bytes.length, 0) + missingCount * gapBytes;
385
+ const limit = Math.min(maxDataBytes, RECORDING_MAX_DATA_BYTES);
386
+ if (dataSize > limit) {
387
+ throw new Error(`BuildRecordingFromSegments: data of ${dataSize} bytes exceeds the maximum WAV data size of ${limit} bytes`);
388
+ }
389
+ // Buffer.alloc zero-fills, so gaps need no explicit write.
390
+ const wav = Buffer.alloc(RECORDING_WAV_HEADER_BYTES + dataSize);
391
+ WriteRecordingWavHeader(wav, sampleRate, dataSize);
392
+ let offset = RECORDING_WAV_HEADER_BYTES;
393
+ let expectedIndex = 0;
394
+ for (const segment of ordered) {
395
+ offset += (segment.Index - expectedIndex) * gapBytes;
396
+ offset += segment.Bytes.copy(wav, offset);
397
+ expectedIndex = segment.Index + 1;
398
+ }
399
+ return { Wav: wav, MissingIndexes: findMissingIndexes(ordered), GapBytes: gapBytes };
400
+ }
401
+ function validateRecordingInputs(segments, sampleRate) {
402
+ if (segments.length === 0) {
403
+ throw new Error('BuildRecordingFromSegments: no segments to assemble');
404
+ }
405
+ if (!Number.isInteger(sampleRate) || sampleRate <= 0) {
406
+ throw new Error(`BuildRecordingFromSegments: sample rate must be a positive integer, got ${sampleRate}`);
407
+ }
408
+ const seen = new Set();
409
+ for (const { Index, Bytes } of segments) {
410
+ if (!Number.isInteger(Index) || Index < 0) {
411
+ throw new Error(`BuildRecordingFromSegments: segment index must be a non-negative integer, got ${Index}`);
412
+ }
413
+ if (seen.has(Index)) {
414
+ throw new Error(`BuildRecordingFromSegments: duplicate segment index ${Index}`);
415
+ }
416
+ seen.add(Index);
417
+ if (Bytes.length === 0) {
418
+ throw new Error(`BuildRecordingFromSegments: segment ${Index} is empty`);
419
+ }
420
+ if (Bytes.length % RECORDING_BYTES_PER_SAMPLE !== 0) {
421
+ throw new Error(`BuildRecordingFromSegments: segment ${Index} has odd length ${Bytes.length}; PCM16 needs an even byte count`);
422
+ }
423
+ }
424
+ }
425
+ /** Median length of the present shards minus the highest-indexed one (a partial window), floored to even, min 2. */
426
+ function computeRecordingGapBytes(ordered) {
427
+ const basis = ordered.length > 1 ? ordered.slice(0, -1) : ordered;
428
+ const lengths = basis.map(s => s.Bytes.length).sort((a, b) => a - b);
429
+ const mid = Math.floor(lengths.length / 2);
430
+ const median = lengths.length % 2 === 1 ? lengths[mid] : (lengths[mid - 1] + lengths[mid]) / 2;
431
+ const even = Math.floor(median / RECORDING_BYTES_PER_SAMPLE) * RECORDING_BYTES_PER_SAMPLE;
432
+ return Math.max(RECORDING_BYTES_PER_SAMPLE, even);
433
+ }
434
+ /** Indexes in [0, highest present) with no shard. `ordered` is sorted ascending. */
435
+ function findMissingIndexes(ordered) {
436
+ const highestIndex = ordered[ordered.length - 1].Index;
437
+ const present = new Set(ordered.map(s => s.Index));
438
+ const missing = [];
439
+ for (let i = 0; i < highestIndex; i++) {
440
+ if (!present.has(i)) {
441
+ missing.push(i);
442
+ }
443
+ }
444
+ return missing;
445
+ }
446
+ /**
447
+ * Writes the canonical 44-byte ({@link RECORDING_WAV_HEADER_BYTES}) mono 16-bit PCM WAV header into the
448
+ * start of `buffer`. Same layout as `RealtimeRecordingCapture.encodeWavBuffer`; shared by every server
449
+ * path that produces a recording WAV so they cannot drift apart.
450
+ *
451
+ * @param buffer Destination; at least {@link RECORDING_WAV_HEADER_BYTES} long.
452
+ * @param sampleRate Sample rate of the PCM data, in Hz.
453
+ * @param dataSize Byte length of the PCM data that follows the header.
454
+ */
455
+ export function WriteRecordingWavHeader(buffer, sampleRate, dataSize) {
456
+ buffer.write('RIFF', 0, 'ascii');
457
+ buffer.writeUInt32LE(36 + dataSize, 4);
458
+ buffer.write('WAVE', 8, 'ascii');
459
+ buffer.write('fmt ', 12, 'ascii');
460
+ buffer.writeUInt32LE(16, 16);
461
+ buffer.writeUInt16LE(1, 20);
462
+ buffer.writeUInt16LE(1, 22);
463
+ buffer.writeUInt32LE(sampleRate, 24);
464
+ buffer.writeUInt32LE(sampleRate * RECORDING_BYTES_PER_SAMPLE, 28);
465
+ buffer.writeUInt16LE(RECORDING_BYTES_PER_SAMPLE, 32);
466
+ buffer.writeUInt16LE(16, 34);
467
+ buffer.write('data', 36, 'ascii');
468
+ buffer.writeUInt32LE(dataSize, 40);
469
+ }
470
+ /**
471
+ * Most shards recovery will assemble. At ~15 s per shard this is an hour of audio, far past any real
472
+ * call; a listing at or beyond it (by count or by highest index) is treated as corrupt or hostile and
473
+ * fails closed rather than allocating a huge WAV.
474
+ */
475
+ export const MAX_RECOVERY_SEGMENTS = 240;
476
+ /**
477
+ * Ceiling on the PCM data a recovery will assemble: 384 MiB covers an hour of 48 kHz mono PCM16
478
+ * (345.6 MB) with headroom. Shard sizes are client-controlled (the GraphQL body limit is 50 MB, so one
479
+ * shard can be ~37 MB) and gaps are filled with silence, so without this a session owner could make the
480
+ * janitor allocate gigabytes. Checked against listed sizes, running actual bytes, and the assembled size.
481
+ *
482
+ * It caps the data, not the process's memory: the shard buffers are still held while the WAV is
483
+ * assembled (2x), and storage drivers can copy on read (the S3 driver copies each shard once more), so
484
+ * peak memory for one recovery is up to about three times this: two 288 MB recoveries raised the API
485
+ * process's RSS by 730 MB and 920 MB.
486
+ */
487
+ export const MAX_RECOVERY_BYTES = 384 * 1024 * 1024;
488
+ /**
489
+ * Seconds of audio in one full shard written before shard keys carried a rate. Those clients flushed a
490
+ * shard every 15 s. The legacy format is frozen, so this deliberately does not follow the client's
491
+ * current flush interval: it is only used to infer the rate of shards that declare none.
492
+ */
493
+ const LEGACY_SHARD_SECONDS = 15;
494
+ /** Sample rates a legacy shard's rate may be inferred as. */
495
+ const STANDARD_PCM_RATES = [8000, 11025, 16000, 22050, 24000, 32000, 44100, 48000];
496
+ /**
497
+ * How far a full legacy shard's size-implied rate may be from a standard rate (relative). Real full
498
+ * shards are within ~0.2% of 15 s; the closest pair of standard rates is ~9% apart.
499
+ */
500
+ const RATE_SNAP_TOLERANCE = 0.02;
501
+ /** `seg-0003.pcm` or `seg-0003.r48000.pcm`: index, optional keyed rate, extension. */
502
+ const SEGMENT_KEY_PATTERN = /^seg-(\d+)(?:\.r(\d+))?\.([A-Za-z0-9]+)$/;
503
+ /**
504
+ * A fresh name per recovery attempt (`recording-recovered-<epoch ms>-<random hex>.wav`). Storage keys are
505
+ * `<folder>/<file name>`, so a fixed name would make retries and concurrent instances write the SAME
506
+ * object behind several `MJ: Files` rows: deleting an orphan row would delete the stamped recording, and
507
+ * a late attempt could overwrite it with a mostly silent WAV.
508
+ */
509
+ function recoveredFileName() {
510
+ return `recording-recovered-${Date.now()}-${randomBytes(4).toString('hex')}.wav`;
511
+ }
512
+ /**
513
+ * Rebuilds a session's recording from the `seg-*` crash-recovery shards left in its storage folder —
514
+ * for a call whose browser died or whose end-of-call upload never ran, so no `recording.*` exists.
515
+ * Shards are concatenated in order (silence for absent ones), uploaded under a per-attempt
516
+ * `recording-recovered-<epoch ms>-<random hex>.wav`, stamped on the session, linked, and only then
517
+ * deleted. Deletion happens only after a reload confirms the session points at the recovered file, so a
518
+ * failure at any step leaves the shards for the next try. If the session has (or gains) another
519
+ * recording, the outcome is `Superseded` and the shards are kept. Deferring to that recording is best
520
+ * effort: the session is re-checked immediately before the stamp, but a recording stamped inside that
521
+ * one load -> save window is overwritten (there is no compare-and-set).
522
+ *
523
+ * The sample rate comes from the shard keys (`seg-NNNN.r<rate>.pcm`) or, for legacy `seg-NNNN.pcm`
524
+ * shards, from each object's stored content type. When no shard declares a rate (a legacy shard on a
525
+ * driver that keeps no content type, such as Box), it is inferred from the size of the full shards; see
526
+ * {@link LEGACY_SHARD_SECONDS}.
527
+ *
528
+ * Once the stamp has saved, the outcome is `Recovered` even if the confirming reload or a shard delete
529
+ * fails; the shards it could not remove are named in a `LogError` (nothing revisits a stamped session).
530
+ *
531
+ * Never throws: every failure is logged with the session id and returned as `Failed`.
532
+ *
533
+ * @param input Session, storage account, recording `t0`, and server context.
534
+ */
535
+ export async function RecoverRealtimeRecordingFromSegments(input) {
536
+ try {
537
+ return await recoverFromSegments(input);
538
+ }
539
+ catch (error) {
540
+ const message = error instanceof Error ? error.message : String(error);
541
+ LogError(`RecoverRealtimeRecordingFromSegments failed (session ${input.SessionID}): ${message}`);
542
+ return recoveryResult('Failed', { ErrorMessage: message });
543
+ }
544
+ }
545
+ function recoveryResult(outcome, fields = {}) {
546
+ return { Outcome: outcome, FileID: null, SegmentCount: 0, MissingIndexes: [], ErrorMessage: null, ...fields };
547
+ }
548
+ async function recoverFromSegments(input) {
549
+ const { SessionID, StorageAccountID, StartedAt, ContextUser, Provider } = input;
550
+ const driver = await FileStorageEngine.Instance.GetDriver(StorageAccountID, ContextUser);
551
+ const shards = await listRecordingShards(driver, SessionID);
552
+ if (shards.length === 0) {
553
+ LogStatus(`RecoverRealtimeRecordingFromSegments: no shards for session ${SessionID} in storage account ${StorageAccountID}`);
554
+ return recoveryResult('NoSegments');
555
+ }
556
+ assertRecoverable(shards);
557
+ const declaredRate = await resolveDeclaredSampleRate(driver, shards);
558
+ const segments = await readShardBytes(driver, shards);
559
+ const sampleRate = declaredRate ?? inferSampleRateFromShardSizes(segments, shards);
560
+ if (declaredRate === null) {
561
+ LogStatus(`RecoverRealtimeRecordingFromSegments (session ${SessionID}): no shard declares a sample rate; inferred ${sampleRate} Hz from the size of its full shards`);
562
+ }
563
+ const assembled = BuildRecordingFromSegments(segments, sampleRate, MAX_RECOVERY_BYTES);
564
+ const description = describeRecovery(shards.length, assembled, sampleRate);
565
+ if (assembled.MissingIndexes.length > 0) {
566
+ LogStatus(`RecoverRealtimeRecordingFromSegments (session ${SessionID}): ${description}`);
567
+ }
568
+ const stored = await StoreRealtimeRecording({
569
+ Audio: assembled.Wav, MimeType: 'audio/wav', Media: 'Audio', StartedAt, StorageAccountID, SessionID,
570
+ ContextUser, Provider, FileName: recoveredFileName(), Description: description, PreserveExistingRecording: true,
571
+ });
572
+ const found = { FileID: stored.FileID, SegmentCount: shards.length, MissingIndexes: assembled.MissingIndexes };
573
+ if (stored.Superseded) {
574
+ return recoveryResult('Superseded', found);
575
+ }
576
+ // An ErrorMessage with a FileID is an uploaded-but-unstamped orphan (re-read or stamp failed).
577
+ if (!stored.FileID || stored.ErrorMessage) {
578
+ throw new Error(stored.ErrorMessage ?? 'storing the recovered recording failed');
579
+ }
580
+ return finishRecovery(input, stored.FileID, found, shards);
581
+ }
582
+ /** Confirms the stamp stuck, then (and only then) deletes the shards. */
583
+ async function finishRecovery(input, fileID, found, shards) {
584
+ const { SessionID, StorageAccountID, ContextUser, Provider } = input;
585
+ const session = await Provider.GetEntityObject('MJ: AI Agent Sessions', ContextUser);
586
+ if (!await session.Load(SessionID)) {
587
+ // The stamp and link already saved, so the recording is in place; only the overwrite check could
588
+ // not run. Keep the shards (they might belong to a recording that replaced ours) and name them.
589
+ LogError(`RecoverRealtimeRecordingFromSegments (session ${SessionID}): recovered file ${fileID} is stamped, but the session ` +
590
+ `could not be reloaded to confirm it before deleting shards; kept for manual cleanup: ${shards.map(s => s.Path).join(', ')}`);
591
+ return recoveryResult('Recovered', found);
592
+ }
593
+ if (session.RecordingFileID && session.RecordingFileID !== fileID) {
594
+ LogStatus(`RecoverRealtimeRecordingFromSegments (session ${SessionID}): session now points at ${session.RecordingFileID}, not recovered file ${fileID}; keeping shards`);
595
+ return recoveryResult('Superseded', found);
596
+ }
597
+ if (session.RecordingFileID !== fileID) {
598
+ throw new Error(`recovered file ${fileID} uploaded but not stamped on session ${SessionID}; shards kept`);
599
+ }
600
+ const notDeleted = await deleteListedShards(StorageAccountID, ContextUser, shards);
601
+ if (notDeleted.length > 0) {
602
+ LogError(`RecoverRealtimeRecordingFromSegments (session ${SessionID}): deleted ${shards.length - notDeleted.length} of ${shards.length} ` +
603
+ `shards after recovery; left for manual cleanup: ${notDeleted.join(', ')}`);
604
+ }
605
+ return recoveryResult('Recovered', found);
606
+ }
607
+ /**
608
+ * Deletes exactly the shards that were assembled. A re-list would also take shards written after our
609
+ * listing, whose audio is not in the recovered file. Returns the paths it could not delete.
610
+ */
611
+ async function deleteListedShards(storageAccountID, contextUser, shards) {
612
+ const driver = await FileStorageEngine.Instance.GetDriver(storageAccountID, contextUser);
613
+ const notDeleted = [];
614
+ for (const shard of shards) {
615
+ if (!await driver.DeleteObject(shard.Path)) {
616
+ notDeleted.push(shard.Path);
617
+ }
618
+ }
619
+ return notDeleted;
620
+ }
621
+ /** Lists the session folder's `seg-*` objects. Other objects (recording.*, peaks.json) are ignored. */
622
+ async function listRecordingShards(driver, sessionID) {
623
+ const folder = RecordingFolder(sessionID);
624
+ const listed = await driver.ListObjects(`${folder}/`);
625
+ const shards = [];
626
+ for (const obj of listed.objects ?? []) {
627
+ const name = obj.name.split('/').pop() ?? obj.name;
628
+ const match = SEGMENT_KEY_PATTERN.exec(name);
629
+ if (match) {
630
+ const keyedRate = match[2] === undefined ? null : Number(match[2]);
631
+ if (keyedRate !== null && !(Number.isSafeInteger(keyedRate) && keyedRate > 0)) {
632
+ throw new Error(`shard ${name} has an invalid sample rate in its key`);
633
+ }
634
+ shards.push({
635
+ Name: name, Path: `${folder}/${name}`, Index: Number(match[1]),
636
+ KeyedRate: keyedRate, Extension: match[3], ListedSize: obj.size ?? 0,
637
+ });
638
+ }
639
+ }
640
+ return shards;
641
+ }
642
+ /** Fail closed on an oversized listing and on anything that is not raw PCM (webm/ogg shards cannot be concatenated). */
643
+ function assertRecoverable(shards) {
644
+ const highestIndex = Math.max(...shards.map(s => s.Index));
645
+ if (shards.length >= MAX_RECOVERY_SEGMENTS || highestIndex >= MAX_RECOVERY_SEGMENTS) {
646
+ throw new Error(`refusing to recover ${shards.length} shards (highest index ${highestIndex}); limit is ${MAX_RECOVERY_SEGMENTS}`);
647
+ }
648
+ const listedBytes = shards.reduce((sum, s) => sum + s.ListedSize, 0);
649
+ if (listedBytes > MAX_RECOVERY_BYTES) {
650
+ throw new Error(`shards total ${listedBytes} bytes, over the recovery limit of ${MAX_RECOVERY_BYTES} bytes`);
651
+ }
652
+ const notPcm = shards.find(s => s.Extension !== 'pcm');
653
+ if (notPcm) {
654
+ throw new Error(`shard ${notPcm.Name} is not raw PCM; only .pcm shards can be reassembled`);
655
+ }
656
+ }
657
+ /**
658
+ * The one sample rate the shards declare: from the key when present, else the object's stored content
659
+ * type. Null when no shard declares one (left to {@link inferSampleRateFromShardSizes}). Throws when
660
+ * shards disagree, or when some declare a rate and others do not.
661
+ */
662
+ async function resolveDeclaredSampleRate(driver, shards) {
663
+ const declared = [];
664
+ for (const shard of shards) {
665
+ const rate = shard.KeyedRate ?? parsePcmRate((await driver.GetObjectMetadata({ fullPath: shard.Path })).contentType ?? '');
666
+ declared.push({ shard, rate });
667
+ }
668
+ const withRate = declared.filter(d => d.rate !== null);
669
+ if (withRate.length === 0) {
670
+ return null;
671
+ }
672
+ const undeclared = declared.find(d => d.rate === null);
673
+ if (undeclared) {
674
+ throw new Error(`cannot determine the sample rate of shard ${undeclared.shard.Name}`);
675
+ }
676
+ const first = withRate[0];
677
+ const disagreeing = withRate.find(d => d.rate !== first.rate);
678
+ if (disagreeing) {
679
+ throw new Error(`shards disagree on sample rate: ${first.shard.Name} is ${first.rate} Hz but ${disagreeing.shard.Name} is ${disagreeing.rate} Hz`);
680
+ }
681
+ return first.rate;
682
+ }
683
+ /**
684
+ * Infers the sample rate of shards that declare none from the size of their full shards: every shard
685
+ * but the highest-indexed (normally a partial window) holds {@link LEGACY_SHARD_SECONDS} of mono PCM16.
686
+ * Each full shard's implied rate must be within {@link RATE_SNAP_TOLERANCE} of a standard rate, and all
687
+ * must agree. A lone shard is refused, since it may be a partial window.
688
+ */
689
+ function inferSampleRateFromShardSizes(segments, shards) {
690
+ const nameOf = (index) => shards.find(s => s.Index === index)?.Name ?? `index ${index}`;
691
+ const ordered = [...segments].sort((a, b) => a.Index - b.Index);
692
+ const full = ordered.slice(0, -1);
693
+ if (full.length === 0) {
694
+ throw new Error(`cannot determine the sample rate of shard ${nameOf(ordered[0].Index)}: neither its key nor its content type carries one, ` +
695
+ `and a lone shard may be a partial window, so its size cannot be trusted`);
696
+ }
697
+ const rates = full.map(segment => {
698
+ const implied = segment.Bytes.length / RECORDING_BYTES_PER_SAMPLE / LEGACY_SHARD_SECONDS;
699
+ const snapped = STANDARD_PCM_RATES.find(r => Math.abs(implied - r) / r <= RATE_SNAP_TOLERANCE);
700
+ if (snapped === undefined) {
701
+ throw new Error(`cannot determine the sample rate of shard ${nameOf(segment.Index)}: its size (${segment.Bytes.length} bytes) ` +
702
+ `implies ${Math.round(implied)} Hz, not a standard rate`);
703
+ }
704
+ return snapped;
705
+ });
706
+ const disagreeing = rates.findIndex(r => r !== rates[0]);
707
+ if (disagreeing !== -1) {
708
+ throw new Error(`shards disagree on sample rate: ${nameOf(full[0].Index)}'s size implies ${rates[0]} Hz ` +
709
+ `but ${nameOf(full[disagreeing].Index)}'s implies ${rates[disagreeing]} Hz`);
710
+ }
711
+ return rates[0];
712
+ }
713
+ /** Sequential on purpose: bounds memory and request concurrency against the storage account. */
714
+ async function readShardBytes(driver, shards) {
715
+ const segments = [];
716
+ let total = 0;
717
+ for (const shard of shards) {
718
+ const bytes = await driver.GetObject({ fullPath: shard.Path });
719
+ total += bytes.length;
720
+ // Listed sizes can be 0 or wrong, so the real total is enforced as bytes arrive.
721
+ if (total > MAX_RECOVERY_BYTES) {
722
+ throw new Error(`shards read so far total ${total} bytes (at ${shard.Name}), over the recovery limit of ${MAX_RECOVERY_BYTES} bytes`);
723
+ }
724
+ segments.push({ Index: shard.Index, Bytes: bytes });
725
+ }
726
+ return segments;
727
+ }
728
+ function describeRecovery(shardCount, assembled, sampleRate) {
729
+ const head = `Recovered from ${shardCount} crash-recovery segment(s)`;
730
+ if (assembled.MissingIndexes.length === 0) {
731
+ return `${head}.`;
732
+ }
733
+ const seconds = assembled.GapBytes / RECORDING_BYTES_PER_SAMPLE / sampleRate;
734
+ return `${head}; missing segment(s) ${assembled.MissingIndexes.join(', ')} filled with estimated silence (~${seconds.toFixed(1)} s each).`;
735
+ }
242
736
  //# sourceMappingURL=realtime-recording-store.js.map