Skip to content

Commit 66a5cfb

Browse files
committed
Merge remote-tracking branch 'origin/main' into codex/fix-main-ui-gates
2 parents 9d21794 + 9b8fa12 commit 66a5cfb

5 files changed

Lines changed: 309 additions & 299 deletions

File tree

‎extensions/google/realtime-voice-provider.ts‎

Lines changed: 4 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import type {
1313
LiveServerToolCall,
1414
Modality,
1515
RealtimeInputConfig,
16+
Session,
1617
StartSensitivity,
1718
ThinkingConfig,
1819
TurnCoverage,
@@ -124,20 +125,6 @@ type GoogleRealtimeLiveConfig = {
124125
type GoogleRealtimeVoiceBridgeConfig = RealtimeVoiceBridgeCreateRequest & GoogleRealtimeLiveConfig;
125126
type GoogleLiveTranscription = NonNullable<LiveServerContent["inputTranscription"]>;
126127

127-
type GoogleLiveSession = {
128-
sendClientContent: (params: {
129-
turns?: Array<{ role: string; parts: Array<{ text: string }> }>;
130-
turnComplete?: boolean;
131-
}) => void;
132-
sendRealtimeInput: (params: {
133-
audio?: { data: string; mimeType: string };
134-
audioStreamEnd?: boolean;
135-
text?: string;
136-
}) => void;
137-
sendToolResponse: (params: { functionResponses: FunctionResponse[] | FunctionResponse }) => void;
138-
close: () => void;
139-
};
140-
141128
function trimToUndefined(value: unknown): string | undefined {
142129
return normalizeOptionalString(value);
143130
}
@@ -496,7 +483,7 @@ class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
496483
readonly supportsToolResultContinuation: boolean;
497484
readonly supportsToolResultSuppression = false;
498485

499-
private session: GoogleLiveSession | null = null;
486+
private session: Session | null = null;
500487
private connected = false;
501488
private sessionConfigured = false;
502489
private intentionallyClosed = false;
@@ -543,7 +530,7 @@ class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
543530
},
544531
});
545532

546-
this.session = (await ai.live.connect({
533+
this.session = await ai.live.connect({
547534
model: this.model,
548535
config: {
549536
...buildGoogleLiveConnectConfig(this.config, this.model),
@@ -594,7 +581,7 @@ class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
594581
this.config.onClose?.("error");
595582
},
596583
},
597-
})) as GoogleLiveSession;
584+
});
598585
this.hasConnectedSession = true;
599586
}
600587

‎extensions/microsoft/tts.ts‎

Lines changed: 5 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -5,29 +5,12 @@ import path from "node:path";
55
import { writeExternalFileWithinRoot } from "openclaw/plugin-sdk/security-runtime";
66
import { normalizeLowercaseStringOrEmpty } from "openclaw/plugin-sdk/string-coerce-runtime";
77

8-
type EdgeTTSRuntimeConfig = {
9-
voice?: string;
10-
lang?: string;
11-
outputFormat?: string;
12-
saveSubtitles?: boolean;
13-
proxy?: string;
14-
rate?: string;
15-
pitch?: string;
16-
volume?: string;
17-
timeout?: number;
18-
};
19-
208
type EdgeTTSDeps = {
21-
EdgeTTS: new (config: EdgeTTSRuntimeConfig) => {
22-
ttsPromise: (text: string, outputPath: string) => Promise<unknown>;
23-
};
9+
EdgeTTS: new (
10+
...args: ConstructorParameters<typeof import("node-edge-tts").EdgeTTS>
11+
) => Pick<import("node-edge-tts").EdgeTTS, "ttsPromise">;
2412
};
2513

26-
async function loadDefaultEdgeTTSDeps(): Promise<EdgeTTSDeps> {
27-
const { EdgeTTS } = await import("node-edge-tts");
28-
return { EdgeTTS };
29-
}
30-
3114
function isMissingOutputFileError(error: unknown): boolean {
3215
return (
3316
typeof error === "object" &&
@@ -89,8 +72,8 @@ export async function edgeTTS(
8972
throw new Error("Microsoft TTS text cannot be empty");
9073
}
9174

92-
const resolvedDeps = deps ?? (await loadDefaultEdgeTTSDeps());
93-
const tts = new resolvedDeps.EdgeTTS({
75+
const EdgeTTSClass = deps?.EdgeTTS ?? (await import("node-edge-tts")).EdgeTTS;
76+
const tts = new EdgeTTSClass({
9477
voice: config.voice,
9578
lang: config.lang,
9679
outputFormat: config.outputFormat,
Lines changed: 274 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,274 @@
1+
/**
2+
* Prepares restored transcript history and applies context-engine assembly.
3+
*/
4+
import { buildHierarchyReinforcementMessage } from "../../../auto-reply/handoff-summarizer.js";
5+
import { filterHeartbeatTranscriptArtifacts } from "../../../auto-reply/heartbeat-filter.js";
6+
import { resolveStorePath } from "../../../config/sessions/paths.js";
7+
import {
8+
listSessionEntries,
9+
updateSessionEntry,
10+
} from "../../../config/sessions/session-accessor.js";
11+
import { OPENCLAW_EMBEDDED_CONTEXT_ENGINE_HOST } from "../../../context-engine/host-compat.js";
12+
import type { AssembleResult } from "../../../context-engine/types.js";
13+
import { resolveHeartbeatSummaryForAgent } from "../../../infra/heartbeat-summary.js";
14+
import type { createPreparedEmbeddedAgentSettingsManager } from "../../agent-project-settings.js";
15+
import type { createCacheTrace } from "../../cache-trace.js";
16+
import { DEFAULT_CONTEXT_TOKENS } from "../../defaults.js";
17+
import type { AgentMessage } from "../../runtime/index.js";
18+
import type { AgentSession, SessionManager } from "../../sessions/index.js";
19+
import { buildActiveSubagentSystemPromptAddition } from "../../subagent-active-context.js";
20+
import type { TranscriptPolicy } from "../../transcript-policy.js";
21+
import { getHistoryLimitFromSessionKey, limitHistoryTurns } from "../history.js";
22+
import { log } from "../logger.js";
23+
import { sanitizeSessionHistory, validateReplayTurns } from "../replay-history.js";
24+
import type { resolveOrphanRepairPlan } from "./attempt-orphan-repair.js";
25+
import {
26+
loadAttemptSessionEntryAfterQuotaMaintenance,
27+
repairAttemptToolUseResultPairing,
28+
} from "./attempt-transcript-helpers.js";
29+
import {
30+
assembleAttemptContextEngine,
31+
type AttemptContextEngine,
32+
} from "./attempt.context-engine-helpers.js";
33+
import { prependSystemPromptAddition } from "./attempt.prompt-helpers.js";
34+
import { estimateRenderedLlmBoundaryTokenPressure } from "./preemptive-compaction.js";
35+
import type { EmbeddedRunAttemptParams } from "./types.js";
36+
37+
type CacheTrace = ReturnType<typeof createCacheTrace>;
38+
type OrphanRepairPlan = ReturnType<typeof resolveOrphanRepairPlan>;
39+
type SettingsManager = Pick<
40+
ReturnType<typeof createPreparedEmbeddedAgentSettingsManager>,
41+
"getCompactionReserveTokens"
42+
>;
43+
44+
type PreparedEmbeddedAttemptHistory = {
45+
contextEnginePromptAuthority: NonNullable<AssembleResult["promptAuthority"]>;
46+
contextEngineAssemblySucceeded: boolean;
47+
unwindowedContextEngineMessagesForPrecheck?: AgentMessage[];
48+
};
49+
50+
export async function prepareEmbeddedAttemptHistory(input: {
51+
attempt: EmbeddedRunAttemptParams;
52+
activeSession: AgentSession;
53+
sessionManager: SessionManager;
54+
activeContextEngine?: AttemptContextEngine;
55+
cacheTrace: CacheTrace;
56+
capabilityToolNames: ReadonlySet<string>;
57+
effectiveWorkspace: string;
58+
isOpenAIResponsesApi: boolean;
59+
isRawModelRun: boolean;
60+
orphanRepair?: OrphanRepairPlan;
61+
replayAllowedToolNames: Set<string>;
62+
sessionAgentId: string;
63+
settingsManager: SettingsManager;
64+
systemPromptText: string;
65+
transcriptPolicy: TranscriptPolicy;
66+
setActiveSessionSystemPrompt: (systemPrompt: string) => void;
67+
}): Promise<PreparedEmbeddedAttemptHistory> {
68+
const { activeSession, attempt } = input;
69+
let systemPromptText = input.systemPromptText;
70+
const setSystemPrompt = (nextSystemPrompt: string) => {
71+
systemPromptText = nextSystemPrompt;
72+
input.setActiveSessionSystemPrompt(nextSystemPrompt);
73+
};
74+
75+
if (input.isRawModelRun) {
76+
activeSession.agent.reset();
77+
setSystemPrompt("");
78+
input.cacheTrace?.recordStage("session:raw-model-run", {
79+
messages: activeSession.messages,
80+
system: systemPromptText,
81+
});
82+
} else {
83+
const prior = await sanitizeSessionHistory({
84+
messages: activeSession.messages,
85+
modelApi: attempt.model.api,
86+
modelId: attempt.modelId,
87+
provider: attempt.provider,
88+
allowedToolNames: input.replayAllowedToolNames,
89+
config: attempt.config,
90+
workspaceDir: input.effectiveWorkspace,
91+
env: process.env,
92+
model: attempt.model,
93+
sessionManager: input.sessionManager,
94+
sessionId: attempt.sessionId,
95+
policy: input.transcriptPolicy,
96+
});
97+
input.cacheTrace?.recordStage("session:sanitized", { messages: prior });
98+
const validated = await validateReplayTurns({
99+
messages: prior,
100+
modelApi: attempt.model.api,
101+
modelId: attempt.modelId,
102+
provider: attempt.provider,
103+
config: attempt.config,
104+
workspaceDir: input.effectiveWorkspace,
105+
env: process.env,
106+
model: attempt.model,
107+
sessionId: attempt.sessionId,
108+
policy: input.transcriptPolicy,
109+
});
110+
111+
if (attempt.sessionKey) {
112+
const storePath = resolveStorePath(attempt.config?.session?.store, {
113+
agentId: input.sessionAgentId,
114+
});
115+
const sessionEntry = await loadAttemptSessionEntryAfterQuotaMaintenance({
116+
storePath,
117+
sessionKey: attempt.sessionKey,
118+
});
119+
const suspension = sessionEntry?.quotaSuspension;
120+
if (sessionEntry && suspension?.state === "resuming") {
121+
const subagents = listSessionEntries({ storePath, clone: false })
122+
.map(({ entry }) => entry)
123+
.filter((entry) => entry.spawnedBy === sessionEntry.sessionId)
124+
.map((entry) => ({
125+
sessionId: entry.sessionId,
126+
role: entry.subagentRole,
127+
lastStatus: entry.status,
128+
}));
129+
validated.push(
130+
buildHierarchyReinforcementMessage({
131+
summary: suspension.summary ?? "No recovery briefing was captured.",
132+
activeSubagents: subagents,
133+
}),
134+
);
135+
await updateSessionEntry(
136+
{ storePath, sessionKey: attempt.sessionKey },
137+
async (entry) => {
138+
if (entry.quotaSuspension?.state !== "resuming") {
139+
return null;
140+
}
141+
return {
142+
quotaSuspension: { ...entry.quotaSuspension, state: "active" },
143+
};
144+
},
145+
{ skipMaintenance: true, takeCacheOwnership: true },
146+
);
147+
}
148+
}
149+
150+
if (attempt.sessionKey && attempt.config) {
151+
// Capability guidance must include deferred OpenClaw tools without
152+
// interpreting arbitrary client tool names as native capabilities.
153+
const activeSubagentPromptAddition = buildActiveSubagentSystemPromptAddition({
154+
cfg: attempt.config,
155+
controllerSessionKey: attempt.sessionKey,
156+
hasSessionsYield: input.capabilityToolNames.has("sessions_yield"),
157+
});
158+
if (activeSubagentPromptAddition) {
159+
setSystemPrompt(
160+
prependSystemPromptAddition({
161+
systemPrompt: systemPromptText,
162+
systemPromptAddition: activeSubagentPromptAddition,
163+
}),
164+
);
165+
}
166+
}
167+
168+
const heartbeatSummary =
169+
attempt.config && input.sessionAgentId
170+
? resolveHeartbeatSummaryForAgent(attempt.config, input.sessionAgentId)
171+
: undefined;
172+
const heartbeatFiltered = filterHeartbeatTranscriptArtifacts(
173+
validated,
174+
heartbeatSummary?.ackMaxChars,
175+
heartbeatSummary?.prompt,
176+
);
177+
const truncated = limitHistoryTurns(
178+
heartbeatFiltered,
179+
getHistoryLimitFromSessionKey(attempt.sessionKey, attempt.config),
180+
);
181+
// Truncation can orphan tool_result blocks by removing the assistant message
182+
// that contained the matching tool_use, so repair the pairs once more.
183+
const limited = input.transcriptPolicy.repairToolUseResultPairing
184+
? repairAttemptToolUseResultPairing(truncated, input.isOpenAIResponsesApi)
185+
: truncated;
186+
input.cacheTrace?.recordStage("session:limited", { messages: limited });
187+
if (limited.length > 0 || prior.length > 0) {
188+
activeSession.agent.state.messages = limited;
189+
}
190+
}
191+
192+
let contextEnginePromptAuthority: NonNullable<AssembleResult["promptAuthority"]> = "assembled";
193+
let contextEngineAssemblySucceeded = false;
194+
let unwindowedContextEngineMessagesForPrecheck: AgentMessage[] | undefined;
195+
if (input.activeContextEngine) {
196+
try {
197+
// Assemble may window the input in place. Preserve the original history for
198+
// the overflow precheck when the engine says preassembly can still overflow.
199+
const preassemblyMessages = activeSession.messages.slice();
200+
const reserveTokens = Math.max(
201+
0,
202+
Math.floor(input.settingsManager.getCompactionReserveTokens()),
203+
);
204+
const contextTokenBudget = Math.max(
205+
1,
206+
Math.floor(
207+
attempt.contextTokenBudget ??
208+
attempt.model.contextWindow ??
209+
attempt.model.maxTokens ??
210+
DEFAULT_CONTEXT_TOKENS,
211+
),
212+
);
213+
const promptBudget = Math.max(1, contextTokenBudget - reserveTokens);
214+
const prompt = input.orphanRepair?.contextEnginePrompt ?? attempt.prompt ?? "";
215+
const renderedPromptTokens = estimateRenderedLlmBoundaryTokenPressure({
216+
systemPrompt: systemPromptText,
217+
prompt,
218+
});
219+
const messageBudget = Math.max(1, promptBudget - renderedPromptTokens);
220+
const assembled = await assembleAttemptContextEngine({
221+
contextEngine: input.activeContextEngine,
222+
sessionId: attempt.sessionId,
223+
sessionKey: attempt.sessionKey,
224+
messages: activeSession.messages,
225+
tokenBudget: messageBudget,
226+
availableTools: new Set(input.capabilityToolNames),
227+
citationsMode: attempt.config?.memory?.citations,
228+
modelId: attempt.modelId,
229+
maxOutputTokens: reserveTokens,
230+
contextEngineHostSupport: OPENCLAW_EMBEDDED_CONTEXT_ENGINE_HOST,
231+
providerId: attempt.provider,
232+
requestedModelId: attempt.requestedModelId,
233+
fallbackReason: attempt.fallbackReason,
234+
degradedReason: attempt.degradedReason,
235+
...(attempt.prompt !== undefined ? { prompt } : {}),
236+
});
237+
if (!assembled) {
238+
throw new Error("context engine assemble returned no result");
239+
}
240+
const assembledMessages = input.transcriptPolicy.repairToolUseResultPairing
241+
? repairAttemptToolUseResultPairing(assembled.messages, input.isOpenAIResponsesApi)
242+
: assembled.messages;
243+
if (assembledMessages !== activeSession.messages) {
244+
activeSession.agent.state.messages = assembledMessages;
245+
}
246+
contextEnginePromptAuthority = assembled.promptAuthority ?? "assembled";
247+
contextEngineAssemblySucceeded = true;
248+
if (contextEnginePromptAuthority === "preassembly_may_overflow") {
249+
unwindowedContextEngineMessagesForPrecheck = preassemblyMessages;
250+
}
251+
if (assembled.systemPromptAddition) {
252+
setSystemPrompt(
253+
prependSystemPromptAddition({
254+
systemPrompt: systemPromptText,
255+
systemPromptAddition: assembled.systemPromptAddition,
256+
}),
257+
);
258+
log.debug(
259+
`context engine: prepended system prompt addition (${assembled.systemPromptAddition.length} chars)`,
260+
);
261+
}
262+
} catch (error) {
263+
log.warn(`context engine assemble failed, using pipeline messages: ${String(error)}`);
264+
}
265+
}
266+
267+
return {
268+
contextEnginePromptAuthority,
269+
contextEngineAssemblySucceeded,
270+
...(unwindowedContextEngineMessagesForPrecheck
271+
? { unwindowedContextEngineMessagesForPrecheck }
272+
: {}),
273+
};
274+
}

0 commit comments

Comments
 (0)