@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.cjs +176 -34
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +176 -34
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -47,6 +47,111 @@ var import_gg_ai3 = require("@kenkaiiii/gg-ai");
|
|
|
47
47
|
var import_zod = require("zod");
|
|
48
48
|
var import_gg_ai2 = require("@kenkaiiii/gg-ai");
|
|
49
49
|
|
|
50
|
+
// src/hedged-stream.ts
|
|
51
|
+
var HEDGE_FIRST_EVENT_AFTER_MS = 3e4;
|
|
52
|
+
var HEDGE_CACHE_WARM_MS = 4 * 6e4;
|
|
53
|
+
var HEDGE_MIN_CACHED_RATIO = 0.5;
|
|
54
|
+
var HEDGE_MIN_WINDOW_MS = 2e4;
|
|
55
|
+
function firstEventHedgeDelayMs(input) {
|
|
56
|
+
const usage = input.priorUsage;
|
|
57
|
+
if (!usage) return null;
|
|
58
|
+
const cached = (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
|
|
59
|
+
const prompt = usage.inputTokens + cached;
|
|
60
|
+
if (prompt <= 0 || cached / prompt < HEDGE_MIN_CACHED_RATIO) return null;
|
|
61
|
+
if (input.msSincePriorResponse < 0 || input.msSincePriorResponse > HEDGE_CACHE_WARM_MS) {
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
const delay = HEDGE_FIRST_EVENT_AFTER_MS + Math.max(0, input.newPromptTokens) / 1e3 * input.prefillMsPer1kTokens;
|
|
65
|
+
if (!Number.isFinite(input.firstEventTimeoutMs)) return null;
|
|
66
|
+
if (delay + HEDGE_MIN_WINDOW_MS > input.firstEventTimeoutMs) return null;
|
|
67
|
+
return delay;
|
|
68
|
+
}
|
|
69
|
+
function linkedController(parent) {
|
|
70
|
+
const controller = new AbortController();
|
|
71
|
+
if (parent.aborted) controller.abort();
|
|
72
|
+
else parent.addEventListener("abort", () => controller.abort(), { once: true });
|
|
73
|
+
return controller;
|
|
74
|
+
}
|
|
75
|
+
function startArm(name, options) {
|
|
76
|
+
const controller = linkedController(options.signal);
|
|
77
|
+
const stream2 = options.start(controller.signal, name);
|
|
78
|
+
stream2.response.catch(() => {
|
|
79
|
+
});
|
|
80
|
+
return { name, stream: stream2, iterator: stream2[Symbol.asyncIterator](), controller };
|
|
81
|
+
}
|
|
82
|
+
function firstOutcome(arm) {
|
|
83
|
+
return arm.iterator.next().then(
|
|
84
|
+
(first) => ({ arm, ok: true, first }),
|
|
85
|
+
(error) => ({ arm, ok: false, error })
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
function hedgedStream(options) {
|
|
89
|
+
if (options.hedgeAfterMs === null) {
|
|
90
|
+
const stream2 = options.start(options.signal, "primary");
|
|
91
|
+
options.onSettled?.("primary", false);
|
|
92
|
+
return stream2;
|
|
93
|
+
}
|
|
94
|
+
const hedgeAfterMs = options.hedgeAfterMs;
|
|
95
|
+
const select = async () => {
|
|
96
|
+
const primary = startArm("primary", options);
|
|
97
|
+
const primaryOutcome = firstOutcome(primary);
|
|
98
|
+
let timer;
|
|
99
|
+
const hedgeDue = new Promise((resolve) => {
|
|
100
|
+
timer = setTimeout(() => resolve("hedge"), hedgeAfterMs);
|
|
101
|
+
});
|
|
102
|
+
let early;
|
|
103
|
+
try {
|
|
104
|
+
early = await Promise.race([primaryOutcome, hedgeDue]);
|
|
105
|
+
} finally {
|
|
106
|
+
clearTimeout(timer);
|
|
107
|
+
}
|
|
108
|
+
if (early !== "hedge" || options.signal.aborted) {
|
|
109
|
+
const outcome = early === "hedge" ? await primaryOutcome : early;
|
|
110
|
+
if (!outcome.ok) throw outcome.error;
|
|
111
|
+
options.onSettled?.("primary", false);
|
|
112
|
+
return { arm: primary, first: outcome.first };
|
|
113
|
+
}
|
|
114
|
+
const hedge = startArm("hedge", options);
|
|
115
|
+
options.onHedgeStarted?.();
|
|
116
|
+
const hedgeOutcome = firstOutcome(hedge);
|
|
117
|
+
let winner = await Promise.race([primaryOutcome, hedgeOutcome]);
|
|
118
|
+
if (!winner.ok) {
|
|
119
|
+
const other = await (winner.arm === primary ? hedgeOutcome : primaryOutcome);
|
|
120
|
+
if (!other.ok) {
|
|
121
|
+
throw winner.arm === primary ? winner.error : other.error;
|
|
122
|
+
}
|
|
123
|
+
winner = other;
|
|
124
|
+
}
|
|
125
|
+
const loser = winner.arm === primary ? hedge : primary;
|
|
126
|
+
loser.controller.abort();
|
|
127
|
+
options.onSettled?.(winner.arm.name, true);
|
|
128
|
+
return { arm: winner.arm, first: winner.first };
|
|
129
|
+
};
|
|
130
|
+
const selection = select();
|
|
131
|
+
selection.catch(() => {
|
|
132
|
+
});
|
|
133
|
+
const response = selection.then((s) => s.arm.stream.response);
|
|
134
|
+
response.catch(() => {
|
|
135
|
+
});
|
|
136
|
+
return {
|
|
137
|
+
response,
|
|
138
|
+
async *[Symbol.asyncIterator]() {
|
|
139
|
+
const { arm, first } = await selection;
|
|
140
|
+
if (first.done) return;
|
|
141
|
+
try {
|
|
142
|
+
yield first.value;
|
|
143
|
+
while (true) {
|
|
144
|
+
const next = await arm.iterator.next();
|
|
145
|
+
if (next.done) return;
|
|
146
|
+
yield next.value;
|
|
147
|
+
}
|
|
148
|
+
} finally {
|
|
149
|
+
await arm.iterator.return?.();
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
50
155
|
// src/local-backend.ts
|
|
51
156
|
function isLocalBackendUrl(baseUrl) {
|
|
52
157
|
if (!baseUrl) return false;
|
|
@@ -629,6 +734,7 @@ async function* agentLoop(messages, options) {
|
|
|
629
734
|
const totalUsage = { inputTokens: 0, outputTokens: 0 };
|
|
630
735
|
let latestProviderUsage;
|
|
631
736
|
let usageAnchorIndex;
|
|
737
|
+
let latestProviderUsageAt = 0;
|
|
632
738
|
let turn = 0;
|
|
633
739
|
let hitMaxTurns = false;
|
|
634
740
|
let firstTurn = true;
|
|
@@ -837,41 +943,76 @@ async function* agentLoop(messages, options) {
|
|
|
837
943
|
});
|
|
838
944
|
}
|
|
839
945
|
}
|
|
840
|
-
const
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
baseUrl: options.baseUrl,
|
|
946
|
+
const hedgeAfterMs = baseFirstEventTimeoutMs === STREAM_FIRST_EVENT_TIMEOUT_MS && !useNonStreamingFallback ? firstEventHedgeDelayMs({
|
|
947
|
+
priorUsage: latestProviderUsage,
|
|
948
|
+
msSincePriorResponse: Date.now() - latestProviderUsageAt,
|
|
949
|
+
newPromptTokens: Math.ceil(
|
|
950
|
+
countMessageChars(
|
|
951
|
+
usageAnchorIndex === void 0 ? messages : messages.slice(usageAnchorIndex + 1)
|
|
952
|
+
) / 3
|
|
953
|
+
),
|
|
954
|
+
firstEventTimeoutMs,
|
|
955
|
+
prefillMsPer1kTokens: PREFILL_TIMEOUT_MS_PER_1K_TOKENS
|
|
956
|
+
}) : null;
|
|
957
|
+
const hedgeStartedAt = Date.now();
|
|
958
|
+
const requestMessages = hedgeAfterMs === null ? messages : messages.slice();
|
|
959
|
+
const result = hedgedStream({
|
|
855
960
|
signal: streamController.signal,
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
961
|
+
hedgeAfterMs,
|
|
962
|
+
onHedgeStarted: () => {
|
|
963
|
+
diag("hedge_started", {
|
|
964
|
+
afterMs: Date.now() - hedgeStartedAt,
|
|
965
|
+
provider: options.provider,
|
|
966
|
+
model: options.model
|
|
967
|
+
});
|
|
968
|
+
},
|
|
969
|
+
onSettled: (winner, hedged) => {
|
|
970
|
+
if (hedged) {
|
|
971
|
+
diag("hedge_settled", {
|
|
972
|
+
winner,
|
|
973
|
+
ttfMs: Date.now() - hedgeStartedAt,
|
|
974
|
+
provider: options.provider,
|
|
975
|
+
model: options.model
|
|
976
|
+
});
|
|
977
|
+
}
|
|
978
|
+
},
|
|
979
|
+
start: (signal, arm) => (0, import_gg_ai2.stream)({
|
|
980
|
+
provider: options.provider,
|
|
981
|
+
model: options.model,
|
|
982
|
+
messages: requestMessages,
|
|
983
|
+
tools: options.tools,
|
|
984
|
+
serverTools: options.serverTools,
|
|
985
|
+
toolChoice: options.toolChoice,
|
|
986
|
+
webSearch: typeof options.webSearch === "function" ? options.webSearch() : options.webSearch,
|
|
987
|
+
// Clamped to whatever ceiling this route has already rejected us for
|
|
988
|
+
// (identity when nothing has been learned).
|
|
989
|
+
maxTokens: clampOutputTokens(ceilingKey, options.maxTokens),
|
|
990
|
+
temperature: options.temperature,
|
|
991
|
+
thinking: options.thinking,
|
|
992
|
+
apiKey: liveApiKey,
|
|
993
|
+
baseUrl: options.baseUrl,
|
|
994
|
+
signal,
|
|
995
|
+
accountId: liveAccountId,
|
|
996
|
+
transportSessionId: options.transportSessionId,
|
|
997
|
+
projectId: liveProjectId,
|
|
998
|
+
cacheRetention: options.cacheRetention,
|
|
999
|
+
// A hedge duplicates an already-observed request; observe it once.
|
|
1000
|
+
onContextPrepared: arm === "primary" ? options.onContextPrepared : void 0,
|
|
1001
|
+
promptCacheKey: options.promptCacheKey,
|
|
1002
|
+
serviceTier: options.serviceTier,
|
|
1003
|
+
responsesLite: options.responsesLite,
|
|
1004
|
+
strictTools: options.strictTools,
|
|
1005
|
+
supportsImages: options.supportsImages,
|
|
1006
|
+
supportsVideo: options.supportsVideo,
|
|
1007
|
+
compaction: options.compaction,
|
|
1008
|
+
clearToolUses: options.clearToolUses,
|
|
1009
|
+
userAgent: options.userAgent,
|
|
1010
|
+
defaultHeaders: options.defaultHeaders,
|
|
1011
|
+
providerOptions: options.providerOptions,
|
|
1012
|
+
fetch: options.fetch,
|
|
1013
|
+
// Flip to non-streaming fallback after repeated stream stalls.
|
|
1014
|
+
...useNonStreamingFallback ? { streaming: false } : {}
|
|
1015
|
+
})
|
|
875
1016
|
});
|
|
876
1017
|
diag("stream_created", { setupMs: Date.now() - streamCallStart });
|
|
877
1018
|
result.response.catch(() => {
|
|
@@ -1452,6 +1593,7 @@ async function* agentLoop(messages, options) {
|
|
|
1452
1593
|
if (!emptyExhausted) {
|
|
1453
1594
|
messages.push(response.message);
|
|
1454
1595
|
latestProviderUsage = response.usage;
|
|
1596
|
+
latestProviderUsageAt = Date.now();
|
|
1455
1597
|
usageAnchorIndex = messages.length - 1;
|
|
1456
1598
|
}
|
|
1457
1599
|
const completedAt = Date.now();
|