-
-
Notifications
You must be signed in to change notification settings - Fork 80.7k
Expand file tree
/
Copy pathagent-consult-runtime.ts
More file actions
324 lines (305 loc) · 11.5 KB
/
Copy pathagent-consult-runtime.ts
File metadata and controls
324 lines (305 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
// Agent consult runtime starts agent consultation flows from talk sessions.
import { randomUUID } from "node:crypto";
import type { RunEmbeddedAgentParams } from "../agents/embedded-agent-runner/run/params.js";
import { forkSessionEntryFromParent } from "../auto-reply/reply/session-fork.js";
import { parseSessionThreadInfoFast } from "../config/sessions/thread-info.js";
import type { SessionEntry } from "../config/sessions/types.js";
import type { OpenClawConfig } from "../config/types.openclaw.js";
import type { RuntimeLogger, PluginRuntimeCore } from "../plugins/runtime/types-core.js";
import { parseAgentSessionKey } from "../routing/session-key.js";
import {
deliveryContextFromSession,
normalizeDeliveryContext,
type DeliveryContext,
} from "../utils/delivery-context.shared.js";
import {
buildRealtimeVoiceAgentConsultPrompt,
collectRealtimeVoiceAgentConsultVisibleText,
type RealtimeVoiceAgentConsultTranscriptEntry,
} from "./agent-consult-tool.js";
/**
* Agent runtime surface used by realtime voice consults.
*/
export type RealtimeVoiceAgentConsultRuntime = PluginRuntimeCore["agent"];
/**
* Speakable text returned to the realtime voice bridge after an agent consult.
*/
export type RealtimeVoiceAgentConsultResult = { text: string };
/**
* Controls whether voice consults run in a fresh session or fork context from the requester.
*/
export type RealtimeVoiceAgentConsultContextMode = "isolated" | "fork";
export {
resolveRealtimeVoiceAgentConsultTools,
resolveRealtimeVoiceAgentConsultToolsAllow,
} from "./agent-consult-tool.js";
type RealtimeVoiceAgentConsultDeps = {
randomUUID: typeof randomUUID;
forkSessionEntryFromParent: typeof forkSessionEntryFromParent;
};
const defaultRealtimeVoiceAgentConsultDeps: RealtimeVoiceAgentConsultDeps = {
randomUUID,
forkSessionEntryFromParent,
};
let realtimeVoiceAgentConsultDeps = defaultRealtimeVoiceAgentConsultDeps;
/**
* Overrides consult runtime dependencies for deterministic tests.
*/
export function setRealtimeVoiceAgentConsultDepsForTest(
deps: Partial<RealtimeVoiceAgentConsultDeps> | null,
): void {
realtimeVoiceAgentConsultDeps = deps
? { ...defaultRealtimeVoiceAgentConsultDeps, ...deps }
: defaultRealtimeVoiceAgentConsultDeps;
}
function resolveRealtimeVoiceAgentSandboxSessionKey(agentId: string, sessionKey: string): string {
// Embedded agent runs expect agent-scoped sandbox keys; keep already-scoped keys intact so
// callers can deliberately share a sandbox with an existing agent session.
const trimmed = sessionKey.trim();
if (trimmed.toLowerCase().startsWith("agent:")) {
return trimmed;
}
return `agent:${agentId}:${trimmed}`;
}
function hasRoutableDeliveryContext(
context: DeliveryContext | undefined,
): context is DeliveryContext & { channel: string; to: string } {
return Boolean(context?.channel && context?.to);
}
function resolveDeliverySessionFields(context?: DeliveryContext): Partial<SessionEntry> {
const normalized = normalizeDeliveryContext(context);
if (!normalized?.channel || !normalized.to) {
return {};
}
return {
deliveryContext: normalized,
lastChannel: normalized.channel,
lastTo: normalized.to,
lastAccountId: normalized.accountId,
lastThreadId: normalized.threadId,
};
}
function resolveRealtimeVoiceAgentDeliveryContext(params: {
agentRuntime: RealtimeVoiceAgentConsultRuntime;
storePath: string;
sessionKey: string;
spawnedBy?: string | null;
}): DeliveryContext | undefined {
const requesterSessionKey = params.spawnedBy?.trim();
try {
// Prefer the live requester session, then its base thread, then the voice consult session.
// This preserves channel/account/thread routing when a voice bridge delegates back to agent.
const candidates: string[] = [];
if (requesterSessionKey) {
const { baseSessionKey } = parseSessionThreadInfoFast(requesterSessionKey);
candidates.push(
...[requesterSessionKey, baseSessionKey].filter((key): key is string => Boolean(key)),
);
}
candidates.push(params.sessionKey);
for (const key of candidates) {
const entry = params.agentRuntime.session.getSessionEntry({
storePath: params.storePath,
sessionKey: key,
});
const context = deliveryContextFromSession(entry);
if (hasRoutableDeliveryContext(context)) {
return context;
}
}
} catch {
// Best-effort routing enrichment only; consults should still work without it.
}
return undefined;
}
async function resolveRealtimeVoiceAgentConsultSessionEntry(params: {
agentId: string;
cfg: OpenClawConfig;
sessionKey: string;
spawnedBy?: string | null;
contextMode?: RealtimeVoiceAgentConsultContextMode;
deliveryContext?: DeliveryContext;
storePath: string;
agentRuntime: RealtimeVoiceAgentConsultRuntime;
logger: Pick<RuntimeLogger, "warn">;
}): Promise<SessionEntry> {
const now = Date.now();
const deliveryFields = resolveDeliverySessionFields(params.deliveryContext);
const requesterSessionKey = params.spawnedBy?.trim();
const requesterAgentId = parseAgentSessionKey(requesterSessionKey)?.agentId;
const shouldFork =
params.contextMode === "fork" &&
requesterSessionKey &&
(!requesterAgentId || requesterAgentId === params.agentId);
let forkDecisionWarning: string | undefined;
let patched: SessionEntry | null = null;
if (shouldFork) {
const forked = await realtimeVoiceAgentConsultDeps.forkSessionEntryFromParent({
storePath: params.storePath,
parentSessionKey: requesterSessionKey,
agentId: params.agentId,
config: params.cfg,
sessionKey: params.sessionKey,
fallbackEntry: {
sessionId: "",
updatedAt: now,
},
skipForkWhen: (entry) => Boolean(entry.sessionId?.trim()),
skipPatch: () => ({ ...deliveryFields, updatedAt: now }),
patch: () => ({
...deliveryFields,
spawnedBy: requesterSessionKey,
updatedAt: now,
}),
});
if (forked.status === "forked" || forked.status === "skipped") {
if (forked.status === "skipped" && forked.decision?.status === "skip") {
forkDecisionWarning = forked.decision.message;
}
if (forked.sessionEntry.sessionId?.trim()) {
patched = forked.sessionEntry;
}
}
}
patched ??= await params.agentRuntime.session.patchSessionEntry({
storePath: params.storePath,
sessionKey: params.sessionKey,
fallbackEntry: {
sessionId: "",
updatedAt: now,
},
update: async (entry) => {
if (entry.sessionId?.trim()) {
return { ...deliveryFields, updatedAt: now };
}
return {
...deliveryFields,
sessionId: realtimeVoiceAgentConsultDeps.randomUUID(),
...(requesterSessionKey ? { spawnedBy: requesterSessionKey } : {}),
updatedAt: now,
};
},
});
if (forkDecisionWarning) {
params.logger.warn(`[talk] ${forkDecisionWarning}`);
}
if (patched?.sessionId?.trim()) {
return patched;
}
throw new Error("realtime voice agent consult session could not be initialized");
}
/**
* Runs an embedded agent consult and returns concise speakable text for realtime voice playback.
*/
export async function consultRealtimeVoiceAgent(params: {
cfg: OpenClawConfig;
agentRuntime: RealtimeVoiceAgentConsultRuntime;
logger: Pick<RuntimeLogger, "warn">;
sessionKey: string;
messageProvider: string;
lane: string;
runIdPrefix: string;
args: unknown;
transcript: RealtimeVoiceAgentConsultTranscriptEntry[];
surface: string;
userLabel: string;
assistantLabel?: string;
questionSourceLabel?: string;
agentId?: string;
spawnedBy?: string | null;
contextMode?: RealtimeVoiceAgentConsultContextMode;
provider?: RunEmbeddedAgentParams["provider"];
model?: RunEmbeddedAgentParams["model"];
thinkLevel?: RunEmbeddedAgentParams["thinkLevel"];
fastMode?: RunEmbeddedAgentParams["fastMode"];
timeoutMs?: number;
toolsAllow?: string[];
extraSystemPrompt?: string;
fallbackText?: string;
}): Promise<RealtimeVoiceAgentConsultResult> {
const agentId = params.agentId ?? "main";
const agentDir = params.agentRuntime.resolveAgentDir(params.cfg, agentId);
const workspaceDir = params.agentRuntime.resolveAgentWorkspaceDir(params.cfg, agentId);
await params.agentRuntime.ensureAgentWorkspace({ dir: workspaceDir });
// The consult session stores normal session metadata so subsequent voice turns can keep
// routing and, in fork mode, recover useful conversation context from the requester.
const storePath = params.agentRuntime.session.resolveStorePath(params.cfg.session?.store, {
agentId,
});
const resolvedDeliveryContext = resolveRealtimeVoiceAgentDeliveryContext({
agentRuntime: params.agentRuntime,
storePath,
sessionKey: params.sessionKey,
spawnedBy: params.spawnedBy,
});
const sessionEntry = await resolveRealtimeVoiceAgentConsultSessionEntry({
agentId,
cfg: params.cfg,
sessionKey: params.sessionKey,
spawnedBy: params.spawnedBy,
contextMode: params.contextMode,
deliveryContext: resolvedDeliveryContext,
storePath,
agentRuntime: params.agentRuntime,
logger: params.logger,
});
const consultDeliveryContext =
resolvedDeliveryContext ?? deliveryContextFromSession(sessionEntry);
const sessionId = sessionEntry.sessionId;
// Voice consults suppress verbose/reasoning output because the bridge needs a short,
// speakable answer, not agent-run diagnostics or hidden reasoning artifacts.
const result = await params.agentRuntime.runEmbeddedAgent({
sessionId,
sessionKey: params.sessionKey,
sessionTarget: {
agentId,
sessionId,
sessionKey: params.sessionKey,
storePath,
},
sandboxSessionKey: resolveRealtimeVoiceAgentSandboxSessionKey(agentId, params.sessionKey),
agentId,
spawnedBy: params.spawnedBy,
messageProvider: consultDeliveryContext?.channel ?? params.messageProvider,
agentAccountId: consultDeliveryContext?.accountId,
messageTo: consultDeliveryContext?.to,
messageThreadId: consultDeliveryContext?.threadId,
currentChannelId: consultDeliveryContext?.to,
currentThreadTs:
consultDeliveryContext?.threadId != null
? String(consultDeliveryContext.threadId)
: undefined,
workspaceDir,
config: params.cfg,
prompt: buildRealtimeVoiceAgentConsultPrompt({
args: params.args,
transcript: params.transcript,
surface: params.surface,
userLabel: params.userLabel,
assistantLabel: params.assistantLabel,
questionSourceLabel: params.questionSourceLabel,
}),
provider: params.provider,
model: params.model,
thinkLevel: params.thinkLevel ?? "high",
fastMode: params.fastMode,
verboseLevel: "off",
reasoningLevel: "off",
toolResultFormat: "plain",
toolsAllow: params.toolsAllow,
timeoutMs: params.timeoutMs ?? params.agentRuntime.resolveAgentTimeoutMs({ cfg: params.cfg }),
runId: `${params.runIdPrefix}:${Date.now()}`,
lane: params.lane,
extraSystemPrompt:
params.extraSystemPrompt ??
"You are the configured OpenClaw agent receiving delegated requests from a live voice bridge. Act on behalf of the user, use available tools when appropriate, and return a brief speakable result.",
agentDir,
});
const text = collectRealtimeVoiceAgentConsultVisibleText(result.payloads ?? []);
if (!text) {
const reason = result.meta?.aborted ? "agent run aborted" : "agent returned no speakable text";
params.logger.warn(`[talk] agent consult produced no answer: ${reason}`);
return { text: params.fallbackText ?? "I need a moment to verify that before answering." };
}
return { text };
}