@kenkaiiii/gg-agent 5.85.0 → 5.86.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/index.js CHANGED
@@ -15,6 +15,111 @@ import {
15
15
  sliceTail
16
16
  } from "@kenkaiiii/gg-ai";
17
17
 
18
+ // src/hedged-stream.ts
19
+ var HEDGE_FIRST_EVENT_AFTER_MS = 3e4;
20
+ var HEDGE_CACHE_WARM_MS = 4 * 6e4;
21
+ var HEDGE_MIN_CACHED_RATIO = 0.5;
22
+ var HEDGE_MIN_WINDOW_MS = 2e4;
23
+ function firstEventHedgeDelayMs(input) {
24
+ const usage = input.priorUsage;
25
+ if (!usage) return null;
26
+ const cached = (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
27
+ const prompt = usage.inputTokens + cached;
28
+ if (prompt <= 0 || cached / prompt < HEDGE_MIN_CACHED_RATIO) return null;
29
+ if (input.msSincePriorResponse < 0 || input.msSincePriorResponse > HEDGE_CACHE_WARM_MS) {
30
+ return null;
31
+ }
32
+ const delay = HEDGE_FIRST_EVENT_AFTER_MS + Math.max(0, input.newPromptTokens) / 1e3 * input.prefillMsPer1kTokens;
33
+ if (!Number.isFinite(input.firstEventTimeoutMs)) return null;
34
+ if (delay + HEDGE_MIN_WINDOW_MS > input.firstEventTimeoutMs) return null;
35
+ return delay;
36
+ }
37
+ function linkedController(parent) {
38
+ const controller = new AbortController();
39
+ if (parent.aborted) controller.abort();
40
+ else parent.addEventListener("abort", () => controller.abort(), { once: true });
41
+ return controller;
42
+ }
43
+ function startArm(name, options) {
44
+ const controller = linkedController(options.signal);
45
+ const stream2 = options.start(controller.signal, name);
46
+ stream2.response.catch(() => {
47
+ });
48
+ return { name, stream: stream2, iterator: stream2[Symbol.asyncIterator](), controller };
49
+ }
50
+ function firstOutcome(arm) {
51
+ return arm.iterator.next().then(
52
+ (first) => ({ arm, ok: true, first }),
53
+ (error) => ({ arm, ok: false, error })
54
+ );
55
+ }
56
+ function hedgedStream(options) {
57
+ if (options.hedgeAfterMs === null) {
58
+ const stream2 = options.start(options.signal, "primary");
59
+ options.onSettled?.("primary", false);
60
+ return stream2;
61
+ }
62
+ const hedgeAfterMs = options.hedgeAfterMs;
63
+ const select = async () => {
64
+ const primary = startArm("primary", options);
65
+ const primaryOutcome = firstOutcome(primary);
66
+ let timer;
67
+ const hedgeDue = new Promise((resolve) => {
68
+ timer = setTimeout(() => resolve("hedge"), hedgeAfterMs);
69
+ });
70
+ let early;
71
+ try {
72
+ early = await Promise.race([primaryOutcome, hedgeDue]);
73
+ } finally {
74
+ clearTimeout(timer);
75
+ }
76
+ if (early !== "hedge" || options.signal.aborted) {
77
+ const outcome = early === "hedge" ? await primaryOutcome : early;
78
+ if (!outcome.ok) throw outcome.error;
79
+ options.onSettled?.("primary", false);
80
+ return { arm: primary, first: outcome.first };
81
+ }
82
+ const hedge = startArm("hedge", options);
83
+ options.onHedgeStarted?.();
84
+ const hedgeOutcome = firstOutcome(hedge);
85
+ let winner = await Promise.race([primaryOutcome, hedgeOutcome]);
86
+ if (!winner.ok) {
87
+ const other = await (winner.arm === primary ? hedgeOutcome : primaryOutcome);
88
+ if (!other.ok) {
89
+ throw winner.arm === primary ? winner.error : other.error;
90
+ }
91
+ winner = other;
92
+ }
93
+ const loser = winner.arm === primary ? hedge : primary;
94
+ loser.controller.abort();
95
+ options.onSettled?.(winner.arm.name, true);
96
+ return { arm: winner.arm, first: winner.first };
97
+ };
98
+ const selection = select();
99
+ selection.catch(() => {
100
+ });
101
+ const response = selection.then((s) => s.arm.stream.response);
102
+ response.catch(() => {
103
+ });
104
+ return {
105
+ response,
106
+ async *[Symbol.asyncIterator]() {
107
+ const { arm, first } = await selection;
108
+ if (first.done) return;
109
+ try {
110
+ yield first.value;
111
+ while (true) {
112
+ const next = await arm.iterator.next();
113
+ if (next.done) return;
114
+ yield next.value;
115
+ }
116
+ } finally {
117
+ await arm.iterator.return?.();
118
+ }
119
+ }
120
+ };
121
+ }
122
+
18
123
  // src/local-backend.ts
19
124
  function isLocalBackendUrl(baseUrl) {
20
125
  if (!baseUrl) return false;
@@ -597,6 +702,7 @@ async function* agentLoop(messages, options) {
597
702
  const totalUsage = { inputTokens: 0, outputTokens: 0 };
598
703
  let latestProviderUsage;
599
704
  let usageAnchorIndex;
705
+ let latestProviderUsageAt = 0;
600
706
  let turn = 0;
601
707
  let hitMaxTurns = false;
602
708
  let firstTurn = true;
@@ -805,41 +911,76 @@ async function* agentLoop(messages, options) {
805
911
  });
806
912
  }
807
913
  }
808
- const result = stream({
809
- provider: options.provider,
810
- model: options.model,
811
- messages,
812
- tools: options.tools,
813
- serverTools: options.serverTools,
814
- toolChoice: options.toolChoice,
815
- webSearch: typeof options.webSearch === "function" ? options.webSearch() : options.webSearch,
816
- // Clamped to whatever ceiling this route has already rejected us for
817
- // (identity when nothing has been learned).
818
- maxTokens: clampOutputTokens(ceilingKey, options.maxTokens),
819
- temperature: options.temperature,
820
- thinking: options.thinking,
821
- apiKey: liveApiKey,
822
- baseUrl: options.baseUrl,
914
+ const hedgeAfterMs = baseFirstEventTimeoutMs === STREAM_FIRST_EVENT_TIMEOUT_MS && !useNonStreamingFallback ? firstEventHedgeDelayMs({
915
+ priorUsage: latestProviderUsage,
916
+ msSincePriorResponse: Date.now() - latestProviderUsageAt,
917
+ newPromptTokens: Math.ceil(
918
+ countMessageChars(
919
+ usageAnchorIndex === void 0 ? messages : messages.slice(usageAnchorIndex + 1)
920
+ ) / 3
921
+ ),
922
+ firstEventTimeoutMs,
923
+ prefillMsPer1kTokens: PREFILL_TIMEOUT_MS_PER_1K_TOKENS
924
+ }) : null;
925
+ const hedgeStartedAt = Date.now();
926
+ const requestMessages = hedgeAfterMs === null ? messages : messages.slice();
927
+ const result = hedgedStream({
823
928
  signal: streamController.signal,
824
- accountId: liveAccountId,
825
- transportSessionId: options.transportSessionId,
826
- projectId: liveProjectId,
827
- cacheRetention: options.cacheRetention,
828
- onContextPrepared: options.onContextPrepared,
829
- promptCacheKey: options.promptCacheKey,
830
- serviceTier: options.serviceTier,
831
- responsesLite: options.responsesLite,
832
- strictTools: options.strictTools,
833
- supportsImages: options.supportsImages,
834
- supportsVideo: options.supportsVideo,
835
- compaction: options.compaction,
836
- clearToolUses: options.clearToolUses,
837
- userAgent: options.userAgent,
838
- defaultHeaders: options.defaultHeaders,
839
- providerOptions: options.providerOptions,
840
- fetch: options.fetch,
841
- // Flip to non-streaming fallback after repeated stream stalls.
842
- ...useNonStreamingFallback ? { streaming: false } : {}
929
+ hedgeAfterMs,
930
+ onHedgeStarted: () => {
931
+ diag("hedge_started", {
932
+ afterMs: Date.now() - hedgeStartedAt,
933
+ provider: options.provider,
934
+ model: options.model
935
+ });
936
+ },
937
+ onSettled: (winner, hedged) => {
938
+ if (hedged) {
939
+ diag("hedge_settled", {
940
+ winner,
941
+ ttfMs: Date.now() - hedgeStartedAt,
942
+ provider: options.provider,
943
+ model: options.model
944
+ });
945
+ }
946
+ },
947
+ start: (signal, arm) => stream({
948
+ provider: options.provider,
949
+ model: options.model,
950
+ messages: requestMessages,
951
+ tools: options.tools,
952
+ serverTools: options.serverTools,
953
+ toolChoice: options.toolChoice,
954
+ webSearch: typeof options.webSearch === "function" ? options.webSearch() : options.webSearch,
955
+ // Clamped to whatever ceiling this route has already rejected us for
956
+ // (identity when nothing has been learned).
957
+ maxTokens: clampOutputTokens(ceilingKey, options.maxTokens),
958
+ temperature: options.temperature,
959
+ thinking: options.thinking,
960
+ apiKey: liveApiKey,
961
+ baseUrl: options.baseUrl,
962
+ signal,
963
+ accountId: liveAccountId,
964
+ transportSessionId: options.transportSessionId,
965
+ projectId: liveProjectId,
966
+ cacheRetention: options.cacheRetention,
967
+ // A hedge duplicates an already-observed request; observe it once.
968
+ onContextPrepared: arm === "primary" ? options.onContextPrepared : void 0,
969
+ promptCacheKey: options.promptCacheKey,
970
+ serviceTier: options.serviceTier,
971
+ responsesLite: options.responsesLite,
972
+ strictTools: options.strictTools,
973
+ supportsImages: options.supportsImages,
974
+ supportsVideo: options.supportsVideo,
975
+ compaction: options.compaction,
976
+ clearToolUses: options.clearToolUses,
977
+ userAgent: options.userAgent,
978
+ defaultHeaders: options.defaultHeaders,
979
+ providerOptions: options.providerOptions,
980
+ fetch: options.fetch,
981
+ // Flip to non-streaming fallback after repeated stream stalls.
982
+ ...useNonStreamingFallback ? { streaming: false } : {}
983
+ })
843
984
  });
844
985
  diag("stream_created", { setupMs: Date.now() - streamCallStart });
845
986
  result.response.catch(() => {
@@ -1420,6 +1561,7 @@ async function* agentLoop(messages, options) {
1420
1561
  if (!emptyExhausted) {
1421
1562
  messages.push(response.message);
1422
1563
  latestProviderUsage = response.usage;
1564
+ latestProviderUsageAt = Date.now();
1423
1565
  usageAnchorIndex = messages.length - 1;
1424
1566
  }
1425
1567
  const completedAt = Date.now();