@theoremjs/agents 0.3.4-next.793.g1b414fe → 0.3.4-next.797.gfda34c9

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.
@@ -37,6 +37,7 @@ export interface LiveOutboundGateSession {
37
37
  export type LiveOutboundBatchResult = {
38
38
  action: 'emit';
39
39
  events: TurnEvent[];
40
+ refused?: true;
40
41
  } | {
41
42
  action: 'withhold';
42
43
  error: TheoremError;
@@ -240,7 +240,7 @@ function finalEgressVerdict(session, gate, prior) {
240
240
  // why: Live never rewrites: audio already spoken cannot be taken back for another try.
241
241
  if (blockedReply.onBlock === 'refuse') {
242
242
  const text = refusalAfter(shown, session.context.labels);
243
- return { action: 'emit', events: [...events, { type: 'text', text }] };
243
+ return { action: 'emit', events: [...events, { type: 'text', text }], refused: true };
244
244
  }
245
245
  return {
246
246
  action: 'withhold',
@@ -435,6 +435,9 @@ held) {
435
435
  return 'pass';
436
436
  if (!answersByTool(flow.currentGen))
437
437
  return 'pass';
438
+ // why: A rewrite that gives no answer leaves the reply it was fixing; the validation gate removes the refused items.
439
+ if (flow.pendingItemFix)
440
+ return 'pass';
438
441
  const validation = profileTurnOutputs(profile)?.validation;
439
442
  if (validation && flow.currentAttempt < (validation.maxRetries ?? 0)) {
440
443
  const rejection = labelText('structured.answer_missing', { tool: ANSWER_TOOL }, profile.labels);
@@ -193,7 +193,25 @@ async function applyOutbound(gate, events, turnPhase, onWithhold) {
193
193
  ...said,
194
194
  ...(finalized.action === 'emit' ? finalized.events : []),
195
195
  ...out.filter(isTurnComplete),
196
- ...out.filter((event) => event.type === 'done'),
196
+ ...(finalized.action === 'emit' && finalized.refused ? refusedDones(out) : doneEvents(out)),
197
+ ];
198
+ }
199
+ function doneEvents(events) {
200
+ return events.filter((event) => event.type === 'done');
201
+ }
202
+ /** A refused reply ends `filtered`, as a text turn does; `generation_complete` stays news. */
203
+ function refusedDones(events) {
204
+ const dones = doneEvents(events);
205
+ const ending = dones.find((event) => !isGenerationDone(event));
206
+ return [
207
+ ...dones.filter(isGenerationDone),
208
+ {
209
+ ...(ending?.type === 'done' && ending.providerState
210
+ ? { providerState: ending.providerState }
211
+ : {}),
212
+ type: 'done',
213
+ stop: EGRESS_FILTERED_STOP,
214
+ },
197
215
  ];
198
216
  }
199
217
  function isTurnComplete(event) {
@@ -351,8 +369,10 @@ function buildLiveSession(args) {
351
369
  },
352
370
  };
353
371
  let cycle = 'idle';
354
- /** How the reply stands: an interrupt before `generation_complete` cuts it off. */
355
- let reply = 'open';
372
+ /** An interrupt ended the reply; its `turnComplete` is still to come. */
373
+ let cutOff = false;
374
+ /** Input landed while this cycle was already open: if an interrupt ends it, that input opens the next. */
375
+ let ingressInCycle = false;
356
376
  let cycleStep = 0;
357
377
  /** What this cycle's tool results read from outside the host; a cycle starts clean, as a turn does. */
358
378
  let cycleTaint;
@@ -616,9 +636,12 @@ function buildLiveSession(args) {
616
636
  await runCycleStage('post_turn', { stop });
617
637
  };
618
638
  const openCycleIfNeeded = async () => {
619
- if (cycle === 'open')
639
+ if (cycle === 'open') {
640
+ ingressInCycle = true;
620
641
  return { aborted: false };
642
+ }
621
643
  cycle = 'open';
644
+ ingressInCycle = false;
622
645
  cycleStep += 1;
623
646
  cycleTaint = undefined;
624
647
  destinations.remote.clear();
@@ -877,15 +900,12 @@ function buildLiveSession(args) {
877
900
  // why: An abort only drops what the gate held; there is no check to time.
878
901
  if (item.turnPhase !== 'abort')
879
902
  trace.outboundTime(performance.now() - gateStart);
880
- if (hostEvents.some(isGenerationDone))
881
- reply = 'generated';
882
903
  // why: A close after a cut-off reply is not a finish, and the next cycle may already be open.
883
- const closesCutOff = item.turnPhase === 'complete' && reply === 'cut_off';
904
+ const closesCutOff = item.turnPhase === 'complete' && cutOff;
884
905
  if (item.turnPhase === 'complete')
885
- reply = 'open';
906
+ cutOff = false;
886
907
  if (item.turnPhase === 'abort') {
887
- const cut = reply !== 'generated' && hostEvents.some((ev) => ev.type === 'done' && ev.interrupted);
888
- reply = cut ? 'cut_off' : 'open';
908
+ cutOff = hostEvents.some((ev) => ev.type === 'done' && ev.interrupted);
889
909
  }
890
910
  for (const ev of gated) {
891
911
  if (ev.type === 'guardrail')
@@ -915,6 +935,10 @@ function buildLiveSession(args) {
915
935
  for await (const ev of endCycleAroundDone(boundaryDone)) {
916
936
  yield projectGuardrailTurnEvent(stampDone(ev), includeMatch);
917
937
  }
938
+ // why: A barge-in reaches the model before its `interrupted` reaches us, so the reply
939
+ // to it comes with no ingress left to open the cycle it belongs to.
940
+ if (interrupted && ingressInCycle)
941
+ await withIngress(() => openCycleIfNeeded().then(() => { }));
918
942
  yield* drainPendingHostEvents(pendingHostEvents);
919
943
  }
920
944
  else {
@@ -5,7 +5,7 @@ import { defineProtocol, } from '../../kernel/protocols/mod.js';
5
5
  import { readGeminiApiError } from '../google/api-error.js';
6
6
  import { googleBuiltins } from '../google/builtins.js';
7
7
  import { buildGeminiLiveClientContent, buildGeminiLiveContext, buildGeminiLiveRealtimeInput, buildGeminiLiveSetupMessage, buildGeminiLiveToolResponse, foldGeminiLiveServerMessage, liveFrameInput, newLiveFold, } from '../google/live/framing.js';
8
- import { closeError, goAwayIn, turnPhaseFromMessage } from '../google/live/stream.js';
8
+ import { closeError, goAwayIn, isBareIdle, turnPhaseFromMessage } from '../google/live/stream.js';
9
9
  import { asProtocolEvent } from '../shared/protocol-events.js';
10
10
  const state = z.strictObject({ liveHandle: z.string().min(1) });
11
11
  const NORMAL_CLOSE = 1000;
@@ -90,6 +90,8 @@ function session(socket, frames, context, resumedFrom) {
90
90
  const send = (frame) => sendFrame(socket, frame);
91
91
  const fold = newLiveFold();
92
92
  let handle = resumedFrom;
93
+ /** The last reply's end was read, and no server content has come since. */
94
+ let ended = false;
93
95
  let goAway;
94
96
  let closed;
95
97
  return {
@@ -131,7 +133,13 @@ function session(socket, frames, context, resumedFrom) {
131
133
  for (const event of events)
132
134
  if (event.type === 'evidence' && event.sessionResumptionHandle)
133
135
  handle = event.sessionResumptionHandle;
134
- yield* batch(events, turnPhaseFromMessage(frame, events), handle);
136
+ const phase = turnPhaseFromMessage(frame, events);
137
+ // why: IDLE may come in a frame of its own after `turnComplete`; that reply already ended.
138
+ yield* batch(events, ended && isBareIdle(frame) ? 'streaming' : phase, handle);
139
+ if (phase === 'complete')
140
+ ended = true;
141
+ else if (frame.serverContent)
142
+ ended = false;
135
143
  }
136
144
  },
137
145
  sendText: (text) => settled(() => send(buildGeminiLiveRealtimeInput({ type: 'text', text }))),
@@ -10,4 +10,6 @@ export declare function goAwayIn(events: readonly ModelEvent[]): {
10
10
  * open across `turnComplete` (background reasoning or async tools may still
11
11
  * produce output). Without it, `turnComplete` is the boundary.
12
12
  */
13
+ /** A server message that says only `interactionStatus: IDLE`. */
14
+ export declare function isBareIdle(message: Record<string, unknown>): boolean;
13
15
  export declare function turnPhaseFromMessage(message: Record<string, unknown>, events: ModelEvent[]): LiveTurnPhase;
@@ -42,6 +42,11 @@ export function goAwayIn(events) {
42
42
  * open across `turnComplete` (background reasoning or async tools may still
43
43
  * produce output). Without it, `turnComplete` is the boundary.
44
44
  */
45
+ /** A server message that says only `interactionStatus: IDLE`. */
46
+ export function isBareIdle(message) {
47
+ return (readLiveInteractionStatus(message) === 'IDLE' &&
48
+ Object.keys(asRecord(message.serverContent) ?? {}).length === 1);
49
+ }
45
50
  export function turnPhaseFromMessage(message, events) {
46
51
  const interrupted = events.some((ev) => ev.type === 'done' && ev.interrupted === true);
47
52
  if (interrupted)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theoremjs/agents",
3
- "version": "0.3.4-next.793.g1b414fe",
3
+ "version": "0.3.4-next.797.gfda34c9",
4
4
  "description": "A flat TypeScript agent kernel for typed profiles, deterministic turn execution, registered tools, provider adapters, guardrails, and host-injected traces.",
5
5
  "keywords": [
6
6
  "agent",