Skip to content

Commit 2fb1da2

Browse files
calebedenCopilotshanselman
authored
feat: handle lifecycle slash commands natively in Windows chat (#1036)
* feat: add native lifecycle slash commands Handle exact /new, /reset, and /compact commands through lifecycle RPCs, preserve structured compaction boundaries, and retain safe compatibility behavior for older gateways. Co-authored-by: Copilot App <[email protected]> Copilot-Session: c41e789a-73e3-41ae-ac62-1ff5287599c0 * fix: harden lifecycle command edge cases Preserve explicit session selection and failed composer sends, retain live entries during authoritative reloads, widen compaction metrics, and clarify lifecycle timeout recovery. Co-authored-by: Copilot App <[email protected]> Copilot-Session: c41e789a-73e3-41ae-ac62-1ff5287599c0 * fix: order lifecycle commands with queued sends Co-authored-by: Copilot App <[email protected]> Copilot-Session: c41e789a-73e3-41ae-ac62-1ff5287599c0 * fix: guard authoritative history reload pending by connection generation The _authoritativeHistoryReloadPending flag was consumed in LoadHistoryCoreAsync's finally block without checking whether the completing request belonged to the current connection generation. A stale old-generation completion after disconnect/reconnect could consume the flag and trigger an unintended authoritative reload in the newer generation. Fix: - Only consume/schedule the pending authoritative reload when requestConnectionVersion == _historyConnectionVersion (same guard as _historyInFlight removal) - Clear _authoritativeHistoryReloadPending in AdvanceHistoryGenerationLocked so generation advances invalidate stale pending flags - Add deterministic regression test: StaleGenerationAuthoritativeReload_DoesNotReloadInNewGeneration Co-authored-by: Copilot App <[email protected]> Copilot-Session: d2982ca8-bb56-4728-85bd-29542ce9d554 * Record paired-review history race fix Co-authored-by: Copilot App <[email protected]> Copilot-Session: 4f0e93ff-d320-454d-b00a-865dac727d0c --------- Co-authored-by: Copilot App <[email protected]> Co-authored-by: Scott Hanselman <[email protected]>
1 parent 282e583 commit 2fb1da2

27 files changed

Lines changed: 2489 additions & 60 deletions

‎src/OpenClaw.Shared/IOperatorGatewayClient.cs‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,8 +77,20 @@ Task<ChatHistoryInfo> RequestChatHistoryAsync(string? sessionKey = null, int tim
7777
Task RequestSessionPreviewAsync(string[] keys, int limit = 12, int maxChars = 240);
7878
Task<bool> PatchSessionAsync(string key, string? model = null, string? thinkingLevel = null, string? verboseLevel = null);
7979
Task<bool> ResetSessionAsync(string key);
80+
Task<SessionResetResult> ResetSessionDetailedAsync(string key, int timeoutMs = 15000) =>
81+
Task.FromResult(new SessionResetResult
82+
{
83+
Ok = false,
84+
Error = "Response-aware sessions.reset is not supported by this gateway client."
85+
});
8086
Task<bool> DeleteSessionAsync(string key, bool deleteTranscript = true);
8187
Task<bool> CompactSessionAsync(string key, int maxLines = 400);
88+
Task<SessionCompactResult> CompactSessionDetailedAsync(string key, int timeoutMs = 120000) =>
89+
Task.FromResult(new SessionCompactResult
90+
{
91+
Ok = false,
92+
Error = "Response-aware sessions.compact is not supported by this gateway client."
93+
});
8294
Task RequestCronListAsync();
8395
Task RequestCronStatusAsync();
8496
Task<bool> RunCronJobAsync(string jobId, bool force = true);
@@ -163,6 +175,14 @@ Task<SessionCompactionMutationResult> BranchCompactionCheckpointAsync(string key
163175
/// <summary>Restore a session to a compaction checkpoint (<c>sessions.compaction.restore</c>).</summary>
164176
Task<SessionCompactionMutationResult> RestoreCompactionCheckpointAsync(string key, string checkpointId, int timeoutMs = 15000)
165177
=> Task.FromResult(new SessionCompactionMutationResult { Key = key, CheckpointId = checkpointId, IsSupported = false });
178+
/// <summary>Create a distinct session through <c>sessions.create</c>.</summary>
179+
Task<SessionCreateResult> CreateSessionAsync(SessionCreateRequest request, int timeoutMs = 15000)
180+
=> Task.FromResult(new SessionCreateResult
181+
{
182+
Ok = false,
183+
IsSupported = false,
184+
Error = "sessions.create is not supported by this gateway client."
185+
});
166186
}
167187

168188
public sealed record CronRunRequestResult(

‎src/OpenClaw.Shared/Models.cs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1855,6 +1855,15 @@ public static bool IsSilentAssistantDirective(string? role, string? text) =>
18551855
/// <summary>Monotonic sequence number within the session from <c>__openclaw.seq</c>.</summary>
18561856
public int? OpenClawSeq { get; set; }
18571857

1858+
/// <summary>Structured gateway message kind from <c>__openclaw.kind</c>.</summary>
1859+
public string? OpenClawKind { get; set; }
1860+
1861+
/// <summary>Context token count before a structured compaction boundary.</summary>
1862+
public long? CompactionTokensBefore { get; set; }
1863+
1864+
/// <summary>Context token count after a structured compaction boundary.</summary>
1865+
public long? CompactionTokensAfter { get; set; }
1866+
18581867
/// <summary>
18591868
/// Stop reason for assistant messages (e.g. "stop", "toolUse", possibly "abort").
18601869
/// Only present on assistant messages in <c>chat.history</c>.

‎src/OpenClaw.Shared/OpenClawGatewayClient.Protocol.cs‎

Lines changed: 298 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ namespace OpenClaw.Shared;
1212
// Typed client methods for the richer gateway protocol, matching the canonical
1313
// openclaw/openclaw schemas exactly:
1414
// • commands.list — command catalog
15+
// • sessions.create — distinct session creation
1516
// • sessions.patch — extended per-session field set
1617
// • sessions.files.list/get — workspace file rail + browser (param: sessionKey)
1718
// • sessions.compaction.* — compaction checkpoints (param: key, checkpointId)
@@ -21,14 +22,310 @@ namespace OpenClaw.Shared;
2122
// (logged at warn) instead of throwing. Genuine protocol errors are NOT
2223
// swallowed: read methods propagate the gateway error (e.g. not-found / too-large
2324
// on sessions.files.get), and mutation methods surface it in the result's Error
24-
// field. Timeouts propagate as TimeoutException from the request helper.
25+
// field. Lifecycle RPCs convert request timeouts into action-specific results.
2526
//
2627
// Parsing is factored into internal static methods so the JSON contract is unit
2728
// testable directly (InternalsVisibleTo OpenClaw.Shared.Tests), reusing the
2829
// private static JsonElement helpers declared in OpenClawGatewayClient.cs.
2930
// ─────────────────────────────────────────────────────────────────────────────
3031
public partial class OpenClawGatewayClient
3132
{
33+
// ── sessions.reset ──
34+
35+
public async Task<SessionResetResult> ResetSessionDetailedAsync(
36+
string key,
37+
int timeoutMs = 15000)
38+
{
39+
if (string.IsNullOrWhiteSpace(key))
40+
{
41+
return new SessionResetResult
42+
{
43+
Ok = false,
44+
Error = "Session key is required"
45+
};
46+
}
47+
if (!IsConnected)
48+
{
49+
return new SessionResetResult
50+
{
51+
Ok = false,
52+
Error = "Gateway connection is not open"
53+
};
54+
}
55+
56+
try
57+
{
58+
var payload = await SendWizardRequestAsync(
59+
"sessions.reset",
60+
new { key },
61+
timeoutMs).ConfigureAwait(false);
62+
return ParseSessionResetResult(payload);
63+
}
64+
catch (TimeoutException ex)
65+
{
66+
_logger.Warn($"sessions.reset timed out: {ex.Message}");
67+
return CreateSessionResetTimeoutResult();
68+
}
69+
catch (InvalidOperationException ex)
70+
{
71+
_logger.Warn($"sessions.reset failed: {ex.Message}");
72+
return new SessionResetResult
73+
{
74+
Ok = false,
75+
Error = ex.Message
76+
};
77+
}
78+
}
79+
80+
internal static SessionResetResult CreateSessionResetTimeoutResult() => new()
81+
{
82+
Ok = false,
83+
Error = "The gateway did not respond before the reset timed out. Refresh the session before trying again."
84+
};
85+
86+
internal static SessionResetResult ParseSessionResetResult(JsonElement payload)
87+
{
88+
var ok = !payload.TryGetProperty("ok", out var okElement) ||
89+
okElement.ValueKind == JsonValueKind.True;
90+
var reason = GetString(payload, "reason");
91+
return new SessionResetResult
92+
{
93+
Ok = ok,
94+
Key = GetString(payload, "key"),
95+
Reason = reason,
96+
Error = ok ? null : reason ?? "The gateway could not reset the session."
97+
};
98+
}
99+
100+
// ── sessions.compact ──
101+
102+
public async Task<SessionCompactResult> CompactSessionDetailedAsync(
103+
string key,
104+
int timeoutMs = 120000)
105+
{
106+
if (string.IsNullOrWhiteSpace(key))
107+
{
108+
return new SessionCompactResult
109+
{
110+
Ok = false,
111+
Error = "Session key is required"
112+
};
113+
}
114+
if (!IsConnected)
115+
{
116+
return new SessionCompactResult
117+
{
118+
Ok = false,
119+
Error = "Gateway connection is not open"
120+
};
121+
}
122+
123+
try
124+
{
125+
var payload = await SendWizardRequestAsync(
126+
"sessions.compact",
127+
new { key },
128+
timeoutMs).ConfigureAwait(false);
129+
return ParseSessionCompactResult(payload);
130+
}
131+
catch (TimeoutException ex)
132+
{
133+
_logger.Warn($"sessions.compact timed out: {ex.Message}");
134+
return CreateSessionCompactTimeoutResult();
135+
}
136+
catch (InvalidOperationException ex)
137+
{
138+
_logger.Warn($"sessions.compact failed: {ex.Message}");
139+
return new SessionCompactResult
140+
{
141+
Ok = false,
142+
Error = ex.Message
143+
};
144+
}
145+
}
146+
147+
internal static SessionCompactResult CreateSessionCompactTimeoutResult() => new()
148+
{
149+
Ok = false,
150+
Error = "The gateway did not respond before compaction timed out. Refresh the conversation to check whether compaction completed."
151+
};
152+
153+
internal static SessionCompactResult ParseSessionCompactResult(JsonElement payload)
154+
{
155+
var ok = !payload.TryGetProperty("ok", out var okElement) ||
156+
okElement.ValueKind == JsonValueKind.True;
157+
var compacted = payload.TryGetProperty("compacted", out var compactedElement) &&
158+
compactedElement.ValueKind == JsonValueKind.True;
159+
long? tokensBefore = null;
160+
long? tokensAfter = null;
161+
if (payload.TryGetProperty("result", out var result) &&
162+
result.ValueKind == JsonValueKind.Object)
163+
{
164+
if (result.TryGetProperty("tokensBefore", out var before) &&
165+
before.TryGetInt64(out var beforeValue))
166+
{
167+
tokensBefore = beforeValue;
168+
}
169+
if (result.TryGetProperty("tokensAfter", out var after) &&
170+
after.TryGetInt64(out var afterValue))
171+
{
172+
tokensAfter = afterValue;
173+
}
174+
}
175+
176+
var reason = GetString(payload, "reason");
177+
return new SessionCompactResult
178+
{
179+
Ok = ok,
180+
Key = GetString(payload, "key"),
181+
Compacted = compacted,
182+
Reason = reason,
183+
TokensBefore = tokensBefore,
184+
TokensAfter = tokensAfter,
185+
Error = ok ? null : reason ?? "The gateway could not compact the session."
186+
};
187+
}
188+
189+
// ── sessions.create ──
190+
191+
/// <summary>
192+
/// Creates a distinct gateway session. Unsupported gateways return a typed
193+
/// result with <see cref="SessionCreateResult.IsSupported"/> = false.
194+
/// Other gateway errors are surfaced in <see cref="SessionCreateResult.Error"/>.
195+
/// </summary>
196+
public async Task<SessionCreateResult> CreateSessionAsync(
197+
SessionCreateRequest request,
198+
int timeoutMs = 15000)
199+
{
200+
ArgumentNullException.ThrowIfNull(request);
201+
if (!IsConnected)
202+
{
203+
return new SessionCreateResult
204+
{
205+
Ok = false,
206+
Error = "Gateway connection is not open"
207+
};
208+
}
209+
210+
try
211+
{
212+
JsonElement payload;
213+
try
214+
{
215+
payload = await SendWizardRequestAsync(
216+
"sessions.create",
217+
BuildSessionCreateParameters(request),
218+
timeoutMs).ConfigureAwait(false);
219+
}
220+
catch (InvalidOperationException ex) when (
221+
request.SucceedsParent.HasValue &&
222+
IsLegacySucceedsParentError(ex.Message))
223+
{
224+
_logger.Warn("sessions.create retrying with legacy lifecycle parameters");
225+
payload = await SendWizardRequestAsync(
226+
"sessions.create",
227+
BuildSessionCreateParameters(request, legacyLifecycleFallback: true),
228+
timeoutMs).ConfigureAwait(false);
229+
}
230+
231+
return ParseSessionCreateResult(payload);
232+
}
233+
catch (TimeoutException ex)
234+
{
235+
_logger.Warn($"sessions.create timed out: {ex.Message}");
236+
return CreateSessionCreationTimeoutResult();
237+
}
238+
catch (InvalidOperationException ex) when (IsUnknownMethodError(ex.Message))
239+
{
240+
_logger.Warn("sessions.create unsupported on gateway");
241+
return new SessionCreateResult
242+
{
243+
Ok = false,
244+
IsSupported = false,
245+
Error = ex.Message
246+
};
247+
}
248+
catch (InvalidOperationException ex)
249+
{
250+
_logger.Warn($"sessions.create failed: {ex.Message}");
251+
return new SessionCreateResult
252+
{
253+
Ok = false,
254+
Error = ex.Message
255+
};
256+
}
257+
}
258+
259+
internal static SessionCreateResult CreateSessionCreationTimeoutResult() => new()
260+
{
261+
Ok = false,
262+
Error = "The gateway did not respond before session creation timed out. Check the session list to see whether a new session was created before trying again."
263+
};
264+
265+
internal static Dictionary<string, object?> BuildSessionCreateParameters(
266+
SessionCreateRequest request,
267+
bool legacyLifecycleFallback = false)
268+
{
269+
ArgumentNullException.ThrowIfNull(request);
270+
271+
var parameters = new Dictionary<string, object?>();
272+
if (!string.IsNullOrWhiteSpace(request.Key))
273+
parameters["key"] = request.Key;
274+
if (!string.IsNullOrWhiteSpace(request.AgentId))
275+
parameters["agentId"] = request.AgentId;
276+
277+
var unlinkLegacyParallelChild =
278+
legacyLifecycleFallback && request.SucceedsParent == false;
279+
if (!unlinkLegacyParallelChild)
280+
{
281+
parameters["emitCommandHooks"] = request.EmitCommandHooks;
282+
if (!string.IsNullOrWhiteSpace(request.ParentSessionKey))
283+
parameters["parentSessionKey"] = request.ParentSessionKey;
284+
}
285+
286+
if (!legacyLifecycleFallback && request.SucceedsParent.HasValue)
287+
parameters["succeedsParent"] = request.SucceedsParent.Value;
288+
289+
return parameters;
290+
}
291+
292+
private static bool IsLegacySucceedsParentError(string? message) =>
293+
message?.Contains(
294+
"invalid sessions.create params",
295+
StringComparison.OrdinalIgnoreCase) == true &&
296+
message.Contains("succeedsParent", StringComparison.OrdinalIgnoreCase);
297+
298+
internal static SessionCreateResult ParseSessionCreateResult(JsonElement payload)
299+
{
300+
var ok = !payload.TryGetProperty("ok", out var okElement) ||
301+
okElement.ValueKind == JsonValueKind.True;
302+
if (!ok)
303+
{
304+
return new SessionCreateResult
305+
{
306+
Ok = false,
307+
Error = GetString(payload, "reason") ?? "The gateway could not create a new session."
308+
};
309+
}
310+
311+
var key = GetString(payload, "key")?.Trim();
312+
if (string.IsNullOrEmpty(key))
313+
{
314+
return new SessionCreateResult
315+
{
316+
Ok = false,
317+
Error = "sessions.create returned no session key"
318+
};
319+
}
320+
321+
return new SessionCreateResult
322+
{
323+
Ok = true,
324+
Key = key,
325+
SessionId = GetString(payload, "sessionId")
326+
};
327+
}
328+
32329
// ── commands.list ──
33330

34331
/// <summary>

0 commit comments

Comments
 (0)