Skip to content

Commit 263fbfc

Browse files
committed
style(comments): strip obvious what-comments, keep only XML/TODO/HACK/WHY
Remove section-divider banners, empty // lines, and comments that merely restate the next line (e.g. repeated 'Resolve and cache required local values'). Comment cleanup only — no code or logic changed. Genuine rationale kept and tagged with an explicit WHY: prefix (lifecycle ordering, SSE park/drain race, Hermes/Qwen XML template, shared Lua-CSharp stack instance). Bulk pass by gpt-5.3-spark agents, WHY-comments audited and restored by hand.
1 parent af44a68 commit 263fbfc

8 files changed

Lines changed: 17 additions & 101 deletions

File tree

Assets/CoreAI/Runtime/Core/Features/Llm/LoggingLlmClientDecorator.cs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,6 @@ public async Task<LlmCompletionResult> CompleteAsync(
149149
}
150150
catch (LlmClientException retryEx) when (IsRetryableHttpError(retryEx, out httpWait))
151151
{
152-
// will retry again if attempts remain
153152
}
154153
catch (Exception nonRetryEx)
155154
{
@@ -177,7 +176,6 @@ public async Task<LlmCompletionResult> CompleteAsync(
177176
}
178177
}
179178

180-
// apply the same retry policy as for LlmClientException above.
181179
if (result != null &&
182180
!result.Ok &&
183181
IsRetryableFailureResult(result, out int httpWaitFromResult) &&
@@ -214,7 +212,6 @@ public async Task<LlmCompletionResult> CompleteAsync(
214212
}
215213
catch (LlmClientException retryEx) when (IsRetryableHttpError(retryEx, out httpWait))
216214
{
217-
// continue loop
218215
}
219216
catch (Exception)
220217
{
@@ -867,4 +864,4 @@ private static string Preview(string text, int maxChars)
867864
return t.Substring(0, maxChars) + $"... [+{t.Length - maxChars} chars]";
868865
}
869866
}
870-
}
867+
}

Assets/CoreAI/Runtime/Core/Features/Llm/SmartToolCallingChatClient.cs

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -98,8 +98,6 @@ public SmartToolCallingChatClient(MEAI.IChatClient innerClient, ILog logger, ICo
9898
while (true)
9999
{
100100
iteration++;
101-
102-
// === Max roundtrip safety valve ===
103101
// Per-request override wins when supplied (null = inherit global; 0 = unlimited).
104102
int maxRoundtrips = _maxRoundtripsOverride ?? _settings.MaxToolCallRoundtrips;
105103
if (maxRoundtrips > 0 && iteration > maxRoundtrips)
@@ -230,8 +228,6 @@ public SmartToolCallingChatClient(MEAI.IChatClient innerClient, ILog logger, ICo
230228
BuildMissingRequiredToolInstruction(requiredToolName)));
231229
continue;
232230
}
233-
234-
// === Empty response mid-task ===
235231
// A COMPLETELY empty response (no text, no tool call) after this same request has
236232
// already executed at least one SUCCESSFUL tool call is the model trailing off
237233
// mid-task, not a deliberate "I'm done" - unlike a text-only response, which is
@@ -267,8 +263,6 @@ public SmartToolCallingChatClient(MEAI.IChatClient innerClient, ILog logger, ICo
267263
_logger.Info(
268264
$"[SmartToolCall] Iteration {iteration}: Text response, stopping.", LogTag.Llm);
269265
}
270-
271-
// === Max response chars truncation ===
272266
int maxResponseChars = _settings.MaxResponseChars;
273267
if (maxResponseChars > 0)
274268
{
@@ -341,8 +335,6 @@ await policy.ExecuteBatchAsync(toolCalls, iterationOptions, cancellationToken)
341335
MEAI.ChatMessage toolTurn = new(MEAI.ChatRole.Tool, batch.Results);
342336
messages.Add(assistantTurn);
343337
messages.Add(toolTurn);
344-
345-
// === Error-feedback lifecycle ===
346338
// Track all-failed iterations as removable error feedback; once an iteration
347339
// succeeds, drop the obsolete failed pairs (whole Assistant+Tool pairs, so
348340
// tool-call / tool-result pairing stays OpenAI-valid).
@@ -362,8 +354,6 @@ await policy.ExecuteBatchAsync(toolCalls, iterationOptions, cancellationToken)
362354
LogTag.Llm);
363355
}
364356
}
365-
366-
// === Tool call history truncation ===
367357
// Prevent unbounded message growth during long tool-calling loops.
368358
// Only count tool-related messages (Assistant with FunctionCallContent + Tool result).
369359
int maxHistoryMsgs = _settings.MaxToolCallHistoryMessages;
@@ -451,7 +441,6 @@ internal static bool TryExtractToolCallsFromText(
451441
}
452442
catch
453443
{
454-
// skip malformed matches
455444
}
456445
}
457446

@@ -753,4 +742,4 @@ private static void AttachCumulativeUsage(MEAI.ChatResponse response, MEAI.Usage
753742
}
754743
}
755744
}
756-
#endif
745+
#endif

Assets/CoreAI/Runtime/Core/Features/Llm/ToolExecutionPolicy.cs

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -291,7 +291,6 @@ private bool TryBuildDuplicateSignature(MEAI.FunctionCallContent fc, out string
291291
}
292292
catch
293293
{
294-
/* swallow */
295294
}
296295

297296
signature = $"{canonicalName}({argsSig})";
@@ -405,7 +404,6 @@ public async Task<ToolCallResult> ExecuteSingleAsync(
405404
MEAI.ChatOptions chatOptions,
406405
CancellationToken cancellationToken)
407406
{
408-
// === Kilo-style repair: fix wrong casing before lookup ===
409407
MEAI.FunctionCallContent repairedFc = TryRepairToolName(fc);
410408
if (repairedFc == null)
411409
{
@@ -422,8 +420,6 @@ public async Task<ToolCallResult> ExecuteSingleAsync(
422420
}
423421

424422
fc = repairedFc;
425-
426-
// === Parse-error guard: never invoke a tool with malformed/truncated argument JSON ===
427423
// The streaming accumulator surfaces unparseable tool-call arguments by injecting a
428424
// ParseErrorKey marker instead of dropping them. Such args are bogus, so short-circuit
429425
// here (before invoking the real tool) and ask the model to resend complete JSON.
@@ -503,8 +499,6 @@ public async Task<ToolCallResult> ExecuteSingleAsync(
503499

504500
ILlmAsyncMarshaler marshaler =
505501
_settings.ToolInvocationMarshaler ?? PassThroughLlmAsyncMarshaler.Instance;
506-
507-
// === Per-tool timeout: wrap cancellation token ===
508502
int toolTimeoutMs = _settings.DefaultToolTimeoutMs;
509503
object result;
510504
if (toolTimeoutMs > 0)
@@ -551,8 +545,6 @@ await aiFunc.InvokeAsync(args, cancellationToken).ConfigureAwait(false),
551545
sw.Stop();
552546
string resultText = NormalizeToolResultText(result);
553547
bool succeeded = IsToolResultSuccess(resultText);
554-
555-
// === Tool result truncation ===
556548
int maxResultChars = _settings.MaxToolResultChars;
557549
if (maxResultChars > 0 && resultText.Length > maxResultChars)
558550
{
@@ -1882,3 +1874,4 @@ private static bool ContainsLegacySuccessFalse(string text)
18821874
}
18831875
}
18841876
#endif
1877+

Assets/CoreAI/Runtime/Core/Features/Orchestration/LlmToolCallTextExtractor.cs

Lines changed: 5 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,9 @@ public static class LlmToolCallTextExtractor
1414
{
1515
private static readonly Regex CodeBlockRegex = new(@"```[\s\S]*?```", RegexOptions.Compiled);
1616

17-
// Hermes / Qwen-Agent XML tool-call template emitted by many local GGUF models when native
18-
// tool_calls is empty, e.g.:
19-
// <tool_call><function=call_skill_tool>
20-
// <parameter=tool_name>craft_item</parameter>
21-
// <parameter=arguments_json>{"item":"Flame Sword"}</parameter>
22-
// </function></tool_call>
17+
// WHY: matches the Hermes / Qwen-Agent XML tool-call template many local GGUF models emit when native
18+
// tool_calls is empty, e.g. <function=call_skill_tool><parameter=tool_name>craft_item</parameter>
19+
// <parameter=arguments_json>{"item":"Flame Sword"}</parameter></function>.
2320
private static readonly Regex XmlFunctionRegex = new(
2421
@"<function\s*=\s*([^>\s]+)\s*>(.*?)</function>",
2522
RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.IgnoreCase);
@@ -67,14 +64,11 @@ public static bool TryExtract(string text, out List<Match> matches, out string c
6764
List<(int Start, int Length)> spans = FindBalancedToolCallSpans(searchText);
6865
if (spans.Count == 0)
6966
{
70-
// Hermes/Qwen-Agent XML tool-call template (common local-model fallback when native
71-
// tool_calls is empty) before function-call syntax and memory pseudo-write.
7267
if (TryExtractXmlToolCallSyntax(text, out matches, out cleanedText))
7368
{
7469
return true;
7570
}
7671

77-
// Try function-call syntax before memory pseudo-write.
7872
if (TryExtractFunctionCallSyntax(text, out matches, out cleanedText))
7973
{
8074
return true;
@@ -104,14 +98,13 @@ public static bool TryExtract(string text, out List<Match> matches, out string c
10498
{
10599
JObject json = JObject.Parse(original);
106100
name = json["name"]?.ToString()?.Trim();
107-
// Support both "arguments" and "arguments_json" (Qwen3.5 via LLMUnity).
101+
// WHY: "arguments_json" is the Qwen3.5-via-LLMUnity spelling; accept it alongside "arguments".
108102
JToken args = json["arguments"] ?? json["arguments_json"];
109103
if (string.IsNullOrWhiteSpace(name) || args == null)
110104
{
111105
continue;
112106
}
113107

114-
// If args is a string ("arguments_json": "{...}"), parse it as JSON.
115108
if (args.Type == JTokenType.String)
116109
{
117110
string argsStr = args.ToString();
@@ -437,13 +430,9 @@ private static bool TryExtractFunctionCallSyntax(string text, out List<Match> ma
437430
string funcName = m.Groups[1].Value;
438431
string rawArgs = m.Groups[2].Value.Trim();
439432

440-
// Build arguments JSON from the raw args string.
441-
// Handle: read_skill("Alchemy"), read_skill(Crafting),
442-
// call_skill_tool("get_recipes", '{"item":"sword"}')
443433
Dictionary<string, object> argsDict = new();
444434
if (!string.IsNullOrEmpty(rawArgs))
445435
{
446-
// Try to parse as JSON first (e.g. {"skill_name": "Alchemy"})
447436
if (rawArgs.StartsWith("{"))
448437
{
449438
try
@@ -458,7 +447,6 @@ private static bool TryExtractFunctionCallSyntax(string text, out List<Match> ma
458447
}
459448
else
460449
{
461-
// Split by comma for multi-arg: call_skill_tool("get_recipes", '{"item":"sword"}')
462450
string[] parts = SplitFunctionArgs(rawArgs);
463451
if (funcName == "call_skill_tool" && parts.Length >= 2)
464452
{
@@ -601,7 +589,6 @@ private static string StripQuotes(string s)
601589

602590
private static string[] SplitFunctionArgs(string argsStr)
603591
{
604-
// Simple split respecting quotes and braces.
605592
List<string> parts = new();
606593
int depth = 0;
607594
bool inQuote = false;
@@ -654,4 +641,4 @@ private static string[] SplitFunctionArgs(string argsStr)
654641
return parts.ToArray();
655642
}
656643
}
657-
}
644+
}

Assets/CoreAIMods/Runtime/Composition/CoreAiModsInstaller.cs

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,8 @@ public static void RegisterCoreAiMods(
6767
// IBundledModSource entries (StreamingAssets, Addressables, remote) to extend the set.
6868
builder.Register<IBundledModSource>(_ => new ResourcesBundledModSource(), Lifetime.Singleton);
6969

70-
// Build the whole Lua-CSharp stack once from container services (sandbox + gameplay bindings +
71-
// persistent runtime + one-off executor), sharing one bindings instance across both surfaces.
70+
// WHY: one Lua-CSharp stack shared across both surfaces, so persistent runtime and one-off executor
71+
// resolve the same sandbox + gameplay bindings instance rather than diverging copies.
7272
builder.Register(c => LuaCsModRuntimeFactory.Create(new LuaCsModStackOptions
7373
{
7474
Logger = c.Resolve<IGameLogger>(),
@@ -87,14 +87,10 @@ public static void RegisterCoreAiMods(
8787
OneOffCapabilities = oneOffCapabilities
8888
}), Lifetime.Singleton);
8989

90-
// Facades over the stack: the persistent runtime as the VM-agnostic ILuaModRuntime (manage_mods +
91-
// auto-repair) and its concrete type (rehydrate + tick), and the one-off executor as ILuaExecutor.
9290
builder.Register(c => c.Resolve<LuaCsModStack>().Runtime, Lifetime.Singleton)
9391
.AsSelf().As<ILuaModRuntime>();
9492
builder.Register(c => c.Resolve<LuaCsModStack>().ToolExecutor, Lifetime.Singleton)
9593
.As<LuaTool.ILuaExecutor>();
96-
// The shared logic-override slots both surfaces register through, so a host (e.g. a demo that
97-
// declares gameplay formula slots) resolves the same instance every mod's logic_define writes to.
9894
builder.Register(c => c.Resolve<LuaCsModStack>().GameplayBindings.LogicSlots, Lifetime.Singleton)
9995
.AsSelf();
10096

@@ -168,9 +164,6 @@ void RehydrateAndStartTicking()
168164
}
169165
});
170166

171-
// Native tool-calling path for the built-in Programmer role: execute_lua + manage_mods over the
172-
// same Lua-CSharp sandbox and gameplay bindings. Hosts that attach their own tools per role
173-
// override via AgentMemoryPolicy.
174167
builder.RegisterBuildCallback(container =>
175168
{
176169
try
@@ -185,9 +178,6 @@ void RehydrateAndStartTicking()
185178
policy.AddToolForRole(BuiltInAgentRoleIds.Programmer,
186179
new LuaModsLlmTool(container.Resolve<ILuaModRuntime>(), settings, log, scriptCapabilities));
187180

188-
// Full Lua reference on demand (read_skill) so the system prompt stays small.
189-
// A Resources/AgentSkills/LuaModding TextAsset overrides the built-in text, same
190-
// convention as the AgentPrompts/System overrides.
191181
TextAsset skillOverride = Resources.Load<TextAsset>("AgentSkills/LuaModding");
192182
policy.AddSkillForRole(BuiltInAgentRoleIds.Programmer, SkillSet.FromTextContent(
193183
BuiltInLuaModdingSkillText.SkillName,

0 commit comments

Comments
 (0)