@fabric-harness/sdk 6.10.1 → 6.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/events.d.ts CHANGED
@@ -45,6 +45,11 @@ export interface AgentEventBase {
45
45
  /** Task id when the event came from `session.task()`. */
46
46
  taskId?: string;
47
47
  }
48
+ interface PromptEventData {
49
+ text?: string;
50
+ metadata?: JsonObject;
51
+ promptRunId?: string;
52
+ }
48
53
  export type AgentEvent = (AgentEventBase & {
49
54
  type: "agent_start";
50
55
  data?: JsonObject;
@@ -55,14 +60,19 @@ export type AgentEvent = (AgentEventBase & {
55
60
  };
56
61
  }) | (AgentEventBase & {
57
62
  type: "prompt_start";
58
- data?: {
59
- text?: string;
63
+ data?: PromptEventData & {
64
+ role?: string;
60
65
  };
61
66
  }) | (AgentEventBase & {
62
67
  type: "prompt_end";
63
- data?: {
64
- text?: string;
68
+ data?: PromptEventData & {
65
69
  result?: unknown;
70
+ terminatedByTool?: boolean;
71
+ };
72
+ }) | (AgentEventBase & {
73
+ type: "prompt_error";
74
+ data: PromptEventData & {
75
+ error: string;
66
76
  };
67
77
  }) | (AgentEventBase & {
68
78
  type: "turn_start";
@@ -279,6 +289,7 @@ export type AgentEvent = (AgentEventBase & {
279
289
  data: {
280
290
  error: string;
281
291
  cause?: unknown;
292
+ cancelled?: boolean;
282
293
  };
283
294
  });
284
295
  export type AgentEventType = AgentEvent["type"];
@@ -301,4 +312,5 @@ export type AgentEventCallback = (event: AgentEvent) => void | Promise<void>;
301
312
  export declare function isEvent<T extends AgentEventType>(event: AgentEvent, type: T): event is Extract<AgentEvent, {
302
313
  type: T;
303
314
  }>;
315
+ export {};
304
316
  //# sourceMappingURL=events.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEH,OAAO,KAAK,EAAE,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MAAM,kBAAkB,GAAG,CAAC,KAAK,EAAE,UAAU,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AAE7E;;;;;;;;;;GAUG;AACH,wBAAgB,OAAO,CAAC,CAAC,SAAS,cAAc,EAC9C,KAAK,EAAE,UAAU,EACjB,IAAI,EAAE,CAAC,GACN,KAAK,IAAI,OAAO,CAAC,UAAU,EAAE;IAAE,IAAI,EAAE,CAAC,CAAA;CAAE,CAAC,CAE3C"}
@@ -1 +1 @@
1
- {"version":3,"file":"events.js","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAuKH;;;;;;;;;;GAUG;AACH,MAAM,UAAU,OAAO,CACrB,KAAiB,EACjB,IAAO;IAEP,OAAO,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC;AAC7B,CAAC"}
1
+ {"version":3,"file":"events.js","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAoLH;;;;;;;;;;GAUG;AACH,MAAM,UAAU,OAAO,CACrB,KAAiB,EACjB,IAAO;IAEP,OAAO,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC;AAC7B,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"governed-voice.d.ts","sourceRoot":"","sources":["../src/governed-voice.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAGlD,OAAO,KAAK,EAAE,QAAQ,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACpE,OAAO,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE3D,OAAO,KAAK,EAAE,mBAAmB,EAAc,aAAa,EAAE,YAAY,EAAqB,MAAM,YAAY,CAAC;AAElH,MAAM,WAAW,oBAAoB;IACnC,QAAQ,EAAE,aAAa,CAAC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,gBAAgB,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAC7D,wGAAwG;IACxG,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACvD;AAED,mFAAmF;AACnF,MAAM,WAAW,oBAAqB,SAAQ,YAAY;IAAG,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAA;CAAE;AAEtF,MAAM,WAAW,oBAAoB;IACnC,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,YAAY,CAAC;IACpB,OAAO,EAAE,CAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,MAAM,EAAE,WAAW,KAAK,OAAO,CAAC,cAAc,CAAC,CAAC;CAC7F;AAED,oEAAoE;AACpE,wBAAsB,iBAAiB,CAAC,OAAO,EAAE,oBAAoB,EAAE,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAsanI"}
@@ -1,6 +1,6 @@
1
1
  import { abandonToolOnAbort } from './abort.js';
2
2
  import { isProposalTool } from './proposal-tool.js';
3
- import { captureVoiceCancel, holdVoiceContinuations } from './voice.js';
3
+ import { captureVoiceCancel, failedVoiceResponses, holdVoiceContinuations } from './voice.js';
4
4
  /** Internal session adapter. Public callers use session.voice(). */
5
5
  export async function openGovernedVoice(options, runtime) {
6
6
  for (const value of [options.limits.durationMs, options.limits.maxTurns, options.limits.maxToolCalls]) {
@@ -46,6 +46,8 @@ export async function openGovernedVoice(options, runtime) {
46
46
  const onCallerAbort = () => { abort.abort(callerSignal?.reason); void close(); };
47
47
  let voice;
48
48
  let closed = false;
49
+ let requestFailed = false;
50
+ let replySettlement;
49
51
  let turns = 0;
50
52
  let calls = 0;
51
53
  let consumed = false;
@@ -63,12 +65,9 @@ export async function openGovernedVoice(options, runtime) {
63
65
  let responseOpen = false;
64
66
  /** Audio was admitted since the events loop last pulled a provider event. */
65
67
  let audioSincePull = false;
66
- /** The journal's latest input marker is `input_open` (not closed by `usage`). */
67
- let journalOpen = false;
68
- let markerWrite;
69
- /** Settles once the pending `usage` entry is durable; input markers are written after it. */
70
- let usageWrite = Promise.resolve();
71
- let pendingUsage;
68
+ // Input can reach the provider only with an audited, durable marker.
69
+ // A pending marker write or reply settlement owns admission until it resolves.
70
+ let inputAdmission = 'unmarked';
72
71
  let timer;
73
72
  const bounded = (work) => abandonToolOnAbort(work, signal);
74
73
  const close = async () => {
@@ -78,6 +77,8 @@ export async function openGovernedVoice(options, runtime) {
78
77
  callerSignal?.removeEventListener('abort', onCallerAbort);
79
78
  clearTimeout(timer);
80
79
  abort.abort();
80
+ if (typeof inputAdmission === 'object' && 'wake' in inputAdmission)
81
+ inputAdmission.wake();
81
82
  const current = voice;
82
83
  if (current)
83
84
  await abandonToolOnAbort(() => current.close(), AbortSignal.timeout(2000)).catch(() => { });
@@ -95,27 +96,36 @@ export async function openGovernedVoice(options, runtime) {
95
96
  if (current?.data?.owner !== owner)
96
97
  throw new Error('Voice connection ownership changed');
97
98
  };
98
- const append = async (data, id = crypto.randomUUID(), claim = false) => {
99
+ const journalBinding = { sessionId: runtime.sessionId, resourceId: options.resourceId, callId: options.callId };
100
+ const append = async (data, { id = crypto.randomUUID(), claim = false, pendingInput } = {}) => {
99
101
  for (let attempt = 0; attempt < 8; attempt++) {
100
102
  const current = await load();
101
103
  signal.throwIfAborted();
102
104
  if (!claim && current?.entries?.filter(entry => entry.data?.kind === 'owner').at(-1)?.data?.owner !== owner)
103
105
  throw new Error('Voice connection ownership changed');
104
- const timestamp = new Date().toISOString();
105
- if (await bounded(() => appendEntries(journalId, [{
106
- id, type: 'activity_result', timestamp,
107
- ...(current?.leafId ? { parentId: current.leafId } : {}),
108
- tenantId: runtime.tenantId,
109
- data: { ...data, sessionId: runtime.sessionId, resourceId: options.resourceId, callId: options.callId, owner },
110
- }], { expectedLeafId: current?.leafId })))
106
+ const entry = {
107
+ id, type: 'activity_result', timestamp: new Date().toISOString(),
108
+ ...(current?.leafId ? { parentId: current.leafId } : {}),
109
+ tenantId: runtime.tenantId,
110
+ data: { ...data, ...journalBinding, owner },
111
+ };
112
+ // A reply can settle only part of the admitted input. Keep the next
113
+ // input marker durable in the same transaction as that reply's usage.
114
+ const entries = pendingInput
115
+ ? [entry, { ...entry, id: crypto.randomUUID(), parentId: id, data: { ...pendingInput, ...journalBinding, owner } }]
116
+ : [entry];
117
+ if (await bounded(() => appendEntries(journalId, entries, { expectedLeafId: current?.leafId })))
111
118
  return;
112
119
  }
113
120
  throw new Error('Voice journal contention');
114
121
  };
122
+ const deliverAudit = (event) => bounded(async () => options.onAudit?.({
123
+ tenantId: runtime.tenantId, actorId: runtime.actorId, ...event, ...journalBinding,
124
+ }));
115
125
  const audit = async (kind, details = {}) => {
116
126
  const event = { kind, tenantId: runtime.tenantId, actorId: runtime.actorId, ...details };
117
127
  await append(event);
118
- await bounded(async () => options.onAudit?.({ ...event, sessionId: runtime.sessionId, resourceId: options.resourceId, callId: options.callId }));
128
+ await deliverAudit(event);
119
129
  };
120
130
  // Idempotent, durable ledgers share the session store. Replaying journal usage
121
131
  // repairs a crash between the journal commit and either ledger commit.
@@ -131,21 +141,29 @@ export async function openGovernedVoice(options, runtime) {
131
141
  for (let attempt = 0; attempt < 8; attempt++) {
132
142
  signal.throwIfAborted();
133
143
  const data = await bounded(() => runtime.store.load(id));
134
- const entries = data?.entries ?? [];
135
- const total = entries.reduce((sum, entry) => sum + (typeof entry.data?.costUsd === 'number' ? entry.data.costUsd : 0), 0);
136
- const exists = !observation || entries.some(entry => entry.id === observation.id);
137
- exceeded ||= total + (exists ? 0 : observation?.costUsd ?? 0) >= ledger.limit;
138
- if (exists || !observation) {
139
- committed = true;
140
- break;
141
- }
142
- if (await bounded(() => appendEntries(id, [{ id: observation.id, type: 'activity_result', timestamp: new Date().toISOString(),
143
- ...(data?.leafId ? { parentId: data.leafId } : {}), tenantId: runtime.tenantId,
144
- data: { kind: 'voice_cost', costUsd: observation.costUsd },
145
- }], { expectedLeafId: data?.leafId }))) {
146
- committed = true;
147
- break;
144
+ let entries = data?.entries ?? [];
145
+ let added = 0;
146
+ if (observation && !entries.some(entry => entry.id === observation.id)) {
147
+ try {
148
+ if (!(await bounded(() => appendEntries(id, [{ id: observation.id, type: 'activity_result', timestamp: new Date().toISOString(),
149
+ ...(data?.leafId ? { parentId: data.leafId } : {}), tenantId: runtime.tenantId,
150
+ data: { kind: 'voice_cost', costUsd: observation.costUsd },
151
+ }], { expectedLeafId: data?.leafId }))))
152
+ continue;
153
+ added = observation.costUsd;
154
+ }
155
+ catch (error) {
156
+ // A concurrent repair can commit this observation under a different
157
+ // leaf or timestamp. Accept it only after confirming the charge.
158
+ entries = (await bounded(() => runtime.store.load(id)))?.entries ?? [];
159
+ if (!entries.some(entry => entry.id === observation.id && entry.data?.kind === 'voice_cost' && entry.data.costUsd === observation.costUsd))
160
+ throw error;
161
+ }
148
162
  }
163
+ const total = entries.reduce((sum, entry) => sum + (typeof entry.data?.costUsd === 'number' ? entry.data.costUsd : 0), added);
164
+ exceeded ||= total >= ledger.limit;
165
+ committed = true;
166
+ break;
149
167
  }
150
168
  if (!committed)
151
169
  throw new Error('Voice cost ledger unavailable');
@@ -155,13 +173,18 @@ export async function openGovernedVoice(options, runtime) {
155
173
  try {
156
174
  if (!(await bounded(async () => options.authorize({ kind: 'connect' }))))
157
175
  throw new Error('Voice admission denied');
158
- await append({ kind: 'owner' }, owner, true);
176
+ await append({ kind: 'owner' }, { id: owner, claim: true });
159
177
  const prior = await load();
160
- if (prior?.entries?.filter(entry => entry.data?.kind === 'input_open' || entry.data?.kind === 'usage').at(-1)?.data?.kind === 'input_open')
161
- throw new Error('Interrupted voice usage requires application reconciliation');
162
178
  const first = prior?.entries?.find(entry => entry.data?.kind === 'owner');
163
179
  if (!first || !Number.isFinite(Date.parse(first.timestamp)))
164
180
  throw new Error('Voice journal timestamp invalid');
181
+ let exceeded = false;
182
+ for (const entry of prior?.entries ?? []) {
183
+ if (entry.data?.kind === 'usage' && typeof entry.data.costUsd === 'number')
184
+ exceeded = (await account({ id: entry.id, costUsd: entry.data.costUsd })) || exceeded;
185
+ }
186
+ if (prior?.entries?.filter(entry => entry.data?.kind === 'input_open' || entry.data?.kind === 'usage').at(-1)?.data?.kind === 'input_open')
187
+ throw new Error('Interrupted voice usage requires application reconciliation');
165
188
  const remaining = options.limits.durationMs - (Date.now() - Date.parse(first.timestamp));
166
189
  if (remaining <= 0)
167
190
  throw new Error('Voice duration limit reached');
@@ -169,11 +192,6 @@ export async function openGovernedVoice(options, runtime) {
169
192
  timer = setTimeout(() => { void close(); }, remaining);
170
193
  turns = prior?.entries?.filter(entry => entry.data?.kind === 'usage').length ?? 0;
171
194
  calls = prior?.entries?.filter(entry => entry.data?.kind === 'tool_started').length ?? 0;
172
- let exceeded = false;
173
- for (const entry of prior?.entries ?? []) {
174
- if (entry.data?.kind === 'usage' && typeof entry.data.costUsd === 'number')
175
- exceeded = (await account({ id: entry.id, costUsd: entry.data.costUsd })) || exceeded;
176
- }
177
195
  if (exceeded || await account() || turns >= options.limits.maxTurns || prior?.entries?.some(entry => entry.data?.kind === 'cost_unknown'))
178
196
  throw new Error('Voice budget exhausted or requires reconciliation');
179
197
  await audit('connected');
@@ -221,26 +239,60 @@ export async function openGovernedVoice(options, runtime) {
221
239
  mediaCheck = check('input').then(() => { mediaValidUntil = Date.now() + 1000; }).finally(() => { mediaCheck = undefined; });
222
240
  await mediaCheck;
223
241
  };
224
- const ensureInputMarker = async () => {
225
- while (!journalOpen) {
226
- if (!markerWrite) {
227
- const write = usageWrite.then(() => audit('input_open')).then(() => { journalOpen = true; });
228
- markerWrite = write;
229
- void write.catch(() => { }).finally(() => { if (markerWrite === write)
230
- markerWrite = undefined; });
231
- }
232
- await markerWrite;
242
+ const assertRequestOpen = () => {
243
+ signal.throwIfAborted();
244
+ if (requestFailed)
245
+ throw new Error('Voice session closing');
246
+ };
247
+ const runRequest = async (request) => {
248
+ try {
249
+ assertRequestOpen();
250
+ await request();
251
+ }
252
+ catch (error) {
253
+ requestFailed = true;
254
+ const settlement = replySettlement;
255
+ // A rejected request can also make its transport close. Wait for the
256
+ // reply already being settled before closing or exposing the rejection.
257
+ if (settlement)
258
+ await bounded(() => settlement).catch(() => { });
259
+ await close();
260
+ throw error;
233
261
  }
234
262
  };
235
- const markInput = async (kind) => {
236
- await ensureInputMarker();
237
- if (kind === 'audio') {
238
- audioSincePull = true;
239
- const last = segments.at(-1);
240
- if (last?.kind === 'audio' && !last.sealed)
241
- return;
263
+ const inputOpen = { kind: 'input_open', tenantId: runtime.tenantId, actorId: runtime.actorId };
264
+ const sendInput = async (kind, send) => {
265
+ while (true) {
266
+ assertRequestOpen();
267
+ if (inputAdmission === 'open') {
268
+ return bounded(() => {
269
+ if (kind === 'audio')
270
+ audioSincePull = true;
271
+ const last = segments.at(-1);
272
+ if (kind !== 'audio' || last?.kind !== 'audio' || last.sealed)
273
+ segments.push({ kind, sealed: false });
274
+ return send();
275
+ });
276
+ }
277
+ if (inputAdmission === 'unmarked') {
278
+ const committed = append(inputOpen);
279
+ const marker = { committed, ready: committed.then(() => deliverAudit(inputOpen)).then(() => {
280
+ // A reply may have started settlement while the marker was in flight.
281
+ if (inputAdmission === marker)
282
+ inputAdmission = 'open';
283
+ }) };
284
+ inputAdmission = marker;
285
+ }
286
+ const admission = inputAdmission;
287
+ try {
288
+ await admission.ready;
289
+ }
290
+ catch (error) {
291
+ // A reply settling this marker owns shutdown so its charge can finish.
292
+ if (inputAdmission === admission)
293
+ throw error;
294
+ }
242
295
  }
243
- segments.push({ kind, sealed: false });
244
296
  };
245
297
  /** Response boundary: everything admitted so far may be what this response answers. */
246
298
  const openResponse = () => {
@@ -265,56 +317,37 @@ export async function openGovernedVoice(options, runtime) {
265
317
  const last = segments.at(-1);
266
318
  if (audioWindow && !(last?.kind === 'audio' && !last.sealed))
267
319
  segments.push({ kind: 'audio', sealed: false });
268
- // The usage entry about to be appended closes the journal marker.
269
- journalOpen = false;
270
320
  };
271
321
  return {
272
322
  governed: true,
273
- async sendAudio(frame) {
274
- try {
275
- if (frame.byteLength > (options.limits.maxAudioFrameBytes ?? 64 * 1024))
276
- throw new Error('Voice frame too large');
277
- await checkMedia();
278
- await markInput('audio');
279
- await bounded(() => upstream.sendAudio(frame));
280
- }
281
- catch (error) {
282
- await close();
283
- throw error;
284
- }
285
- },
286
- async sendText(text) { try {
323
+ sendAudio: frame => runRequest(async () => {
324
+ if (frame.byteLength > (options.limits.maxAudioFrameBytes ?? 64 * 1024))
325
+ throw new Error('Voice frame too large');
326
+ await checkMedia();
327
+ await sendInput('audio', () => upstream.sendAudio(frame));
328
+ }),
329
+ sendText: text => runRequest(async () => {
287
330
  await check('input');
288
331
  if (text.length > 16_384)
289
332
  throw new Error('Voice text too large');
290
- await markInput('text');
291
- await bounded(() => upstream.sendText(text));
292
- }
293
- catch (error) {
294
- await close();
295
- throw error;
296
- } },
333
+ await sendInput('text', () => upstream.sendText(text));
334
+ }),
297
335
  async submitToolResult() { throw new Error('Governed voice tool results are server-owned'); },
298
- async cancelResponse(cancel) {
336
+ cancelResponse: cancel => runRequest(async () => {
299
337
  // Bind the cancel before the asynchronous authorization below, by which
300
338
  // time a newer reply may be playing: to the reply the interruption
301
339
  // stamped at provider receipt (the event is yielded unchanged, so the
302
340
  // stamp survives), otherwise to the reply playing now.
303
341
  const interruption = cancel?.interruption;
304
342
  const cancelCaptured = captureVoiceCancel(upstream, interruption ? { interruption } : undefined);
305
- try {
306
- const playedMs = cancel?.playedMs;
307
- if (playedMs !== undefined && (!Number.isSafeInteger(playedMs) || playedMs < 0))
308
- throw new Error('Invalid voice playback position');
309
- await check('input');
310
- const forwarded = { ...(playedMs === undefined ? {} : { playedMs }), ...(interruption ? { interruption } : {}) };
311
- await bounded(() => cancelCaptured(Object.keys(forwarded).length > 0 ? forwarded : undefined));
312
- }
313
- catch (error) {
314
- await close();
315
- throw error;
316
- }
317
- },
343
+ const playedMs = cancel?.playedMs;
344
+ if (playedMs !== undefined && (!Number.isSafeInteger(playedMs) || playedMs < 0))
345
+ throw new Error('Invalid voice playback position');
346
+ await check('input');
347
+ const forwarded = { ...(playedMs === undefined ? {} : { playedMs }), ...(interruption ? { interruption } : {}) };
348
+ assertRequestOpen();
349
+ await bounded(() => cancelCaptured(Object.keys(forwarded).length > 0 ? forwarded : undefined));
350
+ }),
318
351
  close,
319
352
  events() {
320
353
  if (consumed)
@@ -322,6 +355,7 @@ export async function openGovernedVoice(options, runtime) {
322
355
  consumed = true;
323
356
  return {
324
357
  async *[Symbol.asyncIterator]() {
358
+ let closingAfterError;
325
359
  try {
326
360
  const iterator = upstream.events()[Symbol.asyncIterator]();
327
361
  while (true) {
@@ -329,15 +363,69 @@ export async function openGovernedVoice(options, runtime) {
329
363
  if (next.done)
330
364
  break;
331
365
  const event = next.value;
366
+ if (event.type === 'error')
367
+ throw new Error('Voice provider failed');
332
368
  const audioWindow = audioSincePull;
333
369
  audioSincePull = false;
334
- let usageWritten;
335
370
  if (event.type === 'audio_delta' || event.type === 'text_delta' || event.type === 'transcript' || event.type === 'tool_call')
336
371
  openResponse();
337
372
  if (event.type === 'response_done') {
338
- settleInput(audioWindow);
339
- usageWrite = new Promise(resolve => { usageWritten = resolve; });
340
- pendingUsage = usageWritten;
373
+ let finishSettlement;
374
+ replySettlement = new Promise(resolve => { finishSettlement = resolve; });
375
+ try {
376
+ const priorMarker = typeof inputAdmission === 'object' && 'committed' in inputAdmission ? inputAdmission : undefined;
377
+ let wake;
378
+ const ready = new Promise(resolve => { wake = resolve; });
379
+ inputAdmission = { ready, wake };
380
+ settleInput(audioWindow);
381
+ // Order the journal writes without delaying accounting on an external audit.
382
+ if (priorMarker)
383
+ await priorMarker.committed;
384
+ turns++;
385
+ const cost = event.usage?.costUsd;
386
+ if (cost === undefined || !Number.isFinite(cost) || cost < 0) {
387
+ await audit('cost_unknown');
388
+ throw new Error('Voice cost is unknown');
389
+ }
390
+ const observation = { id: crypto.randomUUID(), costUsd: cost };
391
+ const failed = failedVoiceResponses.has(event);
392
+ const pendingInput = segments.length > 0 ? inputOpen : undefined;
393
+ await append({ kind: 'usage', costUsd: cost, turn: turns }, { id: observation.id, ...(pendingInput ? { pendingInput } : {}) });
394
+ const auditInput = async () => {
395
+ if (priorMarker)
396
+ await priorMarker.ready;
397
+ if (pendingInput)
398
+ await deliverAudit(pendingInput);
399
+ if (failed)
400
+ return; // Close aborts and wakes these senders.
401
+ inputAdmission = pendingInput ? 'open' : 'unmarked';
402
+ wake();
403
+ };
404
+ // A healthy reply releases input as soon as the journal and
405
+ // marker audit are ready. Await the charge even if that audit fails.
406
+ const [charge, input] = await Promise.allSettled([account(observation), auditInput()]);
407
+ if (charge.status === 'rejected')
408
+ throw charge.reason;
409
+ if (input.status === 'rejected')
410
+ throw input.reason;
411
+ await deliverAudit({ kind: 'usage', costUsd: cost, turn: turns });
412
+ if (charge.value)
413
+ throw new Error('Voice cost limit reached');
414
+ if (failed)
415
+ throw new Error('Voice provider failed');
416
+ assertRequestOpen();
417
+ }
418
+ finally {
419
+ replySettlement = undefined;
420
+ finishSettlement();
421
+ }
422
+ if (turns >= options.limits.maxTurns) {
423
+ yield event;
424
+ break;
425
+ }
426
+ settleContinuation?.();
427
+ yield event;
428
+ continue;
341
429
  }
342
430
  if (event.type === 'text_delta') {
343
431
  signal.throwIfAborted();
@@ -412,32 +500,6 @@ export async function openGovernedVoice(options, runtime) {
412
500
  break;
413
501
  continue;
414
502
  }
415
- if (event.type === 'response_done') {
416
- turns++;
417
- const cost = event.usage?.costUsd;
418
- if (cost === undefined || !Number.isFinite(cost) || cost < 0) {
419
- await audit('cost_unknown');
420
- throw new Error('Voice cost is unknown');
421
- }
422
- const observation = { id: crypto.randomUUID(), costUsd: cost };
423
- await append({ kind: 'usage', costUsd: cost, turn: turns }, observation.id);
424
- usageWritten?.();
425
- pendingUsage = undefined;
426
- // Input admitted after the settled segment remains outstanding.
427
- if (segments.length > 0)
428
- await ensureInputMarker();
429
- const exceeded = await account(observation);
430
- await bounded(async () => options.onAudit?.({ kind: 'usage', costUsd: cost, turn: turns, sessionId: runtime.sessionId, tenantId: runtime.tenantId, actorId: runtime.actorId, resourceId: options.resourceId, callId: options.callId }));
431
- if (exceeded)
432
- throw new Error('Voice cost limit reached');
433
- if (turns >= options.limits.maxTurns) {
434
- yield event;
435
- break;
436
- }
437
- settleContinuation?.();
438
- }
439
- if (event.type === 'error')
440
- throw new Error('Voice provider failed');
441
503
  if (event.type === 'transcript')
442
504
  yield { ...event, text: await bounded(async () => options.redactTranscript(event.text)) };
443
505
  else
@@ -446,12 +508,12 @@ export async function openGovernedVoice(options, runtime) {
446
508
  }
447
509
  }
448
510
  catch {
511
+ // Stop the provider even if the consumer pauses on the terminal event.
512
+ closingAfterError = close();
449
513
  yield { type: 'error', message: 'Governed voice stopped; consult server audit and reconcile pending actions' };
450
514
  }
451
515
  finally {
452
- // Release input admissions waiting on a usage entry that will never be written.
453
- pendingUsage?.();
454
- await close();
516
+ await (closingAfterError ?? close());
455
517
  }
456
518
  },
457
519
  };