@memberjunction/ai-agents 6.2.0-edge.4 → 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 (104) hide show
  1. package/README.md +94 -7
  2. package/dist/AgentRunner.d.ts +6 -3
  3. package/dist/AgentRunner.d.ts.map +1 -1
  4. package/dist/AgentRunner.js +163 -38
  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/PayloadChangeAnalyzer.d.ts.map +1 -1
  15. package/dist/PayloadChangeAnalyzer.js +53 -30
  16. package/dist/PayloadChangeAnalyzer.js.map +1 -1
  17. package/dist/PayloadManager.d.ts +35 -2
  18. package/dist/PayloadManager.d.ts.map +1 -1
  19. package/dist/PayloadManager.js +250 -149
  20. package/dist/PayloadManager.js.map +1 -1
  21. package/dist/ScratchpadManager.d.ts +18 -0
  22. package/dist/ScratchpadManager.d.ts.map +1 -1
  23. package/dist/ScratchpadManager.js +61 -0
  24. package/dist/ScratchpadManager.js.map +1 -1
  25. package/dist/agent-audience.d.ts +38 -0
  26. package/dist/agent-audience.d.ts.map +1 -0
  27. package/dist/agent-audience.js +99 -0
  28. package/dist/agent-audience.js.map +1 -0
  29. package/dist/agent-context-injector.d.ts +17 -2
  30. package/dist/agent-context-injector.d.ts.map +1 -1
  31. package/dist/agent-context-injector.js +23 -7
  32. package/dist/agent-context-injector.js.map +1 -1
  33. package/dist/agent-memory-context-builder.d.ts +7 -2
  34. package/dist/agent-memory-context-builder.d.ts.map +1 -1
  35. package/dist/agent-memory-context-builder.js +12 -3
  36. package/dist/agent-memory-context-builder.js.map +1 -1
  37. package/dist/agent-pre-execution-rag.d.ts +101 -9
  38. package/dist/agent-pre-execution-rag.d.ts.map +1 -1
  39. package/dist/agent-pre-execution-rag.js +224 -23
  40. package/dist/agent-pre-execution-rag.js.map +1 -1
  41. package/dist/agent-types/flow-agent-type.d.ts +8 -0
  42. package/dist/agent-types/flow-agent-type.d.ts.map +1 -1
  43. package/dist/agent-types/flow-agent-type.js +48 -6
  44. package/dist/agent-types/flow-agent-type.js.map +1 -1
  45. package/dist/agent-types/loop-agent-response-type.d.ts +8 -2
  46. package/dist/agent-types/loop-agent-response-type.d.ts.map +1 -1
  47. package/dist/agent-types/loop-agent-response-type.js.map +1 -1
  48. package/dist/agent-types/loop-agent-type.d.ts +9 -2
  49. package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
  50. package/dist/agent-types/loop-agent-type.js +60 -16
  51. package/dist/agent-types/loop-agent-type.js.map +1 -1
  52. package/dist/base-agent.d.ts +568 -31
  53. package/dist/base-agent.d.ts.map +1 -1
  54. package/dist/base-agent.js +2294 -421
  55. package/dist/base-agent.js.map +1 -1
  56. package/dist/index.d.ts +4 -0
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js +4 -0
  59. package/dist/index.js.map +1 -1
  60. package/dist/memory-manager-agent.d.ts.map +1 -1
  61. package/dist/memory-manager-agent.js +46 -34
  62. package/dist/memory-manager-agent.js.map +1 -1
  63. package/dist/native-tools/action-param-schema.d.ts +57 -0
  64. package/dist/native-tools/action-param-schema.d.ts.map +1 -0
  65. package/dist/native-tools/action-param-schema.js +238 -0
  66. package/dist/native-tools/action-param-schema.js.map +1 -0
  67. package/dist/native-tools/action-tool-builder.d.ts +5 -4
  68. package/dist/native-tools/action-tool-builder.d.ts.map +1 -1
  69. package/dist/native-tools/action-tool-builder.js +29 -71
  70. package/dist/native-tools/action-tool-builder.js.map +1 -1
  71. package/dist/native-tools/json-argument.d.ts +41 -0
  72. package/dist/native-tools/json-argument.d.ts.map +1 -0
  73. package/dist/native-tools/json-argument.js +79 -0
  74. package/dist/native-tools/json-argument.js.map +1 -0
  75. package/dist/query-builder-agent.d.ts +13 -4
  76. package/dist/query-builder-agent.d.ts.map +1 -1
  77. package/dist/query-builder-agent.js +102 -27
  78. package/dist/query-builder-agent.js.map +1 -1
  79. package/dist/realtime/realtime-client-session-service.d.ts +5 -4
  80. package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
  81. package/dist/realtime/realtime-client-session-service.js +42 -30
  82. package/dist/realtime/realtime-client-session-service.js.map +1 -1
  83. package/dist/realtime/realtime-coagent-config.d.ts +8 -1
  84. package/dist/realtime/realtime-coagent-config.d.ts.map +1 -1
  85. package/dist/realtime/realtime-coagent-config.js +17 -1
  86. package/dist/realtime/realtime-coagent-config.js.map +1 -1
  87. package/dist/realtime/realtime-recording-ledger.d.ts +130 -0
  88. package/dist/realtime/realtime-recording-ledger.d.ts.map +1 -0
  89. package/dist/realtime/realtime-recording-ledger.js +190 -0
  90. package/dist/realtime/realtime-recording-ledger.js.map +1 -0
  91. package/dist/realtime/realtime-recording-opus-assembly.d.ts +211 -0
  92. package/dist/realtime/realtime-recording-opus-assembly.d.ts.map +1 -0
  93. package/dist/realtime/realtime-recording-opus-assembly.js +706 -0
  94. package/dist/realtime/realtime-recording-opus-assembly.js.map +1 -0
  95. package/dist/realtime/realtime-recording-store.d.ts +38 -1
  96. package/dist/realtime/realtime-recording-store.d.ts.map +1 -1
  97. package/dist/realtime/realtime-recording-store.js +58 -30
  98. package/dist/realtime/realtime-recording-store.js.map +1 -1
  99. package/dist/realtime/realtime-turn-moderator.d.ts +2 -1
  100. package/dist/realtime/realtime-turn-moderator.d.ts.map +1 -1
  101. package/dist/realtime/realtime-turn-moderator.js +7 -1
  102. package/dist/realtime/realtime-turn-moderator.js.map +1 -1
  103. package/dist/volatile-child-prompt.js +3 -3
  104. package/package.json +21 -19
@@ -0,0 +1,706 @@
1
+ /**
2
+ * @fileoverview Server-side assembly of a client-direct realtime recording from its `MJOPUS1` shard
3
+ * ledger into `recording.wav` + `peaks.json`.
4
+ *
5
+ * The browser encodes the whole call with ONE Opus encoder and cuts the packet stream into ~5 s shards,
6
+ * so the shards are slices of one stream, not standalone files. Assembly therefore decodes every packet,
7
+ * in index order, with ONE decoder, and places each shard's audio at its own `StartSample` (48 kHz): the
8
+ * timing comes from the shard headers, never from the wall clock, so transcript cues stay aligned even
9
+ * when a shard is missing and its range is filled with silence.
10
+ *
11
+ * Two layers:
12
+ * - {@link AssembleOpusRecordingPcm}, {@link ComputeRecordingPeaks}, {@link EncodePcm16Wav}: pure.
13
+ * - {@link AssembleRealtimeRecordingFromLedger}: the orchestration a claimed assembly runs (load, decode,
14
+ * store, fenced finish). It never throws.
15
+ *
16
+ * @module @memberjunction/ai-agents
17
+ */
18
+ import { endianness } from 'os';
19
+ import { Decoder } from '@evan/opus';
20
+ import { LogError, LogStatus } from '@memberjunction/core';
21
+ import { FileStorageEngine } from '@memberjunction/storage';
22
+ import { ParseRecordingShard, RecordingShardFormatError, RECORDING_SAMPLE_RATE, RECORDING_SHARD_MAX_PACKETS, RECORDING_FRAME_SAMPLES, } from '@memberjunction/ai-core-plus';
23
+ import { LinkRecordingToSession, RecordingFolder, ResolveRecordingStorageAccountID, ResolveStorageAccountIDForProvider, WriteRecordingPeaksSidecar, WriteRecordingWavHeader, RECORDING_WAV_HEADER_BYTES, } from './realtime-recording-store.js';
24
+ /**
25
+ * A deterministic assembly failure: re-running against the same data fails the same way (bounds
26
+ * exceeded, overlapping or duplicate shards, no storage account, agent not loadable), so the recording
27
+ * is finished as `Failed`. Any other error is treated as transient (see {@link AssembleRealtimeRecordingFromLedger}).
28
+ */
29
+ export class RecordingAssemblyError extends Error {
30
+ constructor(message) {
31
+ super(message);
32
+ this.name = 'RecordingAssemblyError';
33
+ }
34
+ }
35
+ /**
36
+ * Most shards one assembly accepts. At 5 s per shard this is ~2.8 h, past any real call; a larger
37
+ * count (from the terminal signal or the ledger) is corrupt or hostile, and assembling it would allocate
38
+ * an unbounded PCM buffer, so assembly refuses it.
39
+ */
40
+ export const MAX_ASSEMBLY_SHARDS = 2000;
41
+ /**
42
+ * Most samples one assembly produces: 3 h at 48 kHz. The WAV is 2 bytes per sample (~1 GB at this cap;
43
+ * on big-endian hosts a separate PCM array doubles that), so this is the memory ceiling of one
44
+ * assembly; the captured count comes from the browser, so it must be bounded before anything is allocated.
45
+ */
46
+ export const MAX_ASSEMBLY_SAMPLES = RECORDING_SAMPLE_RATE * 60 * 180;
47
+ /** Largest value of the shard ledger's INT `Index` column: "below this" counts every stored shard. */
48
+ const SQL_INT_MAX = 2_147_483_647;
49
+ /** Waveform buckets: the 600 the browser used to compute at capture time, so old and new recordings render alike. */
50
+ const PEAK_BUCKETS = 600;
51
+ const BYTES_PER_SAMPLE = 2;
52
+ /**
53
+ * Lays a session's shards out on one 48 kHz timeline and decodes them with one decoder.
54
+ *
55
+ * - A present shard is decoded packet by packet; exactly `SampleCount` samples are kept (decoded audio
56
+ * past it is dropped, a shortfall stays silent). Every packet is still decoded so the decoder state
57
+ * stays continuous into the next shard.
58
+ * - A run of missing indexes becomes one silent gap from the end of the previous shard to the start of
59
+ * the next present one (a trailing run: to the end of the recording), listing the missing indexes.
60
+ * - A present shard that starts after the end of the previous one leaves a silent gap with no indexes.
61
+ * - A shard with a packet libopus cannot decode is silenced whole, listed as a gap with its index and
62
+ * in `DecodeFailures`.
63
+ * - After any gap the decoder is reset.
64
+ *
65
+ * The samples are decoded straight into the returned WAV's data section (see `allocatePcm16Wav`).
66
+ *
67
+ * The shard count is `expectedShards`, or the highest present index + 1 when no terminal signal has
68
+ * arrived. The length is `capturedSamples`, or the end of the last shard when unknown (and never less
69
+ * than the end of the last shard: audio past a stale terminal is kept, not cut).
70
+ *
71
+ * @param shards Parsed shards (any order, unique indexes).
72
+ * @param expectedShards Shard count from the terminal signal, or null when none arrived.
73
+ * @param capturedSamples Captured sample count from the terminal signal, or null.
74
+ * @param decoder The one decoder for this stream.
75
+ * @throws RecordingAssemblyError on a duplicate index, a shard overlapping the audio before it, or a
76
+ * shard/sample count over {@link MAX_ASSEMBLY_SHARDS} / {@link MAX_ASSEMBLY_SAMPLES}.
77
+ */
78
+ export function AssembleOpusRecordingPcm(shards, expectedShards, capturedSamples, decoder) {
79
+ const byIndex = indexShards(shards);
80
+ const ordered = [...byIndex.values()].sort((a, b) => a.ShardIndex - b.ShardIndex);
81
+ const last = ordered[ordered.length - 1];
82
+ const highestIndex = last ? last.ShardIndex : -1;
83
+ const lastEnd = last ? last.StartSample + last.SampleCount : 0;
84
+ const shardCount = Math.max(expectedShards ?? 0, highestIndex + 1);
85
+ const length = Math.max(capturedSamples ?? 0, lastEnd);
86
+ AssertRecordingAssemblyBounds(shardCount, length);
87
+ const output = allocatePcm16Wav(length, RECORDING_SAMPLE_RATE);
88
+ const pcm = output.Pcm;
89
+ const gaps = [];
90
+ const decodeFailures = [];
91
+ let position = 0;
92
+ let missing = [];
93
+ let decodedAny = false;
94
+ const missingRuns = [];
95
+ for (let index = 0; index < shardCount; index++) {
96
+ const shard = byIndex.get(index);
97
+ if (!shard) {
98
+ missing.push(index);
99
+ continue;
100
+ }
101
+ if (shard.StartSample < position) {
102
+ throw new RecordingAssemblyError(`shard ${index} starts at sample ${shard.StartSample}, before the end of the audio before it (${position})`);
103
+ }
104
+ if (shard.StartSample > position || missing.length > 0) {
105
+ const gap = { startSample: position, sampleCount: shard.StartSample - position, indexes: missing };
106
+ gaps.push(gap);
107
+ if (missing.length > 0) {
108
+ missingRuns.push(gap);
109
+ }
110
+ missing = [];
111
+ if (decodedAny) {
112
+ decoder.Reset();
113
+ }
114
+ }
115
+ const failure = decodeShardInto(pcm, shard, decoder);
116
+ if (failure) {
117
+ // One bad packet costs its shard, not the recording: silence the whole shard, list it as a gap,
118
+ // and reset so the next shard does not start from a broken decoder state.
119
+ pcm.fill(0, shard.StartSample, shard.StartSample + shard.SampleCount);
120
+ gaps.push({ startSample: shard.StartSample, sampleCount: shard.SampleCount, indexes: [index] });
121
+ decodeFailures.push(failure);
122
+ decoder.Reset();
123
+ }
124
+ decodedAny = true;
125
+ position = shard.StartSample + shard.SampleCount;
126
+ }
127
+ if (position < length || missing.length > 0) {
128
+ const gap = { startSample: position, sampleCount: length - position, indexes: missing };
129
+ gaps.push(gap);
130
+ if (missing.length > 0) {
131
+ missingRuns.push(gap);
132
+ }
133
+ }
134
+ const terminalMatched = expectedShards !== null && capturedSamples !== null
135
+ && shardCount === expectedShards && length === capturedSamples;
136
+ return {
137
+ Pcm: pcm, Wav: output.Finish(), Gaps: gaps, DecodeFailures: decodeFailures, MissingRuns: missingRuns,
138
+ TerminalMatched: terminalMatched, Complete: terminalMatched && gaps.length === 0,
139
+ };
140
+ }
141
+ /**
142
+ * Most samples one shard can carry: the format's packet cap ({@link RECORDING_SHARD_MAX_PACKETS}),
143
+ * each packet at most one 960-sample frame of kept audio.
144
+ */
145
+ const MAX_SHARD_SAMPLES = RECORDING_SHARD_MAX_PACKETS * RECORDING_FRAME_SAMPLES;
146
+ /**
147
+ * Fills the missing-shard ranges of a re-assembly from the session's previous recording.
148
+ *
149
+ * Why: a Complete assembly deletes its shard rows (everything below its expected count). When a strictly
150
+ * higher terminal later re-opens the session (the tab was hidden, a terminal went out, the call
151
+ * continued), the re-assembly finds those indexes missing. Their audio lives only in the previous
152
+ * `recording.wav`, so it is copied back rather than overwritten with silence.
153
+ *
154
+ * Every missing range the previous file covers is reused, not only the leading one: a re-sent copy of
155
+ * an assembled shard (its ack was lost, so the browser sent it again after the rows were deleted) is
156
+ * stored again, and would otherwise split the deleted range and leave everything after it silent.
157
+ * Reusing is safe because the previous recording's silent ranges are exactly its stored gaps: every
158
+ * assembly stamps its gaps before it overwrites the object (see `StampAssemblyGaps`), so an assembly
159
+ * that wrote silence and then failed to finish still left that silence listed. Those gaps are carried
160
+ * over (clipped to each reused range) and stay gaps. The one remaining way the object can disagree is a
161
+ * superseded assembler whose slow storage write lands after a newer one finished (a known, parked race).
162
+ *
163
+ * The part of a range beyond the previous recording's length stays silent and stays a gap; the range's
164
+ * rows are gone, so per-index boundaries are unknown, and the remainder lists the indexes that can hold
165
+ * samples past the old end: an index `i` ends no later than `(i + 1) * MAX_SHARD_SAMPLES`, so indexes
166
+ * that provably end inside the old recording are dropped.
167
+ *
168
+ * Returns a new result (the samples are written in place) with `Complete` recomputed.
169
+ */
170
+ export function FillGapsFromPreviousRecording(assembled, previous) {
171
+ const { Pcm: pcm } = assembled;
172
+ const reused = new Set();
173
+ const added = [];
174
+ for (const run of assembled.MissingRuns) {
175
+ const reuseEnd = Math.min(run.startSample + run.sampleCount, previous.Pcm.length);
176
+ if (reuseEnd <= run.startSample) {
177
+ continue;
178
+ }
179
+ reused.add(run);
180
+ pcm.set(previous.Pcm.subarray(run.startSample, reuseEnd), run.startSample);
181
+ added.push(...previousGapsWithin(previous.Gaps, run.startSample, reuseEnd));
182
+ const runEnd = run.startSample + run.sampleCount;
183
+ if (runEnd > reuseEnd) {
184
+ const indexes = run.indexes.filter(i => (i + 1) * MAX_SHARD_SAMPLES > reuseEnd);
185
+ added.push({ startSample: reuseEnd, sampleCount: runEnd - reuseEnd, indexes });
186
+ }
187
+ }
188
+ if (reused.size === 0) {
189
+ return assembled;
190
+ }
191
+ const gaps = [...assembled.Gaps.filter(gap => !reused.has(gap)), ...added].sort((a, b) => a.startSample - b.startSample);
192
+ const missingRuns = assembled.MissingRuns.filter(run => !reused.has(run));
193
+ // On little-endian hosts Pcm is a view of the WAV, so the copies above already landed in it.
194
+ const wav = pcm.buffer === assembled.Wav.buffer ? assembled.Wav : EncodePcm16Wav(pcm, RECORDING_SAMPLE_RATE);
195
+ return { ...assembled, Wav: wav, Gaps: gaps, MissingRuns: missingRuns, Complete: assembled.TerminalMatched && gaps.length === 0 };
196
+ }
197
+ /** The previous recording's gaps clipped to `[start, end)`. */
198
+ function previousGapsWithin(previousGaps, start, end) {
199
+ const clipped = [];
200
+ for (const old of previousGaps) {
201
+ const from = Math.max(old.startSample, start);
202
+ const to = Math.min(old.startSample + old.sampleCount, end);
203
+ if (to > from) {
204
+ clipped.push({ startSample: from, sampleCount: to - from, indexes: old.indexes });
205
+ }
206
+ }
207
+ return clipped;
208
+ }
209
+ /**
210
+ * The samples of a canonical recording WAV (exactly the 44-byte mono PCM16 48 kHz layout
211
+ * `WriteRecordingWavHeader` writes, data size matching the file), or null for anything else. Only such
212
+ * a file is trusted as a previous assembly's output.
213
+ */
214
+ export function ParseCanonicalRecordingWav(bytes) {
215
+ if (bytes.length < RECORDING_WAV_HEADER_BYTES) {
216
+ return null;
217
+ }
218
+ const buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
219
+ const dataSize = buffer.length - RECORDING_WAV_HEADER_BYTES;
220
+ const canonical = buffer.toString('ascii', 0, 4) === 'RIFF'
221
+ && buffer.readUInt32LE(4) === 36 + dataSize
222
+ && buffer.toString('ascii', 8, 16) === 'WAVEfmt '
223
+ && buffer.readUInt32LE(16) === 16
224
+ && buffer.readUInt16LE(20) === 1
225
+ && buffer.readUInt16LE(22) === 1
226
+ && buffer.readUInt32LE(24) === RECORDING_SAMPLE_RATE
227
+ && buffer.readUInt32LE(28) === RECORDING_SAMPLE_RATE * BYTES_PER_SAMPLE
228
+ && buffer.readUInt16LE(32) === BYTES_PER_SAMPLE
229
+ && buffer.readUInt16LE(34) === 16
230
+ && buffer.toString('ascii', 36, 40) === 'data'
231
+ && buffer.readUInt32LE(40) === dataSize
232
+ && dataSize % BYTES_PER_SAMPLE === 0;
233
+ if (!canonical) {
234
+ return null;
235
+ }
236
+ const dataOffset = buffer.byteOffset + RECORDING_WAV_HEADER_BYTES;
237
+ if (endianness() === 'LE' && dataOffset % BYTES_PER_SAMPLE === 0) {
238
+ // A view, not a copy: the previous recording can be as large as the new one.
239
+ return new Int16Array(buffer.buffer, dataOffset, dataSize / BYTES_PER_SAMPLE);
240
+ }
241
+ const samples = new Int16Array(dataSize / BYTES_PER_SAMPLE);
242
+ for (let i = 0; i < samples.length; i++) {
243
+ samples[i] = buffer.readInt16LE(RECORDING_WAV_HEADER_BYTES + i * BYTES_PER_SAMPLE);
244
+ }
245
+ return samples;
246
+ }
247
+ /**
248
+ * Throws when an assembly would exceed {@link MAX_ASSEMBLY_SHARDS} or {@link MAX_ASSEMBLY_SAMPLES}.
249
+ * Checked twice on purpose: by the orchestrator on the session's terminal counts BEFORE loading any
250
+ * shard rows, and by {@link AssembleOpusRecordingPcm} on the counts derived from the shards themselves
251
+ * (the only counts there are when no terminal signal arrived).
252
+ */
253
+ export function AssertRecordingAssemblyBounds(shardCount, sampleCount) {
254
+ if (shardCount !== null && shardCount > MAX_ASSEMBLY_SHARDS) {
255
+ throw new RecordingAssemblyError(`refusing to assemble ${shardCount} shards; the limit is ${MAX_ASSEMBLY_SHARDS}`);
256
+ }
257
+ if (sampleCount !== null && sampleCount > MAX_ASSEMBLY_SAMPLES) {
258
+ throw new RecordingAssemblyError(`refusing to assemble ${sampleCount} samples; the limit is ${MAX_ASSEMBLY_SAMPLES} (3 h at ${RECORDING_SAMPLE_RATE} Hz)`);
259
+ }
260
+ }
261
+ function indexShards(shards) {
262
+ const byIndex = new Map();
263
+ for (const shard of shards) {
264
+ if (byIndex.has(shard.ShardIndex)) {
265
+ throw new RecordingAssemblyError(`duplicate shard index ${shard.ShardIndex}`);
266
+ }
267
+ byIndex.set(shard.ShardIndex, shard);
268
+ }
269
+ return byIndex;
270
+ }
271
+ /** Decodes a shard into its range; returns the first packet that failed to decode (the caller silences the shard), else null. */
272
+ function decodeShardInto(pcm, shard, decoder) {
273
+ let written = 0;
274
+ for (let packetIndex = 0; packetIndex < shard.Packets.length; packetIndex++) {
275
+ let frame;
276
+ try {
277
+ frame = decoder.Decode(shard.Packets[packetIndex]);
278
+ }
279
+ catch (error) {
280
+ return { ShardIndex: shard.ShardIndex, PacketIndex: packetIndex, Message: error instanceof Error ? error.message : String(error) };
281
+ }
282
+ const take = Math.min(frame.length, shard.SampleCount - written);
283
+ if (take > 0) {
284
+ pcm.set(frame.subarray(0, take), shard.StartSample + written);
285
+ written += take;
286
+ }
287
+ }
288
+ return null;
289
+ }
290
+ /**
291
+ * A zeroed WAV of `sampleCount` samples plus the Int16 array to write the samples into. On a
292
+ * little-endian host (every Node deployment target) that array is a view over the WAV's data section,
293
+ * so the recording is held once and `Finish` is free; elsewhere it is a separate array that `Finish`
294
+ * copies in little-endian order.
295
+ */
296
+ function allocatePcm16Wav(sampleCount, sampleRate) {
297
+ const dataSize = sampleCount * BYTES_PER_SAMPLE;
298
+ const wav = Buffer.alloc(RECORDING_WAV_HEADER_BYTES + dataSize);
299
+ WriteRecordingWavHeader(wav, sampleRate, dataSize);
300
+ const dataOffset = wav.byteOffset + RECORDING_WAV_HEADER_BYTES;
301
+ if (endianness() === 'LE' && dataOffset % BYTES_PER_SAMPLE === 0) {
302
+ return { Pcm: new Int16Array(wav.buffer, dataOffset, sampleCount), Finish: () => wav };
303
+ }
304
+ const pcm = new Int16Array(sampleCount);
305
+ return {
306
+ Pcm: pcm,
307
+ Finish: () => {
308
+ for (let i = 0; i < pcm.length; i++) {
309
+ wav.writeInt16LE(pcm[i], RECORDING_WAV_HEADER_BYTES + i * BYTES_PER_SAMPLE);
310
+ }
311
+ return wav;
312
+ },
313
+ };
314
+ }
315
+ /**
316
+ * Waveform peaks of a whole recording: max-abs per bucket, normalized by the global max (0..1). Same
317
+ * semantics as the peaks the browser used to compute at capture time for its whole-call WAV upload,
318
+ * so a viewer renders an assembled recording exactly like one uploaded before #5294.
319
+ *
320
+ * @param pcm Mono PCM16 samples.
321
+ * @param buckets Target bucket count (default 600); a shorter buffer yields one bucket per sample.
322
+ * @returns The peaks, or `[]` for an empty or all-silent buffer.
323
+ */
324
+ export function ComputeRecordingPeaks(pcm, buckets = PEAK_BUCKETS) {
325
+ const target = Math.max(1, Math.floor(buckets));
326
+ if (pcm.length === 0) {
327
+ return [];
328
+ }
329
+ const count = Math.min(target, pcm.length);
330
+ const perBucket = pcm.length / count;
331
+ const peaks = new Array(count).fill(0);
332
+ let globalMax = 0;
333
+ for (let b = 0; b < count; b++) {
334
+ const start = Math.floor(b * perBucket);
335
+ const end = b === count - 1 ? pcm.length : Math.floor((b + 1) * perBucket);
336
+ let localMax = 0;
337
+ for (let i = start; i < end; i++) {
338
+ const abs = Math.abs(pcm[i]);
339
+ if (abs > localMax) {
340
+ localMax = abs;
341
+ }
342
+ }
343
+ peaks[b] = localMax;
344
+ globalMax = Math.max(globalMax, localMax);
345
+ }
346
+ return globalMax === 0 ? [] : peaks.map(v => v / globalMax);
347
+ }
348
+ /**
349
+ * Wraps mono PCM16 samples in the canonical 44-byte WAV header (written by the shared
350
+ * `WriteRecordingWavHeader`), samples little-endian regardless of host byte order.
351
+ */
352
+ export function EncodePcm16Wav(pcm, sampleRate) {
353
+ const output = allocatePcm16Wav(pcm.length, sampleRate);
354
+ output.Pcm.set(pcm);
355
+ return output.Finish();
356
+ }
357
+ /** {@link IOpusPacketDecoder} over libopus (`@evan/opus`: native binding, WASM fallback). */
358
+ class LibopusPacketDecoder {
359
+ constructor() {
360
+ // 48000 is RECORDING_SAMPLE_RATE; the binding's option type only accepts the literal rates.
361
+ this.decoder = new Decoder({ channels: 1, sample_rate: 48000 });
362
+ }
363
+ Decode(packet) {
364
+ // The binding returns a view of a buffer it reuses on the next call, so copy the samples out now.
365
+ const bytes = this.decoder.decode(packet);
366
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
367
+ const samples = new Int16Array(bytes.byteLength / BYTES_PER_SAMPLE);
368
+ for (let i = 0; i < samples.length; i++) {
369
+ samples[i] = view.getInt16(i * BYTES_PER_SAMPLE, true);
370
+ }
371
+ return samples;
372
+ }
373
+ Reset() {
374
+ this.decoder.reset();
375
+ }
376
+ }
377
+ /** A fresh 48 kHz mono libopus decoder. Use one per assembly; feed it packets in stream order. */
378
+ export function CreateLibopusDecoder() {
379
+ return new LibopusPacketDecoder();
380
+ }
381
+ /**
382
+ * Assembles a claimed session's shard ledger into `recording.wav` + `peaks.json` and finishes the claim.
383
+ *
384
+ * Flow: read the session's terminal counts and the stored rows' positions (both bounded before any
385
+ * shard bytes are loaded) → without `ForcePartial`, hand the claim back (`Deferred`) when the positions
386
+ * alone show the recording cannot be Complete → resolve where the recording is stored → load and parse
387
+ * the shards (a shard that fails to parse, or whose header disagrees with its ledger row, is logged and
388
+ * treated as missing) → decode ({@link AssembleOpusRecordingPcm}; a shard with an undecodable packet is
389
+ * logged and silenced) → when the session already has its own `recording.wav` and shards are missing,
390
+ * read it and fill those ranges from it ({@link FillGapsFromPreviousRecording}: a Complete assembly deleted
391
+ * the rows its audio came from, so a re-opened session must not overwrite that audio with silence; the
392
+ * early position-only Deferred is skipped for such a session for the same reason). Then:
393
+ * - incomplete and not `ForcePartial`: the claim is handed back as `Pending` with no file, keeping the
394
+ * gaps already stored for the session's existing recording → `Deferred`;
395
+ * - otherwise the gaps are stamped (fenced: a lost claim is `Superseded`, nothing written) and the WAV
396
+ * is stored: a first assembly uploads `recording.wav`
397
+ * into the session folder; a re-assembly overwrites the session's existing WAV object in place, keeping
398
+ * its `MJ: Files` id. `peaks.json` is rewritten next to it. The finish is fenced on `Version`; only then
399
+ * is a new file linked to the session and, for `Complete`, the assembled shard rows deleted.
400
+ *
401
+ * The session is never saved through `BaseEntity` (that rewrites every column and would clobber the
402
+ * concurrent proc writes to the recording state); the finish proc stamps `RecordingFileID`.
403
+ *
404
+ * Never throws. Failures split by kind:
405
+ * - a {@link RecordingAssemblyError} (deterministic: bounds exceeded, overlapping or duplicate shards,
406
+ * no storage account, agent not loadable) is logged, the claim is finished as `Failed` (when the fence
407
+ * still holds), and the outcome is `Failed`;
408
+ * - any other error (SQL, storage, decoder load: likely transient) is logged with the session id and
409
+ * version, and the claim is LEFT in `Assembling` with no finish call; the outcome is `Retry`. The
410
+ * janitor's stale-`Assembling` re-claim (with its backoff and give-up cap) retries a closed session,
411
+ * and a later terminal or shard re-opens a live one.
412
+ * A lost fence is `Superseded` and leaves the shards.
413
+ */
414
+ export async function AssembleRealtimeRecordingFromLedger(input) {
415
+ try {
416
+ return await assembleFromLedger(input);
417
+ }
418
+ catch (error) {
419
+ const message = error instanceof Error ? error.message : String(error);
420
+ if (error instanceof RecordingAssemblyError) {
421
+ LogError(`AssembleRealtimeRecordingFromLedger failed (session ${input.SessionID}, version ${input.Version}): ${message}`);
422
+ await finishAsFailed(input);
423
+ return 'Failed';
424
+ }
425
+ LogError(`AssembleRealtimeRecordingFromLedger hit a transient error (session ${input.SessionID}, version ${input.Version}); ` +
426
+ `the claim stays Assembling for a stale re-claim to retry: ${message}`);
427
+ return 'Retry';
428
+ }
429
+ }
430
+ async function assembleFromLedger(input) {
431
+ const { SessionID, Version, Ledger, ContextUser, ForcePartial } = input;
432
+ const session = await loadSession(input);
433
+ const expected = session.RecordingExpectedShards;
434
+ const captured = session.RecordingCapturedSamples;
435
+ AssertRecordingAssemblyBounds(expected, captured);
436
+ // Bound the row count too before loading: the terminal counts do not limit how many indexes exist.
437
+ const storedShards = await Ledger.CountShardsBelow(SessionID, SQL_INT_MAX);
438
+ AssertRecordingAssemblyBounds(storedShards, null);
439
+ const positions = await Ledger.LoadShardMetadata(SessionID);
440
+ // Decided from row positions alone, so an incomplete ledger never costs a full load and decode. Not
441
+ // when a recording exists: the rows it was assembled from are deleted, and its audio fills them in.
442
+ if (!ForcePartial && !session.RecordingFileID && !couldBeComplete(positions, expected, captured)) {
443
+ return handBack(input, session);
444
+ }
445
+ logOverrun(SessionID, positions, captured);
446
+ const target = await resolveStorageTarget(session, input);
447
+ const shards = parseLedgerShards(SessionID, await Ledger.LoadShards(SessionID));
448
+ let assembled = AssembleOpusRecordingPcm(shards, expected, captured, CreateLibopusDecoder());
449
+ for (const failure of assembled.DecodeFailures) {
450
+ LogError(`AssembleRealtimeRecordingFromLedger (session ${SessionID}): shard ${failure.ShardIndex} packet ${failure.PacketIndex} ` +
451
+ `failed to decode (${failure.Message}); the shard is silenced and listed as a gap`);
452
+ }
453
+ if (assembled.MissingRuns.length > 0 && target.ExistingFile) {
454
+ const previous = await readPreviousRecording(session, target, input);
455
+ if (previous) {
456
+ assembled = FillGapsFromPreviousRecording(assembled, previous);
457
+ }
458
+ }
459
+ if (!assembled.Complete && !ForcePartial) {
460
+ return handBack(input, session);
461
+ }
462
+ // Last check before writing storage, so a superseded assembler does not overwrite a newer result, and
463
+ // it stamps this assembly's gaps first: whatever happens after the write (a failed finish, a crash),
464
+ // the stored gaps then list every silent range the object holds, which is what lets a later
465
+ // re-assembly reuse the rest of it (see FillGapsFromPreviousRecording). Storage has no
466
+ // compare-and-set, so a claim landing during the write is caught by the fenced finish.
467
+ if (!await Ledger.StampAssemblyGaps(SessionID, Version, assembled.Gaps)) {
468
+ LogStatus(`AssembleRealtimeRecordingFromLedger: session ${SessionID} was claimed again after version ${Version}; nothing written`);
469
+ return 'Superseded';
470
+ }
471
+ const status = assembled.Complete ? 'Complete' : 'Partial';
472
+ const stored = await storeWav(target, assembled.Wav, input);
473
+ await WriteRecordingPeaksSidecar(SessionID, target.AccountID, ComputeRecordingPeaks(assembled.Pcm), ContextUser);
474
+ const finished = await Ledger.FinishAssembly({ SessionID, Version, Status: status, Gaps: assembled.Gaps, FileID: stored.FileID });
475
+ if (!finished) {
476
+ logSupersededWrite(SessionID, Version, stored);
477
+ return 'Superseded';
478
+ }
479
+ if (stored.Uploaded) {
480
+ await LinkRecordingToSession(stored.FileID, SessionID, ContextUser, input.Provider);
481
+ }
482
+ if (status === 'Complete' && expected !== null) {
483
+ await deleteAssembledShards(Ledger, SessionID, expected);
484
+ }
485
+ return status;
486
+ }
487
+ /**
488
+ * Reads the session's existing `recording.wav` and its stored gaps, for {@link FillGapsFromPreviousRecording}.
489
+ * Returns null (logged, nothing reused, so the missing ranges stay silent gaps) when the file is not a
490
+ * canonical recording WAV, is over the sample bound, or the stored gaps cannot be read: reusing samples
491
+ * without knowing which of them were silence would misreport the recording as gap-free. A storage read
492
+ * failure throws (transient, see {@link AssembleRealtimeRecordingFromLedger}).
493
+ */
494
+ async function readPreviousRecording(session, target, input) {
495
+ const file = target.ExistingFile;
496
+ if (!file) {
497
+ return null;
498
+ }
499
+ const driver = await FileStorageEngine.Instance.GetDriver(target.AccountID, input.ContextUser);
500
+ const prefix = `AssembleRealtimeRecordingFromLedger (session ${session.ID})`;
501
+ // A missing object is permanent, not transient: treating it as a read error would Retry forever.
502
+ // Assembly goes on and the write recreates the object at the same key.
503
+ if (!await driver.ObjectExists(file.ProviderKey)) {
504
+ LogError(`${prefix}: existing recording file ${file.ID} has no object at ${file.ProviderKey}; nothing to reuse, so missing ranges stay silent gaps`);
505
+ return null;
506
+ }
507
+ const pcm = ParseCanonicalRecordingWav(await driver.GetObject({ fullPath: file.ProviderKey }));
508
+ if (!pcm) {
509
+ LogError(`${prefix}: existing recording file ${file.ID} is not a canonical 48 kHz mono PCM16 WAV; its audio is not reused, so missing ranges stay silent gaps`);
510
+ return null;
511
+ }
512
+ if (pcm.length > MAX_ASSEMBLY_SAMPLES) {
513
+ LogError(`${prefix}: existing recording file ${file.ID} holds ${pcm.length} samples, over the limit of ${MAX_ASSEMBLY_SAMPLES}; not reused`);
514
+ return null;
515
+ }
516
+ const gaps = parseStoredGaps(session.RecordingGaps);
517
+ if (!gaps) {
518
+ LogError(`${prefix}: stored RecordingGaps cannot be read; the audio of existing recording file ${file.ID} is not reused`);
519
+ return null;
520
+ }
521
+ return { Pcm: pcm, Gaps: gaps };
522
+ }
523
+ /** The session's stored `RecordingGaps` JSON as gaps (`[]` when none), or null when it is malformed. */
524
+ function parseStoredGaps(json) {
525
+ if (!json) {
526
+ return [];
527
+ }
528
+ let parsed;
529
+ try {
530
+ parsed = JSON.parse(json);
531
+ }
532
+ catch (error) {
533
+ if (error instanceof SyntaxError) {
534
+ return null;
535
+ }
536
+ throw error;
537
+ }
538
+ if (!Array.isArray(parsed)) {
539
+ return null;
540
+ }
541
+ const gaps = [];
542
+ for (const item of parsed) {
543
+ const gap = item;
544
+ if (!gap || !Number.isSafeInteger(gap.startSample) || !Number.isSafeInteger(gap.sampleCount)
545
+ || !Array.isArray(gap.indexes) || !gap.indexes.every(i => Number.isSafeInteger(i))) {
546
+ return null;
547
+ }
548
+ gaps.push({ startSample: gap.startSample, sampleCount: gap.sampleCount, indexes: gap.indexes });
549
+ }
550
+ return gaps;
551
+ }
552
+ /**
553
+ * True when the stored rows' positions allow a Complete recording: terminal counts known, exactly the
554
+ * indexes `0..expected-1` stored, each starting where the previous one ends, the last ending at
555
+ * `captured`. A true result can still assemble Partial (a corrupt or undecodable shard).
556
+ */
557
+ function couldBeComplete(positions, expected, captured) {
558
+ if (expected === null || captured === null || positions.length !== expected) {
559
+ return false;
560
+ }
561
+ let end = 0;
562
+ for (let i = 0; i < positions.length; i++) {
563
+ if (positions[i].Index !== i || positions[i].StartSample !== end) {
564
+ return false;
565
+ }
566
+ end = positions[i].StartSample + positions[i].SampleCount;
567
+ }
568
+ return end === captured;
569
+ }
570
+ /**
571
+ * Hands an un-forced, incomplete claim back as `Pending` with no file. The stored gaps are passed
572
+ * through unchanged: they describe the session's existing recording (if any), which this does not replace.
573
+ */
574
+ async function handBack(input, session) {
575
+ const { SessionID, Version, Ledger } = input;
576
+ const released = await Ledger.FinishAssembly({ SessionID, Version, Status: 'Pending', Gaps: session.RecordingGaps, FileID: null });
577
+ return released ? 'Deferred' : 'Superseded';
578
+ }
579
+ /** Shards running past a terminal's captured count (the call went on after it): kept, but worth knowing about. */
580
+ function logOverrun(sessionID, positions, captured) {
581
+ if (captured === null) {
582
+ return;
583
+ }
584
+ const past = positions.filter(p => p.StartSample + p.SampleCount > captured);
585
+ if (past.length === 0) {
586
+ return;
587
+ }
588
+ const end = Math.max(...past.map(p => p.StartSample + p.SampleCount));
589
+ LogStatus(`AssembleRealtimeRecordingFromLedger (session ${sessionID}): shards ${past.map(p => p.Index).join(', ')} run to sample ${end}, ` +
590
+ `${end - captured} samples past the terminal's captured count of ${captured}; the recording keeps them`);
591
+ }
592
+ async function loadSession(input) {
593
+ const session = await input.Provider.GetEntityObject('MJ: AI Agent Sessions', input.ContextUser);
594
+ if (!await session.Load(input.SessionID)) {
595
+ throw new Error(`could not load session ${input.SessionID}`);
596
+ }
597
+ return session;
598
+ }
599
+ /**
600
+ * A re-assembly writes through the existing file's own storage provider (the agent's configuration may
601
+ * have changed since). Only the session's own `<RecordingFolder>/recording.wav` object is ever
602
+ * overwritten: `RecordingFileID` is an ordinary column, so it could point at any file (another
603
+ * session's recording, or a legacy browser upload such as `recording.webm` whose `MJ: Files` row would
604
+ * keep the old content type). Anything else gets a new WAV upload, and the finish re-points the session.
605
+ */
606
+ async function resolveStorageTarget(session, input) {
607
+ const { ContextUser, Provider } = input;
608
+ if (session.RecordingFileID) {
609
+ const file = await Provider.GetEntityObject('MJ: Files', ContextUser);
610
+ if (!await file.Load(session.RecordingFileID) || !file.ProviderKey) {
611
+ throw new Error(`could not load recording file ${session.RecordingFileID} of session ${session.ID}`);
612
+ }
613
+ // Some drivers store keys with a leading '/', so compare without it.
614
+ if (file.ProviderKey.replace(/^\/+/, '') === `${RecordingFolder(session.ID)}/recording.wav`) {
615
+ const accountID = await ResolveStorageAccountIDForProvider(file.ProviderID, ContextUser, Provider);
616
+ if (!accountID) {
617
+ throw new RecordingAssemblyError(`no storage account for provider ${file.ProviderID} of recording file ${file.ID}`);
618
+ }
619
+ return { AccountID: accountID, ExistingFile: { ID: file.ID, ProviderKey: file.ProviderKey } };
620
+ }
621
+ LogStatus(`AssembleRealtimeRecordingFromLedger: session ${session.ID} points at recording ${file.ID} (${file.ProviderKey}), not its own recording.wav; uploading a new WAV instead of overwriting it`);
622
+ }
623
+ const agent = await Provider.GetEntityObject('MJ: AI Agents', ContextUser);
624
+ if (!await agent.Load(session.AgentID)) {
625
+ throw new RecordingAssemblyError(`could not load agent ${session.AgentID} of session ${session.ID}`);
626
+ }
627
+ const accountID = await ResolveRecordingStorageAccountID(agent, ContextUser, Provider);
628
+ if (!accountID) {
629
+ throw new RecordingAssemblyError(`agent ${session.AgentID} has no recording storage account configured`);
630
+ }
631
+ return { AccountID: accountID, ExistingFile: null };
632
+ }
633
+ async function storeWav(target, wav, input) {
634
+ const { SessionID, ContextUser, Provider } = input;
635
+ if (target.ExistingFile) {
636
+ const driver = await FileStorageEngine.Instance.GetDriver(target.AccountID, ContextUser);
637
+ if (!await driver.PutObject(target.ExistingFile.ProviderKey, wav, 'audio/wav')) {
638
+ throw new Error(`overwriting recording file ${target.ExistingFile.ID} (${target.ExistingFile.ProviderKey}) returned false`);
639
+ }
640
+ return { FileID: target.ExistingFile.ID, Uploaded: false };
641
+ }
642
+ const uploaded = await FileStorageEngine.Instance.UploadFile({
643
+ content: wav, fileName: 'recording.wav', mimeType: 'audio/wav', contextUser: ContextUser,
644
+ storageAccountId: target.AccountID, provider: Provider, pathPrefix: RecordingFolder(SessionID),
645
+ });
646
+ return { FileID: uploaded.FileID, Uploaded: true };
647
+ }
648
+ /** A lost fence after storage was written: say exactly what was left behind. */
649
+ function logSupersededWrite(sessionID, version, stored) {
650
+ if (stored.Uploaded) {
651
+ // The finish proc is the only thing that stamps RecordingFileID, so no later assembler knows this
652
+ // row exists. Its object key is the session's recording.wav, which the newer assembler writes too.
653
+ LogStatus(`AssembleRealtimeRecordingFromLedger: session ${sessionID} version ${version} was superseded after uploading; ` +
654
+ `MJ: Files row ${stored.FileID} is an orphan (not stamped, not linked). Its object is the session's recording.wav, ` +
655
+ `shared with the newer assembly, so delete only the row, never the object`);
656
+ return;
657
+ }
658
+ LogStatus(`AssembleRealtimeRecordingFromLedger: session ${sessionID} version ${version} was superseded after overwriting ` +
659
+ `recording file ${stored.FileID}; the newer assembly rewrites it`);
660
+ }
661
+ /** Parses each ledger row; a row that fails to parse or disagrees with its own header is logged and left out (a gap). */
662
+ function parseLedgerShards(sessionID, rows) {
663
+ const shards = [];
664
+ for (const row of rows) {
665
+ let parsed;
666
+ try {
667
+ parsed = ParseRecordingShard(row.Data);
668
+ }
669
+ catch (error) {
670
+ if (!(error instanceof RecordingShardFormatError)) {
671
+ throw error;
672
+ }
673
+ LogError(`AssembleRealtimeRecordingFromLedger (session ${sessionID}): shard ${row.Index} is not valid MJOPUS1 (${error.message}); treated as missing`);
674
+ continue;
675
+ }
676
+ if (parsed.ShardIndex !== row.Index || parsed.StartSample !== row.StartSample || parsed.SampleCount !== row.SampleCount) {
677
+ LogError(`AssembleRealtimeRecordingFromLedger (session ${sessionID}): shard ${row.Index} header (index ${parsed.ShardIndex}, ` +
678
+ `start ${parsed.StartSample}, samples ${parsed.SampleCount}) disagrees with its ledger row ` +
679
+ `(start ${row.StartSample}, samples ${row.SampleCount}); treated as missing`);
680
+ continue;
681
+ }
682
+ shards.push(parsed);
683
+ }
684
+ return shards;
685
+ }
686
+ /** The recording is already Complete; a failed cleanup is logged and left for the janitor's purge. */
687
+ async function deleteAssembledShards(ledger, sessionID, expected) {
688
+ try {
689
+ await ledger.DeleteShardsBelow(sessionID, expected);
690
+ }
691
+ catch (error) {
692
+ LogError(`AssembleRealtimeRecordingFromLedger (session ${sessionID}): recording is Complete but deleting its ${expected} shard rows failed; the janitor purge will remove them: ${error instanceof Error ? error.message : String(error)}`);
693
+ }
694
+ }
695
+ async function finishAsFailed(input) {
696
+ const { SessionID, Version, Ledger } = input;
697
+ try {
698
+ if (!await Ledger.FinishAssembly({ SessionID, Version, Status: 'Failed', Gaps: [], FileID: null })) {
699
+ LogStatus(`AssembleRealtimeRecordingFromLedger: session ${SessionID} version ${Version} failed but was already superseded; left to the newer assembly`);
700
+ }
701
+ }
702
+ catch (error) {
703
+ LogError(`AssembleRealtimeRecordingFromLedger: could not mark session ${SessionID} version ${Version} Failed: ${error instanceof Error ? error.message : String(error)}`);
704
+ }
705
+ }
706
+ //# sourceMappingURL=realtime-recording-opus-assembly.js.map