@martian-engineering/lossless-claw 0.2.8 → 0.4.0
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/README.md +151 -4
- package/docs/configuration.md +69 -0
- package/index.ts +2 -1136
- package/openclaw.plugin.json +43 -2
- package/package.json +11 -4
- package/src/assembler.ts +128 -13
- package/src/compaction.ts +60 -8
- package/src/db/config.ts +62 -0
- package/src/db/connection.ts +95 -46
- package/src/db/migration.ts +7 -0
- package/src/engine.ts +696 -198
- package/src/expansion-auth.ts +14 -0
- package/src/plugin/index.ts +1375 -0
- package/src/retrieval.ts +5 -1
- package/src/session-patterns.ts +23 -0
- package/src/startup-banner-log.ts +48 -0
- package/src/store/conversation-store.ts +87 -9
- package/src/store/summary-store.ts +17 -2
- package/src/summarize.ts +104 -20
- package/src/tools/lcm-conversation-scope.ts +55 -4
- package/src/tools/lcm-describe-tool.ts +19 -7
- package/src/tools/lcm-expand-query-tool.ts +4 -0
- package/src/tools/lcm-expand-tool.delegation.ts +27 -3
- package/src/tools/lcm-grep-tool.ts +20 -4
- package/src/types.ts +2 -0
package/index.ts
CHANGED
|
@@ -1,1136 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
*
|
|
4
|
-
* DAG-based conversation summarization with incremental compaction,
|
|
5
|
-
* full-text search, and sub-agent expansion.
|
|
6
|
-
*/
|
|
7
|
-
import { readFileSync, writeFileSync } from "node:fs";
|
|
8
|
-
import { join } from "node:path";
|
|
9
|
-
import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
|
|
10
|
-
import { resolveLcmConfig } from "./src/db/config.js";
|
|
11
|
-
import { LcmContextEngine } from "./src/engine.js";
|
|
12
|
-
import { createLcmDescribeTool } from "./src/tools/lcm-describe-tool.js";
|
|
13
|
-
import { createLcmExpandQueryTool } from "./src/tools/lcm-expand-query-tool.js";
|
|
14
|
-
import { createLcmExpandTool } from "./src/tools/lcm-expand-tool.js";
|
|
15
|
-
import { createLcmGrepTool } from "./src/tools/lcm-grep-tool.js";
|
|
16
|
-
import type { LcmDependencies } from "./src/types.js";
|
|
17
|
-
|
|
18
|
-
/** Parse `agent:<agentId>:<suffix...>` session keys. */
|
|
19
|
-
function parseAgentSessionKey(sessionKey: string): { agentId: string; suffix: string } | null {
|
|
20
|
-
const value = sessionKey.trim();
|
|
21
|
-
if (!value.startsWith("agent:")) {
|
|
22
|
-
return null;
|
|
23
|
-
}
|
|
24
|
-
const parts = value.split(":");
|
|
25
|
-
if (parts.length < 3) {
|
|
26
|
-
return null;
|
|
27
|
-
}
|
|
28
|
-
const agentId = parts[1]?.trim();
|
|
29
|
-
const suffix = parts.slice(2).join(":").trim();
|
|
30
|
-
if (!agentId || !suffix) {
|
|
31
|
-
return null;
|
|
32
|
-
}
|
|
33
|
-
return { agentId, suffix };
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
/** Return a stable normalized agent id. */
|
|
37
|
-
function normalizeAgentId(agentId: string | undefined): string {
|
|
38
|
-
const normalized = (agentId ?? "").trim();
|
|
39
|
-
return normalized.length > 0 ? normalized : "main";
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
type PluginEnvSnapshot = {
|
|
43
|
-
lcmSummaryModel: string;
|
|
44
|
-
lcmSummaryProvider: string;
|
|
45
|
-
pluginSummaryModel: string;
|
|
46
|
-
pluginSummaryProvider: string;
|
|
47
|
-
openclawProvider: string;
|
|
48
|
-
openclawDefaultModel: string;
|
|
49
|
-
agentDir: string;
|
|
50
|
-
home: string;
|
|
51
|
-
};
|
|
52
|
-
|
|
53
|
-
type ReadEnvFn = (key: string) => string | undefined;
|
|
54
|
-
|
|
55
|
-
type CompleteSimpleOptions = {
|
|
56
|
-
apiKey?: string;
|
|
57
|
-
maxTokens: number;
|
|
58
|
-
temperature?: number;
|
|
59
|
-
reasoning?: string;
|
|
60
|
-
};
|
|
61
|
-
|
|
62
|
-
type RuntimeModelAuthResult = {
|
|
63
|
-
apiKey?: string;
|
|
64
|
-
};
|
|
65
|
-
|
|
66
|
-
type RuntimeModelAuthModel = {
|
|
67
|
-
id: string;
|
|
68
|
-
provider: string;
|
|
69
|
-
api: string;
|
|
70
|
-
name?: string;
|
|
71
|
-
reasoning?: boolean;
|
|
72
|
-
input?: string[];
|
|
73
|
-
cost?: {
|
|
74
|
-
input: number;
|
|
75
|
-
output: number;
|
|
76
|
-
cacheRead: number;
|
|
77
|
-
cacheWrite: number;
|
|
78
|
-
};
|
|
79
|
-
contextWindow?: number;
|
|
80
|
-
maxTokens?: number;
|
|
81
|
-
};
|
|
82
|
-
|
|
83
|
-
type RuntimeModelAuth = {
|
|
84
|
-
getApiKeyForModel: (params: {
|
|
85
|
-
model: RuntimeModelAuthModel;
|
|
86
|
-
cfg?: OpenClawPluginApi["config"];
|
|
87
|
-
profileId?: string;
|
|
88
|
-
preferredProfile?: string;
|
|
89
|
-
}) => Promise<RuntimeModelAuthResult | undefined>;
|
|
90
|
-
resolveApiKeyForProvider: (params: {
|
|
91
|
-
provider: string;
|
|
92
|
-
cfg?: OpenClawPluginApi["config"];
|
|
93
|
-
profileId?: string;
|
|
94
|
-
preferredProfile?: string;
|
|
95
|
-
}) => Promise<RuntimeModelAuthResult | undefined>;
|
|
96
|
-
};
|
|
97
|
-
|
|
98
|
-
const MODEL_AUTH_PR_URL = "https://github.com/openclaw/openclaw/pull/41090";
|
|
99
|
-
const MODEL_AUTH_MERGE_COMMIT = "4790e40";
|
|
100
|
-
const MODEL_AUTH_REQUIRED_RELEASE = "the first OpenClaw release after 2026.3.8";
|
|
101
|
-
|
|
102
|
-
/** Capture plugin env values once during initialization. */
|
|
103
|
-
function snapshotPluginEnv(env: NodeJS.ProcessEnv = process.env): PluginEnvSnapshot {
|
|
104
|
-
return {
|
|
105
|
-
lcmSummaryModel: env.LCM_SUMMARY_MODEL?.trim() ?? "",
|
|
106
|
-
lcmSummaryProvider: env.LCM_SUMMARY_PROVIDER?.trim() ?? "",
|
|
107
|
-
pluginSummaryModel: "",
|
|
108
|
-
pluginSummaryProvider: "",
|
|
109
|
-
openclawProvider: env.OPENCLAW_PROVIDER?.trim() ?? "",
|
|
110
|
-
openclawDefaultModel: "",
|
|
111
|
-
agentDir: env.OPENCLAW_AGENT_DIR?.trim() || env.PI_CODING_AGENT_DIR?.trim() || "",
|
|
112
|
-
home: env.HOME?.trim() ?? "",
|
|
113
|
-
};
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
/** Read OpenClaw's configured default model from the validated runtime config. */
|
|
117
|
-
function readDefaultModelFromConfig(config: unknown): string {
|
|
118
|
-
if (!config || typeof config !== "object") {
|
|
119
|
-
return "";
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
const model = (config as { agents?: { defaults?: { model?: unknown } } }).agents?.defaults?.model;
|
|
123
|
-
if (typeof model === "string") {
|
|
124
|
-
return model.trim();
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
const primary = (model as { primary?: unknown } | undefined)?.primary;
|
|
128
|
-
return typeof primary === "string" ? primary.trim() : "";
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
/** Resolve common provider API keys from environment. */
|
|
132
|
-
function resolveApiKey(provider: string, readEnv: ReadEnvFn): string | undefined {
|
|
133
|
-
const keyMap: Record<string, string[]> = {
|
|
134
|
-
openai: ["OPENAI_API_KEY"],
|
|
135
|
-
anthropic: ["ANTHROPIC_API_KEY"],
|
|
136
|
-
google: ["GOOGLE_API_KEY", "GEMINI_API_KEY"],
|
|
137
|
-
groq: ["GROQ_API_KEY"],
|
|
138
|
-
xai: ["XAI_API_KEY"],
|
|
139
|
-
mistral: ["MISTRAL_API_KEY"],
|
|
140
|
-
together: ["TOGETHER_API_KEY"],
|
|
141
|
-
openrouter: ["OPENROUTER_API_KEY"],
|
|
142
|
-
"github-copilot": ["GITHUB_COPILOT_API_KEY", "GITHUB_TOKEN"],
|
|
143
|
-
};
|
|
144
|
-
|
|
145
|
-
const providerKey = provider.trim().toLowerCase();
|
|
146
|
-
const keys = keyMap[providerKey] ?? [];
|
|
147
|
-
const normalizedProviderEnv = `${providerKey.replace(/[^a-z0-9]/g, "_").toUpperCase()}_API_KEY`;
|
|
148
|
-
keys.push(normalizedProviderEnv);
|
|
149
|
-
|
|
150
|
-
for (const key of keys) {
|
|
151
|
-
const value = readEnv(key)?.trim();
|
|
152
|
-
if (value) {
|
|
153
|
-
return value;
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
return undefined;
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
type AuthProfileCredential =
|
|
160
|
-
| { type: "api_key"; provider: string; key?: string; email?: string }
|
|
161
|
-
| { type: "token"; provider: string; token?: string; expires?: number; email?: string }
|
|
162
|
-
| ({
|
|
163
|
-
type: "oauth";
|
|
164
|
-
provider: string;
|
|
165
|
-
access?: string;
|
|
166
|
-
refresh?: string;
|
|
167
|
-
expires?: number;
|
|
168
|
-
email?: string;
|
|
169
|
-
} & Record<string, unknown>);
|
|
170
|
-
|
|
171
|
-
type AuthProfileStore = {
|
|
172
|
-
profiles: Record<string, AuthProfileCredential>;
|
|
173
|
-
order?: Record<string, string[]>;
|
|
174
|
-
};
|
|
175
|
-
|
|
176
|
-
type PiAiOAuthCredentials = {
|
|
177
|
-
refresh: string;
|
|
178
|
-
access: string;
|
|
179
|
-
expires: number;
|
|
180
|
-
[key: string]: unknown;
|
|
181
|
-
};
|
|
182
|
-
|
|
183
|
-
type PiAiModule = {
|
|
184
|
-
completeSimple?: (
|
|
185
|
-
model: {
|
|
186
|
-
id: string;
|
|
187
|
-
provider: string;
|
|
188
|
-
api: string;
|
|
189
|
-
name?: string;
|
|
190
|
-
reasoning?: boolean;
|
|
191
|
-
input?: string[];
|
|
192
|
-
cost?: {
|
|
193
|
-
input: number;
|
|
194
|
-
output: number;
|
|
195
|
-
cacheRead: number;
|
|
196
|
-
cacheWrite: number;
|
|
197
|
-
};
|
|
198
|
-
contextWindow?: number;
|
|
199
|
-
maxTokens?: number;
|
|
200
|
-
},
|
|
201
|
-
request: {
|
|
202
|
-
systemPrompt?: string;
|
|
203
|
-
messages: Array<{ role: string; content: unknown; timestamp?: number }>;
|
|
204
|
-
},
|
|
205
|
-
options: {
|
|
206
|
-
apiKey?: string;
|
|
207
|
-
maxTokens: number;
|
|
208
|
-
temperature?: number;
|
|
209
|
-
reasoning?: string;
|
|
210
|
-
},
|
|
211
|
-
) => Promise<Record<string, unknown> & { content?: Array<{ type: string; text?: string }> }>;
|
|
212
|
-
getModel?: (provider: string, modelId: string) => unknown;
|
|
213
|
-
getModels?: (provider: string) => unknown[];
|
|
214
|
-
getEnvApiKey?: (provider: string) => string | undefined;
|
|
215
|
-
getOAuthApiKey?: (
|
|
216
|
-
providerId: string,
|
|
217
|
-
credentials: Record<string, PiAiOAuthCredentials>,
|
|
218
|
-
) => Promise<{ apiKey: string; newCredentials: PiAiOAuthCredentials } | null>;
|
|
219
|
-
};
|
|
220
|
-
|
|
221
|
-
/** Narrow unknown values to plain objects. */
|
|
222
|
-
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
223
|
-
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
/** Normalize provider ids for case-insensitive matching. */
|
|
227
|
-
function normalizeProviderId(provider: string): string {
|
|
228
|
-
return provider.trim().toLowerCase();
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
/** Resolve known provider API defaults when model lookup misses. */
|
|
232
|
-
function inferApiFromProvider(provider: string): string {
|
|
233
|
-
const normalized = normalizeProviderId(provider);
|
|
234
|
-
const map: Record<string, string> = {
|
|
235
|
-
anthropic: "anthropic-messages",
|
|
236
|
-
openai: "openai-responses",
|
|
237
|
-
"openai-codex": "openai-codex-responses",
|
|
238
|
-
"github-copilot": "openai-codex-responses",
|
|
239
|
-
google: "google-generative-ai",
|
|
240
|
-
"google-gemini-cli": "google-gemini-cli",
|
|
241
|
-
"google-antigravity": "google-gemini-cli",
|
|
242
|
-
"google-vertex": "google-vertex",
|
|
243
|
-
"amazon-bedrock": "bedrock-converse-stream",
|
|
244
|
-
};
|
|
245
|
-
return map[normalized] ?? "openai-responses";
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
/** Codex Responses rejects `temperature`; omit it for that API family. */
|
|
249
|
-
export function shouldOmitTemperatureForApi(api: string | undefined): boolean {
|
|
250
|
-
return (api ?? "").trim().toLowerCase() === "openai-codex-responses";
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
/** Build provider-aware options for pi-ai completeSimple. */
|
|
254
|
-
export function buildCompleteSimpleOptions(params: {
|
|
255
|
-
api: string | undefined;
|
|
256
|
-
apiKey: string | undefined;
|
|
257
|
-
maxTokens: number;
|
|
258
|
-
temperature: number | undefined;
|
|
259
|
-
reasoning: string | undefined;
|
|
260
|
-
}): CompleteSimpleOptions {
|
|
261
|
-
const options: CompleteSimpleOptions = {
|
|
262
|
-
apiKey: params.apiKey,
|
|
263
|
-
maxTokens: params.maxTokens,
|
|
264
|
-
};
|
|
265
|
-
|
|
266
|
-
if (
|
|
267
|
-
typeof params.temperature === "number" &&
|
|
268
|
-
Number.isFinite(params.temperature) &&
|
|
269
|
-
!shouldOmitTemperatureForApi(params.api)
|
|
270
|
-
) {
|
|
271
|
-
options.temperature = params.temperature;
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
if (typeof params.reasoning === "string" && params.reasoning.trim()) {
|
|
275
|
-
options.reasoning = params.reasoning.trim();
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
return options;
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
/** Select provider-specific config values with case-insensitive provider keys. */
|
|
282
|
-
function findProviderConfigValue<T>(
|
|
283
|
-
map: Record<string, T> | undefined,
|
|
284
|
-
provider: string,
|
|
285
|
-
): T | undefined {
|
|
286
|
-
if (!map) {
|
|
287
|
-
return undefined;
|
|
288
|
-
}
|
|
289
|
-
if (map[provider] !== undefined) {
|
|
290
|
-
return map[provider];
|
|
291
|
-
}
|
|
292
|
-
const normalizedProvider = normalizeProviderId(provider);
|
|
293
|
-
for (const [key, value] of Object.entries(map)) {
|
|
294
|
-
if (normalizeProviderId(key) === normalizedProvider) {
|
|
295
|
-
return value;
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
return undefined;
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
/** Resolve provider API from runtime config if available. */
|
|
302
|
-
function resolveProviderApiFromRuntimeConfig(
|
|
303
|
-
runtimeConfig: unknown,
|
|
304
|
-
provider: string,
|
|
305
|
-
): string | undefined {
|
|
306
|
-
if (!isRecord(runtimeConfig)) {
|
|
307
|
-
return undefined;
|
|
308
|
-
}
|
|
309
|
-
const providers = (runtimeConfig as { models?: { providers?: Record<string, unknown> } }).models
|
|
310
|
-
?.providers;
|
|
311
|
-
if (!providers || !isRecord(providers)) {
|
|
312
|
-
return undefined;
|
|
313
|
-
}
|
|
314
|
-
const value = findProviderConfigValue(providers, provider);
|
|
315
|
-
if (!isRecord(value)) {
|
|
316
|
-
return undefined;
|
|
317
|
-
}
|
|
318
|
-
const api = value.api;
|
|
319
|
-
return typeof api === "string" && api.trim() ? api.trim() : undefined;
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
/** Resolve runtime.modelAuth from plugin runtime when available. */
|
|
323
|
-
function getRuntimeModelAuth(api: OpenClawPluginApi): RuntimeModelAuth | undefined {
|
|
324
|
-
const runtime = api.runtime as OpenClawPluginApi["runtime"] & {
|
|
325
|
-
modelAuth?: RuntimeModelAuth;
|
|
326
|
-
};
|
|
327
|
-
return runtime.modelAuth;
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
/** Build the minimal model shape required by runtime.modelAuth.getApiKeyForModel(). */
|
|
331
|
-
function buildModelAuthLookupModel(params: {
|
|
332
|
-
provider: string;
|
|
333
|
-
model: string;
|
|
334
|
-
api?: string;
|
|
335
|
-
}): RuntimeModelAuthModel {
|
|
336
|
-
return {
|
|
337
|
-
id: params.model,
|
|
338
|
-
name: params.model,
|
|
339
|
-
provider: params.provider,
|
|
340
|
-
api: params.api?.trim() || inferApiFromProvider(params.provider),
|
|
341
|
-
reasoning: false,
|
|
342
|
-
input: ["text"],
|
|
343
|
-
cost: {
|
|
344
|
-
input: 0,
|
|
345
|
-
output: 0,
|
|
346
|
-
cacheRead: 0,
|
|
347
|
-
cacheWrite: 0,
|
|
348
|
-
},
|
|
349
|
-
contextWindow: 200_000,
|
|
350
|
-
maxTokens: 8_000,
|
|
351
|
-
};
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
/** Normalize an auth result down to the API key that pi-ai expects. */
|
|
355
|
-
function resolveApiKeyFromAuthResult(auth: RuntimeModelAuthResult | undefined): string | undefined {
|
|
356
|
-
const apiKey = auth?.apiKey?.trim();
|
|
357
|
-
return apiKey ? apiKey : undefined;
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
function buildLegacyAuthFallbackWarning(): string {
|
|
361
|
-
return [
|
|
362
|
-
"[lcm] OpenClaw runtime.modelAuth is unavailable; using legacy auth-profiles fallback.",
|
|
363
|
-
`Stock lossless-claw 0.2.7 expects OpenClaw plugin runtime support from PR #41090 (${MODEL_AUTH_PR_URL}).`,
|
|
364
|
-
`OpenClaw 2026.3.8 and 2026.3.8-beta.1 do not include merge commit ${MODEL_AUTH_MERGE_COMMIT};`,
|
|
365
|
-
`${MODEL_AUTH_REQUIRED_RELEASE} is required for stock lossless-claw 0.2.7 without this fallback patch.`,
|
|
366
|
-
].join(" ");
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
/** Parse auth-profiles JSON into a minimal store shape. */
|
|
370
|
-
function parseAuthProfileStore(raw: string): AuthProfileStore | undefined {
|
|
371
|
-
try {
|
|
372
|
-
const parsed = JSON.parse(raw) as unknown;
|
|
373
|
-
if (!isRecord(parsed) || !isRecord(parsed.profiles)) {
|
|
374
|
-
return undefined;
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
const profiles: Record<string, AuthProfileCredential> = {};
|
|
378
|
-
for (const [profileId, value] of Object.entries(parsed.profiles)) {
|
|
379
|
-
if (!isRecord(value)) {
|
|
380
|
-
continue;
|
|
381
|
-
}
|
|
382
|
-
const type = value.type;
|
|
383
|
-
const provider = typeof value.provider === "string" ? value.provider.trim() : "";
|
|
384
|
-
if (!provider || (type !== "api_key" && type !== "token" && type !== "oauth")) {
|
|
385
|
-
continue;
|
|
386
|
-
}
|
|
387
|
-
profiles[profileId] = value as AuthProfileCredential;
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
const rawOrder = isRecord(parsed.order) ? parsed.order : undefined;
|
|
391
|
-
const order: Record<string, string[]> | undefined = rawOrder
|
|
392
|
-
? Object.entries(rawOrder).reduce<Record<string, string[]>>((acc, [provider, value]) => {
|
|
393
|
-
if (!Array.isArray(value)) {
|
|
394
|
-
return acc;
|
|
395
|
-
}
|
|
396
|
-
const ids = value
|
|
397
|
-
.map((entry) => (typeof entry === "string" ? entry.trim() : ""))
|
|
398
|
-
.filter(Boolean);
|
|
399
|
-
if (ids.length > 0) {
|
|
400
|
-
acc[provider] = ids;
|
|
401
|
-
}
|
|
402
|
-
return acc;
|
|
403
|
-
}, {})
|
|
404
|
-
: undefined;
|
|
405
|
-
|
|
406
|
-
return {
|
|
407
|
-
profiles,
|
|
408
|
-
...(order && Object.keys(order).length > 0 ? { order } : {}),
|
|
409
|
-
};
|
|
410
|
-
} catch {
|
|
411
|
-
return undefined;
|
|
412
|
-
}
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
/** Merge auth stores, letting later stores override earlier profiles/order. */
|
|
416
|
-
function mergeAuthProfileStores(stores: AuthProfileStore[]): AuthProfileStore | undefined {
|
|
417
|
-
if (stores.length === 0) {
|
|
418
|
-
return undefined;
|
|
419
|
-
}
|
|
420
|
-
const merged: AuthProfileStore = { profiles: {} };
|
|
421
|
-
for (const store of stores) {
|
|
422
|
-
merged.profiles = { ...merged.profiles, ...store.profiles };
|
|
423
|
-
if (store.order) {
|
|
424
|
-
merged.order = { ...(merged.order ?? {}), ...store.order };
|
|
425
|
-
}
|
|
426
|
-
}
|
|
427
|
-
return merged;
|
|
428
|
-
}
|
|
429
|
-
|
|
430
|
-
/** Determine candidate auth store paths ordered by precedence. */
|
|
431
|
-
function resolveAuthStorePaths(params: { agentDir?: string; envSnapshot: PluginEnvSnapshot }): string[] {
|
|
432
|
-
const paths: string[] = [];
|
|
433
|
-
const directAgentDir = params.agentDir?.trim();
|
|
434
|
-
if (directAgentDir) {
|
|
435
|
-
paths.push(join(directAgentDir, "auth-profiles.json"));
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
const envAgentDir = params.envSnapshot.agentDir;
|
|
439
|
-
if (envAgentDir) {
|
|
440
|
-
paths.push(join(envAgentDir, "auth-profiles.json"));
|
|
441
|
-
}
|
|
442
|
-
|
|
443
|
-
const home = params.envSnapshot.home;
|
|
444
|
-
if (home) {
|
|
445
|
-
paths.push(join(home, ".openclaw", "agents", "main", "agent", "auth-profiles.json"));
|
|
446
|
-
}
|
|
447
|
-
|
|
448
|
-
return [...new Set(paths)];
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
/** Build profile selection order for provider auth lookup. */
|
|
452
|
-
function resolveAuthProfileCandidates(params: {
|
|
453
|
-
provider: string;
|
|
454
|
-
store: AuthProfileStore;
|
|
455
|
-
authProfileId?: string;
|
|
456
|
-
runtimeConfig?: unknown;
|
|
457
|
-
}): string[] {
|
|
458
|
-
const candidates: string[] = [];
|
|
459
|
-
const normalizedProvider = normalizeProviderId(params.provider);
|
|
460
|
-
const push = (value: string | undefined) => {
|
|
461
|
-
const profileId = value?.trim();
|
|
462
|
-
if (!profileId) {
|
|
463
|
-
return;
|
|
464
|
-
}
|
|
465
|
-
if (!candidates.includes(profileId)) {
|
|
466
|
-
candidates.push(profileId);
|
|
467
|
-
}
|
|
468
|
-
};
|
|
469
|
-
|
|
470
|
-
push(params.authProfileId);
|
|
471
|
-
|
|
472
|
-
const storeOrder = findProviderConfigValue(params.store.order, params.provider);
|
|
473
|
-
for (const profileId of storeOrder ?? []) {
|
|
474
|
-
push(profileId);
|
|
475
|
-
}
|
|
476
|
-
|
|
477
|
-
if (isRecord(params.runtimeConfig)) {
|
|
478
|
-
const auth = params.runtimeConfig.auth;
|
|
479
|
-
if (isRecord(auth)) {
|
|
480
|
-
const order = findProviderConfigValue(
|
|
481
|
-
isRecord(auth.order) ? (auth.order as Record<string, unknown>) : undefined,
|
|
482
|
-
params.provider,
|
|
483
|
-
);
|
|
484
|
-
if (Array.isArray(order)) {
|
|
485
|
-
for (const profileId of order) {
|
|
486
|
-
if (typeof profileId === "string") {
|
|
487
|
-
push(profileId);
|
|
488
|
-
}
|
|
489
|
-
}
|
|
490
|
-
}
|
|
491
|
-
}
|
|
492
|
-
}
|
|
493
|
-
|
|
494
|
-
for (const [profileId, credential] of Object.entries(params.store.profiles)) {
|
|
495
|
-
if (normalizeProviderId(credential.provider) === normalizedProvider) {
|
|
496
|
-
push(profileId);
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
return candidates;
|
|
501
|
-
}
|
|
502
|
-
|
|
503
|
-
/** Resolve OAuth/api-key/token credentials from auth-profiles store. */
|
|
504
|
-
async function resolveApiKeyFromAuthProfiles(params: {
|
|
505
|
-
provider: string;
|
|
506
|
-
authProfileId?: string;
|
|
507
|
-
agentDir?: string;
|
|
508
|
-
runtimeConfig?: unknown;
|
|
509
|
-
piAiModule: PiAiModule;
|
|
510
|
-
envSnapshot: PluginEnvSnapshot;
|
|
511
|
-
}): Promise<string | undefined> {
|
|
512
|
-
const storesWithPaths = resolveAuthStorePaths({
|
|
513
|
-
agentDir: params.agentDir,
|
|
514
|
-
envSnapshot: params.envSnapshot,
|
|
515
|
-
})
|
|
516
|
-
.map((path) => {
|
|
517
|
-
try {
|
|
518
|
-
const parsed = parseAuthProfileStore(readFileSync(path, "utf8"));
|
|
519
|
-
return parsed ? { path, store: parsed } : undefined;
|
|
520
|
-
} catch {
|
|
521
|
-
return undefined;
|
|
522
|
-
}
|
|
523
|
-
})
|
|
524
|
-
.filter((entry): entry is { path: string; store: AuthProfileStore } => !!entry);
|
|
525
|
-
if (storesWithPaths.length === 0) {
|
|
526
|
-
return undefined;
|
|
527
|
-
}
|
|
528
|
-
|
|
529
|
-
const mergedStore = mergeAuthProfileStores(storesWithPaths.map((entry) => entry.store));
|
|
530
|
-
if (!mergedStore) {
|
|
531
|
-
return undefined;
|
|
532
|
-
}
|
|
533
|
-
|
|
534
|
-
const candidates = resolveAuthProfileCandidates({
|
|
535
|
-
provider: params.provider,
|
|
536
|
-
store: mergedStore,
|
|
537
|
-
authProfileId: params.authProfileId,
|
|
538
|
-
runtimeConfig: params.runtimeConfig,
|
|
539
|
-
});
|
|
540
|
-
if (candidates.length === 0) {
|
|
541
|
-
return undefined;
|
|
542
|
-
}
|
|
543
|
-
|
|
544
|
-
const persistPath =
|
|
545
|
-
params.agentDir?.trim() ? join(params.agentDir.trim(), "auth-profiles.json") : storesWithPaths[0]?.path;
|
|
546
|
-
|
|
547
|
-
for (const profileId of candidates) {
|
|
548
|
-
const credential = mergedStore.profiles[profileId];
|
|
549
|
-
if (!credential) {
|
|
550
|
-
continue;
|
|
551
|
-
}
|
|
552
|
-
if (normalizeProviderId(credential.provider) !== normalizeProviderId(params.provider)) {
|
|
553
|
-
continue;
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
if (credential.type === "api_key") {
|
|
557
|
-
const key = credential.key?.trim();
|
|
558
|
-
if (key) {
|
|
559
|
-
return key;
|
|
560
|
-
}
|
|
561
|
-
continue;
|
|
562
|
-
}
|
|
563
|
-
|
|
564
|
-
if (credential.type === "token") {
|
|
565
|
-
const token = credential.token?.trim();
|
|
566
|
-
if (!token) {
|
|
567
|
-
continue;
|
|
568
|
-
}
|
|
569
|
-
const expires = credential.expires;
|
|
570
|
-
if (typeof expires === "number" && Number.isFinite(expires) && expires > 0 && Date.now() >= expires) {
|
|
571
|
-
continue;
|
|
572
|
-
}
|
|
573
|
-
return token;
|
|
574
|
-
}
|
|
575
|
-
|
|
576
|
-
const access = credential.access?.trim();
|
|
577
|
-
const expires = credential.expires;
|
|
578
|
-
const isExpired =
|
|
579
|
-
typeof expires === "number" && Number.isFinite(expires) && expires > 0 && Date.now() >= expires;
|
|
580
|
-
|
|
581
|
-
if (!isExpired && access) {
|
|
582
|
-
if (
|
|
583
|
-
(credential.provider === "google-gemini-cli" || credential.provider === "google-antigravity") &&
|
|
584
|
-
typeof credential.projectId === "string" &&
|
|
585
|
-
credential.projectId.trim()
|
|
586
|
-
) {
|
|
587
|
-
return JSON.stringify({
|
|
588
|
-
token: access,
|
|
589
|
-
projectId: credential.projectId.trim(),
|
|
590
|
-
});
|
|
591
|
-
}
|
|
592
|
-
return access;
|
|
593
|
-
}
|
|
594
|
-
|
|
595
|
-
if (typeof params.piAiModule.getOAuthApiKey !== "function") {
|
|
596
|
-
continue;
|
|
597
|
-
}
|
|
598
|
-
|
|
599
|
-
try {
|
|
600
|
-
const oauthCredential = {
|
|
601
|
-
access: credential.access ?? "",
|
|
602
|
-
refresh: credential.refresh ?? "",
|
|
603
|
-
expires: typeof credential.expires === "number" ? credential.expires : 0,
|
|
604
|
-
...(typeof credential.projectId === "string" ? { projectId: credential.projectId } : {}),
|
|
605
|
-
...(typeof credential.accountId === "string" ? { accountId: credential.accountId } : {}),
|
|
606
|
-
};
|
|
607
|
-
const refreshed = await params.piAiModule.getOAuthApiKey(params.provider, {
|
|
608
|
-
[params.provider]: oauthCredential,
|
|
609
|
-
});
|
|
610
|
-
if (!refreshed?.apiKey) {
|
|
611
|
-
continue;
|
|
612
|
-
}
|
|
613
|
-
mergedStore.profiles[profileId] = {
|
|
614
|
-
...credential,
|
|
615
|
-
...refreshed.newCredentials,
|
|
616
|
-
type: "oauth",
|
|
617
|
-
};
|
|
618
|
-
if (persistPath) {
|
|
619
|
-
try {
|
|
620
|
-
writeFileSync(
|
|
621
|
-
persistPath,
|
|
622
|
-
JSON.stringify(
|
|
623
|
-
{
|
|
624
|
-
version: 1,
|
|
625
|
-
profiles: mergedStore.profiles,
|
|
626
|
-
...(mergedStore.order ? { order: mergedStore.order } : {}),
|
|
627
|
-
},
|
|
628
|
-
null,
|
|
629
|
-
2,
|
|
630
|
-
),
|
|
631
|
-
"utf8",
|
|
632
|
-
);
|
|
633
|
-
} catch {
|
|
634
|
-
// Ignore persistence errors: refreshed credentials remain usable in-memory for this run.
|
|
635
|
-
}
|
|
636
|
-
}
|
|
637
|
-
return refreshed.apiKey;
|
|
638
|
-
} catch {
|
|
639
|
-
if (access) {
|
|
640
|
-
return access;
|
|
641
|
-
}
|
|
642
|
-
}
|
|
643
|
-
}
|
|
644
|
-
|
|
645
|
-
return undefined;
|
|
646
|
-
}
|
|
647
|
-
|
|
648
|
-
/** Build a minimal but useful sub-agent prompt. */
|
|
649
|
-
function buildSubagentSystemPrompt(params: {
|
|
650
|
-
depth: number;
|
|
651
|
-
maxDepth: number;
|
|
652
|
-
taskSummary?: string;
|
|
653
|
-
}): string {
|
|
654
|
-
const task = params.taskSummary?.trim() || "Perform delegated LCM expansion work.";
|
|
655
|
-
return [
|
|
656
|
-
"You are a delegated sub-agent for LCM expansion.",
|
|
657
|
-
`Depth: ${params.depth}/${params.maxDepth}`,
|
|
658
|
-
"Return concise, factual results only.",
|
|
659
|
-
task,
|
|
660
|
-
].join("\n");
|
|
661
|
-
}
|
|
662
|
-
|
|
663
|
-
/** Extract latest assistant text from session message snapshots. */
|
|
664
|
-
function readLatestAssistantReply(messages: unknown[]): string | undefined {
|
|
665
|
-
for (let i = messages.length - 1; i >= 0; i--) {
|
|
666
|
-
const item = messages[i];
|
|
667
|
-
if (!item || typeof item !== "object") {
|
|
668
|
-
continue;
|
|
669
|
-
}
|
|
670
|
-
const record = item as { role?: unknown; content?: unknown };
|
|
671
|
-
if (record.role !== "assistant") {
|
|
672
|
-
continue;
|
|
673
|
-
}
|
|
674
|
-
|
|
675
|
-
if (typeof record.content === "string") {
|
|
676
|
-
const trimmed = record.content.trim();
|
|
677
|
-
if (trimmed) {
|
|
678
|
-
return trimmed;
|
|
679
|
-
}
|
|
680
|
-
continue;
|
|
681
|
-
}
|
|
682
|
-
|
|
683
|
-
if (!Array.isArray(record.content)) {
|
|
684
|
-
continue;
|
|
685
|
-
}
|
|
686
|
-
|
|
687
|
-
const text = record.content
|
|
688
|
-
.filter((entry): entry is { type?: unknown; text?: unknown } => {
|
|
689
|
-
return !!entry && typeof entry === "object";
|
|
690
|
-
})
|
|
691
|
-
.map((entry) => (entry.type === "text" && typeof entry.text === "string" ? entry.text : ""))
|
|
692
|
-
.filter(Boolean)
|
|
693
|
-
.join("\n")
|
|
694
|
-
.trim();
|
|
695
|
-
|
|
696
|
-
if (text) {
|
|
697
|
-
return text;
|
|
698
|
-
}
|
|
699
|
-
}
|
|
700
|
-
|
|
701
|
-
return undefined;
|
|
702
|
-
}
|
|
703
|
-
|
|
704
|
-
/** Construct LCM dependencies from plugin API/runtime surfaces. */
|
|
705
|
-
function createLcmDependencies(api: OpenClawPluginApi): LcmDependencies {
|
|
706
|
-
const envSnapshot = snapshotPluginEnv();
|
|
707
|
-
envSnapshot.openclawDefaultModel = readDefaultModelFromConfig(api.config);
|
|
708
|
-
const modelAuth = getRuntimeModelAuth(api);
|
|
709
|
-
const readEnv: ReadEnvFn = (key) => process.env[key];
|
|
710
|
-
const pluginConfig =
|
|
711
|
-
api.pluginConfig && typeof api.pluginConfig === "object" && !Array.isArray(api.pluginConfig)
|
|
712
|
-
? api.pluginConfig
|
|
713
|
-
: undefined;
|
|
714
|
-
const config = resolveLcmConfig(process.env, pluginConfig);
|
|
715
|
-
|
|
716
|
-
// Read model overrides from plugin config
|
|
717
|
-
if (pluginConfig) {
|
|
718
|
-
const summaryModel = pluginConfig.summaryModel;
|
|
719
|
-
const summaryProvider = pluginConfig.summaryProvider;
|
|
720
|
-
if (typeof summaryModel === "string") {
|
|
721
|
-
envSnapshot.pluginSummaryModel = summaryModel.trim();
|
|
722
|
-
}
|
|
723
|
-
if (typeof summaryProvider === "string") {
|
|
724
|
-
envSnapshot.pluginSummaryProvider = summaryProvider.trim();
|
|
725
|
-
}
|
|
726
|
-
}
|
|
727
|
-
|
|
728
|
-
if (!modelAuth) {
|
|
729
|
-
api.logger.warn(buildLegacyAuthFallbackWarning());
|
|
730
|
-
}
|
|
731
|
-
|
|
732
|
-
return {
|
|
733
|
-
config,
|
|
734
|
-
complete: async ({
|
|
735
|
-
provider,
|
|
736
|
-
model,
|
|
737
|
-
apiKey,
|
|
738
|
-
providerApi,
|
|
739
|
-
authProfileId,
|
|
740
|
-
agentDir,
|
|
741
|
-
runtimeConfig,
|
|
742
|
-
messages,
|
|
743
|
-
system,
|
|
744
|
-
maxTokens,
|
|
745
|
-
temperature,
|
|
746
|
-
reasoning,
|
|
747
|
-
}) => {
|
|
748
|
-
try {
|
|
749
|
-
const piAiModuleId = "@mariozechner/pi-ai";
|
|
750
|
-
const mod = (await import(piAiModuleId)) as PiAiModule;
|
|
751
|
-
|
|
752
|
-
if (typeof mod.completeSimple !== "function") {
|
|
753
|
-
return { content: [] };
|
|
754
|
-
}
|
|
755
|
-
|
|
756
|
-
const providerId = (provider ?? "").trim();
|
|
757
|
-
const modelId = model.trim();
|
|
758
|
-
if (!providerId || !modelId) {
|
|
759
|
-
return { content: [] };
|
|
760
|
-
}
|
|
761
|
-
|
|
762
|
-
const knownModel =
|
|
763
|
-
typeof mod.getModel === "function" ? mod.getModel(providerId, modelId) : undefined;
|
|
764
|
-
const fallbackApi =
|
|
765
|
-
providerApi?.trim() ||
|
|
766
|
-
resolveProviderApiFromRuntimeConfig(runtimeConfig, providerId) ||
|
|
767
|
-
(() => {
|
|
768
|
-
if (typeof mod.getModels !== "function") {
|
|
769
|
-
return undefined;
|
|
770
|
-
}
|
|
771
|
-
const models = mod.getModels(providerId);
|
|
772
|
-
const first = Array.isArray(models) ? models[0] : undefined;
|
|
773
|
-
if (!isRecord(first) || typeof first.api !== "string" || !first.api.trim()) {
|
|
774
|
-
return undefined;
|
|
775
|
-
}
|
|
776
|
-
return first.api.trim();
|
|
777
|
-
})() ||
|
|
778
|
-
inferApiFromProvider(providerId);
|
|
779
|
-
|
|
780
|
-
const resolvedModel =
|
|
781
|
-
isRecord(knownModel) &&
|
|
782
|
-
typeof knownModel.api === "string" &&
|
|
783
|
-
typeof knownModel.provider === "string" &&
|
|
784
|
-
typeof knownModel.id === "string"
|
|
785
|
-
? {
|
|
786
|
-
...knownModel,
|
|
787
|
-
id: knownModel.id,
|
|
788
|
-
provider: knownModel.provider,
|
|
789
|
-
api: knownModel.api,
|
|
790
|
-
}
|
|
791
|
-
: {
|
|
792
|
-
id: modelId,
|
|
793
|
-
name: modelId,
|
|
794
|
-
provider: providerId,
|
|
795
|
-
api: fallbackApi,
|
|
796
|
-
reasoning: false,
|
|
797
|
-
input: ["text"],
|
|
798
|
-
cost: {
|
|
799
|
-
input: 0,
|
|
800
|
-
output: 0,
|
|
801
|
-
cacheRead: 0,
|
|
802
|
-
cacheWrite: 0,
|
|
803
|
-
},
|
|
804
|
-
contextWindow: 200_000,
|
|
805
|
-
maxTokens: 8_000,
|
|
806
|
-
};
|
|
807
|
-
|
|
808
|
-
let resolvedApiKey = apiKey?.trim();
|
|
809
|
-
if (!resolvedApiKey && modelAuth) {
|
|
810
|
-
try {
|
|
811
|
-
resolvedApiKey = resolveApiKeyFromAuthResult(
|
|
812
|
-
await modelAuth.resolveApiKeyForProvider({
|
|
813
|
-
provider: providerId,
|
|
814
|
-
cfg: api.config,
|
|
815
|
-
...(authProfileId ? { profileId: authProfileId } : {}),
|
|
816
|
-
}),
|
|
817
|
-
);
|
|
818
|
-
} catch (err) {
|
|
819
|
-
console.error(
|
|
820
|
-
`[lcm] modelAuth.resolveApiKeyForProvider FAILED:`,
|
|
821
|
-
err instanceof Error ? err.message : err,
|
|
822
|
-
);
|
|
823
|
-
}
|
|
824
|
-
}
|
|
825
|
-
if (!resolvedApiKey && !modelAuth) {
|
|
826
|
-
resolvedApiKey = resolveApiKey(providerId, readEnv);
|
|
827
|
-
}
|
|
828
|
-
if (!resolvedApiKey && !modelAuth && typeof mod.getEnvApiKey === "function") {
|
|
829
|
-
resolvedApiKey = mod.getEnvApiKey(providerId)?.trim();
|
|
830
|
-
}
|
|
831
|
-
if (!resolvedApiKey && !modelAuth) {
|
|
832
|
-
resolvedApiKey = await resolveApiKeyFromAuthProfiles({
|
|
833
|
-
provider: providerId,
|
|
834
|
-
authProfileId,
|
|
835
|
-
agentDir,
|
|
836
|
-
runtimeConfig,
|
|
837
|
-
piAiModule: mod,
|
|
838
|
-
envSnapshot,
|
|
839
|
-
});
|
|
840
|
-
}
|
|
841
|
-
|
|
842
|
-
const completeOptions = buildCompleteSimpleOptions({
|
|
843
|
-
api: resolvedModel.api,
|
|
844
|
-
apiKey: resolvedApiKey,
|
|
845
|
-
maxTokens,
|
|
846
|
-
temperature,
|
|
847
|
-
reasoning,
|
|
848
|
-
});
|
|
849
|
-
|
|
850
|
-
const result = await mod.completeSimple(
|
|
851
|
-
resolvedModel,
|
|
852
|
-
{
|
|
853
|
-
...(typeof system === "string" && system.trim()
|
|
854
|
-
? { systemPrompt: system.trim() }
|
|
855
|
-
: {}),
|
|
856
|
-
messages: messages.map((message) => ({
|
|
857
|
-
role: message.role,
|
|
858
|
-
content: message.content,
|
|
859
|
-
timestamp: Date.now(),
|
|
860
|
-
})),
|
|
861
|
-
},
|
|
862
|
-
completeOptions,
|
|
863
|
-
);
|
|
864
|
-
|
|
865
|
-
if (!isRecord(result)) {
|
|
866
|
-
return {
|
|
867
|
-
content: [],
|
|
868
|
-
request_provider: providerId,
|
|
869
|
-
request_model: modelId,
|
|
870
|
-
request_api: resolvedModel.api,
|
|
871
|
-
request_reasoning:
|
|
872
|
-
typeof reasoning === "string" && reasoning.trim() ? reasoning.trim() : "(none)",
|
|
873
|
-
request_has_system:
|
|
874
|
-
typeof system === "string" && system.trim().length > 0 ? "true" : "false",
|
|
875
|
-
request_temperature:
|
|
876
|
-
typeof completeOptions.temperature === "number"
|
|
877
|
-
? String(completeOptions.temperature)
|
|
878
|
-
: "(omitted)",
|
|
879
|
-
request_temperature_sent:
|
|
880
|
-
typeof completeOptions.temperature === "number" ? "true" : "false",
|
|
881
|
-
};
|
|
882
|
-
}
|
|
883
|
-
|
|
884
|
-
return {
|
|
885
|
-
...result,
|
|
886
|
-
content: Array.isArray(result.content) ? result.content : [],
|
|
887
|
-
request_provider: providerId,
|
|
888
|
-
request_model: modelId,
|
|
889
|
-
request_api: resolvedModel.api,
|
|
890
|
-
request_reasoning:
|
|
891
|
-
typeof reasoning === "string" && reasoning.trim() ? reasoning.trim() : "(none)",
|
|
892
|
-
request_has_system: typeof system === "string" && system.trim().length > 0 ? "true" : "false",
|
|
893
|
-
request_temperature:
|
|
894
|
-
typeof completeOptions.temperature === "number"
|
|
895
|
-
? String(completeOptions.temperature)
|
|
896
|
-
: "(omitted)",
|
|
897
|
-
request_temperature_sent: typeof completeOptions.temperature === "number" ? "true" : "false",
|
|
898
|
-
};
|
|
899
|
-
} catch (err) {
|
|
900
|
-
console.error(`[lcm] completeSimple error:`, err instanceof Error ? err.message : err);
|
|
901
|
-
return { content: [] };
|
|
902
|
-
}
|
|
903
|
-
},
|
|
904
|
-
callGateway: async (params) => {
|
|
905
|
-
const sub = api.runtime.subagent;
|
|
906
|
-
switch (params.method) {
|
|
907
|
-
case "agent":
|
|
908
|
-
return sub.run({
|
|
909
|
-
sessionKey: String(params.params?.sessionKey ?? ""),
|
|
910
|
-
message: String(params.params?.message ?? ""),
|
|
911
|
-
extraSystemPrompt: params.params?.extraSystemPrompt as string | undefined,
|
|
912
|
-
lane: params.params?.lane as string | undefined,
|
|
913
|
-
deliver: (params.params?.deliver as boolean) ?? false,
|
|
914
|
-
idempotencyKey: params.params?.idempotencyKey as string | undefined,
|
|
915
|
-
});
|
|
916
|
-
case "agent.wait":
|
|
917
|
-
return sub.waitForRun({
|
|
918
|
-
runId: String(params.params?.runId ?? ""),
|
|
919
|
-
timeoutMs: (params.params?.timeoutMs as number) ?? params.timeoutMs,
|
|
920
|
-
});
|
|
921
|
-
case "sessions.get":
|
|
922
|
-
return sub.getSession({
|
|
923
|
-
sessionKey: String(params.params?.key ?? ""),
|
|
924
|
-
limit: params.params?.limit as number | undefined,
|
|
925
|
-
});
|
|
926
|
-
case "sessions.delete":
|
|
927
|
-
await sub.deleteSession({
|
|
928
|
-
sessionKey: String(params.params?.key ?? ""),
|
|
929
|
-
deleteTranscript: (params.params?.deleteTranscript as boolean) ?? true,
|
|
930
|
-
});
|
|
931
|
-
return {};
|
|
932
|
-
default:
|
|
933
|
-
throw new Error(`Unsupported gateway method in LCM plugin: ${params.method}`);
|
|
934
|
-
}
|
|
935
|
-
},
|
|
936
|
-
resolveModel: (modelRef, providerHint) => {
|
|
937
|
-
const raw =
|
|
938
|
-
(modelRef?.trim() ||
|
|
939
|
-
envSnapshot.pluginSummaryModel ||
|
|
940
|
-
envSnapshot.lcmSummaryModel ||
|
|
941
|
-
envSnapshot.openclawDefaultModel).trim();
|
|
942
|
-
if (!raw) {
|
|
943
|
-
throw new Error("No model configured for LCM summarization.");
|
|
944
|
-
}
|
|
945
|
-
|
|
946
|
-
if (raw.includes("/")) {
|
|
947
|
-
const [provider, ...rest] = raw.split("/");
|
|
948
|
-
const model = rest.join("/").trim();
|
|
949
|
-
if (provider && model) {
|
|
950
|
-
return { provider: provider.trim(), model };
|
|
951
|
-
}
|
|
952
|
-
}
|
|
953
|
-
|
|
954
|
-
const provider = (
|
|
955
|
-
providerHint?.trim() ||
|
|
956
|
-
envSnapshot.pluginSummaryProvider ||
|
|
957
|
-
envSnapshot.lcmSummaryProvider ||
|
|
958
|
-
envSnapshot.openclawProvider ||
|
|
959
|
-
"openai"
|
|
960
|
-
).trim();
|
|
961
|
-
return { provider, model: raw };
|
|
962
|
-
},
|
|
963
|
-
getApiKey: async (provider, model, options) => {
|
|
964
|
-
if (modelAuth) {
|
|
965
|
-
try {
|
|
966
|
-
const modelAuthKey = resolveApiKeyFromAuthResult(
|
|
967
|
-
await modelAuth.getApiKeyForModel({
|
|
968
|
-
model: buildModelAuthLookupModel({ provider, model }),
|
|
969
|
-
cfg: api.config,
|
|
970
|
-
...(options?.profileId ? { profileId: options.profileId } : {}),
|
|
971
|
-
...(options?.preferredProfile ? { preferredProfile: options.preferredProfile } : {}),
|
|
972
|
-
}),
|
|
973
|
-
);
|
|
974
|
-
if (modelAuthKey) {
|
|
975
|
-
return modelAuthKey;
|
|
976
|
-
}
|
|
977
|
-
} catch {
|
|
978
|
-
// Fall through to auth-profile lookup for older OpenClaw runtimes.
|
|
979
|
-
}
|
|
980
|
-
}
|
|
981
|
-
|
|
982
|
-
const envKey = resolveApiKey(provider, readEnv);
|
|
983
|
-
if (envKey) {
|
|
984
|
-
return envKey;
|
|
985
|
-
}
|
|
986
|
-
|
|
987
|
-
const piAiModuleId = "@mariozechner/pi-ai";
|
|
988
|
-
const mod = (await import(piAiModuleId)) as PiAiModule;
|
|
989
|
-
return resolveApiKeyFromAuthProfiles({
|
|
990
|
-
provider,
|
|
991
|
-
authProfileId: options?.profileId,
|
|
992
|
-
agentDir: api.resolvePath("."),
|
|
993
|
-
runtimeConfig: api.config,
|
|
994
|
-
piAiModule: mod,
|
|
995
|
-
envSnapshot,
|
|
996
|
-
});
|
|
997
|
-
},
|
|
998
|
-
requireApiKey: async (provider, model, options) => {
|
|
999
|
-
const key = await (async () => {
|
|
1000
|
-
if (modelAuth) {
|
|
1001
|
-
try {
|
|
1002
|
-
const modelAuthKey = resolveApiKeyFromAuthResult(
|
|
1003
|
-
await modelAuth.getApiKeyForModel({
|
|
1004
|
-
model: buildModelAuthLookupModel({ provider, model }),
|
|
1005
|
-
cfg: api.config,
|
|
1006
|
-
...(options?.profileId ? { profileId: options.profileId } : {}),
|
|
1007
|
-
...(options?.preferredProfile ? { preferredProfile: options.preferredProfile } : {}),
|
|
1008
|
-
}),
|
|
1009
|
-
);
|
|
1010
|
-
if (modelAuthKey) {
|
|
1011
|
-
return modelAuthKey;
|
|
1012
|
-
}
|
|
1013
|
-
} catch {
|
|
1014
|
-
// Fall through to auth-profile lookup for older OpenClaw runtimes.
|
|
1015
|
-
}
|
|
1016
|
-
}
|
|
1017
|
-
|
|
1018
|
-
const envKey = resolveApiKey(provider, readEnv);
|
|
1019
|
-
if (envKey) {
|
|
1020
|
-
return envKey;
|
|
1021
|
-
}
|
|
1022
|
-
|
|
1023
|
-
const piAiModuleId = "@mariozechner/pi-ai";
|
|
1024
|
-
const mod = (await import(piAiModuleId)) as PiAiModule;
|
|
1025
|
-
return resolveApiKeyFromAuthProfiles({
|
|
1026
|
-
provider,
|
|
1027
|
-
authProfileId: options?.profileId,
|
|
1028
|
-
agentDir: api.resolvePath("."),
|
|
1029
|
-
runtimeConfig: api.config,
|
|
1030
|
-
piAiModule: mod,
|
|
1031
|
-
envSnapshot,
|
|
1032
|
-
});
|
|
1033
|
-
})();
|
|
1034
|
-
if (!key) {
|
|
1035
|
-
throw new Error(`Missing API key for provider '${provider}' (model '${model}').`);
|
|
1036
|
-
}
|
|
1037
|
-
return key;
|
|
1038
|
-
},
|
|
1039
|
-
parseAgentSessionKey,
|
|
1040
|
-
isSubagentSessionKey: (sessionKey) => {
|
|
1041
|
-
const parsed = parseAgentSessionKey(sessionKey);
|
|
1042
|
-
return !!parsed && parsed.suffix.startsWith("subagent:");
|
|
1043
|
-
},
|
|
1044
|
-
normalizeAgentId,
|
|
1045
|
-
buildSubagentSystemPrompt,
|
|
1046
|
-
readLatestAssistantReply,
|
|
1047
|
-
resolveAgentDir: () => api.resolvePath("."),
|
|
1048
|
-
resolveSessionIdFromSessionKey: async (sessionKey) => {
|
|
1049
|
-
const key = sessionKey.trim();
|
|
1050
|
-
if (!key) {
|
|
1051
|
-
return undefined;
|
|
1052
|
-
}
|
|
1053
|
-
|
|
1054
|
-
try {
|
|
1055
|
-
const cfg = api.runtime.config.loadConfig();
|
|
1056
|
-
const parsed = parseAgentSessionKey(key);
|
|
1057
|
-
const agentId = normalizeAgentId(parsed?.agentId);
|
|
1058
|
-
const storePath = api.runtime.channel.session.resolveStorePath(cfg.session?.store, {
|
|
1059
|
-
agentId,
|
|
1060
|
-
});
|
|
1061
|
-
const raw = readFileSync(storePath, "utf8");
|
|
1062
|
-
const store = JSON.parse(raw) as Record<string, { sessionId?: string } | undefined>;
|
|
1063
|
-
const sessionId = store[key]?.sessionId;
|
|
1064
|
-
return typeof sessionId === "string" && sessionId.trim() ? sessionId.trim() : undefined;
|
|
1065
|
-
} catch {
|
|
1066
|
-
return undefined;
|
|
1067
|
-
}
|
|
1068
|
-
},
|
|
1069
|
-
agentLaneSubagent: "subagent",
|
|
1070
|
-
log: {
|
|
1071
|
-
info: (msg) => api.logger.info(msg),
|
|
1072
|
-
warn: (msg) => api.logger.warn(msg),
|
|
1073
|
-
error: (msg) => api.logger.error(msg),
|
|
1074
|
-
debug: (msg) => api.logger.debug?.(msg),
|
|
1075
|
-
},
|
|
1076
|
-
};
|
|
1077
|
-
}
|
|
1078
|
-
|
|
1079
|
-
const lcmPlugin = {
|
|
1080
|
-
id: "lossless-claw",
|
|
1081
|
-
name: "Lossless Context Management",
|
|
1082
|
-
description:
|
|
1083
|
-
"DAG-based conversation summarization with incremental compaction, full-text search, and sub-agent expansion",
|
|
1084
|
-
|
|
1085
|
-
configSchema: {
|
|
1086
|
-
parse(value: unknown) {
|
|
1087
|
-
const raw =
|
|
1088
|
-
value && typeof value === "object" && !Array.isArray(value)
|
|
1089
|
-
? (value as Record<string, unknown>)
|
|
1090
|
-
: {};
|
|
1091
|
-
return resolveLcmConfig(process.env, raw);
|
|
1092
|
-
},
|
|
1093
|
-
},
|
|
1094
|
-
|
|
1095
|
-
register(api: OpenClawPluginApi) {
|
|
1096
|
-
const deps = createLcmDependencies(api);
|
|
1097
|
-
const lcm = new LcmContextEngine(deps);
|
|
1098
|
-
|
|
1099
|
-
api.registerContextEngine("lossless-claw", () => lcm);
|
|
1100
|
-
api.registerTool((ctx) =>
|
|
1101
|
-
createLcmGrepTool({
|
|
1102
|
-
deps,
|
|
1103
|
-
lcm,
|
|
1104
|
-
sessionKey: ctx.sessionKey,
|
|
1105
|
-
}),
|
|
1106
|
-
);
|
|
1107
|
-
api.registerTool((ctx) =>
|
|
1108
|
-
createLcmDescribeTool({
|
|
1109
|
-
deps,
|
|
1110
|
-
lcm,
|
|
1111
|
-
sessionKey: ctx.sessionKey,
|
|
1112
|
-
}),
|
|
1113
|
-
);
|
|
1114
|
-
api.registerTool((ctx) =>
|
|
1115
|
-
createLcmExpandTool({
|
|
1116
|
-
deps,
|
|
1117
|
-
lcm,
|
|
1118
|
-
sessionKey: ctx.sessionKey,
|
|
1119
|
-
}),
|
|
1120
|
-
);
|
|
1121
|
-
api.registerTool((ctx) =>
|
|
1122
|
-
createLcmExpandQueryTool({
|
|
1123
|
-
deps,
|
|
1124
|
-
lcm,
|
|
1125
|
-
sessionKey: ctx.sessionKey,
|
|
1126
|
-
requesterSessionKey: ctx.sessionKey,
|
|
1127
|
-
}),
|
|
1128
|
-
);
|
|
1129
|
-
|
|
1130
|
-
api.logger.info(
|
|
1131
|
-
`[lcm] Plugin loaded (enabled=${deps.config.enabled}, db=${deps.config.databasePath}, threshold=${deps.config.contextThreshold})`,
|
|
1132
|
-
);
|
|
1133
|
-
},
|
|
1134
|
-
};
|
|
1135
|
-
|
|
1136
|
-
export default lcmPlugin;
|
|
1
|
+
export { default } from "./src/plugin/index.js";
|
|
2
|
+
export { buildCompleteSimpleOptions, shouldOmitTemperatureForApi } from "./src/plugin/index.js";
|