@google/gemini-cli 0.42.0 → 0.44.0-nightly.20260513.g5ee05c775
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/bundle/{chunk-COQP2M4D.js → chunk-27SPXGT2.js} +562 -437
- package/bundle/{chunk-EDKX67D6.js → chunk-2VH3SA6M.js} +43 -23
- package/bundle/{chunk-PUDLNWHE.js → chunk-3KOQHVJU.js} +3 -3
- package/bundle/{chunk-COKAF5GM.js → chunk-4QQ5AHZP.js} +2 -2
- package/bundle/{chunk-KVEAHIIV.js → chunk-5EEEHNEE.js} +3 -3
- package/bundle/{chunk-G2VTSEZ6.js → chunk-5SMSFUPB.js} +1 -1
- package/bundle/{chunk-7VVHSNDQ.js → chunk-AC2EWTF7.js} +1970 -731
- package/bundle/{chunk-GA527JB7.js → chunk-ATSNFRDF.js} +1 -1
- package/bundle/{chunk-3IS7GD6D.js → chunk-BA752AEU.js} +3 -3
- package/bundle/{chunk-CYEIWMZJ.js → chunk-FGYOOMPI.js} +1 -1
- package/bundle/{chunk-QOZSZYL7.js → chunk-FK45PHSI.js} +3 -3
- package/bundle/{chunk-I7AME6VC.js → chunk-FTY6BJEY.js} +9 -8
- package/bundle/{chunk-NTOPH4WG.js → chunk-GCWBZXBS.js} +2 -2
- package/bundle/chunk-I2JHD4D3.js +512 -0
- package/bundle/{chunk-7C6GGDK6.js → chunk-IZJOLGNO.js} +3 -3
- package/bundle/{chunk-4SLGT6YD.js → chunk-J4YAW3P3.js} +1 -1
- package/bundle/chunk-KADNKBXT.js +118 -0
- package/bundle/{chunk-DN4XSYRG.js → chunk-LF33N5QM.js} +8696 -13355
- package/bundle/{chunk-CHERUG6W.js → chunk-LO22NRY4.js} +502 -390
- package/bundle/{chunk-JEW7ZIWE.js → chunk-M7OUJJZ2.js} +5270 -5234
- package/bundle/{chunk-WIXUKOZA.js → chunk-MFNKZZOB.js} +1 -1
- package/bundle/chunk-MLPM54XD.js +357247 -0
- package/bundle/{chunk-ECNYAST2.js → chunk-N22WUHJE.js} +5419 -5378
- package/bundle/chunk-OC7XGTLV.js +81656 -0
- package/bundle/{chunk-ZNMQA242.js → chunk-QDEK3TQ6.js} +3 -3
- package/bundle/{chunk-BCYBA52D.js → chunk-QMXQUBC4.js} +43 -23
- package/bundle/chunk-TBHMNRI3.js +1571 -0
- package/bundle/{chunk-LATVEETM.js → chunk-TOOOS4HD.js} +2 -2
- package/bundle/{chunk-XUMRUXOT.js → chunk-UHSQLPNG.js} +50 -27
- package/bundle/chunk-USS2A6NQ.js +156 -0
- package/bundle/chunk-WMTLLWRC.js +391 -0
- package/bundle/chunk-XDWZDV7C.js +17250 -0
- package/bundle/{chunk-DMWX7UP6.js → chunk-YBYQH75I.js} +2252 -829
- package/bundle/{chunk-FCAODPNO.js → chunk-ZZN56QZ3.js} +502 -390
- package/bundle/{cleanup-3RILFNVM.js → cleanup-2H3SANYB.js} +3 -3
- package/bundle/{cleanup-SVRKYBR6.js → cleanup-7GY7BVC6.js} +3 -3
- package/bundle/{cleanup-XFVHHDVO.js → cleanup-FERREFU6.js} +3 -3
- package/bundle/cleanup-VIITMMDH.js +33 -0
- package/bundle/{core-FRVSDP2C.js → core-GS6NXK7Y.js} +30 -2
- package/bundle/{devtoolsService-VM2WTHBX.js → devtoolsService-FKC6Y4OE.js} +3 -3
- package/bundle/{devtoolsService-TRDGMQLJ.js → devtoolsService-K2DRCZEY.js} +5 -4
- package/bundle/{devtoolsService-RUEO5PGP.js → devtoolsService-PS6RYICL.js} +3 -3
- package/bundle/devtoolsService-ZDXC2NPD.js +857 -0
- package/bundle/{dist-6BN2CJPN.js → dist-S3YUNQKP.js} +30 -2
- package/bundle/{core-B5S6HZJT.js → dist-TBGNMYU2.js} +30 -2
- package/bundle/dist-ZEW43MLQ.js +2124 -0
- package/bundle/docs/changelogs/index.md +30 -0
- package/bundle/docs/changelogs/latest.md +261 -166
- package/bundle/docs/changelogs/preview.md +178 -103
- package/bundle/docs/cli/auto-memory.md +60 -38
- package/bundle/docs/cli/settings.md +1 -1
- package/bundle/docs/cli/tutorials/memory-management.md +1 -1
- package/bundle/docs/extensions/releasing.md +58 -24
- package/bundle/docs/reference/configuration.md +14 -1
- package/bundle/docs/reference/keyboard-shortcuts.md +23 -0
- package/bundle/{gemini-QSTQ2DBG.js → gemini-6YGVETF3.js} +165 -61
- package/bundle/{gemini-GHUELHBF.js → gemini-7FCGNXOV.js} +350 -232
- package/bundle/gemini-IXZUGRVP.js +16360 -0
- package/bundle/{gemini-NQPVX5JC.js → gemini-WYTY4CD5.js} +165 -61
- package/bundle/gemini.js +8 -8
- package/bundle/{interactiveCli-AG2YWL2O.js → interactiveCli-A2FV6NYD.js} +1721 -1472
- package/bundle/{interactiveCli-MZFG35NB.js → interactiveCli-DWNRHVIB.js} +2003 -1736
- package/bundle/{interactiveCli-453M2IVE.js → interactiveCli-H7N4UXVQ.js} +1720 -1472
- package/bundle/interactiveCli-XRZEELCX.js +34754 -0
- package/bundle/{liteRtServerManager-G4Q7OVBX.js → liteRtServerManager-5C5EONBK.js} +5 -5
- package/bundle/{liteRtServerManager-S7WL25VD.js → liteRtServerManager-NQKPNCLR.js} +5 -5
- package/bundle/{liteRtServerManager-BXQ6VVWP.js → liteRtServerManager-UJBPII3P.js} +5 -5
- package/bundle/liteRtServerManager-UZCAJJCS.js +66 -0
- package/bundle/{memoryDiscovery-KSYZVCWF.js → memoryDiscovery-ALKMYAPP.js} +1 -1
- package/bundle/{memoryDiscovery-FB7MMKTA.js → memoryDiscovery-XFCKEF3F.js} +1 -1
- package/bundle/node_modules/@google/gemini-cli-devtools/package.json +1 -1
- package/bundle/{oauth2-provider-VR4DL6AL.js → oauth2-provider-JNOY6NUI.js} +2 -2
- package/bundle/{oauth2-provider-H7G6RSFW.js → oauth2-provider-O6OA5EMU.js} +2 -2
- package/bundle/{oauth2-provider-5UF5WEE2.js → oauth2-provider-QYCLASEA.js} +39 -73
- package/bundle/oauth2-provider-VWLTUFO7.js +237 -0
- package/bundle/{start-CQBSKFYB.js → start-6FV3VPPH.js} +7 -7
- package/bundle/{start-NIMXQJYB.js → start-IWAUTCYF.js} +7 -7
- package/bundle/{start-2SKRN43X.js → start-L4DAQUQM.js} +7 -7
- package/bundle/start-XTXUKP77.js +19 -0
- package/package.json +1 -1
|
@@ -89,6 +89,7 @@ import {
|
|
|
89
89
|
PREVIEW_GEMINI_MODEL,
|
|
90
90
|
PREVIEW_GEMINI_MODEL_AUTO,
|
|
91
91
|
PRIORITY_SUBAGENT_TOOL,
|
|
92
|
+
PROJECT_MEMORY_INDEX_FILENAME,
|
|
92
93
|
PolicyDecision,
|
|
93
94
|
READ_FILE_DEFINITION,
|
|
94
95
|
READ_FILE_DISPLAY_NAME,
|
|
@@ -217,7 +218,7 @@ import {
|
|
|
217
218
|
toPathKey,
|
|
218
219
|
unescapePath,
|
|
219
220
|
zodToJsonSchema
|
|
220
|
-
} from "./chunk-
|
|
221
|
+
} from "./chunk-N22WUHJE.js";
|
|
221
222
|
import {
|
|
222
223
|
wrapper_default
|
|
223
224
|
} from "./chunk-664ZODQF.js";
|
|
@@ -2568,7 +2569,7 @@ var require_lib = __commonJS({
|
|
|
2568
2569
|
return numMessages > 0;
|
|
2569
2570
|
}
|
|
2570
2571
|
async function isBinaryFile2(file2, size) {
|
|
2571
|
-
if (
|
|
2572
|
+
if (isString2(file2)) {
|
|
2572
2573
|
const stat9 = await statAsync(file2);
|
|
2573
2574
|
isStatFile(stat9);
|
|
2574
2575
|
const fileDescriptor = await openAsync(file2, "r");
|
|
@@ -2596,7 +2597,7 @@ var require_lib = __commonJS({
|
|
|
2596
2597
|
}
|
|
2597
2598
|
exports2.isBinaryFile = isBinaryFile2;
|
|
2598
2599
|
function isBinaryFileSync(file2, size) {
|
|
2599
|
-
if (
|
|
2600
|
+
if (isString2(file2)) {
|
|
2600
2601
|
const stat9 = fs84.statSync(file2);
|
|
2601
2602
|
isStatFile(stat9);
|
|
2602
2603
|
const fileDescriptor = fs84.openSync(file2, "r");
|
|
@@ -2676,7 +2677,7 @@ var require_lib = __commonJS({
|
|
|
2676
2677
|
}
|
|
2677
2678
|
return false;
|
|
2678
2679
|
}
|
|
2679
|
-
function
|
|
2680
|
+
function isString2(x) {
|
|
2680
2681
|
return typeof x === "string";
|
|
2681
2682
|
}
|
|
2682
2683
|
function isStatFile(stat9) {
|
|
@@ -24444,7 +24445,7 @@ var require_minimal = __commonJS({
|
|
|
24444
24445
|
function isInteger3(value) {
|
|
24445
24446
|
return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
|
|
24446
24447
|
};
|
|
24447
|
-
util2.isString = function
|
|
24448
|
+
util2.isString = function isString2(value) {
|
|
24448
24449
|
return typeof value === "string" || value instanceof String;
|
|
24449
24450
|
};
|
|
24450
24451
|
util2.isObject = function isObject6(value) {
|
|
@@ -25313,13 +25314,13 @@ var require_path = __commonJS({
|
|
|
25313
25314
|
"node_modules/@protobufjs/path/index.js"(exports2) {
|
|
25314
25315
|
"use strict";
|
|
25315
25316
|
var path101 = exports2;
|
|
25316
|
-
var
|
|
25317
|
+
var isAbsolute7 = (
|
|
25317
25318
|
/**
|
|
25318
25319
|
* Tests if the specified path is absolute.
|
|
25319
25320
|
* @param {string} path Path to test
|
|
25320
25321
|
* @returns {boolean} `true` if path is absolute
|
|
25321
25322
|
*/
|
|
25322
|
-
path101.isAbsolute = function
|
|
25323
|
+
path101.isAbsolute = function isAbsolute8(path102) {
|
|
25323
25324
|
return /^(?:\/|\w+:)/.test(path102);
|
|
25324
25325
|
}
|
|
25325
25326
|
);
|
|
@@ -25331,7 +25332,7 @@ var require_path = __commonJS({
|
|
|
25331
25332
|
*/
|
|
25332
25333
|
path101.normalize = function normalize6(path102) {
|
|
25333
25334
|
path102 = path102.replace(/\\/g, "/").replace(/\/{2,}/g, "/");
|
|
25334
|
-
var parts2 = path102.split("/"), absolute =
|
|
25335
|
+
var parts2 = path102.split("/"), absolute = isAbsolute7(path102), prefix = "";
|
|
25335
25336
|
if (absolute)
|
|
25336
25337
|
prefix = parts2.shift() + "/";
|
|
25337
25338
|
for (var i3 = 0; i3 < parts2.length; ) {
|
|
@@ -25353,7 +25354,7 @@ var require_path = __commonJS({
|
|
|
25353
25354
|
path101.resolve = function resolve25(originPath, includePath, alreadyNormalized) {
|
|
25354
25355
|
if (!alreadyNormalized)
|
|
25355
25356
|
includePath = normalize5(includePath);
|
|
25356
|
-
if (
|
|
25357
|
+
if (isAbsolute7(includePath))
|
|
25357
25358
|
return includePath;
|
|
25358
25359
|
if (!alreadyNormalized)
|
|
25359
25360
|
originPath = normalize5(originPath);
|
|
@@ -42945,7 +42946,7 @@ var require_minimal2 = __commonJS({
|
|
|
42945
42946
|
function isInteger3(value) {
|
|
42946
42947
|
return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
|
|
42947
42948
|
};
|
|
42948
|
-
util2.isString = function
|
|
42949
|
+
util2.isString = function isString2(value) {
|
|
42949
42950
|
return typeof value === "string" || value instanceof String;
|
|
42950
42951
|
};
|
|
42951
42952
|
util2.isObject = function isObject6(value) {
|
|
@@ -96320,7 +96321,7 @@ var require_object_inspect = __commonJS({
|
|
|
96320
96321
|
if (isBoolean2(obj)) {
|
|
96321
96322
|
return markBoxed(booleanValueOf.call(obj));
|
|
96322
96323
|
}
|
|
96323
|
-
if (
|
|
96324
|
+
if (isString2(obj)) {
|
|
96324
96325
|
return markBoxed(inspect4(String(obj)));
|
|
96325
96326
|
}
|
|
96326
96327
|
if (typeof window !== "undefined" && obj === window) {
|
|
@@ -96369,7 +96370,7 @@ var require_object_inspect = __commonJS({
|
|
|
96369
96370
|
function isError(obj) {
|
|
96370
96371
|
return toStr(obj) === "[object Error]" && canTrustToString(obj);
|
|
96371
96372
|
}
|
|
96372
|
-
function
|
|
96373
|
+
function isString2(obj) {
|
|
96373
96374
|
return toStr(obj) === "[object String]" && canTrustToString(obj);
|
|
96374
96375
|
}
|
|
96375
96376
|
function isNumber3(obj) {
|
|
@@ -204417,8 +204418,8 @@ var require_ignore = __commonJS({
|
|
|
204417
204418
|
(prev, [matcher, replacer]) => prev.replace(matcher, replacer.bind(pattern)),
|
|
204418
204419
|
pattern
|
|
204419
204420
|
);
|
|
204420
|
-
var
|
|
204421
|
-
var checkPattern = (pattern) => pattern &&
|
|
204421
|
+
var isString2 = (subject) => typeof subject === "string";
|
|
204422
|
+
var checkPattern = (pattern) => pattern && isString2(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) && pattern.indexOf("#") !== 0;
|
|
204422
204423
|
var splitPattern = (pattern) => pattern.split(REGEX_SPLITALL_CRLF).filter(Boolean);
|
|
204423
204424
|
var IgnoreRule = class {
|
|
204424
204425
|
constructor(pattern, mark, body2, ignoreCase, negative, prefix) {
|
|
@@ -204485,7 +204486,7 @@ var require_ignore = __commonJS({
|
|
|
204485
204486
|
this._added = true;
|
|
204486
204487
|
return;
|
|
204487
204488
|
}
|
|
204488
|
-
if (
|
|
204489
|
+
if (isString2(pattern)) {
|
|
204489
204490
|
pattern = {
|
|
204490
204491
|
pattern
|
|
204491
204492
|
};
|
|
@@ -204500,7 +204501,7 @@ var require_ignore = __commonJS({
|
|
|
204500
204501
|
add(pattern) {
|
|
204501
204502
|
this._added = false;
|
|
204502
204503
|
makeArray(
|
|
204503
|
-
|
|
204504
|
+
isString2(pattern) ? splitPattern(pattern) : pattern
|
|
204504
204505
|
).forEach(this._add, this);
|
|
204505
204506
|
return this._added;
|
|
204506
204507
|
}
|
|
@@ -204542,7 +204543,7 @@ var require_ignore = __commonJS({
|
|
|
204542
204543
|
throw new Ctor(message);
|
|
204543
204544
|
};
|
|
204544
204545
|
var checkPath = (path101, originalPath, doThrow) => {
|
|
204545
|
-
if (!
|
|
204546
|
+
if (!isString2(path101)) {
|
|
204546
204547
|
return doThrow(
|
|
204547
204548
|
`path must be a string, but got \`${originalPath}\``,
|
|
204548
204549
|
TypeError
|
|
@@ -229139,13 +229140,13 @@ var require_implementation2 = __commonJS({
|
|
|
229139
229140
|
var isObject6 = object3 !== null && typeof object3 === "object";
|
|
229140
229141
|
var isFunction = toStr.call(object3) === "[object Function]";
|
|
229141
229142
|
var isArguments = isArgs(object3);
|
|
229142
|
-
var
|
|
229143
|
+
var isString2 = isObject6 && toStr.call(object3) === "[object String]";
|
|
229143
229144
|
var theKeys = [];
|
|
229144
229145
|
if (!isObject6 && !isFunction && !isArguments) {
|
|
229145
229146
|
throw new TypeError("Object.keys called on a non-object");
|
|
229146
229147
|
}
|
|
229147
229148
|
var skipProto = hasProtoEnumBug && isFunction;
|
|
229148
|
-
if (
|
|
229149
|
+
if (isString2 && object3.length > 0 && !has.call(object3, 0)) {
|
|
229149
229150
|
for (var i3 = 0; i3 < object3.length; ++i3) {
|
|
229150
229151
|
theKeys.push(String(i3));
|
|
229151
229152
|
}
|
|
@@ -236746,6 +236747,8 @@ var BINARY_FILE_PATTERNS = [
|
|
|
236746
236747
|
"**/*.bz2",
|
|
236747
236748
|
"**/*.rar",
|
|
236748
236749
|
"**/*.7z",
|
|
236750
|
+
"**/*.pak",
|
|
236751
|
+
"**/*.rpa",
|
|
236749
236752
|
"**/*.doc",
|
|
236750
236753
|
"**/*.docx",
|
|
236751
236754
|
"**/*.xls",
|
|
@@ -237791,8 +237794,14 @@ function escapeShellArg(arg, shell) {
|
|
|
237791
237794
|
}
|
|
237792
237795
|
switch (shell) {
|
|
237793
237796
|
case "powershell":
|
|
237797
|
+
if (/^[a-zA-Z0-9\-_.]+$/.test(arg)) {
|
|
237798
|
+
return arg;
|
|
237799
|
+
}
|
|
237794
237800
|
return `'${arg.replace(/'/g, "''")}'`;
|
|
237795
237801
|
case "cmd":
|
|
237802
|
+
if (/^[a-zA-Z0-9\-_.]+$/.test(arg)) {
|
|
237803
|
+
return arg;
|
|
237804
|
+
}
|
|
237796
237805
|
return `"${arg.replace(/"/g, '""')}"`;
|
|
237797
237806
|
case "bash":
|
|
237798
237807
|
default:
|
|
@@ -242234,7 +242243,8 @@ function recordModelRoutingMetrics(config2, event) {
|
|
|
242234
242243
|
"routing.approval_mode": event.approval_mode
|
|
242235
242244
|
};
|
|
242236
242245
|
if (event.reasoning) {
|
|
242237
|
-
|
|
242246
|
+
const isStrictTelemetry = process.env["GEMINI_STRICT_TELEMETRY_LIMITS"] === "true";
|
|
242247
|
+
attributes["routing.reasoning"] = isStrictTelemetry && event.reasoning.length > 1e3 ? event.reasoning.substring(0, 1e3) + "..." : event.reasoning;
|
|
242238
242248
|
}
|
|
242239
242249
|
if (event.enable_numerical_routing !== void 0) {
|
|
242240
242250
|
attributes["routing.enable_numerical_routing"] = event.enable_numerical_routing;
|
|
@@ -242244,9 +242254,10 @@ function recordModelRoutingMetrics(config2, event) {
|
|
|
242244
242254
|
}
|
|
242245
242255
|
modelRoutingLatencyHistogram.record(event.routing_latency_ms, attributes);
|
|
242246
242256
|
if (event.failed) {
|
|
242257
|
+
const isStrictTelemetry = process.env["GEMINI_STRICT_TELEMETRY_LIMITS"] === "true";
|
|
242247
242258
|
modelRoutingFailureCounter.add(1, {
|
|
242248
242259
|
...attributes,
|
|
242249
|
-
"routing.error_message": event.error_message
|
|
242260
|
+
"routing.error_message": isStrictTelemetry && event.error_message && event.error_message.length > 1e3 ? event.error_message.substring(0, 1e3) + "..." : event.error_message
|
|
242250
242261
|
});
|
|
242251
242262
|
}
|
|
242252
242263
|
}
|
|
@@ -245069,7 +245080,7 @@ var KeychainService = class {
|
|
|
245069
245080
|
if (await this.isKeychainFunctional(keychainModule)) {
|
|
245070
245081
|
return keychainModule;
|
|
245071
245082
|
}
|
|
245072
|
-
debugLogger.debug("Keychain functional verification failed");
|
|
245083
|
+
debugLogger.debug("Keychain functional verification failed or timed out");
|
|
245073
245084
|
return null;
|
|
245074
245085
|
} catch (error40) {
|
|
245075
245086
|
const message = error40 instanceof Error ? error40.message : String(error40);
|
|
@@ -245096,16 +245107,30 @@ var KeychainService = class {
|
|
|
245096
245107
|
return null;
|
|
245097
245108
|
}
|
|
245098
245109
|
// Performs a set-get-delete cycle to verify keychain functionality.
|
|
245110
|
+
// Capped with a 2s timeout so a non-responsive Secret Service (common on
|
|
245111
|
+
// headless Linux: WSL/SSH/Docker without gnome-keyring or D-Bus) falls back
|
|
245112
|
+
// to FileKeychain instead of hanging the CLI indefinitely.
|
|
245099
245113
|
async isKeychainFunctional(keychain) {
|
|
245100
245114
|
const testAccount = `${KEYCHAIN_TEST_PREFIX}${crypto7.randomBytes(8).toString("hex")}`;
|
|
245101
245115
|
const testPassword = "test";
|
|
245102
|
-
|
|
245103
|
-
|
|
245104
|
-
|
|
245105
|
-
|
|
245106
|
-
|
|
245107
|
-
|
|
245108
|
-
|
|
245116
|
+
const probe = async () => {
|
|
245117
|
+
await keychain.setPassword(this.serviceName, testAccount, testPassword);
|
|
245118
|
+
const retrieved = await keychain.getPassword(
|
|
245119
|
+
this.serviceName,
|
|
245120
|
+
testAccount
|
|
245121
|
+
);
|
|
245122
|
+
const deleted = await keychain.deletePassword(
|
|
245123
|
+
this.serviceName,
|
|
245124
|
+
testAccount
|
|
245125
|
+
);
|
|
245126
|
+
return deleted && retrieved === testPassword;
|
|
245127
|
+
};
|
|
245128
|
+
return Promise.race([
|
|
245129
|
+
probe(),
|
|
245130
|
+
new Promise(
|
|
245131
|
+
(resolve25) => setTimeout(() => resolve25(false), 2e3).unref()
|
|
245132
|
+
)
|
|
245133
|
+
]);
|
|
245109
245134
|
}
|
|
245110
245135
|
/**
|
|
245111
245136
|
* MacOS-specific check to detect if a default keychain is available.
|
|
@@ -245639,7 +245664,8 @@ async function triggerPostAuthCallbacks(tokens) {
|
|
|
245639
245664
|
refresh_token: tokens.refresh_token ?? void 0,
|
|
245640
245665
|
// Ensure null is not passed
|
|
245641
245666
|
type: "authorized_user",
|
|
245642
|
-
client_email: userAccountManager2.getCachedGoogleAccount() ?? void 0
|
|
245667
|
+
client_email: userAccountManager2.getCachedGoogleAccount() ?? void 0,
|
|
245668
|
+
quota_project_id: process.env["GOOGLE_CLOUD_QUOTA_PROJECT"] || process.env["GOOGLE_CLOUD_PROJECT"] || process.env["GOOGLE_CLOUD_PROJECT_ID"]
|
|
245643
245669
|
};
|
|
245644
245670
|
authEvents.emit("post_auth", jwtInput);
|
|
245645
245671
|
}
|
|
@@ -246115,7 +246141,12 @@ async function fetchCachedCredentials() {
|
|
|
246115
246141
|
for (const keyFile of pathsToTry) {
|
|
246116
246142
|
try {
|
|
246117
246143
|
const keyFileString = await fs20.readFile(keyFile, "utf-8");
|
|
246118
|
-
|
|
246144
|
+
const parsed = JSON.parse(keyFileString);
|
|
246145
|
+
const isOAuthCreds = (val) => typeof val === "object" && val !== null;
|
|
246146
|
+
if (isOAuthCreds(parsed)) {
|
|
246147
|
+
return parsed;
|
|
246148
|
+
}
|
|
246149
|
+
throw new Error("Invalid credentials format");
|
|
246119
246150
|
} catch (error40) {
|
|
246120
246151
|
debugLogger.debug(
|
|
246121
246152
|
`Failed to load credentials from ${keyFile}:`,
|
|
@@ -246396,8 +246427,8 @@ import { createHash } from "node:crypto";
|
|
|
246396
246427
|
import * as os12 from "node:os";
|
|
246397
246428
|
|
|
246398
246429
|
// packages/core/src/generated/git-commit.ts
|
|
246399
|
-
var GIT_COMMIT_INFO = "
|
|
246400
|
-
var CLI_VERSION = "0.
|
|
246430
|
+
var GIT_COMMIT_INFO = "5ee05c775";
|
|
246431
|
+
var CLI_VERSION = "0.44.0-nightly.20260512.g022e8baef";
|
|
246401
246432
|
|
|
246402
246433
|
// packages/core/src/ide/detect-ide.ts
|
|
246403
246434
|
var IDE_DEFINITIONS = {
|
|
@@ -248273,7 +248304,37 @@ var GcpMetricExporter = class extends import_opentelemetry_cloud_monitoring_expo
|
|
|
248273
248304
|
prefix: "custom.googleapis.com/gemini_cli"
|
|
248274
248305
|
});
|
|
248275
248306
|
}
|
|
248307
|
+
export(metrics2, resultCallback) {
|
|
248308
|
+
super.export(metrics2, (result2) => {
|
|
248309
|
+
if (result2.code === import_core5.ExportResultCode.FAILED && result2.error) {
|
|
248310
|
+
const errorMessage = result2.error.message || String(result2.error);
|
|
248311
|
+
if (process.env["GEMINI_STRICT_TELEMETRY_LIMITS"] === "true" && errorMessage.includes(
|
|
248312
|
+
"written more frequently than the maximum sampling period"
|
|
248313
|
+
)) {
|
|
248314
|
+
resultCallback({ code: import_core5.ExportResultCode.SUCCESS });
|
|
248315
|
+
return;
|
|
248316
|
+
}
|
|
248317
|
+
}
|
|
248318
|
+
resultCallback(result2);
|
|
248319
|
+
});
|
|
248320
|
+
}
|
|
248276
248321
|
};
|
|
248322
|
+
function truncateLogPayload(payload, limit = 2e5) {
|
|
248323
|
+
if (typeof payload === "string") {
|
|
248324
|
+
return payload.length > limit ? payload.substring(0, limit) + "... (truncated due to size)" : payload;
|
|
248325
|
+
}
|
|
248326
|
+
if (Array.isArray(payload)) {
|
|
248327
|
+
return payload.map((item) => truncateLogPayload(item, limit));
|
|
248328
|
+
}
|
|
248329
|
+
if (payload !== null && typeof payload === "object") {
|
|
248330
|
+
const truncatedObj = {};
|
|
248331
|
+
for (const [key, value] of Object.entries(payload)) {
|
|
248332
|
+
truncatedObj[key] = truncateLogPayload(value, limit);
|
|
248333
|
+
}
|
|
248334
|
+
return truncatedObj;
|
|
248335
|
+
}
|
|
248336
|
+
return payload;
|
|
248337
|
+
}
|
|
248277
248338
|
var GcpLogExporter = class {
|
|
248278
248339
|
logging;
|
|
248279
248340
|
log;
|
|
@@ -248285,6 +248346,32 @@ var GcpLogExporter = class {
|
|
|
248285
248346
|
export(logs3, resultCallback) {
|
|
248286
248347
|
try {
|
|
248287
248348
|
const entries = logs3.map((log) => {
|
|
248349
|
+
const rawPayload = {
|
|
248350
|
+
...log.attributes,
|
|
248351
|
+
...log.resource?.attributes,
|
|
248352
|
+
message: log.body
|
|
248353
|
+
};
|
|
248354
|
+
const isStrictTelemetry = process.env["GEMINI_STRICT_TELEMETRY_LIMITS"] === "true";
|
|
248355
|
+
let finalPayload = rawPayload;
|
|
248356
|
+
if (isStrictTelemetry) {
|
|
248357
|
+
let safePayload = truncateLogPayload(rawPayload, 1e4);
|
|
248358
|
+
let payloadString = JSON.stringify(safePayload);
|
|
248359
|
+
if (payloadString && payloadString.length > 1e5) {
|
|
248360
|
+
safePayload = truncateLogPayload(rawPayload, 2e3);
|
|
248361
|
+
payloadString = JSON.stringify(safePayload);
|
|
248362
|
+
if (payloadString && payloadString.length > 1e5) {
|
|
248363
|
+
safePayload = truncateLogPayload(rawPayload, 5e3);
|
|
248364
|
+
payloadString = JSON.stringify(safePayload);
|
|
248365
|
+
if (payloadString && payloadString.length > 1e5) {
|
|
248366
|
+
safePayload = {
|
|
248367
|
+
_warning: "Payload heavily truncated due to strict limits",
|
|
248368
|
+
data: payloadString.substring(0, 5e4) + "... (truncated)"
|
|
248369
|
+
};
|
|
248370
|
+
}
|
|
248371
|
+
}
|
|
248372
|
+
}
|
|
248373
|
+
finalPayload = safePayload;
|
|
248374
|
+
}
|
|
248288
248375
|
const entry = this.log.entry(
|
|
248289
248376
|
{
|
|
248290
248377
|
severity: this.mapSeverityToCloudLogging(log.severityNumber),
|
|
@@ -248296,11 +248383,8 @@ var GcpLogExporter = class {
|
|
|
248296
248383
|
}
|
|
248297
248384
|
}
|
|
248298
248385
|
},
|
|
248299
|
-
|
|
248300
|
-
|
|
248301
|
-
...log.resource?.attributes,
|
|
248302
|
-
message: log.body
|
|
248303
|
-
}
|
|
248386
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
|
|
248387
|
+
finalPayload
|
|
248304
248388
|
);
|
|
248305
248389
|
return entry;
|
|
248306
248390
|
});
|
|
@@ -269327,7 +269411,12 @@ async function getConnectionConfigFromFile(pid) {
|
|
|
269327
269411
|
`gemini-ide-server-${pid}.json`
|
|
269328
269412
|
);
|
|
269329
269413
|
const portFileContents = await fs29.promises.readFile(portFile, "utf8");
|
|
269330
|
-
|
|
269414
|
+
const parsed = JSON.parse(portFileContents);
|
|
269415
|
+
const isConfig = (val) => typeof val === "object" && val !== null;
|
|
269416
|
+
if (isConfig(parsed)) {
|
|
269417
|
+
return parsed;
|
|
269418
|
+
}
|
|
269419
|
+
throw new Error("Invalid connection config format");
|
|
269331
269420
|
} catch {
|
|
269332
269421
|
}
|
|
269333
269422
|
const portFileDir = path26.join(os17.tmpdir(), "gemini", "ide");
|
|
@@ -269359,24 +269448,33 @@ async function getConnectionConfigFromFile(pid) {
|
|
|
269359
269448
|
logger.debug("Failed to read IDE connection config file(s):", e2);
|
|
269360
269449
|
return void 0;
|
|
269361
269450
|
}
|
|
269362
|
-
const parsedContents = fileContents.map(
|
|
269363
|
-
|
|
269364
|
-
|
|
269365
|
-
|
|
269366
|
-
|
|
269367
|
-
|
|
269451
|
+
const parsedContents = fileContents.map(
|
|
269452
|
+
(content) => {
|
|
269453
|
+
try {
|
|
269454
|
+
const parsed = JSON.parse(content);
|
|
269455
|
+
const isConfig = (val) => typeof val === "object" && val !== null;
|
|
269456
|
+
if (isConfig(parsed)) {
|
|
269457
|
+
return parsed;
|
|
269458
|
+
}
|
|
269459
|
+
return void 0;
|
|
269460
|
+
} catch (e2) {
|
|
269461
|
+
logger.debug("Failed to parse JSON from config file: ", e2);
|
|
269462
|
+
return void 0;
|
|
269463
|
+
}
|
|
269368
269464
|
}
|
|
269369
|
-
|
|
269370
|
-
const validWorkspaces = parsedContents.filter(
|
|
269371
|
-
|
|
269372
|
-
|
|
269465
|
+
);
|
|
269466
|
+
const validWorkspaces = parsedContents.filter(
|
|
269467
|
+
(content) => {
|
|
269468
|
+
if (!content) {
|
|
269469
|
+
return false;
|
|
269470
|
+
}
|
|
269471
|
+
const { isValid } = validateWorkspacePath(
|
|
269472
|
+
content.workspacePath,
|
|
269473
|
+
process.cwd()
|
|
269474
|
+
);
|
|
269475
|
+
return isValid;
|
|
269373
269476
|
}
|
|
269374
|
-
|
|
269375
|
-
content.workspacePath,
|
|
269376
|
-
process.cwd()
|
|
269377
|
-
);
|
|
269378
|
-
return isValid;
|
|
269379
|
-
});
|
|
269477
|
+
);
|
|
269380
269478
|
if (validWorkspaces.length === 0) {
|
|
269381
269479
|
return void 0;
|
|
269382
269480
|
}
|
|
@@ -269712,7 +269810,7 @@ function getVersion() {
|
|
|
269712
269810
|
}
|
|
269713
269811
|
versionPromise = (async () => {
|
|
269714
269812
|
const pkgJson = await getPackageJson(__dirname4);
|
|
269715
|
-
return "0.
|
|
269813
|
+
return "0.44.0-nightly.20260512.g022e8baef";
|
|
269716
269814
|
})();
|
|
269717
269815
|
return versionPromise;
|
|
269718
269816
|
}
|
|
@@ -269968,8 +270066,11 @@ var IdeClient = class _IdeClient {
|
|
|
269968
270066
|
if (textPart?.text) {
|
|
269969
270067
|
try {
|
|
269970
270068
|
const parsedJson = JSON.parse(textPart.text);
|
|
269971
|
-
if (parsedJson
|
|
269972
|
-
|
|
270069
|
+
if (parsedJson) {
|
|
270070
|
+
const content = parsedJson.content;
|
|
270071
|
+
if (typeof content === "string") {
|
|
270072
|
+
return content;
|
|
270073
|
+
}
|
|
269973
270074
|
}
|
|
269974
270075
|
if (parsedJson && parsedJson.content === null) {
|
|
269975
270076
|
return void 0;
|
|
@@ -270735,25 +270836,36 @@ function cloneChain(chain2) {
|
|
|
270735
270836
|
return chain2.map(clonePolicy);
|
|
270736
270837
|
}
|
|
270737
270838
|
|
|
270839
|
+
// packages/core/src/utils/modelUtils.ts
|
|
270840
|
+
function normalizeModelId(modelId) {
|
|
270841
|
+
return modelId.startsWith("models/") ? modelId.slice(7) : modelId;
|
|
270842
|
+
}
|
|
270843
|
+
|
|
270738
270844
|
// packages/core/src/availability/policyHelpers.ts
|
|
270739
270845
|
function resolvePolicyChain(config2, preferredModel, wrapsAround = false) {
|
|
270740
|
-
const
|
|
270741
|
-
const
|
|
270846
|
+
const normalizedPreferredModel = preferredModel ? normalizeModelId(preferredModel) : void 0;
|
|
270847
|
+
const modelFromConfig = normalizeModelId(
|
|
270848
|
+
normalizedPreferredModel ?? config2.getActiveModel?.() ?? config2.getModel()
|
|
270849
|
+
);
|
|
270850
|
+
const configuredModel = normalizeModelId(config2.getModel());
|
|
270742
270851
|
let chain2;
|
|
270743
270852
|
const useGemini31 = config2.getGemini31LaunchedSync?.() ?? false;
|
|
270744
270853
|
const useGemini31FlashLite = config2.getGemini31FlashLiteLaunchedSync?.() ?? false;
|
|
270745
270854
|
const useCustomToolModel = config2.getUseCustomToolModelSync?.() ?? false;
|
|
270746
270855
|
const hasAccessToPreview = config2.getHasAccessToPreviewModel?.() ?? true;
|
|
270747
|
-
const resolvedModel =
|
|
270748
|
-
|
|
270749
|
-
|
|
270750
|
-
|
|
270751
|
-
|
|
270752
|
-
|
|
270753
|
-
|
|
270856
|
+
const resolvedModel = normalizeModelId(
|
|
270857
|
+
resolveModel(
|
|
270858
|
+
modelFromConfig,
|
|
270859
|
+
useGemini31,
|
|
270860
|
+
useGemini31FlashLite,
|
|
270861
|
+
useCustomToolModel,
|
|
270862
|
+
hasAccessToPreview,
|
|
270863
|
+
config2
|
|
270864
|
+
)
|
|
270754
270865
|
);
|
|
270755
|
-
const isAutoPreferred =
|
|
270866
|
+
const isAutoPreferred = normalizedPreferredModel ? isAutoModel(normalizedPreferredModel, config2) : false;
|
|
270756
270867
|
const isAutoConfigured = isAutoModel(configuredModel, config2);
|
|
270868
|
+
const effectiveWrapsAround = wrapsAround || isAutoPreferred || isAutoConfigured || isGemini3Model(resolvedModel, config2);
|
|
270757
270869
|
if (config2.getExperimentalDynamicModelConfiguration?.() === true) {
|
|
270758
270870
|
const context2 = {
|
|
270759
270871
|
useGemini3_1: useGemini31,
|
|
@@ -270762,7 +270874,7 @@ function resolvePolicyChain(config2, preferredModel, wrapsAround = false) {
|
|
|
270762
270874
|
};
|
|
270763
270875
|
if (resolvedModel === DEFAULT_GEMINI_FLASH_LITE_MODEL) {
|
|
270764
270876
|
chain2 = config2.modelConfigService.resolveChain("lite", context2);
|
|
270765
|
-
} else if (isGemini3Model(resolvedModel, config2) || isAutoPreferred || isAutoConfigured) {
|
|
270877
|
+
} else if (isGemini3Model(normalizeModelId(resolvedModel), config2) || isAutoPreferred || isAutoConfigured) {
|
|
270766
270878
|
if (isAutoConfigured && config2.modelConfigService.getModelChain(configuredModel)) {
|
|
270767
270879
|
chain2 = config2.modelConfigService.resolveChain(
|
|
270768
270880
|
configuredModel,
|
|
@@ -270771,7 +270883,7 @@ function resolvePolicyChain(config2, preferredModel, wrapsAround = false) {
|
|
|
270771
270883
|
}
|
|
270772
270884
|
if (!chain2) {
|
|
270773
270885
|
const isAutoSelection = isAutoPreferred || isAutoConfigured;
|
|
270774
|
-
const previewEnabled = hasAccessToPreview && (isGemini3Model(resolvedModel, config2) ||
|
|
270886
|
+
const previewEnabled = hasAccessToPreview && (isGemini3Model(resolvedModel, config2) || normalizedPreferredModel === PREVIEW_GEMINI_MODEL_AUTO || configuredModel === PREVIEW_GEMINI_MODEL_AUTO);
|
|
270775
270887
|
const autoPrefix = isAutoSelection ? "auto-" : "";
|
|
270776
270888
|
const chainKey = previewEnabled ? "preview" : "default";
|
|
270777
270889
|
chain2 = config2.modelConfigService.resolveChain(
|
|
@@ -270783,14 +270895,14 @@ function resolvePolicyChain(config2, preferredModel, wrapsAround = false) {
|
|
|
270783
270895
|
if (!chain2) {
|
|
270784
270896
|
chain2 = createSingleModelChain(modelFromConfig);
|
|
270785
270897
|
}
|
|
270786
|
-
chain2 = applyDynamicSlicing(chain2, resolvedModel,
|
|
270898
|
+
chain2 = applyDynamicSlicing(chain2, resolvedModel, effectiveWrapsAround);
|
|
270787
270899
|
} else {
|
|
270788
270900
|
if (resolvedModel === DEFAULT_GEMINI_FLASH_LITE_MODEL) {
|
|
270789
270901
|
chain2 = getFlashLitePolicyChain();
|
|
270790
270902
|
} else if (isGemini3Model(resolvedModel, config2) || isAutoPreferred || isAutoConfigured) {
|
|
270791
270903
|
const isAutoSelection = isAutoPreferred || isAutoConfigured;
|
|
270792
270904
|
if (hasAccessToPreview) {
|
|
270793
|
-
const previewEnabled = isGemini3Model(resolvedModel, config2) ||
|
|
270905
|
+
const previewEnabled = isGemini3Model(resolvedModel, config2) || normalizedPreferredModel === PREVIEW_GEMINI_MODEL_AUTO || configuredModel === PREVIEW_GEMINI_MODEL_AUTO;
|
|
270794
270906
|
chain2 = getModelPolicyChain({
|
|
270795
270907
|
previewEnabled,
|
|
270796
270908
|
isAutoSelection,
|
|
@@ -270812,7 +270924,7 @@ function resolvePolicyChain(config2, preferredModel, wrapsAround = false) {
|
|
|
270812
270924
|
} else {
|
|
270813
270925
|
chain2 = createSingleModelChain(modelFromConfig);
|
|
270814
270926
|
}
|
|
270815
|
-
chain2 = applyDynamicSlicing(chain2, resolvedModel,
|
|
270927
|
+
chain2 = applyDynamicSlicing(chain2, resolvedModel, effectiveWrapsAround);
|
|
270816
270928
|
}
|
|
270817
270929
|
if (config2?.getApprovalMode?.() === "plan" /* PLAN */) {
|
|
270818
270930
|
return chain2.map((policy) => ({
|
|
@@ -270823,8 +270935,9 @@ function resolvePolicyChain(config2, preferredModel, wrapsAround = false) {
|
|
|
270823
270935
|
return chain2;
|
|
270824
270936
|
}
|
|
270825
270937
|
function applyDynamicSlicing(chain2, resolvedModel, wrapsAround) {
|
|
270938
|
+
const normalizedResolved = normalizeModelId(resolvedModel);
|
|
270826
270939
|
const activeIndex = chain2.findIndex(
|
|
270827
|
-
(policy) => policy.model ===
|
|
270940
|
+
(policy) => normalizeModelId(policy.model) === normalizedResolved
|
|
270828
270941
|
);
|
|
270829
270942
|
if (activeIndex !== -1) {
|
|
270830
270943
|
return wrapsAround ? [...chain2.slice(activeIndex), ...chain2.slice(0, activeIndex)] : [...chain2.slice(activeIndex)];
|
|
@@ -270832,7 +270945,10 @@ function applyDynamicSlicing(chain2, resolvedModel, wrapsAround) {
|
|
|
270832
270945
|
return [createDefaultPolicy(resolvedModel, { isLastResort: true })];
|
|
270833
270946
|
}
|
|
270834
270947
|
function buildFallbackPolicyContext(chain2, failedModel, wrapsAround = false) {
|
|
270835
|
-
const
|
|
270948
|
+
const normalizedFailed = normalizeModelId(failedModel);
|
|
270949
|
+
const index = chain2.findIndex(
|
|
270950
|
+
(policy) => normalizeModelId(policy.model) === normalizedFailed
|
|
270951
|
+
);
|
|
270836
270952
|
if (index === -1) {
|
|
270837
270953
|
return { failedPolicy: void 0, candidates: chain2 };
|
|
270838
270954
|
}
|
|
@@ -271475,9 +271591,14 @@ var BaseLlmClient = class {
|
|
|
271475
271591
|
"generateJson",
|
|
271476
271592
|
role
|
|
271477
271593
|
);
|
|
271478
|
-
|
|
271594
|
+
const parsed = JSON.parse(
|
|
271479
271595
|
this.cleanJsonResponse(getResponseText(result2).trim(), model)
|
|
271480
271596
|
);
|
|
271597
|
+
const isRecord3 = (val) => typeof val === "object" && val !== null && !Array.isArray(val);
|
|
271598
|
+
if (isRecord3(parsed)) {
|
|
271599
|
+
return parsed;
|
|
271600
|
+
}
|
|
271601
|
+
throw new Error("Invalid JSON response format from LLM");
|
|
271481
271602
|
}
|
|
271482
271603
|
async generateEmbedding(texts) {
|
|
271483
271604
|
if (!texts || texts.length === 0) {
|
|
@@ -271518,6 +271639,15 @@ var BaseLlmClient = class {
|
|
|
271518
271639
|
}
|
|
271519
271640
|
return text;
|
|
271520
271641
|
}
|
|
271642
|
+
async countTokens(options) {
|
|
271643
|
+
const model = options.modelConfigKey ? this.config.modelConfigService.getResolvedConfig(options.modelConfigKey).model : this.config.getActiveModel();
|
|
271644
|
+
const result2 = await this.contentGenerator.countTokens({
|
|
271645
|
+
model,
|
|
271646
|
+
contents: options.contents,
|
|
271647
|
+
config: options.abortSignal ? { abortSignal: options.abortSignal } : void 0
|
|
271648
|
+
});
|
|
271649
|
+
return { totalTokens: result2.totalTokens || 0 };
|
|
271650
|
+
}
|
|
271521
271651
|
async generateContent(options) {
|
|
271522
271652
|
const {
|
|
271523
271653
|
modelConfigKey,
|
|
@@ -272190,6 +272320,9 @@ function isEditToolParams(args2) {
|
|
|
272190
272320
|
}
|
|
272191
272321
|
return "file_path" in args2 && typeof args2.file_path === "string" && "old_string" in args2 && typeof args2.old_string === "string" && "new_string" in args2 && typeof args2.new_string === "string";
|
|
272192
272322
|
}
|
|
272323
|
+
function fileDiffToSummary(diff, editData) {
|
|
272324
|
+
return diff.diffStat ? `${diff.diffStat.model_added_lines} added, ${diff.diffStat.model_removed_lines} removed` : `${editData.occurrences} replacements`;
|
|
272325
|
+
}
|
|
272193
272326
|
var EditToolInvocation = class extends BaseToolInvocation {
|
|
272194
272327
|
constructor(config2, params, messageBus, toolName, displayName) {
|
|
272195
272328
|
super(
|
|
@@ -272632,8 +272765,20 @@ ${snippet2}`);
|
|
|
272632
272765
|
if (jitContext) {
|
|
272633
272766
|
llmContent = appendJitContext(llmContent, jitContext);
|
|
272634
272767
|
}
|
|
272768
|
+
const resultSummary = typeof displayResult === "string" ? displayResult : fileDiffToSummary(displayResult, editData);
|
|
272635
272769
|
return {
|
|
272636
272770
|
llmContent,
|
|
272771
|
+
display: {
|
|
272772
|
+
name: this._toolDisplayName,
|
|
272773
|
+
description: this.getDescription(),
|
|
272774
|
+
resultSummary,
|
|
272775
|
+
result: {
|
|
272776
|
+
type: "diff",
|
|
272777
|
+
path: this.resolvedPath,
|
|
272778
|
+
beforeText: editData.currentContent ?? "",
|
|
272779
|
+
afterText: editData.newContent
|
|
272780
|
+
}
|
|
272781
|
+
},
|
|
272637
272782
|
returnDisplay: displayResult
|
|
272638
272783
|
};
|
|
272639
272784
|
} catch (error40) {
|
|
@@ -273272,6 +273417,17 @@ ${snippet2}`);
|
|
|
273272
273417
|
}
|
|
273273
273418
|
return {
|
|
273274
273419
|
llmContent,
|
|
273420
|
+
display: {
|
|
273421
|
+
name: WRITE_FILE_DISPLAY_NAME,
|
|
273422
|
+
description: this.getDescription(),
|
|
273423
|
+
resultSummary: diffStat ? `${diffStat.model_added_lines} added, ${diffStat.model_removed_lines} removed` : "Written",
|
|
273424
|
+
result: {
|
|
273425
|
+
type: "diff",
|
|
273426
|
+
path: this.resolvedPath,
|
|
273427
|
+
beforeText: correctedContentResult.originalContent ?? "",
|
|
273428
|
+
afterText: correctedContentResult.correctedContent
|
|
273429
|
+
}
|
|
273430
|
+
},
|
|
273275
273431
|
returnDisplay: displayResult
|
|
273276
273432
|
};
|
|
273277
273433
|
} catch (error40) {
|
|
@@ -274111,6 +274267,14 @@ var ProjectIdRequiredError = class extends Error {
|
|
|
274111
274267
|
this.name = "ProjectIdRequiredError";
|
|
274112
274268
|
}
|
|
274113
274269
|
};
|
|
274270
|
+
var InvalidNumericProjectIdError = class extends Error {
|
|
274271
|
+
constructor(projectId) {
|
|
274272
|
+
super(
|
|
274273
|
+
`Invalid Google Cloud Project ID: "${projectId}". The GOOGLE_CLOUD_PROJECT (or GOOGLE_CLOUD_PROJECT_ID) environment variable must be set to your string-based Project ID (e.g., "my-project-123"), not your numeric Project Number. Please update your environment variables.`
|
|
274274
|
+
);
|
|
274275
|
+
this.name = "InvalidNumericProjectIdError";
|
|
274276
|
+
}
|
|
274277
|
+
};
|
|
274114
274278
|
var ValidationCancelledError = class extends Error {
|
|
274115
274279
|
constructor() {
|
|
274116
274280
|
super("User cancelled account validation");
|
|
@@ -274136,6 +274300,9 @@ function resetUserDataCacheForTesting() {
|
|
|
274136
274300
|
}
|
|
274137
274301
|
async function setupUser(client, config2, httpOptions = {}) {
|
|
274138
274302
|
const projectId = process.env["GOOGLE_CLOUD_PROJECT"] || process.env["GOOGLE_CLOUD_PROJECT_ID"] || void 0;
|
|
274303
|
+
if (projectId && /^\d+$/.test(projectId)) {
|
|
274304
|
+
throw new InvalidNumericProjectIdError(projectId);
|
|
274305
|
+
}
|
|
274139
274306
|
const projectCache = userDataCache.getOrCreate(
|
|
274140
274307
|
client,
|
|
274141
274308
|
() => createCache({
|
|
@@ -274315,13 +274482,26 @@ function validateLoadCodeAssistResponse(res) {
|
|
|
274315
274482
|
|
|
274316
274483
|
// packages/core/src/utils/quotaErrorDetection.ts
|
|
274317
274484
|
function isApiError(error40) {
|
|
274318
|
-
|
|
274319
|
-
|
|
274320
|
-
|
|
274485
|
+
if (typeof error40 !== "object" || error40 === null || !("error" in error40)) {
|
|
274486
|
+
return false;
|
|
274487
|
+
}
|
|
274488
|
+
const errorProp = error40.error;
|
|
274489
|
+
if (typeof errorProp !== "object" || errorProp === null) {
|
|
274490
|
+
return false;
|
|
274491
|
+
}
|
|
274492
|
+
return "code" in errorProp && typeof errorProp.code === "number" && "message" in errorProp && typeof errorProp.message === "string" && "status" in errorProp && typeof errorProp.status === "string";
|
|
274321
274493
|
}
|
|
274322
274494
|
function isStructuredError(error40) {
|
|
274323
|
-
|
|
274324
|
-
|
|
274495
|
+
if (typeof error40 !== "object" || error40 === null || !("message" in error40)) {
|
|
274496
|
+
return false;
|
|
274497
|
+
}
|
|
274498
|
+
if (typeof error40.message !== "string") {
|
|
274499
|
+
return false;
|
|
274500
|
+
}
|
|
274501
|
+
if ("status" in error40 && typeof error40.status !== "number") {
|
|
274502
|
+
return false;
|
|
274503
|
+
}
|
|
274504
|
+
return true;
|
|
274325
274505
|
}
|
|
274326
274506
|
|
|
274327
274507
|
// packages/core/src/utils/tokenCalculation.ts
|
|
@@ -274338,9 +274518,10 @@ function estimateTextTokens(text, charsPerToken) {
|
|
|
274338
274518
|
return text.length / charsPerToken;
|
|
274339
274519
|
}
|
|
274340
274520
|
let tokens = 0;
|
|
274521
|
+
const asciiTokensPerChar = 1 / charsPerToken;
|
|
274341
274522
|
for (let i3 = 0; i3 < text.length; i3++) {
|
|
274342
274523
|
if (text.charCodeAt(i3) <= 127) {
|
|
274343
|
-
tokens +=
|
|
274524
|
+
tokens += asciiTokensPerChar;
|
|
274344
274525
|
} else {
|
|
274345
274526
|
tokens += NON_ASCII_TOKENS_PER_CHAR;
|
|
274346
274527
|
}
|
|
@@ -274953,10 +275134,12 @@ var FakeContentGenerator = class _FakeContentGenerator {
|
|
|
274953
275134
|
return response.response;
|
|
274954
275135
|
}
|
|
274955
275136
|
async generateContent(request, _userPromptId, role) {
|
|
274956
|
-
|
|
274957
|
-
|
|
274958
|
-
|
|
274959
|
-
|
|
275137
|
+
const response = this.getNextResponse("generateContent", request);
|
|
275138
|
+
Object.setPrototypeOf(response, GenerateContentResponse.prototype);
|
|
275139
|
+
if (response instanceof GenerateContentResponse) {
|
|
275140
|
+
return response;
|
|
275141
|
+
}
|
|
275142
|
+
throw new Error("Failed to create GenerateContentResponse");
|
|
274960
275143
|
}
|
|
274961
275144
|
async generateContentStream(request, _userPromptId, role) {
|
|
274962
275145
|
const responses = this.getNextResponse("generateContentStream", request);
|
|
@@ -274974,10 +275157,12 @@ var FakeContentGenerator = class _FakeContentGenerator {
|
|
|
274974
275157
|
return this.getNextResponse("countTokens", request);
|
|
274975
275158
|
}
|
|
274976
275159
|
async embedContent(request) {
|
|
274977
|
-
|
|
274978
|
-
|
|
274979
|
-
|
|
274980
|
-
|
|
275160
|
+
const response = this.getNextResponse("embedContent", request);
|
|
275161
|
+
Object.setPrototypeOf(response, EmbedContentResponse.prototype);
|
|
275162
|
+
if (response instanceof EmbedContentResponse) {
|
|
275163
|
+
return response;
|
|
275164
|
+
}
|
|
275165
|
+
throw new Error("Failed to create EmbedContentResponse");
|
|
274981
275166
|
}
|
|
274982
275167
|
};
|
|
274983
275168
|
|
|
@@ -275143,10 +275328,6 @@ function validateBaseUrl(baseUrl) {
|
|
|
275143
275328
|
}
|
|
275144
275329
|
}
|
|
275145
275330
|
async function createContentGeneratorConfig(config2, authType, apiKey, baseUrl, customHeaders, vertexAiRouting) {
|
|
275146
|
-
const geminiApiKey = apiKey || process.env["GEMINI_API_KEY"] || await loadApiKey() || void 0;
|
|
275147
|
-
const googleApiKey = process.env["GOOGLE_API_KEY"] || void 0;
|
|
275148
|
-
const googleCloudProject = process.env["GOOGLE_CLOUD_PROJECT"] || process.env["GOOGLE_CLOUD_PROJECT_ID"] || void 0;
|
|
275149
|
-
const googleCloudLocation = process.env["GOOGLE_CLOUD_LOCATION"] || void 0;
|
|
275150
275331
|
const contentGeneratorConfig = {
|
|
275151
275332
|
authType,
|
|
275152
275333
|
proxy: config2?.getProxy(),
|
|
@@ -275157,6 +275338,10 @@ async function createContentGeneratorConfig(config2, authType, apiKey, baseUrl,
|
|
|
275157
275338
|
if (authType === "oauth-personal" /* LOGIN_WITH_GOOGLE */ || authType === "compute-default-credentials" /* COMPUTE_ADC */) {
|
|
275158
275339
|
return contentGeneratorConfig;
|
|
275159
275340
|
}
|
|
275341
|
+
const geminiApiKey = apiKey || process.env["GEMINI_API_KEY"] || await loadApiKey() || void 0;
|
|
275342
|
+
const googleApiKey = process.env["GOOGLE_API_KEY"] || void 0;
|
|
275343
|
+
const googleCloudProject = process.env["GOOGLE_CLOUD_PROJECT"] || process.env["GOOGLE_CLOUD_PROJECT_ID"] || void 0;
|
|
275344
|
+
const googleCloudLocation = process.env["GOOGLE_CLOUD_LOCATION"] || void 0;
|
|
275160
275345
|
if (authType === "gemini-api-key" /* USE_GEMINI */ && geminiApiKey) {
|
|
275161
275346
|
contentGeneratorConfig.apiKey = geminiApiKey;
|
|
275162
275347
|
contentGeneratorConfig.vertexai = false;
|
|
@@ -276185,6 +276370,11 @@ ${directoryContent}`;
|
|
|
276185
276370
|
}
|
|
276186
276371
|
return {
|
|
276187
276372
|
llmContent: resultMessage,
|
|
276373
|
+
display: {
|
|
276374
|
+
name: LS_DISPLAY_NAME,
|
|
276375
|
+
description: this.getDescription(),
|
|
276376
|
+
resultSummary: displayMessage
|
|
276377
|
+
},
|
|
276188
276378
|
returnDisplay: {
|
|
276189
276379
|
summary: displayMessage,
|
|
276190
276380
|
files: entries.map(
|
|
@@ -276462,7 +276652,9 @@ var IgnoreFileParser = class {
|
|
|
276462
276652
|
return this.patterns;
|
|
276463
276653
|
}
|
|
276464
276654
|
getIgnoreFilePaths() {
|
|
276465
|
-
return this.fileNames.slice().reverse().map((fileName) => path39.join(this.projectRoot, fileName)).filter(
|
|
276655
|
+
return this.fileNames.slice().reverse().map((fileName) => path39.join(this.projectRoot, fileName)).filter(
|
|
276656
|
+
(filePath) => fs34.statSync(filePath, { throwIfNoEntry: false })?.isFile() ?? false
|
|
276657
|
+
);
|
|
276466
276658
|
}
|
|
276467
276659
|
/**
|
|
276468
276660
|
* Returns true if at least one ignore file exists and has patterns.
|
|
@@ -276701,7 +276893,8 @@ var FileDiscoveryService = class {
|
|
|
276701
276893
|
const paths = [];
|
|
276702
276894
|
if (this.gitIgnoreFilter && this.defaultFilterFileOptions.respectGitIgnore) {
|
|
276703
276895
|
const gitIgnorePath = path41.join(this.projectRoot, ".gitignore");
|
|
276704
|
-
|
|
276896
|
+
const stat9 = fs36.statSync(gitIgnorePath, { throwIfNoEntry: false });
|
|
276897
|
+
if (stat9?.isFile()) {
|
|
276705
276898
|
paths.push(gitIgnorePath);
|
|
276706
276899
|
}
|
|
276707
276900
|
}
|
|
@@ -276810,8 +277003,15 @@ ${result2.llmContent}`;
|
|
|
276810
277003
|
llmContent = appendJitContextToParts(llmContent, jitContext);
|
|
276811
277004
|
}
|
|
276812
277005
|
}
|
|
277006
|
+
const displayResultSummary = result2.isTruncated ? `${result2.linesShown[0]}-${result2.linesShown[1]} of ${result2.originalLineCount}` : lines !== void 0 ? `${lines} lines` : void 0;
|
|
276813
277007
|
return {
|
|
276814
277008
|
llmContent,
|
|
277009
|
+
display: {
|
|
277010
|
+
name: READ_FILE_DISPLAY_NAME,
|
|
277011
|
+
description: this.getDescription(),
|
|
277012
|
+
resultSummary: displayResultSummary,
|
|
277013
|
+
result: { type: "text", text: result2.returnDisplay || "" }
|
|
277014
|
+
},
|
|
276815
277015
|
returnDisplay: result2.returnDisplay || ""
|
|
276816
277016
|
};
|
|
276817
277017
|
}
|
|
@@ -276851,12 +277051,6 @@ var ReadFileTool = class _ReadFileTool extends BaseDeclarativeTool {
|
|
|
276851
277051
|
if (validationError) {
|
|
276852
277052
|
return validationError;
|
|
276853
277053
|
}
|
|
276854
|
-
if (params.start_line !== void 0 && params.start_line < 1) {
|
|
276855
|
-
return "start_line must be at least 1";
|
|
276856
|
-
}
|
|
276857
|
-
if (params.end_line !== void 0 && params.end_line < 1) {
|
|
276858
|
-
return "end_line must be at least 1";
|
|
276859
|
-
}
|
|
276860
277054
|
if (params.start_line !== void 0 && params.end_line !== void 0 && params.start_line > params.end_line) {
|
|
276861
277055
|
return "start_line cannot be greater than end_line";
|
|
276862
277056
|
}
|
|
@@ -283127,10 +283321,10 @@ var Ignore = class {
|
|
|
283127
283321
|
ignored(p) {
|
|
283128
283322
|
const fullpath = p.fullpath();
|
|
283129
283323
|
const fullpaths = `${fullpath}/`;
|
|
283130
|
-
const
|
|
283131
|
-
const relatives = `${
|
|
283324
|
+
const relative11 = p.relative() || ".";
|
|
283325
|
+
const relatives = `${relative11}/`;
|
|
283132
283326
|
for (const m of this.relative) {
|
|
283133
|
-
if (m.match(
|
|
283327
|
+
if (m.match(relative11) || m.match(relatives))
|
|
283134
283328
|
return true;
|
|
283135
283329
|
}
|
|
283136
283330
|
for (const m of this.absolute) {
|
|
@@ -283141,9 +283335,9 @@ var Ignore = class {
|
|
|
283141
283335
|
}
|
|
283142
283336
|
childrenIgnored(p) {
|
|
283143
283337
|
const fullpath = p.fullpath() + "/";
|
|
283144
|
-
const
|
|
283338
|
+
const relative11 = (p.relative() || ".") + "/";
|
|
283145
283339
|
for (const m of this.relativeChildren) {
|
|
283146
|
-
if (m.match(
|
|
283340
|
+
if (m.match(relative11))
|
|
283147
283341
|
return true;
|
|
283148
283342
|
}
|
|
283149
283343
|
for (const m of this.absoluteChildren) {
|
|
@@ -284255,12 +284449,24 @@ var GrepToolInvocation = class extends BaseToolInvocation {
|
|
|
284255
284449
|
} else {
|
|
284256
284450
|
searchLocationDescription = `in path "${searchDirDisplay}"`;
|
|
284257
284451
|
}
|
|
284258
|
-
|
|
284452
|
+
const result2 = await formatGrepResults(
|
|
284259
284453
|
allMatches,
|
|
284260
284454
|
this.params,
|
|
284261
284455
|
searchLocationDescription,
|
|
284262
284456
|
totalMaxMatches
|
|
284263
284457
|
);
|
|
284458
|
+
return {
|
|
284459
|
+
...result2,
|
|
284460
|
+
display: {
|
|
284461
|
+
name: this._toolDisplayName,
|
|
284462
|
+
description: this.getDescription(),
|
|
284463
|
+
resultSummary: result2.returnDisplay.summary,
|
|
284464
|
+
result: {
|
|
284465
|
+
type: "text",
|
|
284466
|
+
text: result2.llmContent.split("\n---\n").slice(1).join("\n---\n")
|
|
284467
|
+
}
|
|
284468
|
+
}
|
|
284469
|
+
};
|
|
284264
284470
|
} catch (error40) {
|
|
284265
284471
|
debugLogger.warn(`Error during GrepLogic execution: ${error40}`);
|
|
284266
284472
|
const errorMessage = getErrorMessage(error40);
|
|
@@ -284791,12 +284997,24 @@ var GrepToolInvocation2 = class extends BaseToolInvocation {
|
|
|
284791
284997
|
timeoutController.signal
|
|
284792
284998
|
);
|
|
284793
284999
|
const searchLocationDescription = `in path "${searchDirDisplay}"`;
|
|
284794
|
-
|
|
285000
|
+
const result2 = await formatGrepResults(
|
|
284795
285001
|
allMatches,
|
|
284796
285002
|
this.params,
|
|
284797
285003
|
searchLocationDescription,
|
|
284798
285004
|
totalMaxMatches
|
|
284799
285005
|
);
|
|
285006
|
+
return {
|
|
285007
|
+
...result2,
|
|
285008
|
+
display: {
|
|
285009
|
+
name: this._toolDisplayName,
|
|
285010
|
+
description: this.getDescription(),
|
|
285011
|
+
resultSummary: result2.returnDisplay.summary,
|
|
285012
|
+
result: {
|
|
285013
|
+
type: "text",
|
|
285014
|
+
text: result2.llmContent.split("\n---\n").slice(1).join("\n---\n")
|
|
285015
|
+
}
|
|
285016
|
+
}
|
|
285017
|
+
};
|
|
284800
285018
|
} catch (error40) {
|
|
284801
285019
|
debugLogger.warn(`Error during GrepLogic execution: ${error40}`);
|
|
284802
285020
|
const errorMessage = getErrorMessage(error40);
|
|
@@ -288606,8 +288824,18 @@ ${result2.output}`;
|
|
|
288606
288824
|
...executionError
|
|
288607
288825
|
};
|
|
288608
288826
|
}
|
|
288827
|
+
const displayResultSummary = result2.backgrounded ? `PID: ${result2.pid}` : result2.exitCode !== null && result2.exitCode !== 0 ? `Exit Code: ${result2.exitCode}` : void 0;
|
|
288609
288828
|
return {
|
|
288610
288829
|
llmContent,
|
|
288830
|
+
display: {
|
|
288831
|
+
name: "Shell",
|
|
288832
|
+
description: this.getDescription(),
|
|
288833
|
+
resultSummary: displayResultSummary,
|
|
288834
|
+
result: typeof returnDisplay === "string" ? { type: "text", text: returnDisplay } : (
|
|
288835
|
+
// TODO: Add support for terminal display type (AnsiOutput)
|
|
288836
|
+
void 0
|
|
288837
|
+
)
|
|
288838
|
+
},
|
|
288611
288839
|
returnDisplay,
|
|
288612
288840
|
data,
|
|
288613
288841
|
...executionError
|
|
@@ -294844,6 +295072,11 @@ Strategic Intent: ${strategicIntent.trim()}`;
|
|
|
294844
295072
|
}
|
|
294845
295073
|
return {
|
|
294846
295074
|
llmContent,
|
|
295075
|
+
display: {
|
|
295076
|
+
format: "notice",
|
|
295077
|
+
name: title || UPDATE_TOPIC_DISPLAY_NAME,
|
|
295078
|
+
description: this.getDescription()
|
|
295079
|
+
},
|
|
294847
295080
|
returnDisplay
|
|
294848
295081
|
};
|
|
294849
295082
|
}
|
|
@@ -295310,6 +295543,9 @@ var GeminiChat = class {
|
|
|
295310
295543
|
lastPromptTokenCount;
|
|
295311
295544
|
callCounter = 0;
|
|
295312
295545
|
agentHistory;
|
|
295546
|
+
get loopContext() {
|
|
295547
|
+
return this.context;
|
|
295548
|
+
}
|
|
295313
295549
|
async initialize(resumedSessionData, kind = "main") {
|
|
295314
295550
|
await this.chatRecordingService.initialize(resumedSessionData, kind);
|
|
295315
295551
|
}
|
|
@@ -295626,10 +295862,11 @@ var GeminiChat = class {
|
|
|
295626
295862
|
lastModelToUse = modelToUse;
|
|
295627
295863
|
lastConfig = config2;
|
|
295628
295864
|
lastContentsToUse = contentsToUse;
|
|
295865
|
+
const finalContents = stripToolCallIdPrefixes(contentsToUse);
|
|
295629
295866
|
return this.context.config.getContentGenerator().generateContentStream(
|
|
295630
295867
|
{
|
|
295631
295868
|
model: modelToUse,
|
|
295632
|
-
contents:
|
|
295869
|
+
contents: finalContents,
|
|
295633
295870
|
config: config2
|
|
295634
295871
|
},
|
|
295635
295872
|
prompt_id,
|
|
@@ -295811,7 +296048,9 @@ This error was probably caused by cyclic schema references in one of the followi
|
|
|
295811
296048
|
const finalFunctionCallsMap = /* @__PURE__ */ new Map();
|
|
295812
296049
|
const legacyFunctionCalls = [];
|
|
295813
296050
|
const callIndexToId = /* @__PURE__ */ new Map();
|
|
296051
|
+
let runningFunctionCallCounter = 0;
|
|
295814
296052
|
for await (const chunk of streamResponse) {
|
|
296053
|
+
const currentChunkStartCounter = runningFunctionCallCounter;
|
|
295815
296054
|
const candidateWithReason = chunk?.candidates?.find(
|
|
295816
296055
|
(candidate) => candidate.finishReason
|
|
295817
296056
|
);
|
|
@@ -295822,20 +296061,32 @@ This error was probably caused by cyclic schema references in one of the followi
|
|
|
295822
296061
|
if (this.context.config.isContextManagementEnabled()) {
|
|
295823
296062
|
for (let i3 = 0; i3 < chunk.functionCalls.length; i3++) {
|
|
295824
296063
|
const fnCall = chunk.functionCalls[i3];
|
|
296064
|
+
const globalIndex = currentChunkStartCounter + i3;
|
|
295825
296065
|
if (!fnCall.id) {
|
|
295826
|
-
let id = callIndexToId.get(
|
|
296066
|
+
let id = callIndexToId.get(globalIndex);
|
|
295827
296067
|
if (!id) {
|
|
295828
296068
|
id = `synth_${this.context.promptId}_${Date.now()}_${this.callCounter++}`;
|
|
295829
|
-
callIndexToId.set(
|
|
296069
|
+
callIndexToId.set(globalIndex, id);
|
|
295830
296070
|
debugLogger.log(
|
|
295831
|
-
`[GeminiChat] Assigned synthetic ID: ${id} to tool at index ${
|
|
296071
|
+
`[GeminiChat] Assigned synthetic ID: ${id} to tool at index ${globalIndex}: ${fnCall.name}`
|
|
295832
296072
|
);
|
|
295833
296073
|
}
|
|
295834
296074
|
fnCall.id = id;
|
|
295835
296075
|
}
|
|
296076
|
+
const name3 = fnCall.name?.trim() || "generic_tool";
|
|
296077
|
+
if (fnCall.id && !fnCall.id.startsWith(`${name3}__`)) {
|
|
296078
|
+
fnCall.id = `${name3}__${fnCall.id}`;
|
|
296079
|
+
}
|
|
295836
296080
|
finalFunctionCallsMap.set(fnCall.id, fnCall);
|
|
295837
296081
|
}
|
|
296082
|
+
runningFunctionCallCounter += chunk.functionCalls.length;
|
|
295838
296083
|
} else {
|
|
296084
|
+
for (const fnCall of chunk.functionCalls) {
|
|
296085
|
+
const name3 = fnCall.name?.trim() || "generic_tool";
|
|
296086
|
+
if (fnCall.id && !fnCall.id.startsWith(`${name3}__`)) {
|
|
296087
|
+
fnCall.id = `${name3}__${fnCall.id}`;
|
|
296088
|
+
}
|
|
296089
|
+
}
|
|
295839
296090
|
legacyFunctionCalls.push(...chunk.functionCalls);
|
|
295840
296091
|
}
|
|
295841
296092
|
}
|
|
@@ -295849,16 +296100,19 @@ This error was probably caused by cyclic schema references in one of the followi
|
|
|
295849
296100
|
if (content.parts.some((part) => part.functionCall)) {
|
|
295850
296101
|
hasToolCall = true;
|
|
295851
296102
|
}
|
|
296103
|
+
let localFunctionCallCounter = 0;
|
|
295852
296104
|
modelResponseParts.push(
|
|
295853
296105
|
...content.parts.filter((part) => !part.thought).map((part) => {
|
|
295854
296106
|
if (!this.context.config.isContextManagementEnabled()) {
|
|
295855
296107
|
return part;
|
|
295856
296108
|
}
|
|
296109
|
+
let callIndex;
|
|
296110
|
+
if (part.functionCall) {
|
|
296111
|
+
callIndex = currentChunkStartCounter + localFunctionCallCounter++;
|
|
296112
|
+
}
|
|
295857
296113
|
return {
|
|
295858
296114
|
...part,
|
|
295859
|
-
callIndex
|
|
295860
|
-
(fc) => fc.name === part.functionCall?.name
|
|
295861
|
-
)
|
|
296115
|
+
callIndex
|
|
295862
296116
|
};
|
|
295863
296117
|
})
|
|
295864
296118
|
);
|
|
@@ -296028,6 +296282,95 @@ function isSchemaDepthError(errorMessage) {
|
|
|
296028
296282
|
function isInvalidArgumentError(errorMessage) {
|
|
296029
296283
|
return errorMessage.includes("Request contains an invalid argument");
|
|
296030
296284
|
}
|
|
296285
|
+
function stripToolCallIdPrefixes(contents) {
|
|
296286
|
+
return contents.map((content) => ({
|
|
296287
|
+
...content,
|
|
296288
|
+
parts: (content.parts || []).map((part) => {
|
|
296289
|
+
const newPart = { ...part };
|
|
296290
|
+
if (newPart.functionCall) {
|
|
296291
|
+
const fc = newPart.functionCall;
|
|
296292
|
+
const name3 = fc.name?.trim() || "generic_tool";
|
|
296293
|
+
if (fc.id && fc.id.startsWith(`${name3}__`)) {
|
|
296294
|
+
newPart.functionCall = {
|
|
296295
|
+
name: fc.name,
|
|
296296
|
+
args: fc.args,
|
|
296297
|
+
id: fc.id.substring(name3.length + 2)
|
|
296298
|
+
};
|
|
296299
|
+
}
|
|
296300
|
+
}
|
|
296301
|
+
if (newPart.functionResponse) {
|
|
296302
|
+
const fr = newPart.functionResponse;
|
|
296303
|
+
const name3 = fr.name?.trim() || "generic_tool";
|
|
296304
|
+
if (fr.id && fr.id.startsWith(`${name3}__`)) {
|
|
296305
|
+
newPart.functionResponse = {
|
|
296306
|
+
name: fr.name,
|
|
296307
|
+
response: fr.response,
|
|
296308
|
+
id: fr.id.substring(name3.length + 2)
|
|
296309
|
+
};
|
|
296310
|
+
}
|
|
296311
|
+
}
|
|
296312
|
+
return newPart;
|
|
296313
|
+
})
|
|
296314
|
+
}));
|
|
296315
|
+
}
|
|
296316
|
+
|
|
296317
|
+
// packages/core/src/agent/tool-display-utils.ts
|
|
296318
|
+
function populateToolDisplay({
|
|
296319
|
+
name: name3,
|
|
296320
|
+
invocation,
|
|
296321
|
+
resultDisplay,
|
|
296322
|
+
displayName,
|
|
296323
|
+
display: prevDisplay
|
|
296324
|
+
}) {
|
|
296325
|
+
const display = {
|
|
296326
|
+
name: displayName || name3,
|
|
296327
|
+
description: invocation?.getDescription?.(),
|
|
296328
|
+
...prevDisplay
|
|
296329
|
+
};
|
|
296330
|
+
if (resultDisplay !== void 0 && display.result === void 0) {
|
|
296331
|
+
display.result = toolResultDisplayToDisplayContent(resultDisplay);
|
|
296332
|
+
}
|
|
296333
|
+
return display;
|
|
296334
|
+
}
|
|
296335
|
+
function toolResultDisplayToDisplayContent(resultDisplay) {
|
|
296336
|
+
if (typeof resultDisplay === "string") {
|
|
296337
|
+
return { type: "text", text: resultDisplay };
|
|
296338
|
+
}
|
|
296339
|
+
if (typeof resultDisplay === "object" && resultDisplay !== null && "fileDiff" in resultDisplay && "newContent" in resultDisplay) {
|
|
296340
|
+
return {
|
|
296341
|
+
type: "diff",
|
|
296342
|
+
path: resultDisplay.filePath || resultDisplay.fileName,
|
|
296343
|
+
beforeText: resultDisplay.originalContent ?? "",
|
|
296344
|
+
afterText: resultDisplay.newContent
|
|
296345
|
+
};
|
|
296346
|
+
}
|
|
296347
|
+
return {
|
|
296348
|
+
type: "text",
|
|
296349
|
+
text: JSON.stringify(resultDisplay)
|
|
296350
|
+
};
|
|
296351
|
+
}
|
|
296352
|
+
function renderDisplayDiff(diff) {
|
|
296353
|
+
return createPatch(
|
|
296354
|
+
diff.path || "file",
|
|
296355
|
+
diff.beforeText,
|
|
296356
|
+
diff.afterText,
|
|
296357
|
+
"Original",
|
|
296358
|
+
"Modified",
|
|
296359
|
+
{ context: 3 }
|
|
296360
|
+
);
|
|
296361
|
+
}
|
|
296362
|
+
function displayContentToString(display) {
|
|
296363
|
+
if (!display) {
|
|
296364
|
+
return void 0;
|
|
296365
|
+
}
|
|
296366
|
+
if (display.type === "text") {
|
|
296367
|
+
return display.text;
|
|
296368
|
+
}
|
|
296369
|
+
if (display.type === "diff") {
|
|
296370
|
+
return renderDisplayDiff(display);
|
|
296371
|
+
}
|
|
296372
|
+
return JSON.stringify(display);
|
|
296373
|
+
}
|
|
296031
296374
|
|
|
296032
296375
|
// packages/core/src/core/turn.ts
|
|
296033
296376
|
var GeminiEventType = /* @__PURE__ */ ((GeminiEventType2) => {
|
|
@@ -296194,13 +296537,33 @@ ${[...this.pendingCitations].sort().join("\n")}`
|
|
|
296194
296537
|
}
|
|
296195
296538
|
}
|
|
296196
296539
|
handlePendingFunctionCall(fnCall, traceId) {
|
|
296197
|
-
const name3 = fnCall.name || "
|
|
296540
|
+
const name3 = fnCall.name?.trim() || "generic_tool";
|
|
296198
296541
|
const args2 = fnCall.args || {};
|
|
296199
|
-
const
|
|
296542
|
+
const rawCallId = fnCall.id ?? (this.chat.context.config.isContextManagementEnabled() ? `synth_${this.prompt_id}_${Date.now()}_${this.callCounter++}` : `${name3}_${Date.now()}_${this.callCounter++}`);
|
|
296543
|
+
const callId = rawCallId.startsWith(`${name3}__`) ? rawCallId : `${name3}__${rawCallId}`;
|
|
296544
|
+
fnCall.id = callId;
|
|
296545
|
+
const tool = this.chat.loopContext.toolRegistry.getTool(name3);
|
|
296546
|
+
let display;
|
|
296547
|
+
if (tool) {
|
|
296548
|
+
let invocation;
|
|
296549
|
+
try {
|
|
296550
|
+
invocation = tool.build(args2);
|
|
296551
|
+
} catch {
|
|
296552
|
+
}
|
|
296553
|
+
display = populateToolDisplay({
|
|
296554
|
+
name: name3,
|
|
296555
|
+
invocation,
|
|
296556
|
+
displayName: tool.displayName
|
|
296557
|
+
});
|
|
296558
|
+
if (!display.description) {
|
|
296559
|
+
display.description = tool.description;
|
|
296560
|
+
}
|
|
296561
|
+
}
|
|
296200
296562
|
const toolCallRequest = {
|
|
296201
296563
|
callId,
|
|
296202
296564
|
name: name3,
|
|
296203
296565
|
args: args2,
|
|
296566
|
+
display,
|
|
296204
296567
|
isClientInitiated: false,
|
|
296205
296568
|
prompt_id: this.prompt_id,
|
|
296206
296569
|
traceId
|
|
@@ -296337,7 +296700,7 @@ Use the following guidelines to optimize your search and read patterns.
|
|
|
296337
296700
|
- Prefer using tools like ${GREP_TOOL_NAME} to identify points of interest instead of reading lots of files individually.
|
|
296338
296701
|
- If you need to read multiple ranges in a file, do so parallel, in as few turns as possible.
|
|
296339
296702
|
- It is more important to reduce extra turns, but please also try to minimize unnecessarily large file reads and search results, when doing so doesn't result in extra turns. Do this by always providing conservative limits and scopes to tools like ${READ_FILE_TOOL_NAME} and ${GREP_TOOL_NAME}.
|
|
296340
|
-
- ${
|
|
296703
|
+
- ${EDIT_TOOL_NAME} fails if ${EDIT_PARAM_OLD_STRING} is ambiguous, causing extra turns. Take care to read enough with ${READ_FILE_TOOL_NAME} and ${GREP_TOOL_NAME} to make the edit unambiguous.
|
|
296341
296704
|
- You can compensate for the risk of missing results with scoped or limited searches by doing multiple searches in parallel.
|
|
296342
296705
|
- Your primary goal is still to do your best quality work. Efficiency is an important, but secondary concern.
|
|
296343
296706
|
</guidelines>
|
|
@@ -298930,6 +299293,13 @@ var SubagentActivityErrorType = /* @__PURE__ */ ((SubagentActivityErrorType2) =>
|
|
|
298930
299293
|
})(SubagentActivityErrorType || {});
|
|
298931
299294
|
var SUBAGENT_REJECTED_ERROR_PREFIX = "User rejected this operation.";
|
|
298932
299295
|
var SUBAGENT_CANCELLED_ERROR_MESSAGE = "Request cancelled.";
|
|
299296
|
+
var SubagentState = /* @__PURE__ */ ((SubagentState2) => {
|
|
299297
|
+
SubagentState2["RUNNING"] = "running";
|
|
299298
|
+
SubagentState2["COMPLETED"] = "completed";
|
|
299299
|
+
SubagentState2["ERROR"] = "error";
|
|
299300
|
+
SubagentState2["CANCELLED"] = "cancelled";
|
|
299301
|
+
return SubagentState2;
|
|
299302
|
+
})(SubagentState || {});
|
|
298933
299303
|
function isSubagentProgress(obj) {
|
|
298934
299304
|
return typeof obj === "object" && obj !== null && "isSubagentProgress" in obj && obj.isSubagentProgress === true;
|
|
298935
299305
|
}
|
|
@@ -303280,7 +303650,7 @@ var A2AAuthProviderFactory = class _A2AAuthProviderFactory {
|
|
|
303280
303650
|
return provider;
|
|
303281
303651
|
}
|
|
303282
303652
|
case "oauth2": {
|
|
303283
|
-
const { OAuth2AuthProvider } = await import("./oauth2-provider-
|
|
303653
|
+
const { OAuth2AuthProvider } = await import("./oauth2-provider-JNOY6NUI.js");
|
|
303284
303654
|
const provider = new OAuth2AuthProvider(
|
|
303285
303655
|
authConfig,
|
|
303286
303656
|
options.agentName ?? "unknown",
|
|
@@ -304629,10 +304999,12 @@ var SchedulerStateManager = class {
|
|
|
304629
304999
|
updateArgs(callId, newArgs, newInvocation) {
|
|
304630
305000
|
const call = this.activeCalls.get(callId);
|
|
304631
305001
|
if (!call || call.status === "error" /* Error */) return;
|
|
305002
|
+
const display = call.request.display ? { ...call.request.display } : { name: call.request.name };
|
|
305003
|
+
display.description = newInvocation.getDescription();
|
|
304632
305004
|
this.activeCalls.set(
|
|
304633
305005
|
callId,
|
|
304634
305006
|
this.patchCall(call, {
|
|
304635
|
-
request: { ...call.request, args: newArgs },
|
|
305007
|
+
request: { ...call.request, args: newArgs, display },
|
|
304636
305008
|
invocation: newInvocation
|
|
304637
305009
|
})
|
|
304638
305010
|
);
|
|
@@ -307016,9 +307388,41 @@ function createNodeTruncationProcessor(id, env2, options) {
|
|
|
307016
307388
|
import { randomUUID as randomUUID7 } from "node:crypto";
|
|
307017
307389
|
|
|
307018
307390
|
// packages/core/src/context/graph/types.ts
|
|
307391
|
+
var NodeType = /* @__PURE__ */ ((NodeType2) => {
|
|
307392
|
+
NodeType2["USER_PROMPT"] = "USER_PROMPT";
|
|
307393
|
+
NodeType2["SYSTEM_EVENT"] = "SYSTEM_EVENT";
|
|
307394
|
+
NodeType2["AGENT_THOUGHT"] = "AGENT_THOUGHT";
|
|
307395
|
+
NodeType2["TOOL_EXECUTION"] = "TOOL_EXECUTION";
|
|
307396
|
+
NodeType2["MASKED_TOOL"] = "MASKED_TOOL";
|
|
307397
|
+
NodeType2["AGENT_YIELD"] = "AGENT_YIELD";
|
|
307398
|
+
NodeType2["SNAPSHOT"] = "SNAPSHOT";
|
|
307399
|
+
NodeType2["ROLLING_SUMMARY"] = "ROLLING_SUMMARY";
|
|
307400
|
+
return NodeType2;
|
|
307401
|
+
})(NodeType || {});
|
|
307402
|
+
function isAgentThought(node) {
|
|
307403
|
+
return node.type === "AGENT_THOUGHT" /* AGENT_THOUGHT */;
|
|
307404
|
+
}
|
|
307405
|
+
function isAgentYield(node) {
|
|
307406
|
+
return node.type === "AGENT_YIELD" /* AGENT_YIELD */;
|
|
307407
|
+
}
|
|
307019
307408
|
function isToolExecution(node) {
|
|
307020
307409
|
return node.type === "TOOL_EXECUTION" /* TOOL_EXECUTION */;
|
|
307021
307410
|
}
|
|
307411
|
+
function isMaskedTool(node) {
|
|
307412
|
+
return node.type === "MASKED_TOOL" /* MASKED_TOOL */;
|
|
307413
|
+
}
|
|
307414
|
+
function isUserPrompt(node) {
|
|
307415
|
+
return node.type === "USER_PROMPT" /* USER_PROMPT */;
|
|
307416
|
+
}
|
|
307417
|
+
function isSystemEvent(node) {
|
|
307418
|
+
return node.type === "SYSTEM_EVENT" /* SYSTEM_EVENT */;
|
|
307419
|
+
}
|
|
307420
|
+
function isSnapshot(node) {
|
|
307421
|
+
return node.type === "SNAPSHOT" /* SNAPSHOT */;
|
|
307422
|
+
}
|
|
307423
|
+
function isRollingSummary(node) {
|
|
307424
|
+
return node.type === "ROLLING_SUMMARY" /* ROLLING_SUMMARY */;
|
|
307425
|
+
}
|
|
307022
307426
|
|
|
307023
307427
|
// packages/core/src/context/processors/nodeDistillationProcessor.ts
|
|
307024
307428
|
var NodeDistillationProcessorOptionsSchema = {
|
|
@@ -307161,43 +307565,289 @@ function createNodeDistillationProcessor(id, env2, options) {
|
|
|
307161
307565
|
}
|
|
307162
307566
|
|
|
307163
307567
|
// packages/core/src/context/processors/stateSnapshotProcessor.ts
|
|
307164
|
-
import { randomUUID as
|
|
307568
|
+
import { randomUUID as randomUUID9 } from "node:crypto";
|
|
307569
|
+
|
|
307570
|
+
// packages/core/src/context/utils/formatNodesForLlm.ts
|
|
307571
|
+
function getSemanticToolWrapper(toolName) {
|
|
307572
|
+
if (toolName.includes("search") || toolName.includes("grep"))
|
|
307573
|
+
return `SEARCH RESULTS`;
|
|
307574
|
+
if (toolName.includes("list") || toolName.includes("dir"))
|
|
307575
|
+
return `WORKSPACE STRUCTURE`;
|
|
307576
|
+
if (toolName.includes("shell") || toolName.includes("cmd"))
|
|
307577
|
+
return `SHELL EXECUTION`;
|
|
307578
|
+
if (toolName.includes("read") || toolName.includes("fetch"))
|
|
307579
|
+
return `FILE/WEB CONTENT`;
|
|
307580
|
+
return `TOOL RESPONSE`;
|
|
307581
|
+
}
|
|
307582
|
+
function formatNodesForLlm(nodes, options = {}) {
|
|
307583
|
+
const maxToolChars = options.maxToolResponseChars ?? 2e3;
|
|
307584
|
+
let transcript = "";
|
|
307585
|
+
const uniqueTurns = Array.from(
|
|
307586
|
+
new Set(nodes.map((n3) => n3.turnId).filter(Boolean))
|
|
307587
|
+
);
|
|
307588
|
+
for (const node of nodes) {
|
|
307589
|
+
const payload = node.payload;
|
|
307590
|
+
let nodeContent = "";
|
|
307591
|
+
if (payload.text) {
|
|
307592
|
+
nodeContent = payload.text;
|
|
307593
|
+
} else if (payload.functionCall) {
|
|
307594
|
+
nodeContent = `CALL: ${payload.functionCall.name}(${JSON.stringify(payload.functionCall.args)})`;
|
|
307595
|
+
} else if (payload.functionResponse) {
|
|
307596
|
+
const toolName = payload.functionResponse.name || "unknown_tool";
|
|
307597
|
+
const rawResponse = JSON.stringify(payload.functionResponse.response);
|
|
307598
|
+
const semanticWrapper = getSemanticToolWrapper(toolName);
|
|
307599
|
+
let formattedResponse = rawResponse;
|
|
307600
|
+
if (rawResponse.length > maxToolChars) {
|
|
307601
|
+
const half = Math.floor(maxToolChars / 2);
|
|
307602
|
+
const truncatedCount = rawResponse.length - maxToolChars;
|
|
307603
|
+
formattedResponse = `${rawResponse.substring(0, half)}... [TRUNCATED ${truncatedCount} chars] ...${rawResponse.substring(rawResponse.length - half)}`;
|
|
307604
|
+
}
|
|
307605
|
+
nodeContent = `[${semanticWrapper} (${toolName})]: ${formattedResponse}`;
|
|
307606
|
+
} else {
|
|
307607
|
+
nodeContent = JSON.stringify(payload);
|
|
307608
|
+
}
|
|
307609
|
+
const role = (node.role || "system").toUpperCase();
|
|
307610
|
+
let turnMarker = "";
|
|
307611
|
+
if (node.turnId) {
|
|
307612
|
+
const idx = uniqueTurns.indexOf(node.turnId);
|
|
307613
|
+
if (idx !== -1) {
|
|
307614
|
+
const relativeIdx = idx - (uniqueTurns.length - 1);
|
|
307615
|
+
turnMarker = `[Turn ${relativeIdx}] `;
|
|
307616
|
+
}
|
|
307617
|
+
}
|
|
307618
|
+
transcript += `${turnMarker}[${role}] [${node.type}]: ${nodeContent}
|
|
307619
|
+
`;
|
|
307620
|
+
}
|
|
307621
|
+
return transcript;
|
|
307622
|
+
}
|
|
307165
307623
|
|
|
307166
307624
|
// packages/core/src/context/utils/snapshotGenerator.ts
|
|
307625
|
+
import { randomUUID as randomUUID8 } from "node:crypto";
|
|
307626
|
+
function isStringArray(value) {
|
|
307627
|
+
return Array.isArray(value) && value.every((item) => typeof item === "string");
|
|
307628
|
+
}
|
|
307629
|
+
function isNumberArray(value) {
|
|
307630
|
+
return Array.isArray(value) && value.every((item) => typeof item === "number");
|
|
307631
|
+
}
|
|
307632
|
+
function isTaskArray(value) {
|
|
307633
|
+
return Array.isArray(value) && value.every((item) => {
|
|
307634
|
+
if (!isRecord(item)) return false;
|
|
307635
|
+
const id = item["id"];
|
|
307636
|
+
const desc = item["description"];
|
|
307637
|
+
return typeof id === "string" && typeof desc === "string";
|
|
307638
|
+
});
|
|
307639
|
+
}
|
|
307640
|
+
function isString(value) {
|
|
307641
|
+
return typeof value === "string";
|
|
307642
|
+
}
|
|
307643
|
+
function findLatestSnapshotBaseline(targets) {
|
|
307644
|
+
const lastSnapshotNode = [...targets].reverse().find((n3) => n3.type === "SNAPSHOT" /* SNAPSHOT */ && n3.payload.text);
|
|
307645
|
+
if (lastSnapshotNode?.payload.text) {
|
|
307646
|
+
return {
|
|
307647
|
+
text: lastSnapshotNode.payload.text,
|
|
307648
|
+
abstractsIds: lastSnapshotNode.abstractsIds ? [...lastSnapshotNode.abstractsIds] : [],
|
|
307649
|
+
id: lastSnapshotNode.id
|
|
307650
|
+
};
|
|
307651
|
+
}
|
|
307652
|
+
return void 0;
|
|
307653
|
+
}
|
|
307167
307654
|
var SnapshotGenerator = class {
|
|
307168
307655
|
constructor(env2) {
|
|
307169
307656
|
this.env = env2;
|
|
307170
307657
|
}
|
|
307171
|
-
async synthesizeSnapshot(nodes,
|
|
307172
|
-
const
|
|
307173
|
-
|
|
307658
|
+
async synthesizeSnapshot(nodes, previousStateJson, options = {}) {
|
|
307659
|
+
const emptyState = {
|
|
307660
|
+
active_tasks: [],
|
|
307661
|
+
discovered_facts: [],
|
|
307662
|
+
constraints_and_preferences: [],
|
|
307663
|
+
recent_arc: []
|
|
307664
|
+
};
|
|
307665
|
+
let previousState = emptyState;
|
|
307666
|
+
if (previousStateJson) {
|
|
307667
|
+
try {
|
|
307668
|
+
const parsed = JSON.parse(previousStateJson);
|
|
307669
|
+
if (isRecord(parsed)) {
|
|
307670
|
+
let loadedArc = [];
|
|
307671
|
+
if (isStringArray(parsed["recent_arc"])) {
|
|
307672
|
+
loadedArc = parsed["recent_arc"];
|
|
307673
|
+
} else if (isString(parsed["summary"]) && parsed["summary"]) {
|
|
307674
|
+
loadedArc = [parsed["summary"]];
|
|
307675
|
+
}
|
|
307676
|
+
previousState = {
|
|
307677
|
+
active_tasks: isTaskArray(parsed["active_tasks"]) ? parsed["active_tasks"] : [],
|
|
307678
|
+
discovered_facts: isStringArray(parsed["discovered_facts"]) ? parsed["discovered_facts"] : [],
|
|
307679
|
+
constraints_and_preferences: isStringArray(
|
|
307680
|
+
parsed["constraints_and_preferences"]
|
|
307681
|
+
) ? parsed["constraints_and_preferences"] : [],
|
|
307682
|
+
recent_arc: loadedArc
|
|
307683
|
+
};
|
|
307684
|
+
}
|
|
307685
|
+
} catch {
|
|
307686
|
+
}
|
|
307687
|
+
}
|
|
307688
|
+
let pressureWarning = "";
|
|
307689
|
+
const stateString = JSON.stringify(previousState);
|
|
307690
|
+
const estimatedTokens = this.env.tokenCalculator.estimateTokensForString(stateString);
|
|
307691
|
+
const maxTokens = options.maxStateTokens ?? 4e3;
|
|
307692
|
+
if (estimatedTokens > maxTokens * 0.8) {
|
|
307693
|
+
pressureWarning = `
|
|
307174
307694
|
|
|
307175
|
-
|
|
307176
|
-
let userPromptText = "TRANSCRIPT TO SNAPSHOT:\n\n";
|
|
307177
|
-
for (const node of nodes) {
|
|
307178
|
-
const payload = node.payload;
|
|
307179
|
-
let nodeContent = "";
|
|
307180
|
-
if (payload.text) {
|
|
307181
|
-
nodeContent = payload.text;
|
|
307182
|
-
} else if (payload.functionCall) {
|
|
307183
|
-
nodeContent = `CALL: ${payload.functionCall.name}(${JSON.stringify(payload.functionCall.args)})`;
|
|
307184
|
-
} else if (payload.functionResponse) {
|
|
307185
|
-
nodeContent = `RESPONSE: ${JSON.stringify(payload.functionResponse.response)}`;
|
|
307186
|
-
}
|
|
307187
|
-
userPromptText += `[${node.type}]: ${nodeContent}
|
|
307188
|
-
`;
|
|
307695
|
+
[CRITICAL WARNING]: The Master State is currently at ${(estimatedTokens / maxTokens * 100).toFixed(0)}% of its maximum capacity! You MUST aggressively prune obsolete, irrelevant, or overly granular facts and constraints using \`obsolete_fact_indices\` and \`obsolete_constraint_indices\`.`;
|
|
307189
307696
|
}
|
|
307190
|
-
const
|
|
307191
|
-
|
|
307192
|
-
|
|
307193
|
-
|
|
307194
|
-
|
|
307195
|
-
|
|
307196
|
-
|
|
307197
|
-
|
|
307198
|
-
|
|
307199
|
-
const
|
|
307200
|
-
|
|
307697
|
+
const systemPrompt = `You are an expert Context Memory Manager. You maintain the long-term "Master State" of the AI agent's memory.
|
|
307698
|
+
You will be provided with the CURRENT Master State and a raw transcript of new conversation turns.
|
|
307699
|
+
Your task is to generate a JSON Delta Patch representing what has changed in the transcript.${pressureWarning}
|
|
307700
|
+
|
|
307701
|
+
CRITICAL OPERATIONAL RULES:
|
|
307702
|
+
1. FACTS: Extract explicit empirical facts (file paths, exact error codes, specific configs).
|
|
307703
|
+
2. PRUNING: Keep facts dense. Use obsolete indices to aggressively delete facts that are no longer relevant to the current objective.
|
|
307704
|
+
3. TASKS: Add any new active user requests to "new_tasks".
|
|
307705
|
+
4. TASK RESOLUTION: A task may ONLY be placed in "resolved_task_ids" if a success message or explicit confirmation was provided in the transcript. If the task was being worked on but no final confirmation exists, it MUST remain active. Do not prematurely resolve tasks.`;
|
|
307706
|
+
const userPromptText = `CURRENT MASTER STATE:
|
|
307707
|
+
${JSON.stringify(previousState, null, 2)}
|
|
307708
|
+
|
|
307709
|
+
TRANSCRIPT OF NEW TURNS:
|
|
307710
|
+
${formatNodesForLlm(nodes)}`;
|
|
307711
|
+
const patchSchema = {
|
|
307712
|
+
type: "object",
|
|
307713
|
+
properties: {
|
|
307714
|
+
new_facts: {
|
|
307715
|
+
type: "array",
|
|
307716
|
+
items: { type: "string" },
|
|
307717
|
+
description: "New specific, empirical facts discovered in this transcript chunk."
|
|
307718
|
+
},
|
|
307719
|
+
new_constraints: {
|
|
307720
|
+
type: "array",
|
|
307721
|
+
items: { type: "string" },
|
|
307722
|
+
description: "New specific rules or instructions provided by the user in this chunk."
|
|
307723
|
+
},
|
|
307724
|
+
new_tasks: {
|
|
307725
|
+
type: "array",
|
|
307726
|
+
items: {
|
|
307727
|
+
type: "object",
|
|
307728
|
+
properties: {
|
|
307729
|
+
description: {
|
|
307730
|
+
type: "string",
|
|
307731
|
+
description: "The task goal/description."
|
|
307732
|
+
}
|
|
307733
|
+
}
|
|
307734
|
+
}
|
|
307735
|
+
},
|
|
307736
|
+
resolved_task_ids: {
|
|
307737
|
+
type: "array",
|
|
307738
|
+
items: { type: "string" },
|
|
307739
|
+
description: "IDs of tasks from the CURRENT MASTER STATE that were explicitly completed or abandoned in this transcript chunk."
|
|
307740
|
+
},
|
|
307741
|
+
obsolete_fact_indices: {
|
|
307742
|
+
type: "array",
|
|
307743
|
+
items: { type: "number" },
|
|
307744
|
+
description: "Array indices of facts from CURRENT MASTER STATE that are no longer true or relevant and should be deleted."
|
|
307745
|
+
},
|
|
307746
|
+
obsolete_constraint_indices: {
|
|
307747
|
+
type: "array",
|
|
307748
|
+
items: { type: "number" },
|
|
307749
|
+
description: "Array indices of constraints from CURRENT MASTER STATE that are no longer true or relevant and should be deleted."
|
|
307750
|
+
},
|
|
307751
|
+
chronological_summary: {
|
|
307752
|
+
type: "string",
|
|
307753
|
+
description: "A 1-2 sentence summary of the mechanical actions taken in this transcript chunk."
|
|
307754
|
+
}
|
|
307755
|
+
}
|
|
307756
|
+
};
|
|
307757
|
+
let patch = {};
|
|
307758
|
+
try {
|
|
307759
|
+
const result2 = await this.env.llmClient.generateJson({
|
|
307760
|
+
role: "utility_state_snapshot_processor" /* UTILITY_STATE_SNAPSHOT_PROCESSOR */,
|
|
307761
|
+
modelConfigKey: { model: "context-snapshotter" },
|
|
307762
|
+
contents: [{ role: "user", parts: [{ text: userPromptText }] }],
|
|
307763
|
+
systemInstruction: { role: "system", parts: [{ text: systemPrompt }] },
|
|
307764
|
+
schema: patchSchema,
|
|
307765
|
+
promptId: this.env.promptId,
|
|
307766
|
+
abortSignal: new AbortController().signal
|
|
307767
|
+
});
|
|
307768
|
+
if (isRecord(result2)) {
|
|
307769
|
+
patch = result2;
|
|
307770
|
+
}
|
|
307771
|
+
} catch {
|
|
307772
|
+
return JSON.stringify(previousState);
|
|
307773
|
+
}
|
|
307774
|
+
const newState = {
|
|
307775
|
+
active_tasks: [...previousState.active_tasks],
|
|
307776
|
+
discovered_facts: [...previousState.discovered_facts],
|
|
307777
|
+
constraints_and_preferences: [
|
|
307778
|
+
...previousState.constraints_and_preferences
|
|
307779
|
+
],
|
|
307780
|
+
recent_arc: [...previousState.recent_arc]
|
|
307781
|
+
};
|
|
307782
|
+
const resolvedIds = patch["resolved_task_ids"];
|
|
307783
|
+
if (isStringArray(resolvedIds)) {
|
|
307784
|
+
const resolvedSet = new Set(resolvedIds);
|
|
307785
|
+
newState.active_tasks = newState.active_tasks.filter(
|
|
307786
|
+
(t2) => !resolvedSet.has(t2.id)
|
|
307787
|
+
);
|
|
307788
|
+
}
|
|
307789
|
+
const obsFacts = patch["obsolete_fact_indices"];
|
|
307790
|
+
if (isNumberArray(obsFacts)) {
|
|
307791
|
+
const dropSet = new Set(obsFacts);
|
|
307792
|
+
newState.discovered_facts = newState.discovered_facts.filter(
|
|
307793
|
+
(_, i3) => !dropSet.has(i3)
|
|
307794
|
+
);
|
|
307795
|
+
}
|
|
307796
|
+
const obsConstraints = patch["obsolete_constraint_indices"];
|
|
307797
|
+
if (isNumberArray(obsConstraints)) {
|
|
307798
|
+
const dropSet = new Set(obsConstraints);
|
|
307799
|
+
newState.constraints_and_preferences = newState.constraints_and_preferences.filter((_, i3) => !dropSet.has(i3));
|
|
307800
|
+
}
|
|
307801
|
+
const newTasks = patch["new_tasks"];
|
|
307802
|
+
if (Array.isArray(newTasks)) {
|
|
307803
|
+
for (const t2 of newTasks) {
|
|
307804
|
+
if (isRecord(t2)) {
|
|
307805
|
+
const desc = t2["description"];
|
|
307806
|
+
if (typeof desc === "string" && desc) {
|
|
307807
|
+
newState.active_tasks.push({
|
|
307808
|
+
id: `task_${randomUUID8().slice(0, 8)}`,
|
|
307809
|
+
description: desc
|
|
307810
|
+
});
|
|
307811
|
+
}
|
|
307812
|
+
}
|
|
307813
|
+
}
|
|
307814
|
+
}
|
|
307815
|
+
const newFacts = patch["new_facts"];
|
|
307816
|
+
if (isStringArray(newFacts)) {
|
|
307817
|
+
newState.discovered_facts.push(...newFacts);
|
|
307818
|
+
}
|
|
307819
|
+
const newConstraints = patch["new_constraints"];
|
|
307820
|
+
if (isStringArray(newConstraints)) {
|
|
307821
|
+
newState.constraints_and_preferences.push(...newConstraints);
|
|
307822
|
+
}
|
|
307823
|
+
const chronoSummary = patch["chronological_summary"];
|
|
307824
|
+
if (typeof chronoSummary === "string" && chronoSummary) {
|
|
307825
|
+
newState.recent_arc.push(chronoSummary);
|
|
307826
|
+
const maxTurns = options.maxSummaryTurns ?? 5;
|
|
307827
|
+
if (newState.recent_arc.length > maxTurns) {
|
|
307828
|
+
newState.recent_arc = newState.recent_arc.slice(-maxTurns);
|
|
307829
|
+
}
|
|
307830
|
+
}
|
|
307831
|
+
let currentTokens = this.env.tokenCalculator.estimateTokensForString(
|
|
307832
|
+
JSON.stringify(newState)
|
|
307833
|
+
);
|
|
307834
|
+
while (currentTokens > maxTokens) {
|
|
307835
|
+
if (newState.discovered_facts.length > 0) {
|
|
307836
|
+
newState.discovered_facts.shift();
|
|
307837
|
+
} else if (newState.constraints_and_preferences.length > 0) {
|
|
307838
|
+
newState.constraints_and_preferences.shift();
|
|
307839
|
+
} else if (newState.recent_arc.length > 0) {
|
|
307840
|
+
newState.recent_arc.shift();
|
|
307841
|
+
} else if (newState.active_tasks.length > 0) {
|
|
307842
|
+
newState.active_tasks.shift();
|
|
307843
|
+
} else {
|
|
307844
|
+
break;
|
|
307845
|
+
}
|
|
307846
|
+
currentTokens = this.env.tokenCalculator.estimateTokensForString(
|
|
307847
|
+
JSON.stringify(newState)
|
|
307848
|
+
);
|
|
307849
|
+
}
|
|
307850
|
+
return JSON.stringify(newState);
|
|
307201
307851
|
}
|
|
307202
307852
|
};
|
|
307203
307853
|
|
|
@@ -307212,7 +307862,9 @@ var StateSnapshotProcessorOptionsSchema = {
|
|
|
307212
307862
|
},
|
|
307213
307863
|
freeTokensTarget: { type: "number", nullable: true },
|
|
307214
307864
|
model: { type: "string", nullable: true },
|
|
307215
|
-
systemInstruction: { type: "string", nullable: true }
|
|
307865
|
+
systemInstruction: { type: "string", nullable: true },
|
|
307866
|
+
maxSummaryTurns: { type: "number", nullable: true },
|
|
307867
|
+
maxStateTokens: { type: "number", nullable: true }
|
|
307216
307868
|
},
|
|
307217
307869
|
required: []
|
|
307218
307870
|
};
|
|
@@ -307240,7 +307892,7 @@ function createStateSnapshotProcessor(id, env2, options) {
|
|
|
307240
307892
|
const targetIds = new Set(targets.map((t2) => t2.id));
|
|
307241
307893
|
const isValid = consumedIds.every((id2) => targetIds.has(id2));
|
|
307242
307894
|
if (isValid) {
|
|
307243
|
-
const newId =
|
|
307895
|
+
const newId = randomUUID9();
|
|
307244
307896
|
const snapshotNode = {
|
|
307245
307897
|
id: newId,
|
|
307246
307898
|
turnId: newId,
|
|
@@ -307283,12 +307935,37 @@ function createStateSnapshotProcessor(id, env2, options) {
|
|
|
307283
307935
|
if (deficitAccumulator >= targetTokensToRemove) break;
|
|
307284
307936
|
}
|
|
307285
307937
|
if (nodesToSummarize.length < 2) return targets;
|
|
307938
|
+
let previousStateJson = void 0;
|
|
307939
|
+
let baselineIdToConsume = void 0;
|
|
307940
|
+
const baseline = findLatestSnapshotBaseline(targets);
|
|
307941
|
+
if (baseline) {
|
|
307942
|
+
previousStateJson = baseline.text;
|
|
307943
|
+
const summaryIdx = nodesToSummarize.findIndex(
|
|
307944
|
+
(n3) => n3.id === baseline.id
|
|
307945
|
+
);
|
|
307946
|
+
if (summaryIdx !== -1) {
|
|
307947
|
+
baselineIdToConsume = baseline.id;
|
|
307948
|
+
nodesToSummarize.splice(summaryIdx, 1);
|
|
307949
|
+
}
|
|
307950
|
+
} else {
|
|
307951
|
+
debugLogger.log(
|
|
307952
|
+
"[StateSnapshotProcessor] No previous snapshot found in context graph. Initializing new Master State baseline."
|
|
307953
|
+
);
|
|
307954
|
+
}
|
|
307286
307955
|
try {
|
|
307287
307956
|
const snapshotText = await generator.synthesizeSnapshot(
|
|
307288
307957
|
nodesToSummarize,
|
|
307289
|
-
|
|
307958
|
+
previousStateJson,
|
|
307959
|
+
{
|
|
307960
|
+
maxSummaryTurns: options.maxSummaryTurns,
|
|
307961
|
+
maxStateTokens: options.maxStateTokens
|
|
307962
|
+
}
|
|
307290
307963
|
);
|
|
307291
|
-
const newId =
|
|
307964
|
+
const newId = randomUUID9();
|
|
307965
|
+
const consumedIds = nodesToSummarize.map((n3) => n3.id);
|
|
307966
|
+
if (baselineIdToConsume && !consumedIds.includes(baselineIdToConsume)) {
|
|
307967
|
+
consumedIds.push(baselineIdToConsume);
|
|
307968
|
+
}
|
|
307292
307969
|
const snapshotNode = {
|
|
307293
307970
|
id: newId,
|
|
307294
307971
|
turnId: newId,
|
|
@@ -307296,9 +307973,8 @@ function createStateSnapshotProcessor(id, env2, options) {
|
|
|
307296
307973
|
timestamp: nodesToSummarize[nodesToSummarize.length - 1].timestamp,
|
|
307297
307974
|
role: "user",
|
|
307298
307975
|
payload: { text: snapshotText },
|
|
307299
|
-
abstractsIds:
|
|
307976
|
+
abstractsIds: [...consumedIds]
|
|
307300
307977
|
};
|
|
307301
|
-
const consumedIds = nodesToSummarize.map((n3) => n3.id);
|
|
307302
307978
|
const returnedNodes = targets.filter(
|
|
307303
307979
|
(t2) => !consumedIds.includes(t2.id)
|
|
307304
307980
|
);
|
|
@@ -307321,7 +307997,6 @@ function createStateSnapshotProcessor(id, env2, options) {
|
|
|
307321
307997
|
}
|
|
307322
307998
|
|
|
307323
307999
|
// packages/core/src/context/processors/stateSnapshotAsyncProcessor.ts
|
|
307324
|
-
import { randomUUID as randomUUID9 } from "node:crypto";
|
|
307325
308000
|
var StateSnapshotAsyncProcessorOptionsSchema = {
|
|
307326
308001
|
type: "object",
|
|
307327
308002
|
properties: {
|
|
@@ -307330,7 +308005,9 @@ var StateSnapshotAsyncProcessorOptionsSchema = {
|
|
|
307330
308005
|
enum: ["accumulate", "point-in-time"],
|
|
307331
308006
|
nullable: true
|
|
307332
308007
|
},
|
|
307333
|
-
systemInstruction: { type: "string", nullable: true }
|
|
308008
|
+
systemInstruction: { type: "string", nullable: true },
|
|
308009
|
+
maxSummaryTurns: { type: "number", nullable: true },
|
|
308010
|
+
maxStateTokens: { type: "number", nullable: true }
|
|
307334
308011
|
},
|
|
307335
308012
|
required: []
|
|
307336
308013
|
};
|
|
@@ -307342,9 +308019,10 @@ function createStateSnapshotAsyncProcessor(id, env2, options) {
|
|
|
307342
308019
|
process: async ({ targets, inbox }) => {
|
|
307343
308020
|
if (targets.length === 0) return;
|
|
307344
308021
|
try {
|
|
307345
|
-
let nodesToSummarize = [...targets];
|
|
307346
308022
|
let previousConsumedIds = [];
|
|
307347
308023
|
const processorType = options.type ?? "point-in-time";
|
|
308024
|
+
const nodesToSummarize = [...targets];
|
|
308025
|
+
let previousStateJson = void 0;
|
|
307348
308026
|
if (processorType === "accumulate") {
|
|
307349
308027
|
const proposedSnapshots = inbox.getMessages("PROPOSED_SNAPSHOT");
|
|
307350
308028
|
const accumulateSnapshots = proposedSnapshots.filter(
|
|
@@ -307357,21 +308035,35 @@ function createStateSnapshotAsyncProcessor(id, env2, options) {
|
|
|
307357
308035
|
inbox.consume(latest.id);
|
|
307358
308036
|
env2.inbox.drainConsumed(/* @__PURE__ */ new Set([latest.id]));
|
|
307359
308037
|
previousConsumedIds = latest.payload.consumedIds;
|
|
307360
|
-
|
|
307361
|
-
|
|
307362
|
-
|
|
307363
|
-
|
|
307364
|
-
|
|
307365
|
-
|
|
307366
|
-
|
|
307367
|
-
|
|
307368
|
-
|
|
307369
|
-
|
|
308038
|
+
previousStateJson = latest.payload.newText;
|
|
308039
|
+
} else {
|
|
308040
|
+
const baseline = findLatestSnapshotBaseline(targets);
|
|
308041
|
+
if (baseline) {
|
|
308042
|
+
previousStateJson = baseline.text;
|
|
308043
|
+
previousConsumedIds = [...baseline.abstractsIds];
|
|
308044
|
+
} else {
|
|
308045
|
+
debugLogger.log(
|
|
308046
|
+
"[StateSnapshotAsyncProcessor] No previous snapshot found in Inbox or Graph. Initializing new Master State baseline in background."
|
|
308047
|
+
);
|
|
308048
|
+
}
|
|
307370
308049
|
}
|
|
307371
308050
|
}
|
|
308051
|
+
if (previousStateJson) {
|
|
308052
|
+
const summaryIdx = nodesToSummarize.findIndex(
|
|
308053
|
+
(n3) => n3.type === "SNAPSHOT" /* SNAPSHOT */ && n3.payload.text === previousStateJson
|
|
308054
|
+
);
|
|
308055
|
+
if (summaryIdx !== -1) {
|
|
308056
|
+
nodesToSummarize.splice(summaryIdx, 1);
|
|
308057
|
+
}
|
|
308058
|
+
}
|
|
308059
|
+
if (nodesToSummarize.length === 0) return;
|
|
307372
308060
|
const snapshotText = await generator.synthesizeSnapshot(
|
|
307373
308061
|
nodesToSummarize,
|
|
307374
|
-
|
|
308062
|
+
previousStateJson,
|
|
308063
|
+
{
|
|
308064
|
+
maxSummaryTurns: options.maxSummaryTurns,
|
|
308065
|
+
maxStateTokens: options.maxStateTokens
|
|
308066
|
+
}
|
|
307375
308067
|
);
|
|
307376
308068
|
const newConsumedIds = [
|
|
307377
308069
|
...previousConsumedIds,
|
|
@@ -307471,7 +308163,9 @@ var generalistProfile = {
|
|
|
307471
308163
|
"StateSnapshotSync",
|
|
307472
308164
|
env2,
|
|
307473
308165
|
resolveProcessorOptions(config2, "StateSnapshotSync", {
|
|
307474
|
-
target: "max"
|
|
308166
|
+
target: "max",
|
|
308167
|
+
maxStateTokens: 4e3,
|
|
308168
|
+
maxSummaryTurns: 5
|
|
307475
308169
|
})
|
|
307476
308170
|
)
|
|
307477
308171
|
]
|
|
@@ -307487,7 +308181,9 @@ var generalistProfile = {
|
|
|
307487
308181
|
"StateSnapshotAsync",
|
|
307488
308182
|
env2,
|
|
307489
308183
|
resolveProcessorOptions(config2, "StateSnapshotAsync", {
|
|
307490
|
-
type: "accumulate"
|
|
308184
|
+
type: "accumulate",
|
|
308185
|
+
maxStateTokens: 4e3,
|
|
308186
|
+
maxSummaryTurns: 5
|
|
307491
308187
|
})
|
|
307492
308188
|
)
|
|
307493
308189
|
]
|
|
@@ -307695,6 +308391,12 @@ var ContextTracer = class {
|
|
|
307695
308391
|
// packages/core/src/context/eventBus.ts
|
|
307696
308392
|
import { EventEmitter as EventEmitter4 } from "node:events";
|
|
307697
308393
|
var ContextEventBus = class extends EventEmitter4 {
|
|
308394
|
+
emitTokenGroundTruth(event) {
|
|
308395
|
+
this.emit("TOKEN_GROUND_TRUTH", event);
|
|
308396
|
+
}
|
|
308397
|
+
onTokenGroundTruth(listener) {
|
|
308398
|
+
this.on("TOKEN_GROUND_TRUTH", listener);
|
|
308399
|
+
}
|
|
307698
308400
|
emitPristineHistoryUpdated(event) {
|
|
307699
308401
|
this.emit("PRISTINE_HISTORY_UPDATED", event);
|
|
307700
308402
|
}
|
|
@@ -307721,161 +308423,6 @@ var ContextEventBus = class extends EventEmitter4 {
|
|
|
307721
308423
|
}
|
|
307722
308424
|
};
|
|
307723
308425
|
|
|
307724
|
-
// packages/core/src/context/utils/contextTokenCalculator.ts
|
|
307725
|
-
var ContextTokenCalculator = class {
|
|
307726
|
-
constructor(charsPerToken, registry2) {
|
|
307727
|
-
this.charsPerToken = charsPerToken;
|
|
307728
|
-
this.registry = registry2;
|
|
307729
|
-
}
|
|
307730
|
-
tokenCache = /* @__PURE__ */ new Map();
|
|
307731
|
-
/**
|
|
307732
|
-
* Estimates tokens for a simple string based on character count.
|
|
307733
|
-
* Fast, but inherently inaccurate compared to real model tokenization.
|
|
307734
|
-
*/
|
|
307735
|
-
estimateTokensForString(text) {
|
|
307736
|
-
return Math.ceil(text.length / this.charsPerToken);
|
|
307737
|
-
}
|
|
307738
|
-
/**
|
|
307739
|
-
* Fast, simple heuristic conversion from tokens to expected character length.
|
|
307740
|
-
* Useful for calculating truncation thresholds.
|
|
307741
|
-
*/
|
|
307742
|
-
tokensToChars(tokens) {
|
|
307743
|
-
return tokens * this.charsPerToken;
|
|
307744
|
-
}
|
|
307745
|
-
/**
|
|
307746
|
-
* Pre-calculates and caches the token cost of a newly minted node.
|
|
307747
|
-
* Because nodes are immutable, this cost never changes for this node ID.
|
|
307748
|
-
*/
|
|
307749
|
-
/**
|
|
307750
|
-
* Removes cached token counts for any nodes that are no longer in the given live set.
|
|
307751
|
-
* This prevents unbounded memory growth during long sessions.
|
|
307752
|
-
*/
|
|
307753
|
-
garbageCollectCache(liveNodeIds) {
|
|
307754
|
-
for (const [id] of this.tokenCache) {
|
|
307755
|
-
if (!liveNodeIds.has(id)) {
|
|
307756
|
-
this.tokenCache.delete(id);
|
|
307757
|
-
}
|
|
307758
|
-
}
|
|
307759
|
-
}
|
|
307760
|
-
cacheNodeTokens(node) {
|
|
307761
|
-
const behavior = this.registry.get(node.type);
|
|
307762
|
-
const parts2 = behavior.getEstimatableParts(node);
|
|
307763
|
-
const tokens = this.estimateTokensForParts(parts2);
|
|
307764
|
-
this.tokenCache.set(node.id, tokens);
|
|
307765
|
-
return tokens;
|
|
307766
|
-
}
|
|
307767
|
-
/**
|
|
307768
|
-
* Retrieves the token cost of a single node from the cache.
|
|
307769
|
-
* If it misses the cache, it computes it and caches it.
|
|
307770
|
-
*/
|
|
307771
|
-
getTokenCost(node) {
|
|
307772
|
-
const cached2 = this.tokenCache.get(node.id);
|
|
307773
|
-
if (cached2 !== void 0) return cached2;
|
|
307774
|
-
return this.cacheNodeTokens(node);
|
|
307775
|
-
}
|
|
307776
|
-
/**
|
|
307777
|
-
* Calculates a detailed breakdown of tokens by category for a list of nodes.
|
|
307778
|
-
* Useful for calibration tracing and debugging overestimation.
|
|
307779
|
-
*/
|
|
307780
|
-
calculateTokenBreakdown(nodes) {
|
|
307781
|
-
const breakdown = { total: 0, text: 0, media: 0, tool: 0, overhead: 0 };
|
|
307782
|
-
const seenIds = /* @__PURE__ */ new Set();
|
|
307783
|
-
const seenTurnIds = /* @__PURE__ */ new Set();
|
|
307784
|
-
for (const node of nodes) {
|
|
307785
|
-
if (seenIds.has(node.id)) continue;
|
|
307786
|
-
seenIds.add(node.id);
|
|
307787
|
-
if (node.turnId) {
|
|
307788
|
-
if (!seenTurnIds.has(node.turnId)) {
|
|
307789
|
-
seenTurnIds.add(node.turnId);
|
|
307790
|
-
breakdown.overhead += MSG_OVERHEAD_TOKENS;
|
|
307791
|
-
breakdown.total += MSG_OVERHEAD_TOKENS;
|
|
307792
|
-
}
|
|
307793
|
-
}
|
|
307794
|
-
const cost = this.getTokenCost(node);
|
|
307795
|
-
breakdown.total += cost;
|
|
307796
|
-
const behavior = this.registry.get(node.type);
|
|
307797
|
-
const parts2 = behavior.getEstimatableParts(node);
|
|
307798
|
-
for (const part of parts2) {
|
|
307799
|
-
if (typeof part.text === "string") {
|
|
307800
|
-
breakdown.text += estimateTokenCountSync(
|
|
307801
|
-
[part],
|
|
307802
|
-
0,
|
|
307803
|
-
this.charsPerToken
|
|
307804
|
-
);
|
|
307805
|
-
} else if (part.inlineData?.mimeType?.startsWith("image/") || part.fileData?.mimeType?.startsWith("image/")) {
|
|
307806
|
-
breakdown.media += estimateTokenCountSync(
|
|
307807
|
-
[part],
|
|
307808
|
-
0,
|
|
307809
|
-
this.charsPerToken
|
|
307810
|
-
);
|
|
307811
|
-
} else if (part.functionCall || part.functionResponse) {
|
|
307812
|
-
breakdown.tool += estimateTokenCountSync(
|
|
307813
|
-
[part],
|
|
307814
|
-
0,
|
|
307815
|
-
this.charsPerToken
|
|
307816
|
-
);
|
|
307817
|
-
} else {
|
|
307818
|
-
breakdown.overhead += estimateTokenCountSync(
|
|
307819
|
-
[part],
|
|
307820
|
-
0,
|
|
307821
|
-
this.charsPerToken
|
|
307822
|
-
);
|
|
307823
|
-
}
|
|
307824
|
-
}
|
|
307825
|
-
}
|
|
307826
|
-
return breakdown;
|
|
307827
|
-
}
|
|
307828
|
-
/**
|
|
307829
|
-
* Fast calculation for a flat array of ConcreteNodes (The Nodes).
|
|
307830
|
-
* It relies entirely on the O(1) sidecar token cache.
|
|
307831
|
-
*/
|
|
307832
|
-
calculateConcreteListTokens(nodes) {
|
|
307833
|
-
let tokens = 0;
|
|
307834
|
-
const seenIds = /* @__PURE__ */ new Set();
|
|
307835
|
-
const seenTurnIds = /* @__PURE__ */ new Set();
|
|
307836
|
-
for (const node of nodes) {
|
|
307837
|
-
if (!seenIds.has(node.id)) {
|
|
307838
|
-
seenIds.add(node.id);
|
|
307839
|
-
tokens += this.getTokenCost(node);
|
|
307840
|
-
if (node.turnId) {
|
|
307841
|
-
if (!seenTurnIds.has(node.turnId)) {
|
|
307842
|
-
seenTurnIds.add(node.turnId);
|
|
307843
|
-
tokens += MSG_OVERHEAD_TOKENS;
|
|
307844
|
-
}
|
|
307845
|
-
}
|
|
307846
|
-
}
|
|
307847
|
-
}
|
|
307848
|
-
return tokens;
|
|
307849
|
-
}
|
|
307850
|
-
/**
|
|
307851
|
-
* Calculates the token cost for a single Gemini Content object.
|
|
307852
|
-
*/
|
|
307853
|
-
calculateContentTokens(content) {
|
|
307854
|
-
return this.estimateTokensForParts(content.parts || []) + MSG_OVERHEAD_TOKENS;
|
|
307855
|
-
}
|
|
307856
|
-
/**
|
|
307857
|
-
* Slower, precise estimation for a Gemini Content/Part graph.
|
|
307858
|
-
* Deeply inspects the nested structure and uses the base tokenization math.
|
|
307859
|
-
*/
|
|
307860
|
-
partTokenCache = /* @__PURE__ */ new WeakMap();
|
|
307861
|
-
estimateTokensForParts(parts2) {
|
|
307862
|
-
let total = 0;
|
|
307863
|
-
for (const part of parts2) {
|
|
307864
|
-
if (part !== null && typeof part === "object") {
|
|
307865
|
-
let cost = this.partTokenCache.get(part);
|
|
307866
|
-
if (cost === void 0) {
|
|
307867
|
-
cost = estimateTokenCountSync([part], 0, this.charsPerToken);
|
|
307868
|
-
this.partTokenCache.set(part, cost);
|
|
307869
|
-
}
|
|
307870
|
-
total += cost;
|
|
307871
|
-
} else {
|
|
307872
|
-
total += estimateTokenCountSync([part], 0, this.charsPerToken);
|
|
307873
|
-
}
|
|
307874
|
-
}
|
|
307875
|
-
return total;
|
|
307876
|
-
}
|
|
307877
|
-
};
|
|
307878
|
-
|
|
307879
308426
|
// packages/core/src/context/pipeline/inbox.ts
|
|
307880
308427
|
import { randomUUID as randomUUID11 } from "node:crypto";
|
|
307881
308428
|
var LiveInbox = class {
|
|
@@ -307913,81 +308460,6 @@ var InboxSnapshotImpl = class {
|
|
|
307913
308460
|
}
|
|
307914
308461
|
};
|
|
307915
308462
|
|
|
307916
|
-
// packages/core/src/context/graph/behaviorRegistry.ts
|
|
307917
|
-
var NodeBehaviorRegistry = class {
|
|
307918
|
-
behaviors = /* @__PURE__ */ new Map();
|
|
307919
|
-
register(behavior) {
|
|
307920
|
-
this.behaviors.set(behavior.type, behavior);
|
|
307921
|
-
}
|
|
307922
|
-
get(type2) {
|
|
307923
|
-
const behavior = this.behaviors.get(type2);
|
|
307924
|
-
if (!behavior) {
|
|
307925
|
-
throw new Error(`Unregistered Node type: ${type2}`);
|
|
307926
|
-
}
|
|
307927
|
-
return behavior;
|
|
307928
|
-
}
|
|
307929
|
-
};
|
|
307930
|
-
|
|
307931
|
-
// packages/core/src/context/graph/builtinBehaviors.ts
|
|
307932
|
-
var UserPromptBehavior = {
|
|
307933
|
-
type: "USER_PROMPT" /* USER_PROMPT */,
|
|
307934
|
-
getEstimatableParts(node) {
|
|
307935
|
-
return [node.payload];
|
|
307936
|
-
}
|
|
307937
|
-
};
|
|
307938
|
-
var AgentThoughtBehavior = {
|
|
307939
|
-
type: "AGENT_THOUGHT" /* AGENT_THOUGHT */,
|
|
307940
|
-
getEstimatableParts(node) {
|
|
307941
|
-
return [node.payload];
|
|
307942
|
-
}
|
|
307943
|
-
};
|
|
307944
|
-
var ToolExecutionBehavior = {
|
|
307945
|
-
type: "TOOL_EXECUTION" /* TOOL_EXECUTION */,
|
|
307946
|
-
getEstimatableParts(node) {
|
|
307947
|
-
return [node.payload];
|
|
307948
|
-
}
|
|
307949
|
-
};
|
|
307950
|
-
var MaskedToolBehavior = {
|
|
307951
|
-
type: "MASKED_TOOL" /* MASKED_TOOL */,
|
|
307952
|
-
getEstimatableParts(node) {
|
|
307953
|
-
return [node.payload];
|
|
307954
|
-
}
|
|
307955
|
-
};
|
|
307956
|
-
var AgentYieldBehavior = {
|
|
307957
|
-
type: "AGENT_YIELD" /* AGENT_YIELD */,
|
|
307958
|
-
getEstimatableParts() {
|
|
307959
|
-
return [];
|
|
307960
|
-
}
|
|
307961
|
-
};
|
|
307962
|
-
var SystemEventBehavior = {
|
|
307963
|
-
type: "SYSTEM_EVENT" /* SYSTEM_EVENT */,
|
|
307964
|
-
getEstimatableParts(node) {
|
|
307965
|
-
return [node.payload];
|
|
307966
|
-
}
|
|
307967
|
-
};
|
|
307968
|
-
var SnapshotBehavior = {
|
|
307969
|
-
type: "SNAPSHOT" /* SNAPSHOT */,
|
|
307970
|
-
getEstimatableParts(node) {
|
|
307971
|
-
return [node.payload];
|
|
307972
|
-
}
|
|
307973
|
-
};
|
|
307974
|
-
var RollingSummaryBehavior = {
|
|
307975
|
-
type: "ROLLING_SUMMARY" /* ROLLING_SUMMARY */,
|
|
307976
|
-
getEstimatableParts(node) {
|
|
307977
|
-
return [node.payload];
|
|
307978
|
-
}
|
|
307979
|
-
};
|
|
307980
|
-
function registerBuiltInBehaviors(registry2) {
|
|
307981
|
-
registry2.register(UserPromptBehavior);
|
|
307982
|
-
registry2.register(AgentThoughtBehavior);
|
|
307983
|
-
registry2.register(ToolExecutionBehavior);
|
|
307984
|
-
registry2.register(MaskedToolBehavior);
|
|
307985
|
-
registry2.register(AgentYieldBehavior);
|
|
307986
|
-
registry2.register(SystemEventBehavior);
|
|
307987
|
-
registry2.register(SnapshotBehavior);
|
|
307988
|
-
registry2.register(RollingSummaryBehavior);
|
|
307989
|
-
}
|
|
307990
|
-
|
|
307991
308463
|
// packages/core/src/context/graph/toGraph.ts
|
|
307992
308464
|
import { randomUUID as randomUUID12, createHash as createHash7 } from "node:crypto";
|
|
307993
308465
|
var PART_HASH_CACHE = /* @__PURE__ */ new WeakMap();
|
|
@@ -308058,9 +308530,9 @@ var ContextGraphBuilder = class {
|
|
|
308058
308530
|
for (let turnIdx = 0; turnIdx < history.length; turnIdx++) {
|
|
308059
308531
|
const msg = history[turnIdx];
|
|
308060
308532
|
if (!msg.parts) continue;
|
|
308061
|
-
if (
|
|
308533
|
+
if (msg.role === "user" && msg.parts.length === 1) {
|
|
308062
308534
|
const text = msg.parts[0].text;
|
|
308063
|
-
if (text?.startsWith("<session_context>") && text?.includes("This is the Gemini CLI
|
|
308535
|
+
if (text?.startsWith("<session_context>") && text?.includes("This is the Gemini CLI")) {
|
|
308064
308536
|
debugLogger.log(
|
|
308065
308537
|
"[ContextGraphBuilder] Skipping legacy environment header turn from graph."
|
|
308066
308538
|
);
|
|
@@ -308157,7 +308629,7 @@ var ContextGraphMapper = class {
|
|
|
308157
308629
|
|
|
308158
308630
|
// packages/core/src/context/pipeline/environmentImpl.ts
|
|
308159
308631
|
var ContextEnvironmentImpl = class {
|
|
308160
|
-
constructor(llmClientProvider, sessionId, promptId, traceDir, projectTempDir, tracer, charsPerToken, eventBus) {
|
|
308632
|
+
constructor(llmClientProvider, sessionId, promptId, traceDir, projectTempDir, tracer, charsPerToken, eventBus, tokenCalculator, behaviorRegistry, renderOptions) {
|
|
308161
308633
|
this.llmClientProvider = llmClientProvider;
|
|
308162
308634
|
this.sessionId = sessionId;
|
|
308163
308635
|
this.promptId = promptId;
|
|
@@ -308166,18 +308638,13 @@ var ContextEnvironmentImpl = class {
|
|
|
308166
308638
|
this.tracer = tracer;
|
|
308167
308639
|
this.charsPerToken = charsPerToken;
|
|
308168
308640
|
this.eventBus = eventBus;
|
|
308169
|
-
this.
|
|
308170
|
-
|
|
308171
|
-
this.
|
|
308172
|
-
this.charsPerToken,
|
|
308173
|
-
this.behaviorRegistry
|
|
308174
|
-
);
|
|
308641
|
+
this.tokenCalculator = tokenCalculator;
|
|
308642
|
+
this.behaviorRegistry = behaviorRegistry;
|
|
308643
|
+
this.renderOptions = renderOptions;
|
|
308175
308644
|
this.inbox = new LiveInbox();
|
|
308176
308645
|
this.graphMapper = new ContextGraphMapper();
|
|
308177
308646
|
}
|
|
308178
|
-
tokenCalculator;
|
|
308179
308647
|
inbox;
|
|
308180
|
-
behaviorRegistry;
|
|
308181
308648
|
graphMapper;
|
|
308182
308649
|
get llmClient() {
|
|
308183
308650
|
return this.llmClientProvider();
|
|
@@ -308219,33 +308686,6 @@ var ContextWorkingBufferImpl = class _ContextWorkingBufferImpl {
|
|
|
308219
308686
|
// Empty history
|
|
308220
308687
|
);
|
|
308221
308688
|
}
|
|
308222
|
-
/**
|
|
308223
|
-
* Appends newly observed pristine nodes (e.g. from a user message) to the working buffer.
|
|
308224
|
-
* Ensures they are tracked in the pristine map and point to themselves in provenance.
|
|
308225
|
-
*/
|
|
308226
|
-
appendPristineNodes(newNodes) {
|
|
308227
|
-
if (newNodes.length === 0) return this;
|
|
308228
|
-
const newPristineMap = new Map(this.pristineNodesMap);
|
|
308229
|
-
const newProvenanceMap = new Map(this.provenanceMap);
|
|
308230
|
-
const existingIds = new Set(this.nodes.map((n3) => n3.id));
|
|
308231
|
-
const nodesToAdd = [];
|
|
308232
|
-
const batchIds = /* @__PURE__ */ new Set();
|
|
308233
|
-
for (const node of newNodes) {
|
|
308234
|
-
if (!existingIds.has(node.id) && !batchIds.has(node.id)) {
|
|
308235
|
-
newPristineMap.set(node.id, node);
|
|
308236
|
-
newProvenanceMap.set(node.id, /* @__PURE__ */ new Set([node.id]));
|
|
308237
|
-
nodesToAdd.push(node);
|
|
308238
|
-
batchIds.add(node.id);
|
|
308239
|
-
}
|
|
308240
|
-
}
|
|
308241
|
-
if (nodesToAdd.length === 0) return this;
|
|
308242
|
-
return new _ContextWorkingBufferImpl(
|
|
308243
|
-
[...this.nodes, ...nodesToAdd],
|
|
308244
|
-
newPristineMap,
|
|
308245
|
-
newProvenanceMap,
|
|
308246
|
-
[...this.history]
|
|
308247
|
-
);
|
|
308248
|
-
}
|
|
308249
308689
|
/**
|
|
308250
308690
|
* Generates an entirely new buffer instance by calculating the delta between the processor's input and output.
|
|
308251
308691
|
*/
|
|
@@ -308325,12 +308765,90 @@ var ContextWorkingBufferImpl = class _ContextWorkingBufferImpl {
|
|
|
308325
308765
|
[...this.history, mutation]
|
|
308326
308766
|
);
|
|
308327
308767
|
}
|
|
308328
|
-
/**
|
|
308329
|
-
|
|
308330
|
-
|
|
308331
|
-
|
|
308332
|
-
|
|
308768
|
+
/**
|
|
308769
|
+
* Rebuilds the working buffer in the exact chronological order of the authoritative pristine history,
|
|
308770
|
+
* while preserving injected/summarized nodes at their relative positions.
|
|
308771
|
+
*/
|
|
308772
|
+
syncPristineHistory(authoritativePristineNodes) {
|
|
308773
|
+
const newPristineMap = new Map(this.pristineNodesMap);
|
|
308333
308774
|
const newProvenanceMap = new Map(this.provenanceMap);
|
|
308775
|
+
const authoritativeIds = new Set(
|
|
308776
|
+
authoritativePristineNodes.map((n3) => n3.id)
|
|
308777
|
+
);
|
|
308778
|
+
for (const node of authoritativePristineNodes) {
|
|
308779
|
+
if (!newPristineMap.has(node.id)) {
|
|
308780
|
+
newPristineMap.set(node.id, node);
|
|
308781
|
+
newProvenanceMap.set(node.id, /* @__PURE__ */ new Set([node.id]));
|
|
308782
|
+
}
|
|
308783
|
+
}
|
|
308784
|
+
const survivingCurrentNodes = this.nodes.filter((n3) => {
|
|
308785
|
+
if (authoritativeIds.has(n3.id)) return true;
|
|
308786
|
+
if (!this.pristineNodesMap.has(n3.id)) return true;
|
|
308787
|
+
const roots = newProvenanceMap.get(n3.id);
|
|
308788
|
+
return !roots || roots.size === 0;
|
|
308789
|
+
}).filter((n3) => {
|
|
308790
|
+
if (!authoritativeIds.has(n3.id) && !this.pristineNodesMap.has(n3.id)) {
|
|
308791
|
+
const roots = newProvenanceMap.get(n3.id);
|
|
308792
|
+
if (roots && roots.size > 0) {
|
|
308793
|
+
for (const root of roots) {
|
|
308794
|
+
if (!authoritativeIds.has(root)) {
|
|
308795
|
+
return false;
|
|
308796
|
+
}
|
|
308797
|
+
}
|
|
308798
|
+
}
|
|
308799
|
+
}
|
|
308800
|
+
return true;
|
|
308801
|
+
});
|
|
308802
|
+
const coveredPristineIds = /* @__PURE__ */ new Set();
|
|
308803
|
+
for (const node of survivingCurrentNodes) {
|
|
308804
|
+
if (!authoritativeIds.has(node.id)) {
|
|
308805
|
+
const roots = newProvenanceMap.get(node.id);
|
|
308806
|
+
if (roots) {
|
|
308807
|
+
for (const root of roots) {
|
|
308808
|
+
coveredPristineIds.add(root);
|
|
308809
|
+
}
|
|
308810
|
+
}
|
|
308811
|
+
}
|
|
308812
|
+
}
|
|
308813
|
+
const pristineIndexMap = new Map(
|
|
308814
|
+
authoritativePristineNodes.map((n3, idx) => [n3.id, idx])
|
|
308815
|
+
);
|
|
308816
|
+
const getPristineIndex = (nodeId) => {
|
|
308817
|
+
const roots = newProvenanceMap.get(nodeId);
|
|
308818
|
+
if (!roots || roots.size === 0) return -1;
|
|
308819
|
+
let maxIndex = -1;
|
|
308820
|
+
for (const root of roots) {
|
|
308821
|
+
const idx = pristineIndexMap.get(root);
|
|
308822
|
+
if (idx !== void 0 && idx > maxIndex) {
|
|
308823
|
+
maxIndex = idx;
|
|
308824
|
+
}
|
|
308825
|
+
}
|
|
308826
|
+
return maxIndex;
|
|
308827
|
+
};
|
|
308828
|
+
const nodeOrder = new Array();
|
|
308829
|
+
for (let i3 = 0; i3 < authoritativePristineNodes.length; i3++) {
|
|
308830
|
+
const node = authoritativePristineNodes[i3];
|
|
308831
|
+
if (!coveredPristineIds.has(node.id)) {
|
|
308832
|
+
nodeOrder.push({ node, sortKey: i3, originalIndex: -1 });
|
|
308833
|
+
}
|
|
308834
|
+
}
|
|
308835
|
+
for (let i3 = 0; i3 < survivingCurrentNodes.length; i3++) {
|
|
308836
|
+
const node = survivingCurrentNodes[i3];
|
|
308837
|
+
if (!authoritativeIds.has(node.id)) {
|
|
308838
|
+
const baseSortKey = getPristineIndex(node.id);
|
|
308839
|
+
nodeOrder.push({
|
|
308840
|
+
node,
|
|
308841
|
+
sortKey: baseSortKey === -1 ? -1 : baseSortKey + 0.5,
|
|
308842
|
+
// Interleave after pristine roots, or at start if injected
|
|
308843
|
+
originalIndex: i3
|
|
308844
|
+
});
|
|
308845
|
+
}
|
|
308846
|
+
}
|
|
308847
|
+
nodeOrder.sort((a2, b) => {
|
|
308848
|
+
if (a2.sortKey !== b.sortKey) return a2.sortKey - b.sortKey;
|
|
308849
|
+
return a2.originalIndex - b.originalIndex;
|
|
308850
|
+
});
|
|
308851
|
+
const newGraph = nodeOrder.map((item) => item.node);
|
|
308334
308852
|
const reachablePristineIds = /* @__PURE__ */ new Set();
|
|
308335
308853
|
const reachableCurrentIds = /* @__PURE__ */ new Set();
|
|
308336
308854
|
for (const node of newGraph) {
|
|
@@ -308338,7 +308856,7 @@ var ContextWorkingBufferImpl = class _ContextWorkingBufferImpl {
|
|
|
308338
308856
|
const roots = newProvenanceMap.get(node.id);
|
|
308339
308857
|
if (roots) {
|
|
308340
308858
|
for (const root of roots) {
|
|
308341
|
-
if (
|
|
308859
|
+
if (authoritativeIds.has(root) || !this.pristineNodesMap.has(root)) {
|
|
308342
308860
|
reachablePristineIds.add(root);
|
|
308343
308861
|
}
|
|
308344
308862
|
}
|
|
@@ -308351,7 +308869,7 @@ var ContextWorkingBufferImpl = class _ContextWorkingBufferImpl {
|
|
|
308351
308869
|
}
|
|
308352
308870
|
const prunedPristineMap = /* @__PURE__ */ new Map();
|
|
308353
308871
|
for (const id of reachablePristineIds) {
|
|
308354
|
-
const node =
|
|
308872
|
+
const node = newPristineMap.get(id);
|
|
308355
308873
|
if (node) prunedPristineMap.set(id, node);
|
|
308356
308874
|
}
|
|
308357
308875
|
return new _ContextWorkingBufferImpl(
|
|
@@ -308386,6 +308904,7 @@ var PipelineOrchestrator = class {
|
|
|
308386
308904
|
activeTimers = [];
|
|
308387
308905
|
pendingPipelines = /* @__PURE__ */ new Map();
|
|
308388
308906
|
pipelineMutex = /* @__PURE__ */ new Map();
|
|
308907
|
+
pipelineScheduled = /* @__PURE__ */ new Set();
|
|
308389
308908
|
nodeProvider;
|
|
308390
308909
|
/**
|
|
308391
308910
|
* Sets the provider for the latest live nodes.
|
|
@@ -308420,22 +308939,50 @@ var PipelineOrchestrator = class {
|
|
|
308420
308939
|
this.activeTimers.push(timer);
|
|
308421
308940
|
} else if (trigger === "retained_exceeded" || trigger === "nodes_aged_out") {
|
|
308422
308941
|
this.eventBus.onConsolidationNeeded((event) => {
|
|
308423
|
-
executeFn(
|
|
308942
|
+
void executeFn(
|
|
308943
|
+
pipeline,
|
|
308944
|
+
event.nodes,
|
|
308945
|
+
event.targetNodeIds,
|
|
308946
|
+
/* @__PURE__ */ new Set()
|
|
308947
|
+
);
|
|
308424
308948
|
});
|
|
308425
308949
|
} else if (trigger === "new_message" || trigger === "nodes_added") {
|
|
308426
308950
|
this.eventBus.onChunkReceived((event) => {
|
|
308427
|
-
executeFn(
|
|
308951
|
+
void executeFn(
|
|
308952
|
+
pipeline,
|
|
308953
|
+
event.nodes,
|
|
308954
|
+
event.targetNodeIds,
|
|
308955
|
+
/* @__PURE__ */ new Set()
|
|
308956
|
+
);
|
|
308428
308957
|
});
|
|
308429
308958
|
}
|
|
308430
308959
|
}
|
|
308431
308960
|
}
|
|
308432
308961
|
};
|
|
308433
|
-
|
|
308962
|
+
const handleSyncExecution = async (pipeline, nodes, targets, protectedIds) => {
|
|
308963
|
+
if (this.pipelineScheduled.has(pipeline.name)) {
|
|
308964
|
+
debugLogger.log(
|
|
308965
|
+
`[Orchestrator] Pipeline ${pipeline.name} already scheduled (sync), dropping.`
|
|
308966
|
+
);
|
|
308967
|
+
return;
|
|
308968
|
+
}
|
|
308969
|
+
this.pipelineScheduled.add(pipeline.name);
|
|
308434
308970
|
const existing = this.pipelineMutex.get(pipeline.name) || Promise.resolve();
|
|
308435
308971
|
const nextPromise = (async () => {
|
|
308436
308972
|
try {
|
|
308437
308973
|
await existing;
|
|
308438
|
-
|
|
308974
|
+
this.pipelineScheduled.delete(pipeline.name);
|
|
308975
|
+
const latestNodes = this.nodeProvider ? this.nodeProvider() : nodes;
|
|
308976
|
+
const latestTargets = latestNodes.filter((n3) => targets.has(n3.id));
|
|
308977
|
+
debugLogger.log(
|
|
308978
|
+
`[Orchestrator] Executing sync pipeline ${pipeline.name} with ${latestTargets.length} latest targets.`
|
|
308979
|
+
);
|
|
308980
|
+
if (latestTargets.length === 0) {
|
|
308981
|
+
debugLogger.log(
|
|
308982
|
+
`[Orchestrator] No latest targets for sync pipeline ${pipeline.name}, returning.`
|
|
308983
|
+
);
|
|
308984
|
+
return;
|
|
308985
|
+
}
|
|
308439
308986
|
await this.executePipelineAsync(
|
|
308440
308987
|
pipeline,
|
|
308441
308988
|
latestNodes,
|
|
@@ -308443,7 +308990,7 @@ var PipelineOrchestrator = class {
|
|
|
308443
308990
|
new Set(protectedIds)
|
|
308444
308991
|
);
|
|
308445
308992
|
} catch (e2) {
|
|
308446
|
-
debugLogger.error(`
|
|
308993
|
+
debugLogger.error(`Sync pipeline chain ${pipeline.name} failed:`, e2);
|
|
308447
308994
|
}
|
|
308448
308995
|
})();
|
|
308449
308996
|
this.pipelineMutex.set(pipeline.name, nextPromise);
|
|
@@ -308455,22 +309002,61 @@ var PipelineOrchestrator = class {
|
|
|
308455
309002
|
this.pipelineMutex.delete(pipeline.name);
|
|
308456
309003
|
}
|
|
308457
309004
|
});
|
|
308458
|
-
}
|
|
308459
|
-
|
|
308460
|
-
|
|
308461
|
-
|
|
308462
|
-
|
|
308463
|
-
const targets = nodes.filter((n3) => targetIds.has(n3.id));
|
|
308464
|
-
for (const processor of pipeline.processors) {
|
|
308465
|
-
processor.process({
|
|
308466
|
-
targets,
|
|
308467
|
-
inbox: inboxSnapshot,
|
|
308468
|
-
buffer: ContextWorkingBufferImpl.initialize(nodes)
|
|
308469
|
-
}).catch(
|
|
308470
|
-
(e2) => debugLogger.error(`AsyncProcessor ${processor.name} failed:`, e2)
|
|
309005
|
+
};
|
|
309006
|
+
const handleAsyncExecution = async (pipeline, nodes, targets) => {
|
|
309007
|
+
if (this.pipelineScheduled.has(pipeline.name)) {
|
|
309008
|
+
debugLogger.log(
|
|
309009
|
+
`[Orchestrator] Pipeline ${pipeline.name} already scheduled (async), dropping.`
|
|
308471
309010
|
);
|
|
309011
|
+
return;
|
|
308472
309012
|
}
|
|
308473
|
-
|
|
309013
|
+
this.pipelineScheduled.add(pipeline.name);
|
|
309014
|
+
const existing = this.pipelineMutex.get(pipeline.name) || Promise.resolve();
|
|
309015
|
+
const nextPromise = (async () => {
|
|
309016
|
+
try {
|
|
309017
|
+
await existing;
|
|
309018
|
+
this.pipelineScheduled.delete(pipeline.name);
|
|
309019
|
+
const latestNodes = this.nodeProvider ? this.nodeProvider() : nodes;
|
|
309020
|
+
const latestTargets = latestNodes.filter((n3) => targets.has(n3.id));
|
|
309021
|
+
debugLogger.log(
|
|
309022
|
+
`[Orchestrator] Executing async pipeline ${pipeline.name} with ${latestTargets.length} latest targets.`
|
|
309023
|
+
);
|
|
309024
|
+
const inboxSnapshot = new InboxSnapshotImpl(
|
|
309025
|
+
this.env.inbox.getMessages() || []
|
|
309026
|
+
);
|
|
309027
|
+
for (const processor of pipeline.processors) {
|
|
309028
|
+
debugLogger.log(
|
|
309029
|
+
`[Orchestrator] Running async processor ${processor.id}`
|
|
309030
|
+
);
|
|
309031
|
+
await processor.process({
|
|
309032
|
+
targets: latestTargets,
|
|
309033
|
+
inbox: inboxSnapshot,
|
|
309034
|
+
buffer: ContextWorkingBufferImpl.initialize(latestNodes)
|
|
309035
|
+
});
|
|
309036
|
+
}
|
|
309037
|
+
this.env.inbox.drainConsumed(inboxSnapshot.getConsumedIds());
|
|
309038
|
+
} catch (e2) {
|
|
309039
|
+
debugLogger.error(`Async pipeline chain ${pipeline.name} failed:`, e2);
|
|
309040
|
+
}
|
|
309041
|
+
})();
|
|
309042
|
+
this.pipelineMutex.set(pipeline.name, nextPromise);
|
|
309043
|
+
const pipelineId = `${pipeline.name}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
|
309044
|
+
this.pendingPipelines.set(pipelineId, nextPromise);
|
|
309045
|
+
void nextPromise.finally(() => {
|
|
309046
|
+
this.pendingPipelines.delete(pipelineId);
|
|
309047
|
+
if (this.pipelineMutex.get(pipeline.name) === nextPromise) {
|
|
309048
|
+
this.pipelineMutex.delete(pipeline.name);
|
|
309049
|
+
}
|
|
309050
|
+
});
|
|
309051
|
+
};
|
|
309052
|
+
bindTriggers(
|
|
309053
|
+
this.pipelines,
|
|
309054
|
+
(pipeline, nodes, targets, protectedIds) => handleSyncExecution(pipeline, nodes, targets, protectedIds)
|
|
309055
|
+
);
|
|
309056
|
+
bindTriggers(
|
|
309057
|
+
this.asyncPipelines,
|
|
309058
|
+
(pipeline, nodes, targets) => handleAsyncExecution(pipeline, nodes, targets)
|
|
309059
|
+
);
|
|
308474
309060
|
}
|
|
308475
309061
|
shutdown() {
|
|
308476
309062
|
for (const timer of this.activeTimers) {
|
|
@@ -308668,17 +309254,56 @@ var HistoryObserver = class {
|
|
|
308668
309254
|
}
|
|
308669
309255
|
};
|
|
308670
309256
|
|
|
309257
|
+
// packages/core/src/context/utils/tokenCalibration.ts
|
|
309258
|
+
function performCalibration(env2, finalNodes, finalContents) {
|
|
309259
|
+
if (!env2.renderOptions?.calibrateTokenCalculation) {
|
|
309260
|
+
return;
|
|
309261
|
+
}
|
|
309262
|
+
void (async () => {
|
|
309263
|
+
try {
|
|
309264
|
+
const exactResp = await env2.llmClient.countTokens({
|
|
309265
|
+
contents: finalContents
|
|
309266
|
+
});
|
|
309267
|
+
const exactTokens = typeof exactResp.totalTokens === "number" ? exactResp.totalTokens : 0;
|
|
309268
|
+
const estimatedTokens = env2.tokenCalculator.calculateConcreteListTokens(finalNodes);
|
|
309269
|
+
const delta = Math.abs(exactTokens - estimatedTokens);
|
|
309270
|
+
const tolerance = Math.max(exactTokens, estimatedTokens) * 0.2;
|
|
309271
|
+
env2.tracer.logEvent("Render", "Token Calibration Measurement", {
|
|
309272
|
+
exactTokens,
|
|
309273
|
+
estimatedTokens,
|
|
309274
|
+
delta,
|
|
309275
|
+
isWithinTolerance: delta <= tolerance
|
|
309276
|
+
});
|
|
309277
|
+
if (delta > tolerance) {
|
|
309278
|
+
debugLogger.error(
|
|
309279
|
+
`[Token Calibration] Large deviation detected: exact ${exactTokens} vs estimated ${estimatedTokens} (delta: ${delta})`
|
|
309280
|
+
);
|
|
309281
|
+
}
|
|
309282
|
+
} catch {
|
|
309283
|
+
}
|
|
309284
|
+
})();
|
|
309285
|
+
}
|
|
309286
|
+
|
|
308671
309287
|
// packages/core/src/context/graph/render.ts
|
|
308672
|
-
async function render2(nodes, orchestrator, sidecar, tracer, env2, protectionReasons = /* @__PURE__ */ new Map(),
|
|
309288
|
+
async function render2(nodes, orchestrator, sidecar, tracer, env2, advancedTokenCalculator, protectionReasons = /* @__PURE__ */ new Map(), header, previewNodeIds = /* @__PURE__ */ new Set()) {
|
|
309289
|
+
let headerTokens = 0;
|
|
309290
|
+
let headerBaseUnits = 0;
|
|
309291
|
+
if (header) {
|
|
309292
|
+
const costs = advancedTokenCalculator.calculateContentTokensAndBaseUnits(header);
|
|
309293
|
+
headerTokens = costs.tokens;
|
|
309294
|
+
headerBaseUnits = costs.baseUnits;
|
|
309295
|
+
}
|
|
308673
309296
|
if (!sidecar.config.budget) {
|
|
308674
|
-
const
|
|
309297
|
+
const visibleNodes2 = nodes.filter((n3) => !previewNodeIds.has(n3.id));
|
|
309298
|
+
const contents2 = env2.graphMapper.fromGraph(visibleNodes2);
|
|
308675
309299
|
tracer.logEvent("Render", "Render Context to LLM (No Budget)", {
|
|
308676
309300
|
renderedContext: contents2
|
|
308677
309301
|
});
|
|
308678
|
-
|
|
309302
|
+
const baseUnits = advancedTokenCalculator.getRawBaseUnits(nodes) + headerBaseUnits;
|
|
309303
|
+
return { history: contents2, didApplyManagement: false, baseUnits };
|
|
308679
309304
|
}
|
|
308680
309305
|
const maxTokens = sidecar.config.budget.maxTokens;
|
|
308681
|
-
const graphTokens =
|
|
309306
|
+
const { tokens: graphTokens, baseUnits: graphBaseUnits } = advancedTokenCalculator.calculateTokensAndBaseUnits(nodes);
|
|
308682
309307
|
const currentTokens = graphTokens + headerTokens;
|
|
308683
309308
|
const protectedIds = new Set(protectionReasons.keys());
|
|
308684
309309
|
tracer.logEvent("Render", "Budget Audit", {
|
|
@@ -308701,11 +309326,17 @@ async function render2(nodes, orchestrator, sidecar, tracer, env2, protectionRea
|
|
|
308701
309326
|
"Render",
|
|
308702
309327
|
`View is within maxTokens (${currentTokens} <= ${maxTokens}). Returning view.`
|
|
308703
309328
|
);
|
|
308704
|
-
const
|
|
309329
|
+
const visibleNodes2 = nodes.filter((n3) => !previewNodeIds.has(n3.id));
|
|
309330
|
+
const contents2 = env2.graphMapper.fromGraph(visibleNodes2);
|
|
308705
309331
|
tracer.logEvent("Render", "Render Context for LLM", {
|
|
308706
309332
|
renderedContext: contents2
|
|
308707
309333
|
});
|
|
308708
|
-
|
|
309334
|
+
performCalibration(env2, visibleNodes2, contents2);
|
|
309335
|
+
return {
|
|
309336
|
+
history: contents2,
|
|
309337
|
+
didApplyManagement: false,
|
|
309338
|
+
baseUnits: graphBaseUnits + headerBaseUnits
|
|
309339
|
+
};
|
|
308709
309340
|
}
|
|
308710
309341
|
const targetDelta = currentTokens - sidecar.config.budget.retainedTokens;
|
|
308711
309342
|
tracer.logEvent(
|
|
@@ -308717,9 +309348,10 @@ async function render2(nodes, orchestrator, sidecar, tracer, env2, protectionRea
|
|
|
308717
309348
|
let rollingTokens = 0;
|
|
308718
309349
|
for (let i3 = nodes.length - 1; i3 >= 0; i3--) {
|
|
308719
309350
|
const node = nodes[i3];
|
|
309351
|
+
const priorTokens = rollingTokens;
|
|
308720
309352
|
const nodeTokens = env2.tokenCalculator.calculateConcreteListTokens([node]);
|
|
308721
309353
|
rollingTokens += nodeTokens;
|
|
308722
|
-
if (
|
|
309354
|
+
if (priorTokens > sidecar.config.budget.retainedTokens) {
|
|
308723
309355
|
agedOutNodes.add(node.id);
|
|
308724
309356
|
}
|
|
308725
309357
|
}
|
|
@@ -308735,12 +309367,19 @@ async function render2(nodes, orchestrator, sidecar, tracer, env2, protectionRea
|
|
|
308735
309367
|
for (const id of node.abstractsIds) skipList.add(id);
|
|
308736
309368
|
}
|
|
308737
309369
|
}
|
|
308738
|
-
const visibleNodes = processedNodes.filter(
|
|
309370
|
+
const visibleNodes = processedNodes.filter(
|
|
309371
|
+
(n3) => !skipList.has(n3.id) && !previewNodeIds.has(n3.id)
|
|
309372
|
+
);
|
|
308739
309373
|
const contents = env2.graphMapper.fromGraph(visibleNodes);
|
|
308740
309374
|
tracer.logEvent("Render", "Render Sanitized Context for LLM", {
|
|
308741
309375
|
renderedContextSanitized: contents
|
|
308742
309376
|
});
|
|
308743
|
-
|
|
309377
|
+
performCalibration(env2, visibleNodes, contents);
|
|
309378
|
+
return {
|
|
309379
|
+
history: contents,
|
|
309380
|
+
didApplyManagement: true,
|
|
309381
|
+
baseUnits: advancedTokenCalculator.getRawBaseUnits(visibleNodes) + headerBaseUnits
|
|
309382
|
+
};
|
|
308744
309383
|
}
|
|
308745
309384
|
|
|
308746
309385
|
// packages/core/src/context/utils/invariantChecker.ts
|
|
@@ -308776,10 +309415,11 @@ function checkContextInvariants(nodes, context2) {
|
|
|
308776
309415
|
|
|
308777
309416
|
// packages/core/src/context/contextManager.ts
|
|
308778
309417
|
var ContextManager = class {
|
|
308779
|
-
constructor(sidecar, env2, tracer, orchestrator, chatHistory, headerProvider) {
|
|
309418
|
+
constructor(sidecar, env2, tracer, orchestrator, chatHistory, advancedTokenCalculator, headerProvider) {
|
|
308780
309419
|
this.sidecar = sidecar;
|
|
308781
309420
|
this.env = env2;
|
|
308782
309421
|
this.tracer = tracer;
|
|
309422
|
+
this.advancedTokenCalculator = advancedTokenCalculator;
|
|
308783
309423
|
this.headerProvider = headerProvider;
|
|
308784
309424
|
this.eventBus = env2.eventBus;
|
|
308785
309425
|
this.orchestrator = orchestrator;
|
|
@@ -308791,12 +309431,7 @@ var ContextManager = class {
|
|
|
308791
309431
|
this.env.graphMapper
|
|
308792
309432
|
);
|
|
308793
309433
|
this.eventBus.onPristineHistoryUpdated((event) => {
|
|
308794
|
-
|
|
308795
|
-
const addedNodes = event.nodes.filter((n3) => event.newNodes.has(n3.id));
|
|
308796
|
-
this.buffer = this.buffer.prunePristineNodes(newIds);
|
|
308797
|
-
if (addedNodes.length > 0) {
|
|
308798
|
-
this.buffer = this.buffer.appendPristineNodes(addedNodes);
|
|
308799
|
-
}
|
|
309434
|
+
this.buffer = this.buffer.syncPristineHistory(event.nodes);
|
|
308800
309435
|
this.evaluateTriggers(event.newNodes);
|
|
308801
309436
|
});
|
|
308802
309437
|
this.eventBus.onProcessorResult((event) => {
|
|
@@ -308814,8 +309449,11 @@ var ContextManager = class {
|
|
|
308814
309449
|
// Internal sub-components
|
|
308815
309450
|
orchestrator;
|
|
308816
309451
|
historyObserver;
|
|
309452
|
+
// Hysteresis tracking to prevent utility call churn
|
|
309453
|
+
lastTriggeredDeficit = 0;
|
|
308817
309454
|
// Cache for Anomaly 3 (Redundant Renders)
|
|
308818
309455
|
lastRenderCache;
|
|
309456
|
+
hasPerformedHotStart = false;
|
|
308819
309457
|
/**
|
|
308820
309458
|
* Returns a promise that resolves when all currently executing async pipelines have finished.
|
|
308821
309459
|
*/
|
|
@@ -308855,10 +309493,11 @@ var ContextManager = class {
|
|
|
308855
309493
|
}
|
|
308856
309494
|
for (let i3 = this.buffer.nodes.length - 1; i3 >= 0; i3--) {
|
|
308857
309495
|
const node = this.buffer.nodes[i3];
|
|
309496
|
+
const priorTokens = rollingTokens;
|
|
308858
309497
|
rollingTokens += this.env.tokenCalculator.calculateConcreteListTokens([
|
|
308859
309498
|
node
|
|
308860
309499
|
]);
|
|
308861
|
-
if (
|
|
309500
|
+
if (priorTokens > this.sidecar.config.budget.retainedTokens) {
|
|
308862
309501
|
if (!protectedIds.has(node.id)) {
|
|
308863
309502
|
agedOutNodes.add(node.id);
|
|
308864
309503
|
}
|
|
@@ -308866,8 +309505,13 @@ var ContextManager = class {
|
|
|
308866
309505
|
}
|
|
308867
309506
|
if (agedOutNodes.size > 0) {
|
|
308868
309507
|
const targetDeficit = currentTokens - this.sidecar.config.budget.retainedTokens;
|
|
309508
|
+
if (targetDeficit < this.lastTriggeredDeficit) {
|
|
309509
|
+
this.lastTriggeredDeficit = targetDeficit;
|
|
309510
|
+
}
|
|
308869
309511
|
const threshold = this.sidecar.config.budget.coalescingThresholdTokens || 0;
|
|
308870
|
-
|
|
309512
|
+
const growthSinceLast = targetDeficit - this.lastTriggeredDeficit;
|
|
309513
|
+
if (targetDeficit >= threshold && (growthSinceLast >= threshold || this.lastTriggeredDeficit === 0)) {
|
|
309514
|
+
this.lastTriggeredDeficit = targetDeficit;
|
|
308871
309515
|
this.env.tokenCalculator.garbageCollectCache(
|
|
308872
309516
|
new Set(this.buffer.nodes.map((n3) => n3.id))
|
|
308873
309517
|
);
|
|
@@ -308877,6 +309521,8 @@ var ContextManager = class {
|
|
|
308877
309521
|
targetNodeIds: agedOutNodes
|
|
308878
309522
|
});
|
|
308879
309523
|
}
|
|
309524
|
+
} else {
|
|
309525
|
+
this.lastTriggeredDeficit = 0;
|
|
308880
309526
|
}
|
|
308881
309527
|
}
|
|
308882
309528
|
}
|
|
@@ -308936,24 +309582,42 @@ var ContextManager = class {
|
|
|
308936
309582
|
getNodes() {
|
|
308937
309583
|
return [...this.buffer.nodes];
|
|
308938
309584
|
}
|
|
309585
|
+
getEnvironment() {
|
|
309586
|
+
return this.env;
|
|
309587
|
+
}
|
|
308939
309588
|
/**
|
|
308940
309589
|
* Executes the final 'gc_backstop' pipeline if necessary, enforcing the token budget,
|
|
308941
309590
|
* and maps the Episodic Context Graph back into a raw Gemini Content[] array for transmission.
|
|
308942
309591
|
* This is the primary method called by the agent framework before sending a request.
|
|
308943
309592
|
*/
|
|
308944
|
-
async renderHistory(pendingRequest, activeTaskIds = /* @__PURE__ */ new Set()) {
|
|
309593
|
+
async renderHistory(pendingRequest, activeTaskIds = /* @__PURE__ */ new Set(), abortSignal) {
|
|
308945
309594
|
this.tracer.logEvent("ContextManager", "Starting rendering of LLM context");
|
|
308946
|
-
|
|
308947
|
-
let nodes = this.buffer.nodes;
|
|
309595
|
+
let previewNodes = [];
|
|
308948
309596
|
if (pendingRequest) {
|
|
308949
|
-
|
|
309597
|
+
previewNodes = this.env.graphMapper.applyEvent({
|
|
308950
309598
|
type: "PUSH",
|
|
308951
309599
|
payload: [pendingRequest]
|
|
308952
309600
|
});
|
|
309601
|
+
}
|
|
309602
|
+
const hotStartPromise = (async () => {
|
|
309603
|
+
if (!this.hasPerformedHotStart) {
|
|
309604
|
+
this.hasPerformedHotStart = true;
|
|
309605
|
+
if (this.buffer.nodes.length > 0) {
|
|
309606
|
+
const nodesForHotStart = [...this.buffer.nodes, ...previewNodes];
|
|
309607
|
+
await this.performHotStartCalibration(nodesForHotStart, abortSignal);
|
|
309608
|
+
}
|
|
309609
|
+
}
|
|
309610
|
+
})();
|
|
309611
|
+
await Promise.all([this.orchestrator.waitForPipelines(), hotStartPromise]);
|
|
309612
|
+
let nodes = this.buffer.nodes;
|
|
309613
|
+
const previewNodeIds = /* @__PURE__ */ new Set();
|
|
309614
|
+
if (previewNodes.length > 0) {
|
|
309615
|
+
for (const n3 of previewNodes) {
|
|
309616
|
+
previewNodeIds.add(n3.id);
|
|
309617
|
+
}
|
|
308953
309618
|
nodes = [...nodes, ...previewNodes];
|
|
308954
309619
|
}
|
|
308955
309620
|
const header = this.headerProvider ? await this.headerProvider() : void 0;
|
|
308956
|
-
const headerTokens = header ? this.env.tokenCalculator.calculateContentTokens(header) : 0;
|
|
308957
309621
|
const graphHash = nodes.map((n3) => n3.id).join("|");
|
|
308958
309622
|
const headerHash = header ? JSON.stringify(header.parts) : "no-header";
|
|
308959
309623
|
const totalHash = `${graphHash}::${headerHash}`;
|
|
@@ -308964,14 +309628,20 @@ var ContextManager = class {
|
|
|
308964
309628
|
return this.lastRenderCache.result;
|
|
308965
309629
|
}
|
|
308966
309630
|
const protectionReasons = this.getProtectedNodeIds(nodes, activeTaskIds);
|
|
308967
|
-
const {
|
|
309631
|
+
const {
|
|
309632
|
+
history: renderedHistory,
|
|
309633
|
+
didApplyManagement,
|
|
309634
|
+
baseUnits
|
|
309635
|
+
} = await render2(
|
|
308968
309636
|
nodes,
|
|
308969
309637
|
this.orchestrator,
|
|
308970
309638
|
this.sidecar,
|
|
308971
309639
|
this.tracer,
|
|
308972
309640
|
this.env,
|
|
309641
|
+
this.advancedTokenCalculator,
|
|
308973
309642
|
protectionReasons,
|
|
308974
|
-
|
|
309643
|
+
header,
|
|
309644
|
+
previewNodeIds
|
|
308975
309645
|
);
|
|
308976
309646
|
checkContextInvariants(this.buffer.nodes, "RenderHistory");
|
|
308977
309647
|
this.tracer.logEvent("ContextManager", "Finished rendering");
|
|
@@ -308980,11 +309650,42 @@ var ContextManager = class {
|
|
|
308980
309650
|
history: hardenHistory(combinedHistory, {
|
|
308981
309651
|
sentinels: this.sidecar.sentinels
|
|
308982
309652
|
}),
|
|
308983
|
-
didApplyManagement
|
|
309653
|
+
didApplyManagement,
|
|
309654
|
+
baseUnits
|
|
308984
309655
|
};
|
|
308985
309656
|
this.lastRenderCache = { nodesHash: totalHash, result: result2 };
|
|
308986
309657
|
return result2;
|
|
308987
309658
|
}
|
|
309659
|
+
async performHotStartCalibration(nodes, abortSignal) {
|
|
309660
|
+
try {
|
|
309661
|
+
this.tracer.logEvent(
|
|
309662
|
+
"ContextManager",
|
|
309663
|
+
"Performing Hot Start Token Calibration"
|
|
309664
|
+
);
|
|
309665
|
+
const contents = this.env.graphMapper.fromGraph(nodes);
|
|
309666
|
+
const header = this.headerProvider ? await this.headerProvider() : void 0;
|
|
309667
|
+
const combinedHistory = header ? [header, ...contents] : contents;
|
|
309668
|
+
const baseUnits = this.advancedTokenCalculator.getRawBaseUnits(nodes) + (header ? this.advancedTokenCalculator.getRawBaseUnitsForContent(header) : 0);
|
|
309669
|
+
if (combinedHistory.length > 0) {
|
|
309670
|
+
const result2 = await this.env.llmClient.countTokens({
|
|
309671
|
+
contents: combinedHistory,
|
|
309672
|
+
abortSignal
|
|
309673
|
+
});
|
|
309674
|
+
if (result2.totalTokens > 0) {
|
|
309675
|
+
this.env.eventBus.emitTokenGroundTruth({
|
|
309676
|
+
actualTokens: result2.totalTokens,
|
|
309677
|
+
promptBaseUnits: baseUnits
|
|
309678
|
+
});
|
|
309679
|
+
}
|
|
309680
|
+
}
|
|
309681
|
+
} catch (error40) {
|
|
309682
|
+
this.tracer.logEvent(
|
|
309683
|
+
"ContextManager",
|
|
309684
|
+
"Hot Start Token Calibration Failed (Ignored)",
|
|
309685
|
+
{ error: error40 }
|
|
309686
|
+
);
|
|
309687
|
+
}
|
|
309688
|
+
}
|
|
308988
309689
|
};
|
|
308989
309690
|
|
|
308990
309691
|
// packages/core/src/context/processors/historyTruncationProcessor.ts
|
|
@@ -309017,6 +309718,350 @@ var RollingSummaryProcessorOptionsSchema = {
|
|
|
309017
309718
|
required: []
|
|
309018
309719
|
};
|
|
309019
309720
|
|
|
309721
|
+
// packages/core/src/context/utils/contextTokenCalculator.ts
|
|
309722
|
+
var StaticTokenCalculator = class {
|
|
309723
|
+
constructor(charsPerToken, registry2) {
|
|
309724
|
+
this.charsPerToken = charsPerToken;
|
|
309725
|
+
this.registry = registry2;
|
|
309726
|
+
}
|
|
309727
|
+
tokenCache = /* @__PURE__ */ new Map();
|
|
309728
|
+
/**
|
|
309729
|
+
* Estimates tokens for a simple string based on character count.
|
|
309730
|
+
* Fast, but inherently inaccurate compared to real model tokenization.
|
|
309731
|
+
*/
|
|
309732
|
+
estimateTokensForString(text) {
|
|
309733
|
+
return Math.ceil(text.length / this.charsPerToken);
|
|
309734
|
+
}
|
|
309735
|
+
/**
|
|
309736
|
+
* Fast, simple heuristic conversion from tokens to expected character length.
|
|
309737
|
+
* Useful for calculating truncation thresholds.
|
|
309738
|
+
*/
|
|
309739
|
+
tokensToChars(tokens) {
|
|
309740
|
+
return tokens * this.charsPerToken;
|
|
309741
|
+
}
|
|
309742
|
+
/**
|
|
309743
|
+
* Pre-calculates and caches the token cost of a newly minted node.
|
|
309744
|
+
* Because nodes are immutable, this cost never changes for this node ID.
|
|
309745
|
+
*/
|
|
309746
|
+
/**
|
|
309747
|
+
* Removes cached token counts for any nodes that are no longer in the given live set.
|
|
309748
|
+
* This prevents unbounded memory growth during long sessions.
|
|
309749
|
+
*/
|
|
309750
|
+
garbageCollectCache(liveNodeIds) {
|
|
309751
|
+
for (const [id] of this.tokenCache) {
|
|
309752
|
+
if (!liveNodeIds.has(id)) {
|
|
309753
|
+
this.tokenCache.delete(id);
|
|
309754
|
+
}
|
|
309755
|
+
}
|
|
309756
|
+
}
|
|
309757
|
+
cacheNodeTokens(node) {
|
|
309758
|
+
const behavior = this.registry.get(node.type);
|
|
309759
|
+
const parts2 = behavior.getEstimatableParts(node);
|
|
309760
|
+
const tokens = this.estimateTokensForParts(parts2);
|
|
309761
|
+
this.tokenCache.set(node.id, tokens);
|
|
309762
|
+
return tokens;
|
|
309763
|
+
}
|
|
309764
|
+
/**
|
|
309765
|
+
* Retrieves the token cost of a single node from the cache.
|
|
309766
|
+
* If it misses the cache, it computes it and caches it.
|
|
309767
|
+
*/
|
|
309768
|
+
getTokenCost(node) {
|
|
309769
|
+
const cached2 = this.tokenCache.get(node.id);
|
|
309770
|
+
if (cached2 !== void 0) return cached2;
|
|
309771
|
+
return this.cacheNodeTokens(node);
|
|
309772
|
+
}
|
|
309773
|
+
/**
|
|
309774
|
+
* Calculates a detailed breakdown of tokens by category for a list of nodes.
|
|
309775
|
+
* Useful for calibration tracing and debugging overestimation.
|
|
309776
|
+
*/
|
|
309777
|
+
calculateTokenBreakdown(nodes) {
|
|
309778
|
+
const breakdown = { total: 0, text: 0, media: 0, tool: 0, overhead: 0 };
|
|
309779
|
+
const seenIds = /* @__PURE__ */ new Set();
|
|
309780
|
+
const seenTurnIds = /* @__PURE__ */ new Set();
|
|
309781
|
+
for (const node of nodes) {
|
|
309782
|
+
if (seenIds.has(node.id)) continue;
|
|
309783
|
+
seenIds.add(node.id);
|
|
309784
|
+
if (node.turnId) {
|
|
309785
|
+
if (!seenTurnIds.has(node.turnId)) {
|
|
309786
|
+
seenTurnIds.add(node.turnId);
|
|
309787
|
+
breakdown.overhead += MSG_OVERHEAD_TOKENS;
|
|
309788
|
+
breakdown.total += MSG_OVERHEAD_TOKENS;
|
|
309789
|
+
}
|
|
309790
|
+
}
|
|
309791
|
+
const cost = this.getTokenCost(node);
|
|
309792
|
+
breakdown.total += cost;
|
|
309793
|
+
const behavior = this.registry.get(node.type);
|
|
309794
|
+
const parts2 = behavior.getEstimatableParts(node);
|
|
309795
|
+
for (const part of parts2) {
|
|
309796
|
+
if (typeof part.text === "string") {
|
|
309797
|
+
breakdown.text += estimateTokenCountSync(
|
|
309798
|
+
[part],
|
|
309799
|
+
0,
|
|
309800
|
+
this.charsPerToken
|
|
309801
|
+
);
|
|
309802
|
+
} else if (part.inlineData?.mimeType?.startsWith("image/") || part.fileData?.mimeType?.startsWith("image/")) {
|
|
309803
|
+
breakdown.media += estimateTokenCountSync(
|
|
309804
|
+
[part],
|
|
309805
|
+
0,
|
|
309806
|
+
this.charsPerToken
|
|
309807
|
+
);
|
|
309808
|
+
} else if (part.functionCall || part.functionResponse) {
|
|
309809
|
+
breakdown.tool += estimateTokenCountSync(
|
|
309810
|
+
[part],
|
|
309811
|
+
0,
|
|
309812
|
+
this.charsPerToken
|
|
309813
|
+
);
|
|
309814
|
+
} else {
|
|
309815
|
+
breakdown.overhead += estimateTokenCountSync(
|
|
309816
|
+
[part],
|
|
309817
|
+
0,
|
|
309818
|
+
this.charsPerToken
|
|
309819
|
+
);
|
|
309820
|
+
}
|
|
309821
|
+
}
|
|
309822
|
+
}
|
|
309823
|
+
return breakdown;
|
|
309824
|
+
}
|
|
309825
|
+
/**
|
|
309826
|
+
* For the static calculator, Raw Base Units are exactly the same as the final tokens,
|
|
309827
|
+
* because there is no dynamic learned weight (the multiplier is effectively 1.0).
|
|
309828
|
+
*/
|
|
309829
|
+
getRawBaseUnits(nodes) {
|
|
309830
|
+
return this.calculateConcreteListTokens(nodes);
|
|
309831
|
+
}
|
|
309832
|
+
getRawBaseUnitsForContent(content) {
|
|
309833
|
+
return this.calculateContentTokens(content);
|
|
309834
|
+
}
|
|
309835
|
+
calculateTokensAndBaseUnits(nodes) {
|
|
309836
|
+
const baseUnits = this.calculateConcreteListTokens(nodes);
|
|
309837
|
+
return { tokens: baseUnits, baseUnits };
|
|
309838
|
+
}
|
|
309839
|
+
calculateContentTokensAndBaseUnits(content) {
|
|
309840
|
+
const baseUnits = this.calculateContentTokens(content);
|
|
309841
|
+
return { tokens: baseUnits, baseUnits };
|
|
309842
|
+
}
|
|
309843
|
+
/**
|
|
309844
|
+
* Fast calculation for a flat array of ConcreteNodes (The Nodes).
|
|
309845
|
+
* It relies entirely on the O(1) sidecar token cache.
|
|
309846
|
+
*/
|
|
309847
|
+
calculateConcreteListTokens(nodes) {
|
|
309848
|
+
let tokens = 0;
|
|
309849
|
+
const seenIds = /* @__PURE__ */ new Set();
|
|
309850
|
+
const seenTurnIds = /* @__PURE__ */ new Set();
|
|
309851
|
+
for (const node of nodes) {
|
|
309852
|
+
if (!seenIds.has(node.id)) {
|
|
309853
|
+
seenIds.add(node.id);
|
|
309854
|
+
tokens += this.getTokenCost(node);
|
|
309855
|
+
if (node.turnId) {
|
|
309856
|
+
if (!seenTurnIds.has(node.turnId)) {
|
|
309857
|
+
seenTurnIds.add(node.turnId);
|
|
309858
|
+
tokens += MSG_OVERHEAD_TOKENS;
|
|
309859
|
+
}
|
|
309860
|
+
}
|
|
309861
|
+
}
|
|
309862
|
+
}
|
|
309863
|
+
return tokens;
|
|
309864
|
+
}
|
|
309865
|
+
/**
|
|
309866
|
+
* Calculates the token cost for a single Gemini Content object.
|
|
309867
|
+
*/
|
|
309868
|
+
calculateContentTokens(content) {
|
|
309869
|
+
return this.estimateTokensForParts(content.parts || []) + MSG_OVERHEAD_TOKENS;
|
|
309870
|
+
}
|
|
309871
|
+
/**
|
|
309872
|
+
* Slower, precise estimation for a Gemini Content/Part graph.
|
|
309873
|
+
* Deeply inspects the nested structure and uses the base tokenization math.
|
|
309874
|
+
*/
|
|
309875
|
+
partTokenCache = /* @__PURE__ */ new WeakMap();
|
|
309876
|
+
estimateTokensForParts(parts2) {
|
|
309877
|
+
let total = 0;
|
|
309878
|
+
for (const part of parts2) {
|
|
309879
|
+
if (part !== null && typeof part === "object") {
|
|
309880
|
+
let cost = this.partTokenCache.get(part);
|
|
309881
|
+
if (cost === void 0) {
|
|
309882
|
+
cost = estimateTokenCountSync([part], 0, this.charsPerToken);
|
|
309883
|
+
this.partTokenCache.set(part, cost);
|
|
309884
|
+
}
|
|
309885
|
+
total += cost;
|
|
309886
|
+
} else {
|
|
309887
|
+
total += estimateTokenCountSync([part], 0, this.charsPerToken);
|
|
309888
|
+
}
|
|
309889
|
+
}
|
|
309890
|
+
return total;
|
|
309891
|
+
}
|
|
309892
|
+
};
|
|
309893
|
+
|
|
309894
|
+
// packages/core/src/context/utils/adaptiveTokenCalculator.ts
|
|
309895
|
+
var AdaptiveTokenCalculator = class {
|
|
309896
|
+
learnedWeight = 1;
|
|
309897
|
+
baseCalculator;
|
|
309898
|
+
constructor(charsPerToken, registry2, eventBus) {
|
|
309899
|
+
this.baseCalculator = new StaticTokenCalculator(charsPerToken, registry2);
|
|
309900
|
+
eventBus.onTokenGroundTruth((event) => {
|
|
309901
|
+
this.handleGroundTruth(event.actualTokens, event.promptBaseUnits);
|
|
309902
|
+
});
|
|
309903
|
+
}
|
|
309904
|
+
handleGroundTruth(actualTokens, promptBaseUnits) {
|
|
309905
|
+
if (promptBaseUnits <= 0) return;
|
|
309906
|
+
const targetWeight = actualTokens / promptBaseUnits;
|
|
309907
|
+
const oldWeight = this.learnedWeight;
|
|
309908
|
+
const learningRate = 0.2;
|
|
309909
|
+
const newWeight = oldWeight * (1 - learningRate) + targetWeight * learningRate;
|
|
309910
|
+
this.learnedWeight = Math.max(0.5, Math.min(newWeight, 2));
|
|
309911
|
+
debugLogger.log(
|
|
309912
|
+
`[AdaptiveTokenCalculator] Learned weight updated to ${this.learnedWeight.toFixed(3)} (API Tokens: ${actualTokens}, Base Units: ${promptBaseUnits}, Target Ratio: ${targetWeight.toFixed(3)})`
|
|
309913
|
+
);
|
|
309914
|
+
}
|
|
309915
|
+
/**
|
|
309916
|
+
* Retrieves the current learned weight multiplier.
|
|
309917
|
+
*/
|
|
309918
|
+
getLearnedWeight() {
|
|
309919
|
+
return this.learnedWeight;
|
|
309920
|
+
}
|
|
309921
|
+
/**
|
|
309922
|
+
* Returns the exact, unweighted Base Heuristic Units for the graph.
|
|
309923
|
+
* This is used exactly once per interaction to capture the baseline sent to the API.
|
|
309924
|
+
*/
|
|
309925
|
+
getRawBaseUnits(nodes) {
|
|
309926
|
+
return this.baseCalculator.calculateConcreteListTokens(nodes);
|
|
309927
|
+
}
|
|
309928
|
+
/**
|
|
309929
|
+
* Returns the exact, unweighted Base Heuristic Units for a raw content chunk.
|
|
309930
|
+
*/
|
|
309931
|
+
getRawBaseUnitsForContent(content) {
|
|
309932
|
+
return this.baseCalculator.calculateContentTokens(content);
|
|
309933
|
+
}
|
|
309934
|
+
calculateTokensAndBaseUnits(nodes) {
|
|
309935
|
+
const baseUnits = this.baseCalculator.calculateConcreteListTokens(nodes);
|
|
309936
|
+
return {
|
|
309937
|
+
tokens: Math.round(baseUnits * this.learnedWeight),
|
|
309938
|
+
baseUnits
|
|
309939
|
+
};
|
|
309940
|
+
}
|
|
309941
|
+
calculateContentTokensAndBaseUnits(content) {
|
|
309942
|
+
const baseUnits = this.baseCalculator.calculateContentTokens(content);
|
|
309943
|
+
return {
|
|
309944
|
+
tokens: Math.round(baseUnits * this.learnedWeight),
|
|
309945
|
+
baseUnits
|
|
309946
|
+
};
|
|
309947
|
+
}
|
|
309948
|
+
// --- Delegation and Weighting ---
|
|
309949
|
+
garbageCollectCache(liveNodeIds) {
|
|
309950
|
+
this.baseCalculator.garbageCollectCache(liveNodeIds);
|
|
309951
|
+
}
|
|
309952
|
+
cacheNodeTokens(node) {
|
|
309953
|
+
return this.baseCalculator.cacheNodeTokens(node);
|
|
309954
|
+
}
|
|
309955
|
+
calculateTokenBreakdown(nodes) {
|
|
309956
|
+
const raw = this.baseCalculator.calculateTokenBreakdown(nodes);
|
|
309957
|
+
return {
|
|
309958
|
+
text: Math.round(raw.text * this.learnedWeight),
|
|
309959
|
+
media: Math.round(raw.media * this.learnedWeight),
|
|
309960
|
+
tool: Math.round(raw.tool * this.learnedWeight),
|
|
309961
|
+
overhead: Math.round(raw.overhead * this.learnedWeight),
|
|
309962
|
+
total: Math.round(raw.total * this.learnedWeight)
|
|
309963
|
+
};
|
|
309964
|
+
}
|
|
309965
|
+
estimateTokensForParts(parts2) {
|
|
309966
|
+
const baseUnits = this.baseCalculator.estimateTokensForParts(parts2);
|
|
309967
|
+
return Math.round(baseUnits * this.learnedWeight);
|
|
309968
|
+
}
|
|
309969
|
+
getTokenCost(node) {
|
|
309970
|
+
const baseUnits = this.baseCalculator.getTokenCost(node);
|
|
309971
|
+
return Math.round(baseUnits * this.learnedWeight);
|
|
309972
|
+
}
|
|
309973
|
+
calculateConcreteListTokens(nodes) {
|
|
309974
|
+
const baseUnits = this.baseCalculator.calculateConcreteListTokens(nodes);
|
|
309975
|
+
return Math.round(baseUnits * this.learnedWeight);
|
|
309976
|
+
}
|
|
309977
|
+
calculateContentTokens(content) {
|
|
309978
|
+
const baseUnits = this.baseCalculator.calculateContentTokens(content);
|
|
309979
|
+
return Math.round(baseUnits * this.learnedWeight);
|
|
309980
|
+
}
|
|
309981
|
+
estimateTokensForString(text) {
|
|
309982
|
+
const baseUnits = this.baseCalculator.estimateTokensForString(text);
|
|
309983
|
+
return Math.round(baseUnits * this.learnedWeight);
|
|
309984
|
+
}
|
|
309985
|
+
tokensToChars(tokens) {
|
|
309986
|
+
return this.baseCalculator.tokensToChars(tokens / this.learnedWeight);
|
|
309987
|
+
}
|
|
309988
|
+
};
|
|
309989
|
+
|
|
309990
|
+
// packages/core/src/context/graph/behaviorRegistry.ts
|
|
309991
|
+
var NodeBehaviorRegistry = class {
|
|
309992
|
+
behaviors = /* @__PURE__ */ new Map();
|
|
309993
|
+
register(behavior) {
|
|
309994
|
+
this.behaviors.set(behavior.type, behavior);
|
|
309995
|
+
}
|
|
309996
|
+
get(type2) {
|
|
309997
|
+
const behavior = this.behaviors.get(type2);
|
|
309998
|
+
if (!behavior) {
|
|
309999
|
+
throw new Error(`Unregistered Node type: ${type2}`);
|
|
310000
|
+
}
|
|
310001
|
+
return behavior;
|
|
310002
|
+
}
|
|
310003
|
+
};
|
|
310004
|
+
|
|
310005
|
+
// packages/core/src/context/graph/builtinBehaviors.ts
|
|
310006
|
+
var UserPromptBehavior = {
|
|
310007
|
+
type: "USER_PROMPT" /* USER_PROMPT */,
|
|
310008
|
+
getEstimatableParts(node) {
|
|
310009
|
+
return [node.payload];
|
|
310010
|
+
}
|
|
310011
|
+
};
|
|
310012
|
+
var AgentThoughtBehavior = {
|
|
310013
|
+
type: "AGENT_THOUGHT" /* AGENT_THOUGHT */,
|
|
310014
|
+
getEstimatableParts(node) {
|
|
310015
|
+
return [node.payload];
|
|
310016
|
+
}
|
|
310017
|
+
};
|
|
310018
|
+
var ToolExecutionBehavior = {
|
|
310019
|
+
type: "TOOL_EXECUTION" /* TOOL_EXECUTION */,
|
|
310020
|
+
getEstimatableParts(node) {
|
|
310021
|
+
return [node.payload];
|
|
310022
|
+
}
|
|
310023
|
+
};
|
|
310024
|
+
var MaskedToolBehavior = {
|
|
310025
|
+
type: "MASKED_TOOL" /* MASKED_TOOL */,
|
|
310026
|
+
getEstimatableParts(node) {
|
|
310027
|
+
return [node.payload];
|
|
310028
|
+
}
|
|
310029
|
+
};
|
|
310030
|
+
var AgentYieldBehavior = {
|
|
310031
|
+
type: "AGENT_YIELD" /* AGENT_YIELD */,
|
|
310032
|
+
getEstimatableParts() {
|
|
310033
|
+
return [];
|
|
310034
|
+
}
|
|
310035
|
+
};
|
|
310036
|
+
var SystemEventBehavior = {
|
|
310037
|
+
type: "SYSTEM_EVENT" /* SYSTEM_EVENT */,
|
|
310038
|
+
getEstimatableParts(node) {
|
|
310039
|
+
return [node.payload];
|
|
310040
|
+
}
|
|
310041
|
+
};
|
|
310042
|
+
var SnapshotBehavior = {
|
|
310043
|
+
type: "SNAPSHOT" /* SNAPSHOT */,
|
|
310044
|
+
getEstimatableParts(node) {
|
|
310045
|
+
return [node.payload];
|
|
310046
|
+
}
|
|
310047
|
+
};
|
|
310048
|
+
var RollingSummaryBehavior = {
|
|
310049
|
+
type: "ROLLING_SUMMARY" /* ROLLING_SUMMARY */,
|
|
310050
|
+
getEstimatableParts(node) {
|
|
310051
|
+
return [node.payload];
|
|
310052
|
+
}
|
|
310053
|
+
};
|
|
310054
|
+
function registerBuiltInBehaviors(registry2) {
|
|
310055
|
+
registry2.register(UserPromptBehavior);
|
|
310056
|
+
registry2.register(AgentThoughtBehavior);
|
|
310057
|
+
registry2.register(ToolExecutionBehavior);
|
|
310058
|
+
registry2.register(MaskedToolBehavior);
|
|
310059
|
+
registry2.register(AgentYieldBehavior);
|
|
310060
|
+
registry2.register(SystemEventBehavior);
|
|
310061
|
+
registry2.register(SnapshotBehavior);
|
|
310062
|
+
registry2.register(RollingSummaryBehavior);
|
|
310063
|
+
}
|
|
310064
|
+
|
|
309020
310065
|
// packages/core/src/context/initializer.ts
|
|
309021
310066
|
async function initializeContextManager(config2, chat, lastPromptId) {
|
|
309022
310067
|
const isV1Enabled = config2.getContextManagementConfig().enabled;
|
|
@@ -309069,6 +310114,14 @@ async function initializeContextManager(config2, chat, lastPromptId) {
|
|
|
309069
310114
|
sessionId: lastPromptId
|
|
309070
310115
|
});
|
|
309071
310116
|
const eventBus = new ContextEventBus();
|
|
310117
|
+
const charsPerToken = 3;
|
|
310118
|
+
const behaviorRegistry = new NodeBehaviorRegistry();
|
|
310119
|
+
registerBuiltInBehaviors(behaviorRegistry);
|
|
310120
|
+
const calculator = new AdaptiveTokenCalculator(
|
|
310121
|
+
charsPerToken,
|
|
310122
|
+
behaviorRegistry,
|
|
310123
|
+
eventBus
|
|
310124
|
+
);
|
|
309072
310125
|
const env2 = new ContextEnvironmentImpl(
|
|
309073
310126
|
() => config2.getBaseLlmClient(),
|
|
309074
310127
|
config2.getSessionId(),
|
|
@@ -309076,8 +310129,13 @@ async function initializeContextManager(config2, chat, lastPromptId) {
|
|
|
309076
310129
|
logDir,
|
|
309077
310130
|
projectTempDir,
|
|
309078
310131
|
tracer,
|
|
309079
|
-
|
|
309080
|
-
eventBus
|
|
310132
|
+
charsPerToken,
|
|
310133
|
+
eventBus,
|
|
310134
|
+
calculator,
|
|
310135
|
+
behaviorRegistry,
|
|
310136
|
+
{
|
|
310137
|
+
calibrateTokenCalculation: !!process.env["GEMINI_CONTEXT_CALIBRATE_TOKEN_CALCULATIONS"]
|
|
310138
|
+
}
|
|
309081
310139
|
);
|
|
309082
310140
|
const orchestrator = new PipelineOrchestrator(
|
|
309083
310141
|
sidecarProfile.buildPipelines(env2),
|
|
@@ -309092,6 +310150,7 @@ async function initializeContextManager(config2, chat, lastPromptId) {
|
|
|
309092
310150
|
tracer,
|
|
309093
310151
|
orchestrator,
|
|
309094
310152
|
chat.agentHistory,
|
|
310153
|
+
calculator,
|
|
309095
310154
|
async () => {
|
|
309096
310155
|
const parts2 = await getEnvironmentContext(config2);
|
|
309097
310156
|
return { role: "user", parts: parts2 };
|
|
@@ -309506,10 +310565,20 @@ var GeminiClient = class {
|
|
|
309506
310565
|
return turn;
|
|
309507
310566
|
}
|
|
309508
310567
|
const modelForLimitCheck = this._getActiveModelForCurrentTurn();
|
|
310568
|
+
let currentBaseUnits = 0;
|
|
309509
310569
|
if (this.config.getContextManagementConfig().enabled) {
|
|
309510
310570
|
if (this.contextManager) {
|
|
309511
310571
|
const pendingRequest = createUserContent(request);
|
|
309512
|
-
const {
|
|
310572
|
+
const {
|
|
310573
|
+
history: newHistory,
|
|
310574
|
+
didApplyManagement,
|
|
310575
|
+
baseUnits
|
|
310576
|
+
} = await this.contextManager.renderHistory(
|
|
310577
|
+
pendingRequest,
|
|
310578
|
+
void 0,
|
|
310579
|
+
signal
|
|
310580
|
+
);
|
|
310581
|
+
currentBaseUnits = baseUnits;
|
|
309513
310582
|
if (didApplyManagement) {
|
|
309514
310583
|
this.getChat().setHistory(newHistory, { silent: true });
|
|
309515
310584
|
}
|
|
@@ -309633,6 +310702,15 @@ var GeminiClient = class {
|
|
|
309633
310702
|
break;
|
|
309634
310703
|
}
|
|
309635
310704
|
yield event;
|
|
310705
|
+
if (event.type === "finished" /* Finished */ && this.contextManager) {
|
|
310706
|
+
const usageMetadata = event.value.usageMetadata;
|
|
310707
|
+
if (usageMetadata && usageMetadata.promptTokenCount !== void 0) {
|
|
310708
|
+
this.contextManager.getEnvironment().eventBus.emitTokenGroundTruth({
|
|
310709
|
+
actualTokens: usageMetadata.promptTokenCount,
|
|
310710
|
+
promptBaseUnits: currentBaseUnits
|
|
310711
|
+
});
|
|
310712
|
+
}
|
|
310713
|
+
}
|
|
309636
310714
|
this.updateTelemetryTokenCount();
|
|
309637
310715
|
if (event.type === "error" /* Error */) {
|
|
309638
310716
|
isError = true;
|
|
@@ -310277,7 +311355,8 @@ var ToolExecutor = class {
|
|
|
310277
311355
|
new Error(toolResult.error.message),
|
|
310278
311356
|
toolResult.error.type,
|
|
310279
311357
|
displayText,
|
|
310280
|
-
toolResult.tailToolCallRequest
|
|
311358
|
+
toolResult.tailToolCallRequest,
|
|
311359
|
+
toolResult.display
|
|
310281
311360
|
);
|
|
310282
311361
|
}
|
|
310283
311362
|
} catch (executionError) {
|
|
@@ -310420,6 +311499,7 @@ var ToolExecutor = class {
|
|
|
310420
311499
|
response: {
|
|
310421
311500
|
callId: call.request.callId,
|
|
310422
311501
|
responseParts,
|
|
311502
|
+
display: toolResult?.display,
|
|
310423
311503
|
resultDisplay: toolResult?.returnDisplay,
|
|
310424
311504
|
error: void 0,
|
|
310425
311505
|
errorType: void 0,
|
|
@@ -310448,6 +311528,7 @@ var ToolExecutor = class {
|
|
|
310448
311528
|
const successResponse = {
|
|
310449
311529
|
callId,
|
|
310450
311530
|
responseParts: response,
|
|
311531
|
+
display: toolResult.display,
|
|
310451
311532
|
resultDisplay: toolResult.returnDisplay,
|
|
310452
311533
|
error: void 0,
|
|
310453
311534
|
errorType: void 0,
|
|
@@ -310472,12 +311553,13 @@ var ToolExecutor = class {
|
|
|
310472
311553
|
tailToolCallRequest: toolResult.tailToolCallRequest
|
|
310473
311554
|
};
|
|
310474
311555
|
}
|
|
310475
|
-
createErrorResult(call, error40, errorType, returnDisplay, tailToolCallRequest) {
|
|
311556
|
+
createErrorResult(call, error40, errorType, returnDisplay, tailToolCallRequest, display) {
|
|
310476
311557
|
const response = this.createErrorResponse(
|
|
310477
311558
|
call.request,
|
|
310478
311559
|
error40,
|
|
310479
311560
|
errorType,
|
|
310480
|
-
returnDisplay
|
|
311561
|
+
returnDisplay,
|
|
311562
|
+
display
|
|
310481
311563
|
);
|
|
310482
311564
|
const startTime = "startTime" in call ? call.startTime : void 0;
|
|
310483
311565
|
return {
|
|
@@ -310492,11 +311574,12 @@ var ToolExecutor = class {
|
|
|
310492
311574
|
tailToolCallRequest
|
|
310493
311575
|
};
|
|
310494
311576
|
}
|
|
310495
|
-
createErrorResponse(request, error40, errorType, returnDisplay) {
|
|
311577
|
+
createErrorResponse(request, error40, errorType, returnDisplay, display) {
|
|
310496
311578
|
const displayText = returnDisplay ?? error40.message;
|
|
310497
311579
|
return {
|
|
310498
311580
|
callId: request.callId,
|
|
310499
311581
|
error: error40,
|
|
311582
|
+
display,
|
|
310500
311583
|
responseParts: [
|
|
310501
311584
|
{
|
|
310502
311585
|
functionResponse: {
|
|
@@ -310809,6 +311892,16 @@ var Scheduler = class {
|
|
|
310809
311892
|
() => {
|
|
310810
311893
|
try {
|
|
310811
311894
|
const invocation = tool.build(request.args);
|
|
311895
|
+
if (!request.display) {
|
|
311896
|
+
request.display = populateToolDisplay({
|
|
311897
|
+
name: tool.name,
|
|
311898
|
+
invocation,
|
|
311899
|
+
displayName: tool.displayName
|
|
311900
|
+
});
|
|
311901
|
+
if (!request.display.description) {
|
|
311902
|
+
request.display.description = tool.description;
|
|
311903
|
+
}
|
|
311904
|
+
}
|
|
310812
311905
|
return {
|
|
310813
311906
|
status: "validating" /* Validating */,
|
|
310814
311907
|
request,
|
|
@@ -311674,8 +312767,8 @@ var WorkspaceContext = class {
|
|
|
311674
312767
|
* @returns True if the path is within the root directory, false otherwise
|
|
311675
312768
|
*/
|
|
311676
312769
|
isPathWithinRoot(pathToCheck, rootDirectory) {
|
|
311677
|
-
const
|
|
311678
|
-
return !
|
|
312770
|
+
const relative11 = path61.relative(rootDirectory, pathToCheck);
|
|
312771
|
+
return !relative11.startsWith(`..${path61.sep}`) && relative11 !== ".." && !path61.isAbsolute(relative11);
|
|
311679
312772
|
}
|
|
311680
312773
|
};
|
|
311681
312774
|
|
|
@@ -312023,6 +313116,7 @@ var LocalAgentExecutor = class _LocalAgentExecutor {
|
|
|
312023
313116
|
compressionService;
|
|
312024
313117
|
parentCallId;
|
|
312025
313118
|
hasFailedCompressionAttempt = false;
|
|
313119
|
+
cache;
|
|
312026
313120
|
get executionContext() {
|
|
312027
313121
|
return {
|
|
312028
313122
|
config: this.context.config,
|
|
@@ -312159,6 +313253,7 @@ var LocalAgentExecutor = class _LocalAgentExecutor {
|
|
|
312159
313253
|
this.onActivity = onActivity;
|
|
312160
313254
|
this.compressionService = new ChatCompressionService();
|
|
312161
313255
|
this.parentCallId = parentCallId;
|
|
313256
|
+
this.cache = new import_lru_cache.default(10);
|
|
312162
313257
|
this.agentId = Math.random().toString(36).slice(2, 8);
|
|
312163
313258
|
}
|
|
312164
313259
|
/**
|
|
@@ -312397,7 +313492,14 @@ var LocalAgentExecutor = class _LocalAgentExecutor {
|
|
|
312397
313492
|
"user_steering"
|
|
312398
313493
|
);
|
|
312399
313494
|
const formattedInitialHints = formatUserHintsForModel(initialHints);
|
|
312400
|
-
|
|
313495
|
+
let environmentMemory;
|
|
313496
|
+
if (this.context.config.isJitContextEnabled?.()) {
|
|
313497
|
+
environmentMemory = this.definition.includeExtensionContext === false ? this.context.config.getSessionMemory({
|
|
313498
|
+
includeExtensionContext: false
|
|
313499
|
+
}) : this.context.config.getSessionMemory();
|
|
313500
|
+
} else {
|
|
313501
|
+
environmentMemory = this.context.config.getEnvironmentMemory();
|
|
313502
|
+
}
|
|
312401
313503
|
const initialParts = [];
|
|
312402
313504
|
if (environmentMemory) {
|
|
312403
313505
|
initialParts.push({ text: environmentMemory });
|
|
@@ -312627,22 +313729,26 @@ var LocalAgentExecutor = class _LocalAgentExecutor {
|
|
|
312627
313729
|
const requestedModel = resolvedConfig.model;
|
|
312628
313730
|
let modelToUse;
|
|
312629
313731
|
if (isAutoModel(requestedModel)) {
|
|
312630
|
-
|
|
312631
|
-
|
|
312632
|
-
|
|
312633
|
-
|
|
312634
|
-
|
|
312635
|
-
|
|
312636
|
-
|
|
312637
|
-
|
|
312638
|
-
|
|
312639
|
-
|
|
312640
|
-
|
|
312641
|
-
|
|
312642
|
-
|
|
312643
|
-
|
|
312644
|
-
|
|
312645
|
-
|
|
313732
|
+
modelToUse = this.cache.get("modelToUse");
|
|
313733
|
+
if (!modelToUse) {
|
|
313734
|
+
try {
|
|
313735
|
+
const routingContext = {
|
|
313736
|
+
history: chat.getHistory(
|
|
313737
|
+
/*curated=*/
|
|
313738
|
+
true
|
|
313739
|
+
),
|
|
313740
|
+
request: message.parts || [],
|
|
313741
|
+
signal,
|
|
313742
|
+
requestedModel
|
|
313743
|
+
};
|
|
313744
|
+
const router = this.context.config.getModelRouterService();
|
|
313745
|
+
const decision = await router.route(routingContext);
|
|
313746
|
+
modelToUse = decision.model;
|
|
313747
|
+
} catch (error40) {
|
|
313748
|
+
debugLogger.warn(`Error during model routing: ${error40}`);
|
|
313749
|
+
modelToUse = DEFAULT_GEMINI_MODEL;
|
|
313750
|
+
}
|
|
313751
|
+
this.cache.set("modelToUse", modelToUse);
|
|
312646
313752
|
}
|
|
312647
313753
|
} else {
|
|
312648
313754
|
modelToUse = requestedModel;
|
|
@@ -312879,12 +313985,16 @@ var LocalAgentExecutor = class _LocalAgentExecutor {
|
|
|
312879
313985
|
const part = syncResults.get(callId);
|
|
312880
313986
|
if (part) {
|
|
312881
313987
|
toolResponseParts.push(part);
|
|
313988
|
+
continue;
|
|
312882
313989
|
}
|
|
312883
|
-
|
|
312884
|
-
|
|
312885
|
-
|
|
312886
|
-
|
|
312887
|
-
}
|
|
313990
|
+
const isAborted = signal.aborted;
|
|
313991
|
+
const isTaskComplete = functionCall.name === COMPLETE_TASK_TOOL_NAME && taskCompleted;
|
|
313992
|
+
if (isAborted || isTaskComplete) {
|
|
313993
|
+
continue;
|
|
313994
|
+
}
|
|
313995
|
+
throw new Error(
|
|
313996
|
+
`[LocalAgentExecutor] Critical System Failure: Tool execution result was lost/dropped by the scheduler for callId ${callId} (${functionCall.name}). This indicates an internal race condition or scheduler bug.`
|
|
313997
|
+
);
|
|
312888
313998
|
}
|
|
312889
313999
|
return {
|
|
312890
314000
|
nextMessage: { role: "user", parts: toolResponseParts },
|
|
@@ -313218,7 +314328,7 @@ var LocalSubagentInvocation = class extends BaseToolInvocation {
|
|
|
313218
314328
|
isSubagentProgress: true,
|
|
313219
314329
|
agentName: this.definition.name,
|
|
313220
314330
|
recentActivity: [],
|
|
313221
|
-
state: "running"
|
|
314331
|
+
state: "running" /* RUNNING */
|
|
313222
314332
|
};
|
|
313223
314333
|
updateOutput(initialProgress);
|
|
313224
314334
|
}
|
|
@@ -313229,14 +314339,14 @@ var LocalSubagentInvocation = class extends BaseToolInvocation {
|
|
|
313229
314339
|
case "THOUGHT_CHUNK": {
|
|
313230
314340
|
const text = String(activity.data["text"]);
|
|
313231
314341
|
const lastItem = recentActivity[recentActivity.length - 1];
|
|
313232
|
-
if (lastItem && lastItem.type === "thought" && lastItem.status === "running") {
|
|
314342
|
+
if (lastItem && lastItem.type === "thought" && lastItem.status === "running" /* RUNNING */) {
|
|
313233
314343
|
lastItem.content = sanitizeThoughtContent(text);
|
|
313234
314344
|
} else {
|
|
313235
314345
|
recentActivity.push({
|
|
313236
314346
|
id: randomUUID14(),
|
|
313237
314347
|
type: "thought",
|
|
313238
314348
|
content: sanitizeThoughtContent(text),
|
|
313239
|
-
status: "running"
|
|
314349
|
+
status: "running" /* RUNNING */
|
|
313240
314350
|
});
|
|
313241
314351
|
}
|
|
313242
314352
|
updated = true;
|
|
@@ -313260,7 +314370,7 @@ var LocalSubagentInvocation = class extends BaseToolInvocation {
|
|
|
313260
314370
|
displayName,
|
|
313261
314371
|
description,
|
|
313262
314372
|
args: args2,
|
|
313263
|
-
status: "running"
|
|
314373
|
+
status: "running" /* RUNNING */
|
|
313264
314374
|
});
|
|
313265
314375
|
updated = true;
|
|
313266
314376
|
const latestTool = recentActivity[recentActivity.length - 1];
|
|
@@ -313274,8 +314384,8 @@ var LocalSubagentInvocation = class extends BaseToolInvocation {
|
|
|
313274
314384
|
const data = activity.data["data"];
|
|
313275
314385
|
const isError = isToolActivityError(data);
|
|
313276
314386
|
for (let i3 = recentActivity.length - 1; i3 >= 0; i3--) {
|
|
313277
|
-
if (recentActivity[i3].type === "tool_call" && recentActivity[i3].content === name3 && recentActivity[i3].status === "running") {
|
|
313278
|
-
recentActivity[i3].status = isError ? "error" : "completed"
|
|
314387
|
+
if (recentActivity[i3].type === "tool_call" && recentActivity[i3].content === name3 && recentActivity[i3].status === "running" /* RUNNING */) {
|
|
314388
|
+
recentActivity[i3].status = isError ? "error" /* ERROR */ : "completed" /* COMPLETED */;
|
|
313279
314389
|
updated = true;
|
|
313280
314390
|
this.publishActivity(recentActivity[i3]);
|
|
313281
314391
|
break;
|
|
@@ -313292,16 +314402,16 @@ var LocalSubagentInvocation = class extends BaseToolInvocation {
|
|
|
313292
314402
|
const toolName = activity.data["name"] ? String(activity.data["name"]) : void 0;
|
|
313293
314403
|
if (toolName && (isCancellation || isRejection)) {
|
|
313294
314404
|
for (let i3 = recentActivity.length - 1; i3 >= 0; i3--) {
|
|
313295
|
-
if (recentActivity[i3].type === "tool_call" && recentActivity[i3].content === toolName && recentActivity[i3].status === "running") {
|
|
313296
|
-
recentActivity[i3].status = "cancelled"
|
|
314405
|
+
if (recentActivity[i3].type === "tool_call" && recentActivity[i3].content === toolName && recentActivity[i3].status === "running" /* RUNNING */) {
|
|
314406
|
+
recentActivity[i3].status = "cancelled" /* CANCELLED */;
|
|
313297
314407
|
updated = true;
|
|
313298
314408
|
break;
|
|
313299
314409
|
}
|
|
313300
314410
|
}
|
|
313301
314411
|
} else if (toolName) {
|
|
313302
314412
|
for (let i3 = recentActivity.length - 1; i3 >= 0; i3--) {
|
|
313303
|
-
if (recentActivity[i3].type === "tool_call" && recentActivity[i3].content === toolName && recentActivity[i3].status === "running") {
|
|
313304
|
-
recentActivity[i3].status = "error"
|
|
314413
|
+
if (recentActivity[i3].type === "tool_call" && recentActivity[i3].content === toolName && recentActivity[i3].status === "running" /* RUNNING */) {
|
|
314414
|
+
recentActivity[i3].status = "error" /* ERROR */;
|
|
313305
314415
|
updated = true;
|
|
313306
314416
|
break;
|
|
313307
314417
|
}
|
|
@@ -313311,7 +314421,7 @@ var LocalSubagentInvocation = class extends BaseToolInvocation {
|
|
|
313311
314421
|
id: randomUUID14(),
|
|
313312
314422
|
type: "thought",
|
|
313313
314423
|
content: isCancellation || isRejection ? sanitizedError : `Error: ${sanitizedError}`,
|
|
313314
|
-
status: isCancellation || isRejection ? "cancelled" : "error"
|
|
314424
|
+
status: isCancellation || isRejection ? "cancelled" /* CANCELLED */ : "error" /* ERROR */
|
|
313315
314425
|
});
|
|
313316
314426
|
updated = true;
|
|
313317
314427
|
break;
|
|
@@ -313325,7 +314435,7 @@ var LocalSubagentInvocation = class extends BaseToolInvocation {
|
|
|
313325
314435
|
agentName: this.definition.name,
|
|
313326
314436
|
recentActivity: [...recentActivity],
|
|
313327
314437
|
// Copy to avoid mutation issues
|
|
313328
|
-
state: "running"
|
|
314438
|
+
state: "running" /* RUNNING */
|
|
313329
314439
|
};
|
|
313330
314440
|
updateOutput(progress2);
|
|
313331
314441
|
}
|
|
@@ -313341,7 +314451,7 @@ var LocalSubagentInvocation = class extends BaseToolInvocation {
|
|
|
313341
314451
|
isSubagentProgress: true,
|
|
313342
314452
|
agentName: this.definition.name,
|
|
313343
314453
|
recentActivity: [...recentActivity],
|
|
313344
|
-
state: "cancelled"
|
|
314454
|
+
state: "cancelled" /* CANCELLED */
|
|
313345
314455
|
};
|
|
313346
314456
|
if (updateOutput) {
|
|
313347
314457
|
updateOutput(progress2);
|
|
@@ -313354,7 +314464,7 @@ var LocalSubagentInvocation = class extends BaseToolInvocation {
|
|
|
313354
314464
|
isSubagentProgress: true,
|
|
313355
314465
|
agentName: this.definition.name,
|
|
313356
314466
|
recentActivity: [...recentActivity],
|
|
313357
|
-
state: "completed"
|
|
314467
|
+
state: "completed" /* COMPLETED */,
|
|
313358
314468
|
result: output.result,
|
|
313359
314469
|
terminateReason: output.terminate_reason
|
|
313360
314470
|
};
|
|
@@ -313375,18 +314485,18 @@ ${output.result}`;
|
|
|
313375
314485
|
debugLogger.error(`Subagent '${this.definition.name}' failed:`, error40);
|
|
313376
314486
|
const isAbort = error40 instanceof Error && error40.name === "AbortError" || errorMessage.includes("Aborted");
|
|
313377
314487
|
for (const item of recentActivity) {
|
|
313378
|
-
if (item.status === "running") {
|
|
313379
|
-
item.status = isAbort ? "cancelled" : "error"
|
|
314488
|
+
if (item.status === "running" /* RUNNING */) {
|
|
314489
|
+
item.status = isAbort ? "cancelled" /* CANCELLED */ : "error" /* ERROR */;
|
|
313380
314490
|
}
|
|
313381
314491
|
}
|
|
313382
314492
|
if (!isAbort) {
|
|
313383
314493
|
const lastActivity = recentActivity[recentActivity.length - 1];
|
|
313384
|
-
if (!lastActivity || lastActivity.status !== "error") {
|
|
314494
|
+
if (!lastActivity || lastActivity.status !== "error" /* ERROR */) {
|
|
313385
314495
|
recentActivity.push({
|
|
313386
314496
|
id: randomUUID14(),
|
|
313387
314497
|
type: "thought",
|
|
313388
314498
|
content: `Error: ${errorMessage}`,
|
|
313389
|
-
status: "error"
|
|
314499
|
+
status: "error" /* ERROR */
|
|
313390
314500
|
});
|
|
313391
314501
|
}
|
|
313392
314502
|
}
|
|
@@ -313394,7 +314504,7 @@ ${output.result}`;
|
|
|
313394
314504
|
isSubagentProgress: true,
|
|
313395
314505
|
agentName: this.definition.name,
|
|
313396
314506
|
recentActivity: [...recentActivity],
|
|
313397
|
-
state: isAbort ? "cancelled" : "error"
|
|
314507
|
+
state: isAbort ? "cancelled" /* CANCELLED */ : "error" /* ERROR */
|
|
313398
314508
|
};
|
|
313399
314509
|
if (updateOutput) {
|
|
313400
314510
|
updateOutput(progress);
|
|
@@ -313506,7 +314616,7 @@ var A2AResultReassembler = class {
|
|
|
313506
314616
|
id: "auth-required",
|
|
313507
314617
|
type: "thought",
|
|
313508
314618
|
content: AUTH_REQUIRED_MSG,
|
|
313509
|
-
status: "running"
|
|
314619
|
+
status: "running" /* RUNNING */
|
|
313510
314620
|
});
|
|
313511
314621
|
}
|
|
313512
314622
|
this.messageLog.forEach((msg, index) => {
|
|
@@ -313514,7 +314624,7 @@ var A2AResultReassembler = class {
|
|
|
313514
314624
|
id: `msg-${index}`,
|
|
313515
314625
|
type: "thought",
|
|
313516
314626
|
content: msg.trim(),
|
|
313517
|
-
status: "completed"
|
|
314627
|
+
status: "completed" /* COMPLETED */
|
|
313518
314628
|
});
|
|
313519
314629
|
});
|
|
313520
314630
|
if (items.length === 0 && !isAuthRequired) {
|
|
@@ -313522,7 +314632,7 @@ var A2AResultReassembler = class {
|
|
|
313522
314632
|
id: "pending",
|
|
313523
314633
|
type: "thought",
|
|
313524
314634
|
content: "Working...",
|
|
313525
|
-
status: "running"
|
|
314635
|
+
status: "running" /* RUNNING */
|
|
313526
314636
|
});
|
|
313527
314637
|
}
|
|
313528
314638
|
return items;
|
|
@@ -313714,13 +314824,13 @@ var RemoteAgentInvocation = class _RemoteAgentInvocation extends BaseToolInvocat
|
|
|
313714
314824
|
updateOutput({
|
|
313715
314825
|
isSubagentProgress: true,
|
|
313716
314826
|
agentName,
|
|
313717
|
-
state: "running"
|
|
314827
|
+
state: "running" /* RUNNING */,
|
|
313718
314828
|
recentActivity: [
|
|
313719
314829
|
{
|
|
313720
314830
|
id: "pending",
|
|
313721
314831
|
type: "thought",
|
|
313722
314832
|
content: "Working...",
|
|
313723
|
-
status: "running"
|
|
314833
|
+
status: "running" /* RUNNING */
|
|
313724
314834
|
}
|
|
313725
314835
|
]
|
|
313726
314836
|
});
|
|
@@ -313761,7 +314871,7 @@ var RemoteAgentInvocation = class _RemoteAgentInvocation extends BaseToolInvocat
|
|
|
313761
314871
|
updateOutput({
|
|
313762
314872
|
isSubagentProgress: true,
|
|
313763
314873
|
agentName,
|
|
313764
|
-
state: "running"
|
|
314874
|
+
state: "running" /* RUNNING */,
|
|
313765
314875
|
recentActivity: reassembler.toActivityItems(),
|
|
313766
314876
|
result: reassembler.toString()
|
|
313767
314877
|
});
|
|
@@ -313787,7 +314897,7 @@ ${JSON.stringify(finalResponse, null, 2)}`
|
|
|
313787
314897
|
const finalProgress = {
|
|
313788
314898
|
isSubagentProgress: true,
|
|
313789
314899
|
agentName,
|
|
313790
|
-
state: "completed"
|
|
314900
|
+
state: "completed" /* COMPLETED */,
|
|
313791
314901
|
result: finalOutput,
|
|
313792
314902
|
recentActivity: reassembler.toActivityItems()
|
|
313793
314903
|
};
|
|
@@ -313807,7 +314917,7 @@ ${errorMessage}` : errorMessage;
|
|
|
313807
314917
|
const errorProgress = {
|
|
313808
314918
|
isSubagentProgress: true,
|
|
313809
314919
|
agentName,
|
|
313810
|
-
state: "error"
|
|
314920
|
+
state: "error" /* ERROR */,
|
|
313811
314921
|
result: fullDisplay,
|
|
313812
314922
|
recentActivity: reassembler.toActivityItems()
|
|
313813
314923
|
};
|
|
@@ -315512,7 +316622,7 @@ var BrowserAgentInvocation = class extends BaseToolInvocation {
|
|
|
315512
316622
|
isSubagentProgress: true,
|
|
315513
316623
|
agentName: this.agentName,
|
|
315514
316624
|
recentActivity: [],
|
|
315515
|
-
state: "running"
|
|
316625
|
+
state: "running" /* RUNNING */
|
|
315516
316626
|
};
|
|
315517
316627
|
updateOutput(initialProgress);
|
|
315518
316628
|
}
|
|
@@ -315522,7 +316632,7 @@ var BrowserAgentInvocation = class extends BaseToolInvocation {
|
|
|
315522
316632
|
id: randomUUID15(),
|
|
315523
316633
|
type: "thought",
|
|
315524
316634
|
content: sanitizedMsg,
|
|
315525
|
-
status: "completed"
|
|
316635
|
+
status: "completed" /* COMPLETED */
|
|
315526
316636
|
});
|
|
315527
316637
|
if (recentActivity.length > MAX_RECENT_ACTIVITY) {
|
|
315528
316638
|
recentActivity = recentActivity.slice(-MAX_RECENT_ACTIVITY);
|
|
@@ -315531,7 +316641,7 @@ var BrowserAgentInvocation = class extends BaseToolInvocation {
|
|
|
315531
316641
|
isSubagentProgress: true,
|
|
315532
316642
|
agentName: this.agentName,
|
|
315533
316643
|
recentActivity: [...recentActivity],
|
|
315534
|
-
state: "running"
|
|
316644
|
+
state: "running" /* RUNNING */
|
|
315535
316645
|
});
|
|
315536
316646
|
} : void 0;
|
|
315537
316647
|
const result2 = await createBrowserAgentDefinition(
|
|
@@ -315550,14 +316660,14 @@ var BrowserAgentInvocation = class extends BaseToolInvocation {
|
|
|
315550
316660
|
case "THOUGHT_CHUNK": {
|
|
315551
316661
|
const text = String(activity.data["text"]);
|
|
315552
316662
|
const lastItem = recentActivity[recentActivity.length - 1];
|
|
315553
|
-
if (lastItem && lastItem.type === "thought" && lastItem.status === "running") {
|
|
316663
|
+
if (lastItem && lastItem.type === "thought" && lastItem.status === "running" /* RUNNING */) {
|
|
315554
316664
|
lastItem.content = sanitizeThoughtContent(text);
|
|
315555
316665
|
} else {
|
|
315556
316666
|
recentActivity.push({
|
|
315557
316667
|
id: randomUUID15(),
|
|
315558
316668
|
type: "thought",
|
|
315559
316669
|
content: sanitizeThoughtContent(text),
|
|
315560
|
-
status: "running"
|
|
316670
|
+
status: "running" /* RUNNING */
|
|
315561
316671
|
});
|
|
315562
316672
|
}
|
|
315563
316673
|
updated = true;
|
|
@@ -315578,7 +316688,7 @@ var BrowserAgentInvocation = class extends BaseToolInvocation {
|
|
|
315578
316688
|
displayName,
|
|
315579
316689
|
description,
|
|
315580
316690
|
args: args2,
|
|
315581
|
-
status: "running"
|
|
316691
|
+
status: "running" /* RUNNING */
|
|
315582
316692
|
});
|
|
315583
316693
|
updated = true;
|
|
315584
316694
|
break;
|
|
@@ -315588,8 +316698,8 @@ var BrowserAgentInvocation = class extends BaseToolInvocation {
|
|
|
315588
316698
|
const data = activity.data["data"];
|
|
315589
316699
|
const isError = isToolActivityError(data);
|
|
315590
316700
|
for (let i3 = recentActivity.length - 1; i3 >= 0; i3--) {
|
|
315591
|
-
if (recentActivity[i3].type === "tool_call" && callId != null && recentActivity[i3].id === callId && recentActivity[i3].status === "running") {
|
|
315592
|
-
recentActivity[i3].status = isError ? "error" : "completed"
|
|
316701
|
+
if (recentActivity[i3].type === "tool_call" && callId != null && recentActivity[i3].id === callId && recentActivity[i3].status === "running" /* RUNNING */) {
|
|
316702
|
+
recentActivity[i3].status = isError ? "error" /* ERROR */ : "completed" /* COMPLETED */;
|
|
315593
316703
|
updated = true;
|
|
315594
316704
|
break;
|
|
315595
316705
|
}
|
|
@@ -315600,10 +316710,10 @@ var BrowserAgentInvocation = class extends BaseToolInvocation {
|
|
|
315600
316710
|
const error40 = String(activity.data["error"]);
|
|
315601
316711
|
const isCancellation = error40 === "Request cancelled.";
|
|
315602
316712
|
const callId = activity.data["callId"] ? String(activity.data["callId"]) : void 0;
|
|
315603
|
-
const newStatus = isCancellation ? "cancelled" : "error"
|
|
316713
|
+
const newStatus = isCancellation ? "cancelled" /* CANCELLED */ : "error" /* ERROR */;
|
|
315604
316714
|
if (callId) {
|
|
315605
316715
|
for (let i3 = recentActivity.length - 1; i3 >= 0; i3--) {
|
|
315606
|
-
if (recentActivity[i3].type === "tool_call" && recentActivity[i3].id === callId && recentActivity[i3].status === "running") {
|
|
316716
|
+
if (recentActivity[i3].type === "tool_call" && recentActivity[i3].id === callId && recentActivity[i3].status === "running" /* RUNNING */) {
|
|
315607
316717
|
recentActivity[i3].status = newStatus;
|
|
315608
316718
|
updated = true;
|
|
315609
316719
|
break;
|
|
@@ -315611,7 +316721,7 @@ var BrowserAgentInvocation = class extends BaseToolInvocation {
|
|
|
315611
316721
|
}
|
|
315612
316722
|
} else {
|
|
315613
316723
|
for (const item of recentActivity) {
|
|
315614
|
-
if (item.type === "tool_call" && item.status === "running") {
|
|
316724
|
+
if (item.type === "tool_call" && item.status === "running" /* RUNNING */) {
|
|
315615
316725
|
item.status = newStatus;
|
|
315616
316726
|
updated = true;
|
|
315617
316727
|
}
|
|
@@ -315638,7 +316748,7 @@ var BrowserAgentInvocation = class extends BaseToolInvocation {
|
|
|
315638
316748
|
isSubagentProgress: true,
|
|
315639
316749
|
agentName: this.agentName,
|
|
315640
316750
|
recentActivity: [...recentActivity],
|
|
315641
|
-
state: "running"
|
|
316751
|
+
state: "running" /* RUNNING */
|
|
315642
316752
|
};
|
|
315643
316753
|
updateOutput(progress2);
|
|
315644
316754
|
}
|
|
@@ -315664,11 +316774,11 @@ Result:
|
|
|
315664
316774
|
${output.result}`;
|
|
315665
316775
|
let progressState;
|
|
315666
316776
|
if (output.terminate_reason === "ABORTED" /* ABORTED */) {
|
|
315667
|
-
progressState = "cancelled"
|
|
316777
|
+
progressState = "cancelled" /* CANCELLED */;
|
|
315668
316778
|
} else if (output.terminate_reason === "GOAL" /* GOAL */) {
|
|
315669
|
-
progressState = "completed"
|
|
316779
|
+
progressState = "completed" /* COMPLETED */;
|
|
315670
316780
|
} else {
|
|
315671
|
-
progressState = "error"
|
|
316781
|
+
progressState = "error" /* ERROR */;
|
|
315672
316782
|
}
|
|
315673
316783
|
const progress = {
|
|
315674
316784
|
isSubagentProgress: true,
|
|
@@ -315690,15 +316800,15 @@ ${output.result}`;
|
|
|
315690
316800
|
const isAbort = error40 instanceof Error && error40.name === "AbortError" || rawErrorMessage.includes("Aborted");
|
|
315691
316801
|
const errorMessage = sanitizeErrorMessage(rawErrorMessage);
|
|
315692
316802
|
for (const item of recentActivity) {
|
|
315693
|
-
if (item.status === "running") {
|
|
315694
|
-
item.status = isAbort ? "cancelled" : "error"
|
|
316803
|
+
if (item.status === "running" /* RUNNING */) {
|
|
316804
|
+
item.status = isAbort ? "cancelled" /* CANCELLED */ : "error" /* ERROR */;
|
|
315695
316805
|
}
|
|
315696
316806
|
}
|
|
315697
316807
|
const progress = {
|
|
315698
316808
|
isSubagentProgress: true,
|
|
315699
316809
|
agentName: this.agentName,
|
|
315700
316810
|
recentActivity: [...recentActivity],
|
|
315701
|
-
state: isAbort ? "cancelled" : "error"
|
|
316811
|
+
state: isAbort ? "cancelled" /* CANCELLED */ : "error" /* ERROR */
|
|
315702
316812
|
};
|
|
315703
316813
|
if (updateOutput) {
|
|
315704
316814
|
updateOutput(progress);
|
|
@@ -316478,7 +317588,12 @@ ${reminder}`;
|
|
|
316478
317588
|
"Invalid response from Local Gemini API: No text found"
|
|
316479
317589
|
);
|
|
316480
317590
|
}
|
|
316481
|
-
|
|
317591
|
+
const parsed = JSON.parse(result2.text);
|
|
317592
|
+
const isRecord3 = (val) => typeof val === "object" && val !== null && !Array.isArray(val);
|
|
317593
|
+
if (isRecord3(parsed)) {
|
|
317594
|
+
return parsed;
|
|
317595
|
+
}
|
|
317596
|
+
throw new Error("Invalid JSON response format from Local LLM");
|
|
316482
317597
|
} catch (error40) {
|
|
316483
317598
|
debugLogger.error(
|
|
316484
317599
|
`[LocalLiteRtLmClient] Failed to generate content:`,
|
|
@@ -321099,9 +322214,18 @@ var GitService = class _GitService {
|
|
|
321099
322214
|
const gitConfigPath = path66.join(repoDir, ".gitconfig");
|
|
321100
322215
|
const systemConfigPath = path66.join(repoDir, ".gitconfig_system_empty");
|
|
321101
322216
|
return {
|
|
322217
|
+
...sanitizeEnvironment(
|
|
322218
|
+
process.env,
|
|
322219
|
+
getSecureSanitizationConfig({
|
|
322220
|
+
enableEnvironmentVariableRedaction: true
|
|
322221
|
+
})
|
|
322222
|
+
),
|
|
321102
322223
|
// Prevent git from using the user's global git config.
|
|
321103
322224
|
GIT_CONFIG_GLOBAL: gitConfigPath,
|
|
321104
322225
|
GIT_CONFIG_SYSTEM: systemConfigPath,
|
|
322226
|
+
// Ensure we don't inherit isolation-breaking variables from the user environment.
|
|
322227
|
+
GIT_DIR: void 0,
|
|
322228
|
+
GIT_WORK_TREE: void 0,
|
|
321105
322229
|
// Explicitly provide identity to prevent "Author identity unknown" errors
|
|
321106
322230
|
// inside sandboxed environments like Docker where the gitconfig might not
|
|
321107
322231
|
// be picked up properly.
|
|
@@ -321158,9 +322282,9 @@ var GitService = class _GitService {
|
|
|
321158
322282
|
get shadowGitRepository() {
|
|
321159
322283
|
const repoDir = this.getHistoryDir();
|
|
321160
322284
|
return simpleGit(this.projectRoot).env({
|
|
322285
|
+
...this.getShadowRepoEnv(repoDir),
|
|
321161
322286
|
GIT_DIR: path66.join(repoDir, ".git"),
|
|
321162
|
-
GIT_WORK_TREE: this.projectRoot
|
|
321163
|
-
...this.getShadowRepoEnv(repoDir)
|
|
322287
|
+
GIT_WORK_TREE: this.projectRoot
|
|
321164
322288
|
});
|
|
321165
322289
|
}
|
|
321166
322290
|
async getCurrentCommitHash() {
|
|
@@ -322109,16 +323233,19 @@ var TrackerVisualizeTool = class _TrackerVisualizeTool extends BaseDeclarativeTo
|
|
|
322109
323233
|
// packages/core/src/availability/modelAvailabilityService.ts
|
|
322110
323234
|
var ModelAvailabilityService = class {
|
|
322111
323235
|
health = /* @__PURE__ */ new Map();
|
|
322112
|
-
markTerminal(
|
|
323236
|
+
markTerminal(modelId, reason) {
|
|
323237
|
+
const model = normalizeModelId(modelId);
|
|
322113
323238
|
this.setState(model, {
|
|
322114
323239
|
status: "terminal",
|
|
322115
323240
|
reason
|
|
322116
323241
|
});
|
|
322117
323242
|
}
|
|
322118
|
-
markHealthy(
|
|
323243
|
+
markHealthy(modelId) {
|
|
323244
|
+
const model = normalizeModelId(modelId);
|
|
322119
323245
|
this.clearState(model);
|
|
322120
323246
|
}
|
|
322121
|
-
markRetryOncePerTurn(
|
|
323247
|
+
markRetryOncePerTurn(modelId, attempts = 1) {
|
|
323248
|
+
const model = normalizeModelId(modelId);
|
|
322122
323249
|
const currentState = this.health.get(model);
|
|
322123
323250
|
if (currentState?.status === "terminal") {
|
|
322124
323251
|
return;
|
|
@@ -322134,13 +323261,15 @@ var ModelAvailabilityService = class {
|
|
|
322134
323261
|
attempts
|
|
322135
323262
|
});
|
|
322136
323263
|
}
|
|
322137
|
-
consumeStickyAttempt(
|
|
323264
|
+
consumeStickyAttempt(modelId) {
|
|
323265
|
+
const model = normalizeModelId(modelId);
|
|
322138
323266
|
const state = this.health.get(model);
|
|
322139
323267
|
if (state?.status === "sticky_retry") {
|
|
322140
323268
|
this.setState(model, { ...state, consumed: true });
|
|
322141
323269
|
}
|
|
322142
323270
|
}
|
|
322143
|
-
snapshot(
|
|
323271
|
+
snapshot(modelId) {
|
|
323272
|
+
const model = normalizeModelId(modelId);
|
|
322144
323273
|
const state = this.health.get(model);
|
|
322145
323274
|
if (!state) {
|
|
322146
323275
|
return { available: true };
|
|
@@ -322153,9 +323282,10 @@ var ModelAvailabilityService = class {
|
|
|
322153
323282
|
}
|
|
322154
323283
|
return { available: true };
|
|
322155
323284
|
}
|
|
322156
|
-
selectFirstAvailable(
|
|
323285
|
+
selectFirstAvailable(modelIds) {
|
|
322157
323286
|
const skipped = [];
|
|
322158
|
-
for (const
|
|
323287
|
+
for (const modelId of modelIds) {
|
|
323288
|
+
const model = normalizeModelId(modelId);
|
|
322159
323289
|
const snapshot = this.snapshot(model);
|
|
322160
323290
|
if (snapshot.available) {
|
|
322161
323291
|
const state = this.health.get(model);
|
|
@@ -322331,9 +323461,25 @@ ${formattedHistory}
|
|
|
322331
323461
|
const routerResponse = ClassifierResponseSchema.parse(jsonResponse);
|
|
322332
323462
|
const reasoning = routerResponse.reasoning;
|
|
322333
323463
|
const latencyMs = Date.now() - startTime;
|
|
323464
|
+
const [
|
|
323465
|
+
useGemini3_1,
|
|
323466
|
+
useGemini3_1FlashLite,
|
|
323467
|
+
useCustomToolModel,
|
|
323468
|
+
hasAccessToPreview
|
|
323469
|
+
] = await Promise.all([
|
|
323470
|
+
config2.getGemini31Launched(),
|
|
323471
|
+
config2.getGemini31FlashLiteLaunched(),
|
|
323472
|
+
config2.getUseCustomToolModel(),
|
|
323473
|
+
config2.getHasAccessToPreviewModel?.() ?? true
|
|
323474
|
+
]);
|
|
322334
323475
|
const selectedModel = resolveClassifierModel(
|
|
322335
323476
|
context2.requestedModel ?? config2.getModel(),
|
|
322336
|
-
routerResponse.model_choice
|
|
323477
|
+
routerResponse.model_choice,
|
|
323478
|
+
useGemini3_1,
|
|
323479
|
+
useGemini3_1FlashLite,
|
|
323480
|
+
useCustomToolModel,
|
|
323481
|
+
hasAccessToPreview,
|
|
323482
|
+
config2
|
|
322337
323483
|
);
|
|
322338
323484
|
return {
|
|
322339
323485
|
model: selectedModel,
|
|
@@ -322501,15 +323647,25 @@ var ClassifierStrategy = class {
|
|
|
322501
323647
|
config2.getGemini31FlashLiteLaunched(),
|
|
322502
323648
|
config2.getUseCustomToolModel()
|
|
322503
323649
|
]);
|
|
322504
|
-
const selectedModel =
|
|
322505
|
-
|
|
322506
|
-
|
|
322507
|
-
|
|
322508
|
-
|
|
322509
|
-
|
|
322510
|
-
|
|
322511
|
-
|
|
323650
|
+
const selectedModel = normalizeModelId(
|
|
323651
|
+
resolveClassifierModel(
|
|
323652
|
+
normalizeModelId(model),
|
|
323653
|
+
routerResponse.model_choice,
|
|
323654
|
+
useGemini3_1,
|
|
323655
|
+
useGemini3_1FlashLite,
|
|
323656
|
+
useCustomToolModel,
|
|
323657
|
+
config2.getHasAccessToPreviewModel?.() ?? true,
|
|
323658
|
+
config2
|
|
323659
|
+
)
|
|
322512
323660
|
);
|
|
323661
|
+
const service = config2.getModelAvailabilityService();
|
|
323662
|
+
const snapshot = service.snapshot(selectedModel);
|
|
323663
|
+
if (!snapshot.available) {
|
|
323664
|
+
debugLogger.warn(
|
|
323665
|
+
`[Routing] Classifier selected unavailable model ${selectedModel} (${snapshot.reason}). Bypassing.`
|
|
323666
|
+
);
|
|
323667
|
+
return null;
|
|
323668
|
+
}
|
|
322513
323669
|
return {
|
|
322514
323670
|
model: selectedModel,
|
|
322515
323671
|
metadata: {
|
|
@@ -322607,7 +323763,15 @@ var NumericalClassifierStrategy = class {
|
|
|
322607
323763
|
return null;
|
|
322608
323764
|
}
|
|
322609
323765
|
const promptId = getPromptIdWithFallback("classifier-router");
|
|
322610
|
-
const
|
|
323766
|
+
const candidateSlice = context2.history.slice(-HISTORY_TURNS_FOR_CONTEXT3);
|
|
323767
|
+
let firstTextIndex = -1;
|
|
323768
|
+
for (let i3 = 0; i3 < candidateSlice.length; i3++) {
|
|
323769
|
+
if (!isFunctionCall(candidateSlice[i3]) && !isFunctionResponse(candidateSlice[i3])) {
|
|
323770
|
+
firstTextIndex = i3;
|
|
323771
|
+
break;
|
|
323772
|
+
}
|
|
323773
|
+
}
|
|
323774
|
+
const finalHistory = firstTextIndex === -1 ? [] : candidateSlice.slice(firstTextIndex);
|
|
322611
323775
|
const requestParts = Array.isArray(context2.request) ? context2.request : [context2.request];
|
|
322612
323776
|
const sanitizedRequest = requestParts.map((part) => {
|
|
322613
323777
|
if (typeof part === "string") {
|
|
@@ -322635,15 +323799,25 @@ var NumericalClassifierStrategy = class {
|
|
|
322635
323799
|
config2.getGemini31FlashLiteLaunched(),
|
|
322636
323800
|
config2.getUseCustomToolModel()
|
|
322637
323801
|
]);
|
|
322638
|
-
const selectedModel =
|
|
322639
|
-
|
|
322640
|
-
|
|
322641
|
-
|
|
322642
|
-
|
|
322643
|
-
|
|
322644
|
-
|
|
322645
|
-
|
|
323802
|
+
const selectedModel = normalizeModelId(
|
|
323803
|
+
resolveClassifierModel(
|
|
323804
|
+
normalizeModelId(model),
|
|
323805
|
+
modelAlias,
|
|
323806
|
+
useGemini3_1,
|
|
323807
|
+
useGemini3_1FlashLite,
|
|
323808
|
+
useCustomToolModel,
|
|
323809
|
+
config2.getHasAccessToPreviewModel?.() ?? true,
|
|
323810
|
+
config2
|
|
323811
|
+
)
|
|
322646
323812
|
);
|
|
323813
|
+
const service = config2.getModelAvailabilityService();
|
|
323814
|
+
const snapshot = service.snapshot(selectedModel);
|
|
323815
|
+
if (!snapshot.available) {
|
|
323816
|
+
debugLogger.warn(
|
|
323817
|
+
`[Routing] Numerical classifier selected unavailable model ${selectedModel} (${snapshot.reason}). Bypassing.`
|
|
323818
|
+
);
|
|
323819
|
+
return null;
|
|
323820
|
+
}
|
|
322647
323821
|
const latencyMs = Date.now() - startTime;
|
|
322648
323822
|
return {
|
|
322649
323823
|
model: selectedModel,
|
|
@@ -322819,16 +323993,26 @@ var ApprovalModeStrategy = class {
|
|
|
322819
323993
|
const startTime = Date.now();
|
|
322820
323994
|
const approvalMode = config2.getApprovalMode();
|
|
322821
323995
|
const approvedPlanPath = config2.getApprovedPlanPath();
|
|
322822
|
-
const [
|
|
323996
|
+
const [
|
|
323997
|
+
useGemini3_1,
|
|
323998
|
+
useGemini3_1FlashLite,
|
|
323999
|
+
useCustomToolModel,
|
|
324000
|
+
hasAccessToPreview
|
|
324001
|
+
] = await Promise.all([
|
|
322823
324002
|
config2.getGemini31Launched(),
|
|
322824
|
-
config2.
|
|
324003
|
+
config2.getGemini31FlashLiteLaunched(),
|
|
324004
|
+
config2.getUseCustomToolModel(),
|
|
324005
|
+
config2.getHasAccessToPreviewModel()
|
|
322825
324006
|
]);
|
|
322826
324007
|
if (approvalMode === "plan" /* PLAN */) {
|
|
322827
324008
|
const proModel = resolveClassifierModel(
|
|
322828
324009
|
model,
|
|
322829
324010
|
GEMINI_MODEL_ALIAS_PRO,
|
|
322830
324011
|
useGemini3_1,
|
|
322831
|
-
|
|
324012
|
+
useGemini3_1FlashLite,
|
|
324013
|
+
useCustomToolModel,
|
|
324014
|
+
hasAccessToPreview,
|
|
324015
|
+
config2
|
|
322832
324016
|
);
|
|
322833
324017
|
return {
|
|
322834
324018
|
model: proModel,
|
|
@@ -322843,7 +324027,10 @@ var ApprovalModeStrategy = class {
|
|
|
322843
324027
|
model,
|
|
322844
324028
|
GEMINI_MODEL_ALIAS_FLASH,
|
|
322845
324029
|
useGemini3_1,
|
|
322846
|
-
|
|
324030
|
+
useGemini3_1FlashLite,
|
|
324031
|
+
useCustomToolModel,
|
|
324032
|
+
hasAccessToPreview,
|
|
324033
|
+
config2
|
|
322847
324034
|
);
|
|
322848
324035
|
return {
|
|
322849
324036
|
model: flashModel,
|
|
@@ -323170,6 +324357,19 @@ var DEFAULT_MODEL_CONFIGS = {
|
|
|
323170
324357
|
extends: "gemini-3-flash-base",
|
|
323171
324358
|
modelConfig: {}
|
|
323172
324359
|
},
|
|
324360
|
+
"context-snapshotter": {
|
|
324361
|
+
extends: "gemini-3-flash-base",
|
|
324362
|
+
modelConfig: {
|
|
324363
|
+
generateContentConfig: {
|
|
324364
|
+
thinkingConfig: {
|
|
324365
|
+
thinkingLevel: ThinkingLevel.HIGH
|
|
324366
|
+
},
|
|
324367
|
+
temperature: 1,
|
|
324368
|
+
topP: 0.95,
|
|
324369
|
+
topK: 64
|
|
324370
|
+
}
|
|
324371
|
+
}
|
|
324372
|
+
},
|
|
323173
324373
|
"chat-compression-3-pro": {
|
|
323174
324374
|
modelConfig: {
|
|
323175
324375
|
model: "gemini-3-pro-preview"
|
|
@@ -326076,7 +327276,7 @@ var HookEventHandler = class {
|
|
|
326076
327276
|
result2.error?.message
|
|
326077
327277
|
);
|
|
326078
327278
|
logHookCall(this.context.config, hookCallEvent);
|
|
326079
|
-
if (result2.output?.systemMessage
|
|
327279
|
+
if (result2.output?.systemMessage) {
|
|
326080
327280
|
coreEvents.emitHookSystemMessage({
|
|
326081
327281
|
hookName,
|
|
326082
327282
|
eventName,
|
|
@@ -328287,8 +329487,8 @@ var AllowedPathChecker = class {
|
|
|
328287
329487
|
while (current && current !== path73.dirname(current)) {
|
|
328288
329488
|
if (fs65.existsSync(current)) {
|
|
328289
329489
|
const canonical = fs65.realpathSync(current);
|
|
328290
|
-
const
|
|
328291
|
-
return path73.join(canonical,
|
|
329490
|
+
const relative11 = path73.relative(current, resolved);
|
|
329491
|
+
return path73.join(canonical, relative11);
|
|
328292
329492
|
}
|
|
328293
329493
|
current = path73.dirname(current);
|
|
328294
329494
|
}
|
|
@@ -328298,8 +329498,8 @@ var AllowedPathChecker = class {
|
|
|
328298
329498
|
}
|
|
328299
329499
|
}
|
|
328300
329500
|
isPathAllowed(targetPath, allowedDir) {
|
|
328301
|
-
const
|
|
328302
|
-
return
|
|
329501
|
+
const relative11 = path73.relative(allowedDir, targetPath);
|
|
329502
|
+
return relative11 === "" || !relative11.startsWith("..") && !path73.isAbsolute(relative11);
|
|
328303
329503
|
}
|
|
328304
329504
|
collectPathsToCheck(args2, includedArgs, excludedArgs, prefix = "") {
|
|
328305
329505
|
const paths = [];
|
|
@@ -332050,6 +333250,14 @@ async function connectToMcpServer(clientVersion, mcpServerName, mcpServerConfig,
|
|
|
332050
333250
|
}
|
|
332051
333251
|
}
|
|
332052
333252
|
function createUrlTransport(mcpServerName, mcpServerConfig, transportOptions) {
|
|
333253
|
+
const baseFetch = transportOptions.fetch ?? globalThis.fetch;
|
|
333254
|
+
const httpOptions = {
|
|
333255
|
+
...transportOptions,
|
|
333256
|
+
fetch: async (url3, init2) => {
|
|
333257
|
+
const res = await baseFetch(url3, init2);
|
|
333258
|
+
return init2?.method === "GET" && res.status === 404 ? new Response(null, { status: 405, statusText: "Method Not Allowed" }) : res;
|
|
333259
|
+
}
|
|
333260
|
+
};
|
|
332053
333261
|
if (mcpServerConfig.httpUrl) {
|
|
332054
333262
|
if (mcpServerConfig.url) {
|
|
332055
333263
|
debugLogger.warn(
|
|
@@ -332058,14 +333266,14 @@ function createUrlTransport(mcpServerName, mcpServerConfig, transportOptions) {
|
|
|
332058
333266
|
}
|
|
332059
333267
|
return new StreamableHTTPClientTransport(
|
|
332060
333268
|
new URL(mcpServerConfig.httpUrl),
|
|
332061
|
-
|
|
333269
|
+
httpOptions
|
|
332062
333270
|
);
|
|
332063
333271
|
}
|
|
332064
333272
|
if (mcpServerConfig.url && mcpServerConfig.type) {
|
|
332065
333273
|
if (mcpServerConfig.type === "http") {
|
|
332066
333274
|
return new StreamableHTTPClientTransport(
|
|
332067
333275
|
new URL(mcpServerConfig.url),
|
|
332068
|
-
|
|
333276
|
+
httpOptions
|
|
332069
333277
|
);
|
|
332070
333278
|
} else if (mcpServerConfig.type === "sse") {
|
|
332071
333279
|
return new SSEClientTransport(
|
|
@@ -332077,7 +333285,7 @@ function createUrlTransport(mcpServerName, mcpServerConfig, transportOptions) {
|
|
|
332077
333285
|
if (mcpServerConfig.url) {
|
|
332078
333286
|
return new StreamableHTTPClientTransport(
|
|
332079
333287
|
new URL(mcpServerConfig.url),
|
|
332080
|
-
|
|
333288
|
+
httpOptions
|
|
332081
333289
|
);
|
|
332082
333290
|
}
|
|
332083
333291
|
throw new Error(`No URL configured for MCP server '${mcpServerName}'`);
|
|
@@ -341137,7 +342345,19 @@ var Config = class {
|
|
|
341137
342345
|
this.workspaceContext.addDirectory(dir);
|
|
341138
342346
|
}
|
|
341139
342347
|
if (this.planEnabled) {
|
|
341140
|
-
|
|
342348
|
+
let plansDir;
|
|
342349
|
+
try {
|
|
342350
|
+
plansDir = this.storage.getPlansDir();
|
|
342351
|
+
} catch (error40) {
|
|
342352
|
+
const errorMessage = error40 instanceof Error ? error40.message : String(error40);
|
|
342353
|
+
coreEvents.emitFeedback(
|
|
342354
|
+
"warning",
|
|
342355
|
+
"Invalid custom plans directory: " + errorMessage + ". Falling back to default project temp directory.",
|
|
342356
|
+
error40
|
|
342357
|
+
);
|
|
342358
|
+
this.storage.setCustomPlansDir(void 0);
|
|
342359
|
+
plansDir = this.storage.getPlansDir();
|
|
342360
|
+
}
|
|
341141
342361
|
try {
|
|
341142
342362
|
await fs68.promises.access(plansDir);
|
|
341143
342363
|
this.workspaceContext.addDirectory(plansDir);
|
|
@@ -341891,7 +343111,7 @@ var Config = class {
|
|
|
341891
343111
|
if (this.experimentalJitContext && this.memoryContextManager) {
|
|
341892
343112
|
await this.memoryContextManager.refresh();
|
|
341893
343113
|
} else {
|
|
341894
|
-
const { refreshServerHierarchicalMemory: refreshServerHierarchicalMemory2 } = await import("./memoryDiscovery-
|
|
343114
|
+
const { refreshServerHierarchicalMemory: refreshServerHierarchicalMemory2 } = await import("./memoryDiscovery-ALKMYAPP.js");
|
|
341895
343115
|
await refreshServerHierarchicalMemory2(this);
|
|
341896
343116
|
}
|
|
341897
343117
|
if (this._geminiClient?.isInitialized()) {
|
|
@@ -341926,12 +343146,13 @@ var Config = class {
|
|
|
341926
343146
|
* user message when JIT is enabled. Returns empty string when JIT is
|
|
341927
343147
|
* disabled (Tier 2 memory is already in the system instruction).
|
|
341928
343148
|
*/
|
|
341929
|
-
getSessionMemory() {
|
|
343149
|
+
getSessionMemory(options) {
|
|
341930
343150
|
if (!this.experimentalJitContext || !this.memoryContextManager) {
|
|
341931
343151
|
return "";
|
|
341932
343152
|
}
|
|
341933
343153
|
const sections = [];
|
|
341934
|
-
const
|
|
343154
|
+
const includeExtensionContext = options?.includeExtensionContext ?? true;
|
|
343155
|
+
const extension = includeExtensionContext ? this.memoryContextManager.getExtensionMemory() : "";
|
|
341935
343156
|
const project = this.memoryContextManager.getEnvironmentMemory();
|
|
341936
343157
|
if (extension?.trim()) {
|
|
341937
343158
|
sections.push(
|
|
@@ -342360,20 +343581,36 @@ ${sections.join("\n")}
|
|
|
342360
343581
|
setIdeMode(value) {
|
|
342361
343582
|
this.ideMode = value;
|
|
342362
343583
|
}
|
|
342363
|
-
isScopedMemoryInboxPatchPathAllowed(absolutePath, resolvedPath, inboxRoot) {
|
|
343584
|
+
isScopedMemoryInboxPatchPathAllowed(absolutePath, resolvedPath, inboxRoot, checkType = "write") {
|
|
342364
343585
|
if (!hasScopedMemoryInboxAccess()) {
|
|
342365
343586
|
return false;
|
|
342366
343587
|
}
|
|
342367
343588
|
const normalizedPath = path76.resolve(absolutePath);
|
|
343589
|
+
const resolvedMemoryRoot = resolveToRealPath(
|
|
343590
|
+
this.storage.getProjectMemoryTempDir()
|
|
343591
|
+
);
|
|
343592
|
+
if (checkType === "read") {
|
|
343593
|
+
const resolvedInboxRoot = resolveToRealPath(inboxRoot);
|
|
343594
|
+
const normalizedInboxRoot = path76.resolve(inboxRoot);
|
|
343595
|
+
if (resolvedPath === resolvedInboxRoot || normalizedPath === normalizedInboxRoot) {
|
|
343596
|
+
return isSubpath(resolvedMemoryRoot, resolvedPath);
|
|
343597
|
+
}
|
|
343598
|
+
for (const kind of ["private", "global"]) {
|
|
343599
|
+
const kindRoot = path76.join(inboxRoot, kind);
|
|
343600
|
+
const resolvedKindRoot = resolveToRealPath(kindRoot);
|
|
343601
|
+
const normalizedKindRoot = path76.resolve(kindRoot);
|
|
343602
|
+
if (resolvedPath === resolvedKindRoot || normalizedPath === normalizedKindRoot || isSubpath(resolvedKindRoot, resolvedPath) || isSubpath(normalizedKindRoot, normalizedPath)) {
|
|
343603
|
+
return isSubpath(resolvedMemoryRoot, resolvedPath);
|
|
343604
|
+
}
|
|
343605
|
+
}
|
|
343606
|
+
return false;
|
|
343607
|
+
}
|
|
342368
343608
|
const isCanonicalPatchPath = ["private", "global"].some(
|
|
342369
343609
|
(kind) => normalizedPath === path76.resolve(inboxRoot, kind, "extraction.patch")
|
|
342370
343610
|
);
|
|
342371
343611
|
if (!isCanonicalPatchPath) {
|
|
342372
343612
|
return false;
|
|
342373
343613
|
}
|
|
342374
|
-
const resolvedMemoryRoot = resolveToRealPath(
|
|
342375
|
-
this.storage.getProjectMemoryTempDir()
|
|
342376
|
-
);
|
|
342377
343614
|
return isSubpath(resolvedMemoryRoot, resolvedPath);
|
|
342378
343615
|
}
|
|
342379
343616
|
isScopedAutoMemoryExtractionWritePathAllowed(absolutePath, resolvedPath) {
|
|
@@ -342409,7 +343646,9 @@ ${sections.join("\n")}
|
|
|
342409
343646
|
* the auto-memory extraction agent and the `/memory inbox` review flow. The
|
|
342410
343647
|
* main agent is denied access to it even though it falls inside the project
|
|
342411
343648
|
* temp dir; the extraction agent receives a narrow execution-scoped exception
|
|
342412
|
-
* for `.inbox/{private,global}/extraction.patch`.
|
|
343649
|
+
* for *writes* to `.inbox/{private,global}/extraction.patch`. Scoped *read*
|
|
343650
|
+
* access to the wider `.inbox/{private,global}/` subtree is granted in
|
|
343651
|
+
* `validatePathAccess` so the extractor can enumerate prior patches.
|
|
342413
343652
|
*
|
|
342414
343653
|
* @param absolutePath The absolute path to check.
|
|
342415
343654
|
* @returns true if the path is allowed, false otherwise.
|
|
@@ -342474,6 +343713,20 @@ ${sections.join("\n")}
|
|
|
342474
343713
|
if (this.getWorkspaceContext().isPathReadable(absolutePath)) {
|
|
342475
343714
|
return null;
|
|
342476
343715
|
}
|
|
343716
|
+
if (hasScopedMemoryInboxAccess()) {
|
|
343717
|
+
const inboxRoot = path76.join(
|
|
343718
|
+
this.storage.getProjectMemoryTempDir(),
|
|
343719
|
+
".inbox"
|
|
343720
|
+
);
|
|
343721
|
+
if (this.isScopedMemoryInboxPatchPathAllowed(
|
|
343722
|
+
absolutePath,
|
|
343723
|
+
resolveToRealPath(absolutePath),
|
|
343724
|
+
inboxRoot,
|
|
343725
|
+
"read"
|
|
343726
|
+
)) {
|
|
343727
|
+
return null;
|
|
343728
|
+
}
|
|
343729
|
+
}
|
|
342477
343730
|
}
|
|
342478
343731
|
if (this.isPathAllowed(absolutePath)) {
|
|
342479
343732
|
return null;
|
|
@@ -342808,10 +344061,10 @@ ${sections.join("\n")}
|
|
|
342808
344061
|
return this.gemmaModelRouter;
|
|
342809
344062
|
}
|
|
342810
344063
|
getAgentSessionNoninteractiveEnabled() {
|
|
342811
|
-
return this.agentSessionNoninteractiveEnabled;
|
|
344064
|
+
return process15.env["GEMINI_CLI_EXP_AGENT"] === "true" || this.agentSessionNoninteractiveEnabled;
|
|
342812
344065
|
}
|
|
342813
344066
|
getAgentSessionInteractiveEnabled() {
|
|
342814
|
-
return this.agentSessionInteractiveEnabled;
|
|
344067
|
+
return process15.env["GEMINI_CLI_EXP_AGENT"] === "true" || this.agentSessionInteractiveEnabled;
|
|
342815
344068
|
}
|
|
342816
344069
|
/**
|
|
342817
344070
|
* Get override settings for a specific agent.
|
|
@@ -343931,11 +345184,271 @@ async function isProjectSkillPatchTarget(targetPath, config2) {
|
|
|
343931
345184
|
function hasParsedPatchHunks(parsedPatches) {
|
|
343932
345185
|
return parsedPatches.length > 0 && parsedPatches.every((patch) => patch.hunks.length > 0);
|
|
343933
345186
|
}
|
|
345187
|
+
function getMemoryPatchRoot(memoryDir, kind) {
|
|
345188
|
+
return path80.join(memoryDir, ".inbox", kind);
|
|
345189
|
+
}
|
|
345190
|
+
function isSubpathOrSame(childPath, parentPath) {
|
|
345191
|
+
return isSubpath(parentPath, childPath);
|
|
345192
|
+
}
|
|
345193
|
+
function normalizeInboxMemoryPatchPath(relativePath) {
|
|
345194
|
+
if (relativePath.length === 0 || path80.isAbsolute(relativePath) || relativePath.includes("\\")) {
|
|
345195
|
+
return void 0;
|
|
345196
|
+
}
|
|
345197
|
+
const normalizedPath = path80.posix.normalize(relativePath);
|
|
345198
|
+
if (normalizedPath === "." || normalizedPath.startsWith("../") || normalizedPath === ".." || !normalizedPath.endsWith(".patch")) {
|
|
345199
|
+
return void 0;
|
|
345200
|
+
}
|
|
345201
|
+
return normalizedPath;
|
|
345202
|
+
}
|
|
345203
|
+
function getAllowedMemoryPatchRoots(config2, kind) {
|
|
345204
|
+
switch (kind) {
|
|
345205
|
+
case "private":
|
|
345206
|
+
return [path80.resolve(config2.storage.getProjectMemoryTempDir())];
|
|
345207
|
+
case "global":
|
|
345208
|
+
return [path80.resolve(getGlobalMemoryFilePath())];
|
|
345209
|
+
default:
|
|
345210
|
+
throw new Error(`Unknown memory patch kind: ${kind}`);
|
|
345211
|
+
}
|
|
345212
|
+
}
|
|
345213
|
+
function hasMarkdownExtension(fileName) {
|
|
345214
|
+
return fileName.toLowerCase().endsWith(".md");
|
|
345215
|
+
}
|
|
345216
|
+
function isAllowedPrivateMemoryFileName(fileName) {
|
|
345217
|
+
if (fileName === PROJECT_MEMORY_INDEX_FILENAME) {
|
|
345218
|
+
return true;
|
|
345219
|
+
}
|
|
345220
|
+
return !fileName.startsWith(".") && hasMarkdownExtension(fileName);
|
|
345221
|
+
}
|
|
345222
|
+
function uniqueResolvedPaths(paths) {
|
|
345223
|
+
return Array.from(new Set(paths.map((filePath) => path80.resolve(filePath))));
|
|
345224
|
+
}
|
|
345225
|
+
function isSamePath(leftPath, rightPath) {
|
|
345226
|
+
return isSubpath(leftPath, rightPath) && isSubpath(rightPath, leftPath);
|
|
345227
|
+
}
|
|
345228
|
+
function includesSamePath(paths, targetPath) {
|
|
345229
|
+
return paths.some((candidate) => isSamePath(candidate, targetPath));
|
|
345230
|
+
}
|
|
345231
|
+
function isAllowedPrivateMemoryDocumentPath(targetPath, memoryDirs) {
|
|
345232
|
+
const resolvedTargetPath = path80.resolve(targetPath);
|
|
345233
|
+
const targetDir = path80.dirname(resolvedTargetPath);
|
|
345234
|
+
if (!includesSamePath(memoryDirs, targetDir)) {
|
|
345235
|
+
return false;
|
|
345236
|
+
}
|
|
345237
|
+
return isAllowedPrivateMemoryFileName(path80.basename(resolvedTargetPath));
|
|
345238
|
+
}
|
|
345239
|
+
function isAllowedGlobalMemoryDocumentPath(targetPath, globalMemoryFiles) {
|
|
345240
|
+
const resolvedTargetPath = path80.resolve(targetPath);
|
|
345241
|
+
return includesSamePath(globalMemoryFiles, resolvedTargetPath);
|
|
345242
|
+
}
|
|
345243
|
+
async function getMemoryPatchTargetValidationContext(config2, kind) {
|
|
345244
|
+
const allowedRoots = await canonicalizeAllowedPatchRoots(
|
|
345245
|
+
getAllowedMemoryPatchRoots(config2, kind)
|
|
345246
|
+
);
|
|
345247
|
+
if (kind === "global") {
|
|
345248
|
+
const rawGlobalMemoryFile = path80.resolve(getGlobalMemoryFilePath());
|
|
345249
|
+
const canonicalGlobalMemoryFiles = await canonicalizeAllowedPatchRoots([
|
|
345250
|
+
rawGlobalMemoryFile
|
|
345251
|
+
]);
|
|
345252
|
+
return {
|
|
345253
|
+
kind,
|
|
345254
|
+
allowedRoots,
|
|
345255
|
+
privateMemoryDirs: [],
|
|
345256
|
+
globalMemoryFiles: uniqueResolvedPaths([
|
|
345257
|
+
rawGlobalMemoryFile,
|
|
345258
|
+
...canonicalGlobalMemoryFiles
|
|
345259
|
+
])
|
|
345260
|
+
};
|
|
345261
|
+
}
|
|
345262
|
+
const rawPrivateMemoryDir = path80.resolve(
|
|
345263
|
+
config2.storage.getProjectMemoryTempDir()
|
|
345264
|
+
);
|
|
345265
|
+
const canonicalPrivateMemoryDirs = await canonicalizeAllowedPatchRoots([
|
|
345266
|
+
rawPrivateMemoryDir
|
|
345267
|
+
]);
|
|
345268
|
+
const privateMemoryDirs = uniqueResolvedPaths([
|
|
345269
|
+
rawPrivateMemoryDir,
|
|
345270
|
+
...canonicalPrivateMemoryDirs
|
|
345271
|
+
]);
|
|
345272
|
+
return { kind, allowedRoots, privateMemoryDirs, globalMemoryFiles: [] };
|
|
345273
|
+
}
|
|
345274
|
+
function isResolvedMemoryPatchTargetAllowed(resolvedTargetPath, context2) {
|
|
345275
|
+
if (context2.kind === "global") {
|
|
345276
|
+
return isAllowedGlobalMemoryDocumentPath(
|
|
345277
|
+
resolvedTargetPath,
|
|
345278
|
+
context2.globalMemoryFiles
|
|
345279
|
+
);
|
|
345280
|
+
}
|
|
345281
|
+
if (context2.kind === "private") {
|
|
345282
|
+
return isAllowedPrivateMemoryDocumentPath(
|
|
345283
|
+
resolvedTargetPath,
|
|
345284
|
+
context2.privateMemoryDirs
|
|
345285
|
+
);
|
|
345286
|
+
}
|
|
345287
|
+
return true;
|
|
345288
|
+
}
|
|
345289
|
+
async function resolveMemoryPatchTargetWithinAllowedSet(targetPath, context2) {
|
|
345290
|
+
const resolvedTargetPath = await resolveTargetWithinAllowedRoots(
|
|
345291
|
+
targetPath,
|
|
345292
|
+
context2.allowedRoots
|
|
345293
|
+
);
|
|
345294
|
+
if (!resolvedTargetPath) {
|
|
345295
|
+
return void 0;
|
|
345296
|
+
}
|
|
345297
|
+
if (context2.kind === "private" && (!isAllowedPrivateMemoryDocumentPath(
|
|
345298
|
+
targetPath,
|
|
345299
|
+
context2.privateMemoryDirs
|
|
345300
|
+
) || !isAllowedPrivateMemoryDocumentPath(
|
|
345301
|
+
resolvedTargetPath,
|
|
345302
|
+
context2.privateMemoryDirs
|
|
345303
|
+
))) {
|
|
345304
|
+
return void 0;
|
|
345305
|
+
}
|
|
345306
|
+
if (context2.kind === "global" && (!isAllowedGlobalMemoryDocumentPath(
|
|
345307
|
+
targetPath,
|
|
345308
|
+
context2.globalMemoryFiles
|
|
345309
|
+
) || !isAllowedGlobalMemoryDocumentPath(
|
|
345310
|
+
resolvedTargetPath,
|
|
345311
|
+
context2.globalMemoryFiles
|
|
345312
|
+
))) {
|
|
345313
|
+
return void 0;
|
|
345314
|
+
}
|
|
345315
|
+
return resolvedTargetPath;
|
|
345316
|
+
}
|
|
345317
|
+
async function findDisallowedMemoryPatchTarget(parsedPatches, context2) {
|
|
345318
|
+
const validated = validateParsedSkillPatchHeaders(parsedPatches);
|
|
345319
|
+
if (!validated.success) {
|
|
345320
|
+
return void 0;
|
|
345321
|
+
}
|
|
345322
|
+
for (const header of validated.patches) {
|
|
345323
|
+
if (!await resolveMemoryPatchTargetWithinAllowedSet(
|
|
345324
|
+
header.targetPath,
|
|
345325
|
+
context2
|
|
345326
|
+
)) {
|
|
345327
|
+
return header.targetPath;
|
|
345328
|
+
}
|
|
345329
|
+
}
|
|
345330
|
+
return void 0;
|
|
345331
|
+
}
|
|
345332
|
+
async function getInboxMemoryPatchSourcePath(config2, kind, relativePath) {
|
|
345333
|
+
const normalizedPath = normalizeInboxMemoryPatchPath(relativePath);
|
|
345334
|
+
if (!normalizedPath) {
|
|
345335
|
+
return void 0;
|
|
345336
|
+
}
|
|
345337
|
+
const patchRoot = path80.resolve(
|
|
345338
|
+
getMemoryPatchRoot(config2.storage.getProjectMemoryTempDir(), kind)
|
|
345339
|
+
);
|
|
345340
|
+
const sourcePath = path80.resolve(patchRoot, ...normalizedPath.split("/"));
|
|
345341
|
+
if (!isSubpathOrSame(sourcePath, patchRoot)) {
|
|
345342
|
+
return void 0;
|
|
345343
|
+
}
|
|
345344
|
+
return sourcePath;
|
|
345345
|
+
}
|
|
345346
|
+
async function listInboxPatchFiles(config2, kind) {
|
|
345347
|
+
const patchRoot = getMemoryPatchRoot(
|
|
345348
|
+
config2.storage.getProjectMemoryTempDir(),
|
|
345349
|
+
kind
|
|
345350
|
+
);
|
|
345351
|
+
const found = [];
|
|
345352
|
+
async function walk(currentDir) {
|
|
345353
|
+
let dirEntries;
|
|
345354
|
+
try {
|
|
345355
|
+
dirEntries = await fs71.readdir(currentDir, { withFileTypes: true });
|
|
345356
|
+
} catch {
|
|
345357
|
+
return;
|
|
345358
|
+
}
|
|
345359
|
+
for (const entry of dirEntries) {
|
|
345360
|
+
const entryPath = path80.join(currentDir, entry.name);
|
|
345361
|
+
if (entry.isDirectory()) {
|
|
345362
|
+
await walk(entryPath);
|
|
345363
|
+
continue;
|
|
345364
|
+
}
|
|
345365
|
+
if (entry.isFile() && entry.name.endsWith(".patch")) {
|
|
345366
|
+
found.push(entryPath);
|
|
345367
|
+
}
|
|
345368
|
+
}
|
|
345369
|
+
}
|
|
345370
|
+
await walk(patchRoot);
|
|
345371
|
+
return found.sort();
|
|
345372
|
+
}
|
|
345373
|
+
async function validateInboxMemoryPatchFile(config2, kind, sourcePath) {
|
|
345374
|
+
let content;
|
|
345375
|
+
try {
|
|
345376
|
+
content = await fs71.readFile(sourcePath, "utf-8");
|
|
345377
|
+
} catch (error40) {
|
|
345378
|
+
return {
|
|
345379
|
+
valid: false,
|
|
345380
|
+
reason: `failed to read patch: ${error40 instanceof Error ? error40.message : String(error40)}`
|
|
345381
|
+
};
|
|
345382
|
+
}
|
|
345383
|
+
let parsed;
|
|
345384
|
+
try {
|
|
345385
|
+
parsed = parsePatch(content);
|
|
345386
|
+
} catch (error40) {
|
|
345387
|
+
return {
|
|
345388
|
+
valid: false,
|
|
345389
|
+
reason: `failed to parse patch: ${error40 instanceof Error ? error40.message : String(error40)}`
|
|
345390
|
+
};
|
|
345391
|
+
}
|
|
345392
|
+
if (!hasParsedPatchHunks(parsed)) {
|
|
345393
|
+
return { valid: false, reason: "no hunks found in patch" };
|
|
345394
|
+
}
|
|
345395
|
+
const validated = validateParsedSkillPatchHeaders(parsed);
|
|
345396
|
+
if (!validated.success) {
|
|
345397
|
+
switch (validated.reason) {
|
|
345398
|
+
case "missingTargetPath":
|
|
345399
|
+
return {
|
|
345400
|
+
valid: false,
|
|
345401
|
+
reason: "missing target file path in patch header"
|
|
345402
|
+
};
|
|
345403
|
+
case "invalidPatchHeaders":
|
|
345404
|
+
return {
|
|
345405
|
+
valid: false,
|
|
345406
|
+
reason: `invalid diff headers${validated.targetPath ? `: ${validated.targetPath}` : ""}`
|
|
345407
|
+
};
|
|
345408
|
+
default:
|
|
345409
|
+
return { valid: false, reason: "invalid patch headers" };
|
|
345410
|
+
}
|
|
345411
|
+
}
|
|
345412
|
+
const validationContext = await getMemoryPatchTargetValidationContext(
|
|
345413
|
+
config2,
|
|
345414
|
+
kind
|
|
345415
|
+
);
|
|
345416
|
+
for (const header of validated.patches) {
|
|
345417
|
+
if (!await resolveMemoryPatchTargetWithinAllowedSet(
|
|
345418
|
+
header.targetPath,
|
|
345419
|
+
validationContext
|
|
345420
|
+
)) {
|
|
345421
|
+
return {
|
|
345422
|
+
valid: false,
|
|
345423
|
+
reason: `target file is outside ${kind} memory roots: ${header.targetPath}`
|
|
345424
|
+
};
|
|
345425
|
+
}
|
|
345426
|
+
}
|
|
345427
|
+
return { valid: true };
|
|
345428
|
+
}
|
|
345429
|
+
async function listValidInboxPatchFiles(config2, kind) {
|
|
345430
|
+
const patchFiles = await listInboxPatchFiles(config2, kind);
|
|
345431
|
+
if (patchFiles.length === 0) {
|
|
345432
|
+
return [];
|
|
345433
|
+
}
|
|
345434
|
+
const valid = [];
|
|
345435
|
+
for (const sourcePath of patchFiles) {
|
|
345436
|
+
const validation = await validateInboxMemoryPatchFile(
|
|
345437
|
+
config2,
|
|
345438
|
+
kind,
|
|
345439
|
+
sourcePath
|
|
345440
|
+
);
|
|
345441
|
+
if (validation.valid) {
|
|
345442
|
+
valid.push(sourcePath);
|
|
345443
|
+
}
|
|
345444
|
+
}
|
|
345445
|
+
return valid;
|
|
345446
|
+
}
|
|
343934
345447
|
async function applyParsedSkillPatches(parsedPatches, config2) {
|
|
343935
345448
|
const allowedRoots = await getCanonicalAllowedSkillPatchRoots(config2);
|
|
343936
345449
|
return applyParsedPatchesWithAllowedRoots(parsedPatches, allowedRoots);
|
|
343937
345450
|
}
|
|
343938
|
-
async function applyParsedPatchesWithAllowedRoots(parsedPatches, allowedRoots) {
|
|
345451
|
+
async function applyParsedPatchesWithAllowedRoots(parsedPatches, allowedRoots, options = {}) {
|
|
343939
345452
|
const results = /* @__PURE__ */ new Map();
|
|
343940
345453
|
const patchedContentByTarget = /* @__PURE__ */ new Map();
|
|
343941
345454
|
const originalContentByTarget = /* @__PURE__ */ new Map();
|
|
@@ -343949,7 +345462,7 @@ async function applyParsedPatchesWithAllowedRoots(parsedPatches, allowedRoots) {
|
|
|
343949
345462
|
targetPath,
|
|
343950
345463
|
allowedRoots
|
|
343951
345464
|
);
|
|
343952
|
-
if (!resolvedTargetPath) {
|
|
345465
|
+
if (!resolvedTargetPath || options.isResolvedTargetAllowed && !options.isResolvedTargetAllowed(resolvedTargetPath)) {
|
|
343953
345466
|
return {
|
|
343954
345467
|
success: false,
|
|
343955
345468
|
reason: "outsideAllowedRoots",
|
|
@@ -344411,6 +345924,7 @@ var SkillExtractionAgent = (skillsDir, sessionIndex, existingSkillsSummary, memo
|
|
|
344411
345924
|
},
|
|
344412
345925
|
memoryInboxAccess: true,
|
|
344413
345926
|
autoMemoryExtractionWriteAccess: true,
|
|
345927
|
+
includeExtensionContext: false,
|
|
344414
345928
|
toolConfig: {
|
|
344415
345929
|
tools: [
|
|
344416
345930
|
ACTIVATE_SKILL_TOOL_NAME,
|
|
@@ -345169,6 +346683,36 @@ async function snapshotFiles(rootDir, shouldIncludeFile = () => true, shouldDesc
|
|
|
345169
346683
|
async function snapshotInboxCandidates(memoryDir) {
|
|
345170
346684
|
return snapshotFiles(path81.join(memoryDir, ".inbox"));
|
|
345171
346685
|
}
|
|
346686
|
+
var MEMORY_INBOX_PATCH_KINDS = [
|
|
346687
|
+
"private",
|
|
346688
|
+
"global"
|
|
346689
|
+
];
|
|
346690
|
+
async function validateMemoryInboxPatches(config2) {
|
|
346691
|
+
for (const kind of MEMORY_INBOX_PATCH_KINDS) {
|
|
346692
|
+
const patchFiles = await listInboxPatchFiles(config2, kind);
|
|
346693
|
+
for (const patchFile of patchFiles) {
|
|
346694
|
+
const validation = await validateInboxMemoryPatchFile(
|
|
346695
|
+
config2,
|
|
346696
|
+
kind,
|
|
346697
|
+
patchFile
|
|
346698
|
+
);
|
|
346699
|
+
if (validation.valid) {
|
|
346700
|
+
continue;
|
|
346701
|
+
}
|
|
346702
|
+
try {
|
|
346703
|
+
await fs72.unlink(patchFile);
|
|
346704
|
+
debugLogger.warn(
|
|
346705
|
+
`[MemoryService] Dropped invalid ${kind} memory inbox patch ${patchFile}: ${validation.reason}`
|
|
346706
|
+
);
|
|
346707
|
+
} catch (error40) {
|
|
346708
|
+
const message = error40 instanceof Error ? error40.message : String(error40);
|
|
346709
|
+
debugLogger.warn(
|
|
346710
|
+
`[MemoryService] Failed to drop invalid ${kind} memory inbox patch ${patchFile}: ${validation.reason}; unlink failed: ${message}`
|
|
346711
|
+
);
|
|
346712
|
+
}
|
|
346713
|
+
}
|
|
346714
|
+
}
|
|
346715
|
+
}
|
|
345172
346716
|
async function buildPendingInboxSummary(memoryDir) {
|
|
345173
346717
|
const sections = [];
|
|
345174
346718
|
for (const kind of ["private", "global"]) {
|
|
@@ -345418,6 +346962,7 @@ ${pendingInboxSummary}`
|
|
|
345418
346962
|
`[MemoryService] ${validPatches.length} valid patch(es) currently in inbox; ${patchesCreatedThisRun.length} created or updated this run`
|
|
345419
346963
|
);
|
|
345420
346964
|
}
|
|
346965
|
+
await validateMemoryInboxPatches(config2);
|
|
345421
346966
|
const memoryFilesUpdated = [];
|
|
345422
346967
|
const memoryCandidatesCreated = prefixRelativePaths(
|
|
345423
346968
|
".inbox",
|
|
@@ -345742,33 +347287,6 @@ function formatParsedDiff(parsed) {
|
|
|
345742
347287
|
function getErrorMessage4(error40) {
|
|
345743
347288
|
return error40 instanceof Error ? error40.message : String(error40);
|
|
345744
347289
|
}
|
|
345745
|
-
function getMemoryPatchRoot(memoryDir, kind) {
|
|
345746
|
-
return path82.join(memoryDir, ".inbox", kind);
|
|
345747
|
-
}
|
|
345748
|
-
function isSubpathOrSame(childPath, parentPath) {
|
|
345749
|
-
const relativePath = path82.relative(parentPath, childPath);
|
|
345750
|
-
return relativePath === "" || !relativePath.startsWith("..") && !path82.isAbsolute(relativePath);
|
|
345751
|
-
}
|
|
345752
|
-
function normalizeInboxMemoryPatchPath(relativePath) {
|
|
345753
|
-
if (relativePath.length === 0 || path82.isAbsolute(relativePath) || relativePath.includes("\\")) {
|
|
345754
|
-
return void 0;
|
|
345755
|
-
}
|
|
345756
|
-
const normalizedPath = path82.posix.normalize(relativePath);
|
|
345757
|
-
if (normalizedPath === "." || normalizedPath.startsWith("../") || normalizedPath === ".." || !normalizedPath.endsWith(".patch")) {
|
|
345758
|
-
return void 0;
|
|
345759
|
-
}
|
|
345760
|
-
return normalizedPath;
|
|
345761
|
-
}
|
|
345762
|
-
function getAllowedMemoryPatchRoots(config2, kind) {
|
|
345763
|
-
switch (kind) {
|
|
345764
|
-
case "private":
|
|
345765
|
-
return [path82.resolve(config2.storage.getProjectMemoryTempDir())];
|
|
345766
|
-
case "global":
|
|
345767
|
-
return [path82.resolve(getGlobalMemoryFilePath())];
|
|
345768
|
-
default:
|
|
345769
|
-
throw new Error(`Unknown memory patch kind: ${kind}`);
|
|
345770
|
-
}
|
|
345771
|
-
}
|
|
345772
347290
|
async function getFileMtimeIso(filePath) {
|
|
345773
347291
|
try {
|
|
345774
347292
|
const stats = await fs73.stat(filePath);
|
|
@@ -345777,20 +347295,6 @@ async function getFileMtimeIso(filePath) {
|
|
|
345777
347295
|
return void 0;
|
|
345778
347296
|
}
|
|
345779
347297
|
}
|
|
345780
|
-
async function getInboxMemoryPatchSourcePath(config2, kind, relativePath) {
|
|
345781
|
-
const normalizedPath = normalizeInboxMemoryPatchPath(relativePath);
|
|
345782
|
-
if (!normalizedPath) {
|
|
345783
|
-
return void 0;
|
|
345784
|
-
}
|
|
345785
|
-
const patchRoot = path82.resolve(
|
|
345786
|
-
getMemoryPatchRoot(config2.storage.getProjectMemoryTempDir(), kind)
|
|
345787
|
-
);
|
|
345788
|
-
const sourcePath = path82.resolve(patchRoot, ...normalizedPath.split("/"));
|
|
345789
|
-
if (!isSubpathOrSame(sourcePath, patchRoot)) {
|
|
345790
|
-
return void 0;
|
|
345791
|
-
}
|
|
345792
|
-
return sourcePath;
|
|
345793
|
-
}
|
|
345794
347298
|
async function patchTargetsProjectSkills(targetPaths, config2) {
|
|
345795
347299
|
for (const targetPath of targetPaths) {
|
|
345796
347300
|
if (await isProjectSkillPatchTarget(targetPath, config2)) {
|
|
@@ -345817,83 +347321,13 @@ function formatMemoryKindLabel(kind) {
|
|
|
345817
347321
|
return kind;
|
|
345818
347322
|
}
|
|
345819
347323
|
}
|
|
345820
|
-
async function listInboxPatchFiles(config2, kind) {
|
|
345821
|
-
const patchRoot = getMemoryPatchRoot(
|
|
345822
|
-
config2.storage.getProjectMemoryTempDir(),
|
|
345823
|
-
kind
|
|
345824
|
-
);
|
|
345825
|
-
const found = [];
|
|
345826
|
-
async function walk(currentDir) {
|
|
345827
|
-
let dirEntries;
|
|
345828
|
-
try {
|
|
345829
|
-
dirEntries = await fs73.readdir(currentDir, { withFileTypes: true });
|
|
345830
|
-
} catch {
|
|
345831
|
-
return;
|
|
345832
|
-
}
|
|
345833
|
-
for (const entry of dirEntries) {
|
|
345834
|
-
const entryPath = path82.join(currentDir, entry.name);
|
|
345835
|
-
if (entry.isDirectory()) {
|
|
345836
|
-
await walk(entryPath);
|
|
345837
|
-
continue;
|
|
345838
|
-
}
|
|
345839
|
-
if (entry.isFile() && entry.name.endsWith(".patch")) {
|
|
345840
|
-
found.push(entryPath);
|
|
345841
|
-
}
|
|
345842
|
-
}
|
|
345843
|
-
}
|
|
345844
|
-
await walk(patchRoot);
|
|
345845
|
-
return found.sort();
|
|
345846
|
-
}
|
|
345847
|
-
async function listValidInboxPatchFiles(config2, kind) {
|
|
345848
|
-
const patchFiles = await listInboxPatchFiles(config2, kind);
|
|
345849
|
-
if (patchFiles.length === 0) {
|
|
345850
|
-
return [];
|
|
345851
|
-
}
|
|
345852
|
-
const allowedRoots = await canonicalizeAllowedPatchRoots(
|
|
345853
|
-
getAllowedMemoryPatchRoots(config2, kind)
|
|
345854
|
-
);
|
|
345855
|
-
const valid = [];
|
|
345856
|
-
for (const sourcePath of patchFiles) {
|
|
345857
|
-
let content;
|
|
345858
|
-
try {
|
|
345859
|
-
content = await fs73.readFile(sourcePath, "utf-8");
|
|
345860
|
-
} catch {
|
|
345861
|
-
continue;
|
|
345862
|
-
}
|
|
345863
|
-
let parsed;
|
|
345864
|
-
try {
|
|
345865
|
-
parsed = parsePatch(content);
|
|
345866
|
-
} catch {
|
|
345867
|
-
continue;
|
|
345868
|
-
}
|
|
345869
|
-
if (!hasParsedPatchHunks(parsed)) {
|
|
345870
|
-
continue;
|
|
345871
|
-
}
|
|
345872
|
-
const validated = validateParsedSkillPatchHeaders(parsed);
|
|
345873
|
-
if (!validated.success) {
|
|
345874
|
-
continue;
|
|
345875
|
-
}
|
|
345876
|
-
const targetsAllAllowed = await Promise.all(
|
|
345877
|
-
validated.patches.map(
|
|
345878
|
-
async (header) => await resolveTargetWithinAllowedRoots(
|
|
345879
|
-
header.targetPath,
|
|
345880
|
-
allowedRoots
|
|
345881
|
-
) !== void 0
|
|
345882
|
-
)
|
|
345883
|
-
);
|
|
345884
|
-
if (!targetsAllAllowed.every(Boolean)) {
|
|
345885
|
-
continue;
|
|
345886
|
-
}
|
|
345887
|
-
valid.push(sourcePath);
|
|
345888
|
-
}
|
|
345889
|
-
return valid;
|
|
345890
|
-
}
|
|
345891
347324
|
async function listInboxMemoryPatches(config2) {
|
|
345892
347325
|
const kinds = ["private", "global"];
|
|
345893
347326
|
const aggregated = [];
|
|
345894
347327
|
for (const kind of kinds) {
|
|
345895
|
-
const
|
|
345896
|
-
|
|
347328
|
+
const validationContext = await getMemoryPatchTargetValidationContext(
|
|
347329
|
+
config2,
|
|
347330
|
+
kind
|
|
345897
347331
|
);
|
|
345898
347332
|
const patchFiles = await listInboxPatchFiles(config2, kind);
|
|
345899
347333
|
const aggregatedEntries = [];
|
|
@@ -345921,9 +347355,9 @@ async function listInboxMemoryPatches(config2) {
|
|
|
345921
347355
|
}
|
|
345922
347356
|
const targetsAllAllowed = await Promise.all(
|
|
345923
347357
|
validated.patches.map(
|
|
345924
|
-
async (header) => await
|
|
347358
|
+
async (header) => await resolveMemoryPatchTargetWithinAllowedSet(
|
|
345925
347359
|
header.targetPath,
|
|
345926
|
-
|
|
347360
|
+
validationContext
|
|
345927
347361
|
) !== void 0
|
|
345928
347362
|
)
|
|
345929
347363
|
);
|
|
@@ -346119,12 +347553,29 @@ async function applyMemoryPatchFile(config2, kind, patchPath, displayName) {
|
|
|
346119
347553
|
message: `Memory patch "${displayName}" contains no valid hunks.`
|
|
346120
347554
|
};
|
|
346121
347555
|
}
|
|
346122
|
-
const
|
|
346123
|
-
|
|
347556
|
+
const validationContext = await getMemoryPatchTargetValidationContext(
|
|
347557
|
+
config2,
|
|
347558
|
+
kind
|
|
346124
347559
|
);
|
|
347560
|
+
const disallowedTargetPath = await findDisallowedMemoryPatchTarget(
|
|
347561
|
+
parsed,
|
|
347562
|
+
validationContext
|
|
347563
|
+
);
|
|
347564
|
+
if (disallowedTargetPath) {
|
|
347565
|
+
return {
|
|
347566
|
+
success: false,
|
|
347567
|
+
message: `Memory patch "${displayName}" targets a file outside the ${kind} memory root or target allowlist: ${disallowedTargetPath}`
|
|
347568
|
+
};
|
|
347569
|
+
}
|
|
346125
347570
|
const applied = await applyParsedPatchesWithAllowedRoots(
|
|
346126
347571
|
parsed,
|
|
346127
|
-
allowedRoots
|
|
347572
|
+
validationContext.allowedRoots,
|
|
347573
|
+
{
|
|
347574
|
+
isResolvedTargetAllowed: (resolvedTargetPath) => isResolvedMemoryPatchTargetAllowed(
|
|
347575
|
+
resolvedTargetPath,
|
|
347576
|
+
validationContext
|
|
347577
|
+
)
|
|
347578
|
+
}
|
|
346128
347579
|
);
|
|
346129
347580
|
if (!applied.success) {
|
|
346130
347581
|
switch (applied.reason) {
|
|
@@ -346141,7 +347592,7 @@ async function applyMemoryPatchFile(config2, kind, patchPath, displayName) {
|
|
|
346141
347592
|
case "outsideAllowedRoots":
|
|
346142
347593
|
return {
|
|
346143
347594
|
success: false,
|
|
346144
|
-
message: `Memory patch "${displayName}" targets a file outside the ${kind} memory root: ${applied.targetPath}`
|
|
347595
|
+
message: `Memory patch "${displayName}" targets a file outside the ${kind} memory root or target allowlist: ${applied.targetPath}`
|
|
346145
347596
|
};
|
|
346146
347597
|
case "newFileAlreadyExists":
|
|
346147
347598
|
return {
|
|
@@ -347091,8 +348542,9 @@ function loadIgnoreRules(service, ignoreDirs = []) {
|
|
|
347091
348542
|
const ignorer = new Ignore2();
|
|
347092
348543
|
const ignoreFiles = service.getAllIgnoreFilePaths();
|
|
347093
348544
|
for (const filePath of ignoreFiles) {
|
|
347094
|
-
|
|
348545
|
+
try {
|
|
347095
348546
|
ignorer.add(fs75.readFileSync(filePath, "utf8"));
|
|
348547
|
+
} catch {
|
|
347096
348548
|
}
|
|
347097
348549
|
}
|
|
347098
348550
|
const allIgnoreDirs = [".git", ...ignoreDirs];
|
|
@@ -348261,11 +349713,11 @@ var AsyncFzf = class {
|
|
|
348261
349713
|
// packages/core/node_modules/chokidar/index.js
|
|
348262
349714
|
import { EventEmitter as EventEmitter8 } from "node:events";
|
|
348263
349715
|
import { stat as statcb, Stats } from "node:fs";
|
|
348264
|
-
import { readdir as
|
|
349716
|
+
import { readdir as readdir11, stat as stat7 } from "node:fs/promises";
|
|
348265
349717
|
import * as sp2 from "node:path";
|
|
348266
349718
|
|
|
348267
349719
|
// packages/core/node_modules/readdirp/index.js
|
|
348268
|
-
import { lstat as lstat3, readdir as
|
|
349720
|
+
import { lstat as lstat3, readdir as readdir10, realpath as realpath4, stat as stat5 } from "node:fs/promises";
|
|
348269
349721
|
import { join as pjoin, relative as prelative, resolve as presolve, sep as psep } from "node:path";
|
|
348270
349722
|
import { Readable as Readable3 } from "node:stream";
|
|
348271
349723
|
var EntryTypes = {
|
|
@@ -348417,7 +349869,7 @@ var ReaddirpStream = class extends Readable3 {
|
|
|
348417
349869
|
async _exploreDir(path101, depth) {
|
|
348418
349870
|
let files;
|
|
348419
349871
|
try {
|
|
348420
|
-
files = await
|
|
349872
|
+
files = await readdir10(path101, this._rdOptions);
|
|
348421
349873
|
} catch (error40) {
|
|
348422
349874
|
this._onError(error40);
|
|
348423
349875
|
}
|
|
@@ -349282,11 +350734,11 @@ function createPattern(matcher) {
|
|
|
349282
350734
|
if (matcher.path === string4)
|
|
349283
350735
|
return true;
|
|
349284
350736
|
if (matcher.recursive) {
|
|
349285
|
-
const
|
|
349286
|
-
if (!
|
|
350737
|
+
const relative11 = sp2.relative(matcher.path, string4);
|
|
350738
|
+
if (!relative11) {
|
|
349287
350739
|
return false;
|
|
349288
350740
|
}
|
|
349289
|
-
return !
|
|
350741
|
+
return !relative11.startsWith("..") && !sp2.isAbsolute(relative11);
|
|
349290
350742
|
}
|
|
349291
350743
|
return false;
|
|
349292
350744
|
};
|
|
@@ -349388,7 +350840,7 @@ var DirEntry = class {
|
|
|
349388
350840
|
return;
|
|
349389
350841
|
const dir = this.path;
|
|
349390
350842
|
try {
|
|
349391
|
-
await
|
|
350843
|
+
await readdir11(dir);
|
|
349392
350844
|
} catch (err2) {
|
|
349393
350845
|
if (this._removeWatcher) {
|
|
349394
350846
|
this._removeWatcher(sp2.dirname(dir), sp2.basename(dir));
|
|
@@ -350234,15 +351686,23 @@ var RecursiveFileSearch = class {
|
|
|
350234
351686
|
if (pattern.includes("*") || !this.fzf) {
|
|
350235
351687
|
filteredCandidates = await filter3(candidates, pattern, options.signal);
|
|
350236
351688
|
} else {
|
|
350237
|
-
|
|
350238
|
-
|
|
350239
|
-
|
|
350240
|
-
|
|
350241
|
-
|
|
350242
|
-
|
|
351689
|
+
try {
|
|
351690
|
+
const fzfResult = await this.fzf.find(pattern);
|
|
351691
|
+
if (Array.isArray(fzfResult)) {
|
|
351692
|
+
filteredCandidates = fzfResult.map((entry) => {
|
|
351693
|
+
if (typeof entry === "object" && entry !== null && "item" in entry) {
|
|
351694
|
+
return String(entry.item);
|
|
351695
|
+
}
|
|
351696
|
+
return String(entry);
|
|
351697
|
+
});
|
|
351698
|
+
} else {
|
|
351699
|
+
shouldCache = false;
|
|
351700
|
+
filteredCandidates = [];
|
|
351701
|
+
}
|
|
351702
|
+
} catch {
|
|
350243
351703
|
shouldCache = false;
|
|
350244
|
-
|
|
350245
|
-
}
|
|
351704
|
+
filteredCandidates = [];
|
|
351705
|
+
}
|
|
350246
351706
|
}
|
|
350247
351707
|
if (shouldCache) {
|
|
350248
351708
|
this.resultCache.set(pattern, filteredCandidates);
|
|
@@ -350855,8 +352315,8 @@ function normalizePathCandidate(candidate, projectRoot) {
|
|
|
350855
352315
|
}
|
|
350856
352316
|
let normalized2 = trimmed2.replace(/\\/g, "/");
|
|
350857
352317
|
if (path88.isAbsolute(trimmed2)) {
|
|
350858
|
-
const
|
|
350859
|
-
normalized2 =
|
|
352318
|
+
const relative11 = path88.relative(projectRoot, trimmed2);
|
|
352319
|
+
normalized2 = relative11 && !relative11.startsWith("..") && !path88.isAbsolute(relative11) ? relative11.replace(/\\/g, "/") : path88.basename(trimmed2);
|
|
350860
352320
|
}
|
|
350861
352321
|
if (normalized2.length > 120) {
|
|
350862
352322
|
normalized2 = normalized2.split("/").slice(-3).join("/");
|
|
@@ -351661,6 +353121,9 @@ function contentPartsToGeminiParts(content) {
|
|
|
351661
353121
|
result2.push({ text: part.text });
|
|
351662
353122
|
break;
|
|
351663
353123
|
default:
|
|
353124
|
+
debugLogger.warn(
|
|
353125
|
+
`Unhandled ContentPart type: ${JSON.stringify(part)} fallback to serialization`
|
|
353126
|
+
);
|
|
351664
353127
|
result2.push({ text: JSON.stringify(part) });
|
|
351665
353128
|
break;
|
|
351666
353129
|
}
|
|
@@ -351677,62 +353140,6 @@ function buildToolResponseData(response) {
|
|
|
351677
353140
|
return Object.keys(parts2).length > 0 ? parts2 : void 0;
|
|
351678
353141
|
}
|
|
351679
353142
|
|
|
351680
|
-
// packages/core/src/agent/tool-display-utils.ts
|
|
351681
|
-
function populateToolDisplay({
|
|
351682
|
-
name: name3,
|
|
351683
|
-
invocation,
|
|
351684
|
-
resultDisplay,
|
|
351685
|
-
displayName
|
|
351686
|
-
}) {
|
|
351687
|
-
const display = {
|
|
351688
|
-
name: displayName || name3,
|
|
351689
|
-
description: invocation?.getDescription?.()
|
|
351690
|
-
};
|
|
351691
|
-
if (resultDisplay) {
|
|
351692
|
-
display.result = toolResultDisplayToDisplayContent(resultDisplay);
|
|
351693
|
-
}
|
|
351694
|
-
return display;
|
|
351695
|
-
}
|
|
351696
|
-
function toolResultDisplayToDisplayContent(resultDisplay) {
|
|
351697
|
-
if (typeof resultDisplay === "string") {
|
|
351698
|
-
return { type: "text", text: resultDisplay };
|
|
351699
|
-
}
|
|
351700
|
-
if (typeof resultDisplay === "object" && resultDisplay !== null && "fileDiff" in resultDisplay && "newContent" in resultDisplay) {
|
|
351701
|
-
return {
|
|
351702
|
-
type: "diff",
|
|
351703
|
-
path: resultDisplay.filePath || resultDisplay.fileName,
|
|
351704
|
-
beforeText: resultDisplay.originalContent ?? "",
|
|
351705
|
-
afterText: resultDisplay.newContent
|
|
351706
|
-
};
|
|
351707
|
-
}
|
|
351708
|
-
return {
|
|
351709
|
-
type: "text",
|
|
351710
|
-
text: JSON.stringify(resultDisplay)
|
|
351711
|
-
};
|
|
351712
|
-
}
|
|
351713
|
-
function renderDisplayDiff(diff) {
|
|
351714
|
-
return createPatch(
|
|
351715
|
-
diff.path || "file",
|
|
351716
|
-
diff.beforeText,
|
|
351717
|
-
diff.afterText,
|
|
351718
|
-
"Original",
|
|
351719
|
-
"Modified",
|
|
351720
|
-
{ context: 3 }
|
|
351721
|
-
);
|
|
351722
|
-
}
|
|
351723
|
-
function displayContentToString(display) {
|
|
351724
|
-
if (!display) {
|
|
351725
|
-
return void 0;
|
|
351726
|
-
}
|
|
351727
|
-
if (display.type === "text") {
|
|
351728
|
-
return display.text;
|
|
351729
|
-
}
|
|
351730
|
-
if (display.type === "diff") {
|
|
351731
|
-
return renderDisplayDiff(display);
|
|
351732
|
-
}
|
|
351733
|
-
return JSON.stringify(display);
|
|
351734
|
-
}
|
|
351735
|
-
|
|
351736
353143
|
// packages/core/src/agent/event-translator.ts
|
|
351737
353144
|
function createTranslationState(streamId) {
|
|
351738
353145
|
return {
|
|
@@ -351881,18 +353288,19 @@ function translateEvent(event, state) {
|
|
|
351881
353288
|
makeEvent("tool_request", state, {
|
|
351882
353289
|
requestId: event.value.callId,
|
|
351883
353290
|
name: event.value.name,
|
|
351884
|
-
args: event.value.args
|
|
353291
|
+
args: event.value.args,
|
|
353292
|
+
display: event.value.display
|
|
351885
353293
|
})
|
|
351886
353294
|
);
|
|
351887
353295
|
break;
|
|
351888
353296
|
case "tool_call_response" /* ToolCallResponse */: {
|
|
351889
353297
|
ensureStreamStart(state, out2);
|
|
351890
353298
|
const data = buildToolResponseData(event.value);
|
|
351891
|
-
const display = event.value.resultDisplay ? {
|
|
353299
|
+
const display = event.value.display ?? (event.value.resultDisplay ? {
|
|
351892
353300
|
result: toolResultDisplayToDisplayContent(
|
|
351893
353301
|
event.value.resultDisplay
|
|
351894
353302
|
)
|
|
351895
|
-
} : void 0;
|
|
353303
|
+
} : void 0);
|
|
351896
353304
|
out2.push(
|
|
351897
353305
|
makeEvent("tool_response", state, {
|
|
351898
353306
|
requestId: event.value.callId,
|
|
@@ -351916,7 +353324,6 @@ function translateEvent(event, state) {
|
|
|
351916
353324
|
((x) => {
|
|
351917
353325
|
throw new Error(`Unhandled event type: ${JSON.stringify(x)}`);
|
|
351918
353326
|
})(event);
|
|
351919
|
-
break;
|
|
351920
353327
|
}
|
|
351921
353328
|
return out2;
|
|
351922
353329
|
}
|
|
@@ -352122,6 +353529,7 @@ var LegacyAgentProtocol = class {
|
|
|
352122
353529
|
} else {
|
|
352123
353530
|
this._emitErrorAndAgentEnd(err2);
|
|
352124
353531
|
}
|
|
353532
|
+
} finally {
|
|
352125
353533
|
this._clearActiveStream();
|
|
352126
353534
|
}
|
|
352127
353535
|
}
|
|
@@ -352204,7 +353612,8 @@ var LegacyAgentProtocol = class {
|
|
|
352204
353612
|
name: request.name,
|
|
352205
353613
|
invocation: "invocation" in tc ? tc.invocation : void 0,
|
|
352206
353614
|
resultDisplay: response.resultDisplay,
|
|
352207
|
-
displayName: "tool" in tc ? tc.tool?.displayName : void 0
|
|
353615
|
+
displayName: "tool" in tc ? tc.tool?.displayName : void 0,
|
|
353616
|
+
display: response.display
|
|
352208
353617
|
});
|
|
352209
353618
|
const data = buildToolResponseData(response);
|
|
352210
353619
|
this._emit([
|
|
@@ -352304,6 +353713,7 @@ var LegacyAgentProtocol = class {
|
|
|
352304
353713
|
const meta = {};
|
|
352305
353714
|
if (err2 instanceof Error) {
|
|
352306
353715
|
meta["errorName"] = err2.constructor.name;
|
|
353716
|
+
meta["stack"] = err2.stack;
|
|
352307
353717
|
if ("exitCode" in err2 && typeof err2.exitCode === "number") {
|
|
352308
353718
|
meta["exitCode"] = err2.exitCode;
|
|
352309
353719
|
}
|
|
@@ -355040,7 +356450,7 @@ var ENCODING_ALIASES = {
|
|
|
355040
356450
|
var serializeEncoding = (encoding) => typeof encoding === "string" ? `"${encoding}"` : String(encoding);
|
|
355041
356451
|
|
|
355042
356452
|
// node_modules/execa/lib/arguments/cwd.js
|
|
355043
|
-
import { statSync as
|
|
356453
|
+
import { statSync as statSync4 } from "node:fs";
|
|
355044
356454
|
import path94 from "node:path";
|
|
355045
356455
|
import process20 from "node:process";
|
|
355046
356456
|
var normalizeCwd = (cwd = getDefaultCwd()) => {
|
|
@@ -355062,7 +356472,7 @@ var fixCwdError = (originalMessage, cwd) => {
|
|
|
355062
356472
|
}
|
|
355063
356473
|
let cwdStat;
|
|
355064
356474
|
try {
|
|
355065
|
-
cwdStat =
|
|
356475
|
+
cwdStat = statSync4(cwd);
|
|
355066
356476
|
} catch (error40) {
|
|
355067
356477
|
return `The "cwd" option is invalid: ${cwd}.
|
|
355068
356478
|
${error40.message}
|
|
@@ -359725,8 +361135,8 @@ function isGeminiWorktree(dirPath, projectRoot) {
|
|
|
359725
361135
|
const realDirPath = realpathSync4(dirPath);
|
|
359726
361136
|
const realProjectRoot = realpathSync4(projectRoot);
|
|
359727
361137
|
const worktreesBaseDir = path96.join(realProjectRoot, ".gemini", "worktrees");
|
|
359728
|
-
const
|
|
359729
|
-
return !
|
|
361138
|
+
const relative11 = path96.relative(worktreesBaseDir, realDirPath);
|
|
361139
|
+
return !relative11.startsWith("..") && !path96.isAbsolute(relative11);
|
|
359730
361140
|
} catch {
|
|
359731
361141
|
return false;
|
|
359732
361142
|
}
|
|
@@ -361122,6 +362532,7 @@ export {
|
|
|
361122
362532
|
CacheService,
|
|
361123
362533
|
createCache,
|
|
361124
362534
|
ProjectIdRequiredError,
|
|
362535
|
+
InvalidNumericProjectIdError,
|
|
361125
362536
|
ValidationCancelledError,
|
|
361126
362537
|
IneligibleTierError,
|
|
361127
362538
|
resetUserDataCacheForTesting,
|
|
@@ -361209,6 +362620,11 @@ export {
|
|
|
361209
362620
|
GeminiChat,
|
|
361210
362621
|
isSchemaDepthError,
|
|
361211
362622
|
isInvalidArgumentError,
|
|
362623
|
+
stripToolCallIdPrefixes,
|
|
362624
|
+
populateToolDisplay,
|
|
362625
|
+
toolResultDisplayToDisplayContent,
|
|
362626
|
+
renderDisplayDiff,
|
|
362627
|
+
displayContentToString,
|
|
361212
362628
|
GeminiEventType,
|
|
361213
362629
|
CompressionStatus,
|
|
361214
362630
|
Turn,
|
|
@@ -361246,6 +362662,7 @@ export {
|
|
|
361246
362662
|
SubagentActivityErrorType,
|
|
361247
362663
|
SUBAGENT_REJECTED_ERROR_PREFIX,
|
|
361248
362664
|
SUBAGENT_CANCELLED_ERROR_MESSAGE,
|
|
362665
|
+
SubagentState,
|
|
361249
362666
|
isSubagentProgress,
|
|
361250
362667
|
isToolActivityError,
|
|
361251
362668
|
getAgentCardLoadOptions,
|
|
@@ -361275,6 +362692,16 @@ export {
|
|
|
361275
362692
|
getPolicyDenialError,
|
|
361276
362693
|
checkPolicy,
|
|
361277
362694
|
updatePolicy,
|
|
362695
|
+
NodeType,
|
|
362696
|
+
isAgentThought,
|
|
362697
|
+
isAgentYield,
|
|
362698
|
+
isToolExecution,
|
|
362699
|
+
isMaskedTool,
|
|
362700
|
+
isUserPrompt,
|
|
362701
|
+
isSystemEvent,
|
|
362702
|
+
isSnapshot,
|
|
362703
|
+
isRollingSummary,
|
|
362704
|
+
SnapshotGenerator,
|
|
361278
362705
|
generalistProfile,
|
|
361279
362706
|
stressTestProfile,
|
|
361280
362707
|
GeminiClient,
|
|
@@ -361420,6 +362847,7 @@ export {
|
|
|
361420
362847
|
performRestore,
|
|
361421
362848
|
performInit,
|
|
361422
362849
|
isProjectSkillPatchTarget,
|
|
362850
|
+
getAllowedMemoryPatchRoots,
|
|
361423
362851
|
validatePatches,
|
|
361424
362852
|
startMemoryService,
|
|
361425
362853
|
showMemory,
|
|
@@ -361429,7 +362857,6 @@ export {
|
|
|
361429
362857
|
listInboxSkills,
|
|
361430
362858
|
moveInboxSkill,
|
|
361431
362859
|
dismissInboxSkill,
|
|
361432
|
-
getAllowedMemoryPatchRoots,
|
|
361433
362860
|
listInboxMemoryPatches,
|
|
361434
362861
|
applyInboxMemoryPatch,
|
|
361435
362862
|
dismissInboxMemoryPatch,
|
|
@@ -361465,10 +362892,6 @@ export {
|
|
|
361465
362892
|
geminiPartsToContentParts,
|
|
361466
362893
|
contentPartsToGeminiParts,
|
|
361467
362894
|
buildToolResponseData,
|
|
361468
|
-
populateToolDisplay,
|
|
361469
|
-
toolResultDisplayToDisplayContent,
|
|
361470
|
-
renderDisplayDiff,
|
|
361471
|
-
displayContentToString,
|
|
361472
362895
|
createTranslationState,
|
|
361473
362896
|
translateEvent,
|
|
361474
362897
|
mapFinishReason,
|