@qingchencloud/openclaw-zh 2026.2.1-zh.2 → 2026.2.1-zh.3
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/CHANGELOG.md +19 -1
- package/dist/agents/auth-profiles/oauth.js +11 -2
- package/dist/agents/bash-tools.exec.js +45 -0
- package/dist/agents/context-window-guard.js +10 -11
- package/dist/agents/openclaw-tools.js +1 -0
- package/dist/agents/pi-embedded-runner/compact.js +5 -14
- package/dist/agents/pi-embedded-runner/extensions.js +8 -0
- package/dist/agents/pi-embedded-runner/extra-params.d.ts +1 -0
- package/dist/agents/pi-embedded-runner/extra-params.js +50 -12
- package/dist/agents/pi-embedded-runner/run/attempt.js +10 -15
- package/dist/agents/pi-embedded-runner/system-prompt.d.ts +2 -0
- package/dist/agents/pi-embedded-runner/system-prompt.js +7 -0
- package/dist/agents/pi-extensions/compaction-safeguard-runtime.d.ts +1 -0
- package/dist/agents/pi-extensions/compaction-safeguard.js +3 -2
- package/dist/agents/pi-tool-definition-adapter.d.ts +4 -1
- package/dist/agents/pi-tool-definition-adapter.js +17 -2
- package/dist/agents/pi-tools.before-tool-call.d.ts +25 -0
- package/dist/agents/pi-tools.before-tool-call.js +69 -0
- package/dist/agents/pi-tools.js +7 -2
- package/dist/agents/tool-policy.conformance.d.ts +11 -0
- package/dist/agents/tool-policy.conformance.js +14 -0
- package/dist/agents/tools/message-tool.d.ts +1 -0
- package/dist/agents/tools/message-tool.js +11 -0
- package/dist/agents/tools/web-fetch.js +100 -29
- package/dist/agents/tools/web-search.js +15 -8
- package/dist/browser/cdp.helpers.d.ts +3 -1
- package/dist/browser/cdp.helpers.js +7 -4
- package/dist/browser/extension-relay.d.ts +1 -0
- package/dist/browser/extension-relay.js +64 -0
- package/dist/browser/pw-session.js +2 -1
- package/dist/build-info.json +3 -3
- package/dist/canvas-host/a2ui/.bundle.hash +1 -1
- package/dist/cli/program/register.status-health-sessions.js +1 -1
- package/dist/commands/onboard.js +3 -2
- package/dist/config/defaults.js +4 -4
- package/dist/config/types.agent-defaults.d.ts +1 -1
- package/dist/config/zod-schema.providers-core.js +32 -0
- package/dist/control-ui/assets/index-BZkju1RS.css +1 -0
- package/dist/control-ui/assets/{index-BebBTKqz.js → index-BgR4pesr.js} +24 -24
- package/dist/control-ui/assets/index-BgR4pesr.js.map +1 -0
- package/dist/control-ui/index.html +2 -2
- package/dist/infra/tls/gateway.js +1 -1
- package/dist/media-understanding/apply.js +142 -34
- package/dist/security/external-content.d.ts +7 -2
- package/dist/security/external-content.js +81 -3
- package/dist/telegram/bot-handlers.js +5 -5
- package/dist/telegram/bot-message-context.js +9 -6
- package/dist/telegram/bot-native-commands.js +2 -2
- package/dist/tui/components/searchable-select-list.js +3 -3
- package/dist/web/accounts.js +2 -2
- package/docs/.i18n/README.md +31 -0
- package/docs/.i18n/glossary.zh-CN.json +82 -0
- package/docs/.i18n/zh-CN.tm.jsonl +1371 -0
- package/docs/channels/discord.md +6 -0
- package/docs/channels/grammy.md +1 -1
- package/docs/channels/telegram.md +5 -5
- package/docs/concepts/model-providers.md +3 -3
- package/docs/concepts/session-pruning.md +6 -6
- package/docs/docs.json +320 -301
- package/docs/gateway/configuration.md +1 -1
- package/docs/gateway/security/index.md +1 -0
- package/docs/install/index.md +5 -1
- package/docs/pi.md +20 -8
- package/docs/platforms/exe-dev.md +2 -2
- package/docs/platforms/windows.md +2 -1
- package/docs/providers/anthropic.md +24 -4
- package/docs/providers/moonshot.md +3 -3
- package/docs/start/onboarding.md +10 -6
- package/docs/token-use.md +1 -1
- package/docs/tools/chrome-extension.md +1 -0
- package/docs/tools/exec.md +7 -5
- package/docs/tools/skills.md +1 -1
- package/docs/web/control-ui.md +30 -0
- package/docs/zh-CN/index.md +263 -0
- package/docs/zh-CN/start/getting-started.md +212 -0
- package/docs/zh-CN/start/wizard.md +331 -0
- package/extensions/googlechat/src/accounts.ts +1 -1
- package/extensions/line/src/channel.ts +4 -3
- package/extensions/tlon/src/urbit/sse-client.ts +16 -0
- package/package.json +24 -6
- package/skills/canvas/SKILL.md +9 -9
- package/skills/session-logs/SKILL.md +1 -1
- package/dist/control-ui/assets/index-BKPyesll.css +0 -1
- package/dist/control-ui/assets/index-BebBTKqz.js.map +0 -1
- package/dist/telegram/pairing-store.d.ts +0 -43
- package/dist/telegram/pairing-store.js +0 -78
package/CHANGELOG.md
CHANGED
|
@@ -6,14 +6,31 @@ Docs: https://docs.openclaw.ai
|
|
|
6
6
|
|
|
7
7
|
### Changes
|
|
8
8
|
|
|
9
|
+
- Docs: onboarding/install/i18n/exec-approvals/Control UI/exe.dev/cacheRetention updates + misc nav/typos.
|
|
10
|
+
- Telegram: use shared pairing store. (#6127) Thanks @obviyus.
|
|
11
|
+
- Agents: add OpenRouter app attribution headers. (#5050) Thanks @alexanderatallah.
|
|
12
|
+
- Agents: add system prompt safety guardrails. (#5445) Thanks @joshp123.
|
|
13
|
+
- Agents: update pi-ai to 0.50.9 and rename cacheControlTtl -> cacheRetention (with back-compat mapping).
|
|
14
|
+
- Discord: inherit thread parent bindings for routing. (#3892) Thanks @aerolalit.
|
|
15
|
+
- Gateway: require TLS 1.3 minimum for TLS listeners. (#5970) Thanks @loganaden.
|
|
16
|
+
|
|
9
17
|
### Fixes
|
|
10
18
|
|
|
11
19
|
- Auto-reply: avoid referencing workspace files in /new greeting prompt. (#5706) Thanks @bravostation.
|
|
12
20
|
- Process: resolve Windows `spawn()` failures for npm-family CLIs by appending `.cmd` when needed. (#5815) Thanks @thejhinvirtuoso.
|
|
13
|
-
- Docs: update MiniMax OAuth setup commands; Extensions: use OpenClaw plugin SDK for MiniMax OAuth. (#5402) Thanks @Maosghoul.
|
|
14
21
|
- Discord: resolve PluralKit proxied senders for allowlists and labels. (#5838) Thanks @thewilloftheshadow.
|
|
22
|
+
- Agents: ensure OpenRouter attribution headers apply in the embedded runner.
|
|
23
|
+
- Agents: cap context window resolution for compaction safeguard. (#6187) Thanks @iamEvanYT.
|
|
24
|
+
- System prompt: hint using session_status for current date/time. (#1897, #1928, #2108)
|
|
15
25
|
- Telegram: restore draft streaming partials. (#5543) Thanks @obviyus.
|
|
26
|
+
- Onboarding: friendlier Windows onboarding message. (#6242) Thanks @shanselman.
|
|
27
|
+
- TUI: prevent crash when searching with digits in the model selector.
|
|
28
|
+
- Agents: wire before_tool_call plugin hook into tool execution. (#6570) Thanks @ryancnelson.
|
|
29
|
+
- Browser: secure Chrome extension relay CDP sessions.
|
|
30
|
+
- Docker: use container port for gateway command instead of host port. (#5110) Thanks @mise42.
|
|
16
31
|
- fix(lobster): block arbitrary exec via lobsterPath/cwd injection (GHSA-4mhr-g7xj-cg8j). (#5335) Thanks @vignesh07.
|
|
32
|
+
- Security: block LD_/DYLD_ env overrides for host exec. (#4896) Thanks @HassanFleyah.
|
|
33
|
+
- Security: harden web tool content wrapping + file parsing safeguards. (#4058) Thanks @VACInc.
|
|
17
34
|
|
|
18
35
|
## 2026.1.30
|
|
19
36
|
|
|
@@ -123,6 +140,7 @@ Docs: https://docs.openclaw.ai
|
|
|
123
140
|
|
|
124
141
|
### Fixes
|
|
125
142
|
|
|
143
|
+
- Skills: update session-logs paths to use ~/.openclaw. (#4502) Thanks @bonald.
|
|
126
144
|
- Telegram: avoid silent empty replies by tracking normalization skips before fallback. (#3796)
|
|
127
145
|
- Mentions: honor mentionPatterns even when explicit mentions are present. (#3303) Thanks @HirokiKobayashi-R.
|
|
128
146
|
- Discord: restore username directory lookup in target resolution. (#3131) Thanks @bonald.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { getOAuthApiKey } from "@mariozechner/pi-ai";
|
|
1
|
+
import { getOAuthApiKey, getOAuthProviders, } from "@mariozechner/pi-ai";
|
|
2
2
|
import lockfile from "proper-lockfile";
|
|
3
3
|
import { refreshQwenPortalCredentials } from "../../providers/qwen-portal-oauth.js";
|
|
4
4
|
import { refreshChutesTokens } from "../chutes-oauth.js";
|
|
@@ -7,6 +7,9 @@ import { formatAuthDoctorHint } from "./doctor.js";
|
|
|
7
7
|
import { ensureAuthStoreFile, resolveAuthStorePath } from "./paths.js";
|
|
8
8
|
import { suggestOAuthProfileIdForLegacyDefault } from "./repair.js";
|
|
9
9
|
import { ensureAuthProfileStore, saveAuthProfileStore } from "./store.js";
|
|
10
|
+
const OAUTH_PROVIDER_IDS = new Set(getOAuthProviders().map((provider) => provider.id));
|
|
11
|
+
const isOAuthProvider = (provider) => OAUTH_PROVIDER_IDS.has(provider);
|
|
12
|
+
const resolveOAuthProvider = (provider) => isOAuthProvider(provider) ? provider : null;
|
|
10
13
|
function buildOAuthApiKey(provider, credentials) {
|
|
11
14
|
const needsProjectId = provider === "google-gemini-cli" || provider === "google-antigravity";
|
|
12
15
|
return needsProjectId
|
|
@@ -50,7 +53,13 @@ async function refreshOAuthTokenWithLock(params) {
|
|
|
50
53
|
const newCredentials = await refreshQwenPortalCredentials(cred);
|
|
51
54
|
return { apiKey: newCredentials.access, newCredentials };
|
|
52
55
|
})()
|
|
53
|
-
: await
|
|
56
|
+
: await (async () => {
|
|
57
|
+
const oauthProvider = resolveOAuthProvider(cred.provider);
|
|
58
|
+
if (!oauthProvider) {
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
return await getOAuthApiKey(oauthProvider, oauthCreds);
|
|
62
|
+
})();
|
|
54
63
|
if (!result) {
|
|
55
64
|
return null;
|
|
56
65
|
}
|
|
@@ -15,6 +15,46 @@ import { buildCursorPositionResponse, stripDsrRequests } from "./pty-dsr.js";
|
|
|
15
15
|
import { getShellConfig, sanitizeBinaryOutput } from "./shell-utils.js";
|
|
16
16
|
import { callGatewayTool } from "./tools/gateway.js";
|
|
17
17
|
import { listNodes, resolveNodeIdFromList } from "./tools/nodes-utils.js";
|
|
18
|
+
// Security: Blocklist of environment variables that could alter execution flow
|
|
19
|
+
// or inject code when running on non-sandboxed hosts (Gateway/Node).
|
|
20
|
+
const DANGEROUS_HOST_ENV_VARS = new Set([
|
|
21
|
+
"LD_PRELOAD",
|
|
22
|
+
"LD_LIBRARY_PATH",
|
|
23
|
+
"LD_AUDIT",
|
|
24
|
+
"DYLD_INSERT_LIBRARIES",
|
|
25
|
+
"DYLD_LIBRARY_PATH",
|
|
26
|
+
"NODE_OPTIONS",
|
|
27
|
+
"NODE_PATH",
|
|
28
|
+
"PYTHONPATH",
|
|
29
|
+
"PYTHONHOME",
|
|
30
|
+
"RUBYLIB",
|
|
31
|
+
"PERL5LIB",
|
|
32
|
+
"BASH_ENV",
|
|
33
|
+
"ENV",
|
|
34
|
+
"GCONV_PATH",
|
|
35
|
+
"IFS",
|
|
36
|
+
"SSLKEYLOGFILE",
|
|
37
|
+
]);
|
|
38
|
+
const DANGEROUS_HOST_ENV_PREFIXES = ["DYLD_", "LD_"];
|
|
39
|
+
// Centralized sanitization helper.
|
|
40
|
+
// Throws an error if dangerous variables or PATH modifications are detected on the host.
|
|
41
|
+
function validateHostEnv(env) {
|
|
42
|
+
for (const key of Object.keys(env)) {
|
|
43
|
+
const upperKey = key.toUpperCase();
|
|
44
|
+
// 1. Block known dangerous variables (Fail Closed)
|
|
45
|
+
if (DANGEROUS_HOST_ENV_PREFIXES.some((prefix) => upperKey.startsWith(prefix))) {
|
|
46
|
+
throw new Error(`Security Violation: Environment variable '${key}' is forbidden during host execution.`);
|
|
47
|
+
}
|
|
48
|
+
if (DANGEROUS_HOST_ENV_VARS.has(upperKey)) {
|
|
49
|
+
throw new Error(`Security Violation: Environment variable '${key}' is forbidden during host execution.`);
|
|
50
|
+
}
|
|
51
|
+
// 2. Strictly block PATH modification on host
|
|
52
|
+
// Allowing custom PATH on the gateway/node can lead to binary hijacking.
|
|
53
|
+
if (upperKey === "PATH") {
|
|
54
|
+
throw new Error("Security Violation: Custom 'PATH' variable is forbidden during host execution.");
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
18
58
|
const DEFAULT_MAX_OUTPUT = clampNumber(readEnvInt("PI_BASH_MAX_OUTPUT_CHARS"), 200_000, 1_000, 200_000);
|
|
19
59
|
const DEFAULT_PENDING_MAX_OUTPUT = clampNumber(readEnvInt("OPENCLAW_BASH_PENDING_MAX_OUTPUT_CHARS"), 200_000, 1_000, 200_000);
|
|
20
60
|
const DEFAULT_PATH = process.env.PATH ?? "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
|
|
@@ -668,6 +708,11 @@ export function createExecTool(defaults) {
|
|
|
668
708
|
workdir = resolveWorkdir(rawWorkdir, warnings);
|
|
669
709
|
}
|
|
670
710
|
const baseEnv = coerceEnv(process.env);
|
|
711
|
+
// Logic: Sandbox gets raw env. Host (gateway/node) must pass validation.
|
|
712
|
+
// We validate BEFORE merging to prevent any dangerous vars from entering the stream.
|
|
713
|
+
if (host !== "sandbox" && params.env) {
|
|
714
|
+
validateHostEnv(params.env);
|
|
715
|
+
}
|
|
671
716
|
const mergedEnv = params.env ? { ...baseEnv, ...params.env } : baseEnv;
|
|
672
717
|
const env = sandbox
|
|
673
718
|
? buildSandboxEnv({
|
|
@@ -8,10 +8,6 @@ function normalizePositiveInt(value) {
|
|
|
8
8
|
return int > 0 ? int : null;
|
|
9
9
|
}
|
|
10
10
|
export function resolveContextWindowInfo(params) {
|
|
11
|
-
const fromModel = normalizePositiveInt(params.modelContextWindow);
|
|
12
|
-
if (fromModel) {
|
|
13
|
-
return { tokens: fromModel, source: "model" };
|
|
14
|
-
}
|
|
15
11
|
const fromModelsConfig = (() => {
|
|
16
12
|
const providers = params.cfg?.models?.providers;
|
|
17
13
|
const providerEntry = providers?.[params.provider];
|
|
@@ -19,14 +15,17 @@ export function resolveContextWindowInfo(params) {
|
|
|
19
15
|
const match = models.find((m) => m?.id === params.modelId);
|
|
20
16
|
return normalizePositiveInt(match?.contextWindow);
|
|
21
17
|
})();
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
18
|
+
const fromModel = normalizePositiveInt(params.modelContextWindow);
|
|
19
|
+
const baseInfo = fromModelsConfig
|
|
20
|
+
? { tokens: fromModelsConfig, source: "modelsConfig" }
|
|
21
|
+
: fromModel
|
|
22
|
+
? { tokens: fromModel, source: "model" }
|
|
23
|
+
: { tokens: Math.floor(params.defaultTokens), source: "default" };
|
|
24
|
+
const capTokens = normalizePositiveInt(params.cfg?.agents?.defaults?.contextTokens);
|
|
25
|
+
if (capTokens && capTokens < baseInfo.tokens) {
|
|
26
|
+
return { tokens: capTokens, source: "agentContextTokens" };
|
|
28
27
|
}
|
|
29
|
-
return
|
|
28
|
+
return baseInfo;
|
|
30
29
|
}
|
|
31
30
|
export function evaluateContextWindowGuard(params) {
|
|
32
31
|
const warnBelow = Math.max(1, Math.floor(params.warnBelowTokens ?? CONTEXT_WINDOW_WARN_BELOW_TOKENS));
|
|
@@ -54,6 +54,7 @@ export function createOpenClawTools(options) {
|
|
|
54
54
|
currentThreadTs: options?.currentThreadTs,
|
|
55
55
|
replyToMode: options?.replyToMode,
|
|
56
56
|
hasRepliedRef: options?.hasRepliedRef,
|
|
57
|
+
sandboxRoot: options?.sandboxRoot,
|
|
57
58
|
}),
|
|
58
59
|
createTtsTool({
|
|
59
60
|
agentChannel: options?.agentChannel,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createAgentSession,
|
|
1
|
+
import { createAgentSession, estimateTokens, SessionManager, SettingsManager, } from "@mariozechner/pi-coding-agent";
|
|
2
2
|
import fs from "node:fs/promises";
|
|
3
3
|
import os from "node:os";
|
|
4
4
|
import { resolveHeartbeatPrompt } from "../../auto-reply/heartbeat.js";
|
|
@@ -38,7 +38,7 @@ import { log } from "./logger.js";
|
|
|
38
38
|
import { buildModelAliasLines, resolveModel } from "./model.js";
|
|
39
39
|
import { buildEmbeddedSandboxInfo } from "./sandbox-info.js";
|
|
40
40
|
import { prewarmSessionFile, trackSessionManagerAccess } from "./session-manager-cache.js";
|
|
41
|
-
import { buildEmbeddedSystemPrompt, createSystemPromptOverride } from "./system-prompt.js";
|
|
41
|
+
import { applySystemPromptOverrideToSession, buildEmbeddedSystemPrompt, createSystemPromptOverride, } from "./system-prompt.js";
|
|
42
42
|
import { splitSdkTools } from "./tool-split.js";
|
|
43
43
|
import { describeUnknownError, mapThinkingLevel, resolveExecToolDefaults } from "./utils.js";
|
|
44
44
|
/**
|
|
@@ -273,7 +273,7 @@ export async function compactEmbeddedPiSessionDirect(params) {
|
|
|
273
273
|
userTimeFormat,
|
|
274
274
|
contextFiles,
|
|
275
275
|
});
|
|
276
|
-
const
|
|
276
|
+
const systemPromptOverride = createSystemPromptOverride(appendPrompt);
|
|
277
277
|
const sessionLock = await acquireSessionWriteLock({
|
|
278
278
|
sessionFile: params.sessionFile,
|
|
279
279
|
});
|
|
@@ -306,16 +306,6 @@ export async function compactEmbeddedPiSessionDirect(params) {
|
|
|
306
306
|
tools,
|
|
307
307
|
sandboxEnabled: !!sandbox?.enabled,
|
|
308
308
|
});
|
|
309
|
-
const resourceLoader = new DefaultResourceLoader({
|
|
310
|
-
cwd: resolvedWorkspace,
|
|
311
|
-
agentDir,
|
|
312
|
-
settingsManager,
|
|
313
|
-
additionalExtensionPaths,
|
|
314
|
-
noSkills: true,
|
|
315
|
-
systemPromptOverride: systemPrompt,
|
|
316
|
-
agentsFilesOverride: () => ({ agentsFiles: [] }),
|
|
317
|
-
});
|
|
318
|
-
await resourceLoader.reload();
|
|
319
309
|
const { session } = await createAgentSession({
|
|
320
310
|
cwd: resolvedWorkspace,
|
|
321
311
|
agentDir,
|
|
@@ -325,10 +315,11 @@ export async function compactEmbeddedPiSessionDirect(params) {
|
|
|
325
315
|
thinkingLevel: mapThinkingLevel(params.thinkLevel),
|
|
326
316
|
tools: builtInTools,
|
|
327
317
|
customTools,
|
|
318
|
+
additionalExtensionPaths,
|
|
328
319
|
sessionManager,
|
|
329
320
|
settingsManager,
|
|
330
|
-
resourceLoader,
|
|
331
321
|
});
|
|
322
|
+
applySystemPromptOverrideToSession(session, systemPromptOverride);
|
|
332
323
|
try {
|
|
333
324
|
const prior = await sanitizeSessionHistory({
|
|
334
325
|
messages: session.messages,
|
|
@@ -53,8 +53,16 @@ export function buildEmbeddedExtensionPaths(params) {
|
|
|
53
53
|
const paths = [];
|
|
54
54
|
if (resolveCompactionMode(params.cfg) === "safeguard") {
|
|
55
55
|
const compactionCfg = params.cfg?.agents?.defaults?.compaction;
|
|
56
|
+
const contextWindowInfo = resolveContextWindowInfo({
|
|
57
|
+
cfg: params.cfg,
|
|
58
|
+
provider: params.provider,
|
|
59
|
+
modelId: params.modelId,
|
|
60
|
+
modelContextWindow: params.model?.contextWindow,
|
|
61
|
+
defaultTokens: DEFAULT_CONTEXT_TOKENS,
|
|
62
|
+
});
|
|
56
63
|
setCompactionSafeguardRuntime(params.sessionManager, {
|
|
57
64
|
maxHistoryShare: compactionCfg?.maxHistoryShare,
|
|
65
|
+
contextWindowTokens: contextWindowInfo.tokens,
|
|
58
66
|
});
|
|
59
67
|
paths.push(resolvePiExtensionPath("compaction-safeguard"));
|
|
60
68
|
}
|
|
@@ -13,6 +13,7 @@ export declare function resolveExtraParams(params: {
|
|
|
13
13
|
}): Record<string, unknown> | undefined;
|
|
14
14
|
/**
|
|
15
15
|
* Apply extra params (like temperature) to an agent's streamFn.
|
|
16
|
+
* Also adds OpenRouter app attribution headers when using the OpenRouter provider.
|
|
16
17
|
*
|
|
17
18
|
* @internal Exported for testing
|
|
18
19
|
*/
|
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { streamSimple } from "@mariozechner/pi-ai";
|
|
2
2
|
import { log } from "./logger.js";
|
|
3
|
+
const OPENROUTER_APP_HEADERS = {
|
|
4
|
+
"HTTP-Referer": "https://openclaw.ai",
|
|
5
|
+
"X-Title": "OpenClaw",
|
|
6
|
+
};
|
|
3
7
|
/**
|
|
4
8
|
* Resolve provider-specific extra params from model config.
|
|
5
9
|
* Used to pass through stream params like temperature/maxTokens.
|
|
@@ -11,20 +15,35 @@ export function resolveExtraParams(params) {
|
|
|
11
15
|
const modelConfig = params.cfg?.agents?.defaults?.models?.[modelKey];
|
|
12
16
|
return modelConfig?.params ? { ...modelConfig.params } : undefined;
|
|
13
17
|
}
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
18
|
+
/**
|
|
19
|
+
* Resolve cacheRetention from extraParams, supporting both new `cacheRetention`
|
|
20
|
+
* and legacy `cacheControlTtl` values for backwards compatibility.
|
|
21
|
+
*
|
|
22
|
+
* Mapping: "5m" → "short", "1h" → "long"
|
|
23
|
+
*
|
|
24
|
+
* Only applies to Anthropic provider (OpenRouter uses openai-completions API
|
|
25
|
+
* with hardcoded cache_control, not the cacheRetention stream option).
|
|
26
|
+
*/
|
|
27
|
+
function resolveCacheRetention(extraParams, provider) {
|
|
28
|
+
if (provider !== "anthropic") {
|
|
17
29
|
return undefined;
|
|
18
30
|
}
|
|
19
|
-
|
|
20
|
-
|
|
31
|
+
// Prefer new cacheRetention if present
|
|
32
|
+
const newVal = extraParams?.cacheRetention;
|
|
33
|
+
if (newVal === "none" || newVal === "short" || newVal === "long") {
|
|
34
|
+
return newVal;
|
|
35
|
+
}
|
|
36
|
+
// Fall back to legacy cacheControlTtl with mapping
|
|
37
|
+
const legacy = extraParams?.cacheControlTtl;
|
|
38
|
+
if (legacy === "5m") {
|
|
39
|
+
return "short";
|
|
21
40
|
}
|
|
22
|
-
if (
|
|
23
|
-
return
|
|
41
|
+
if (legacy === "1h") {
|
|
42
|
+
return "long";
|
|
24
43
|
}
|
|
25
44
|
return undefined;
|
|
26
45
|
}
|
|
27
|
-
function createStreamFnWithExtraParams(baseStreamFn, extraParams, provider
|
|
46
|
+
function createStreamFnWithExtraParams(baseStreamFn, extraParams, provider) {
|
|
28
47
|
if (!extraParams || Object.keys(extraParams).length === 0) {
|
|
29
48
|
return undefined;
|
|
30
49
|
}
|
|
@@ -35,9 +54,9 @@ function createStreamFnWithExtraParams(baseStreamFn, extraParams, provider, mode
|
|
|
35
54
|
if (typeof extraParams.maxTokens === "number") {
|
|
36
55
|
streamParams.maxTokens = extraParams.maxTokens;
|
|
37
56
|
}
|
|
38
|
-
const
|
|
39
|
-
if (
|
|
40
|
-
streamParams.
|
|
57
|
+
const cacheRetention = resolveCacheRetention(extraParams, provider);
|
|
58
|
+
if (cacheRetention) {
|
|
59
|
+
streamParams.cacheRetention = cacheRetention;
|
|
41
60
|
}
|
|
42
61
|
if (Object.keys(streamParams).length === 0) {
|
|
43
62
|
return undefined;
|
|
@@ -50,8 +69,23 @@ function createStreamFnWithExtraParams(baseStreamFn, extraParams, provider, mode
|
|
|
50
69
|
});
|
|
51
70
|
return wrappedStreamFn;
|
|
52
71
|
}
|
|
72
|
+
/**
|
|
73
|
+
* Create a streamFn wrapper that adds OpenRouter app attribution headers.
|
|
74
|
+
* These headers allow OpenClaw to appear on OpenRouter's leaderboard.
|
|
75
|
+
*/
|
|
76
|
+
function createOpenRouterHeadersWrapper(baseStreamFn) {
|
|
77
|
+
const underlying = baseStreamFn ?? streamSimple;
|
|
78
|
+
return (model, context, options) => underlying(model, context, {
|
|
79
|
+
...options,
|
|
80
|
+
headers: {
|
|
81
|
+
...OPENROUTER_APP_HEADERS,
|
|
82
|
+
...options?.headers,
|
|
83
|
+
},
|
|
84
|
+
});
|
|
85
|
+
}
|
|
53
86
|
/**
|
|
54
87
|
* Apply extra params (like temperature) to an agent's streamFn.
|
|
88
|
+
* Also adds OpenRouter app attribution headers when using the OpenRouter provider.
|
|
55
89
|
*
|
|
56
90
|
* @internal Exported for testing
|
|
57
91
|
*/
|
|
@@ -65,9 +99,13 @@ export function applyExtraParamsToAgent(agent, cfg, provider, modelId, extraPara
|
|
|
65
99
|
? Object.fromEntries(Object.entries(extraParamsOverride).filter(([, value]) => value !== undefined))
|
|
66
100
|
: undefined;
|
|
67
101
|
const merged = Object.assign({}, extraParams, override);
|
|
68
|
-
const wrappedStreamFn = createStreamFnWithExtraParams(agent.streamFn, merged, provider
|
|
102
|
+
const wrappedStreamFn = createStreamFnWithExtraParams(agent.streamFn, merged, provider);
|
|
69
103
|
if (wrappedStreamFn) {
|
|
70
104
|
log.debug(`applying extraParams to agent streamFn for ${provider}/${modelId}`);
|
|
71
105
|
agent.streamFn = wrappedStreamFn;
|
|
72
106
|
}
|
|
107
|
+
if (provider === "openrouter") {
|
|
108
|
+
log.debug(`applying OpenRouter app attribution headers for ${provider}/${modelId}`);
|
|
109
|
+
agent.streamFn = createOpenRouterHeadersWrapper(agent.streamFn);
|
|
110
|
+
}
|
|
73
111
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { streamSimple } from "@mariozechner/pi-ai";
|
|
2
|
-
import { createAgentSession,
|
|
2
|
+
import { createAgentSession, SessionManager, SettingsManager } from "@mariozechner/pi-coding-agent";
|
|
3
3
|
import fs from "node:fs/promises";
|
|
4
4
|
import os from "node:os";
|
|
5
5
|
import { resolveHeartbeatPrompt } from "../../../auto-reply/heartbeat.js";
|
|
@@ -51,7 +51,7 @@ import { clearActiveEmbeddedRun, setActiveEmbeddedRun, } from "../runs.js";
|
|
|
51
51
|
import { buildEmbeddedSandboxInfo } from "../sandbox-info.js";
|
|
52
52
|
import { prewarmSessionFile, trackSessionManagerAccess } from "../session-manager-cache.js";
|
|
53
53
|
import { prepareSessionManagerForRun } from "../session-manager-init.js";
|
|
54
|
-
import { buildEmbeddedSystemPrompt, createSystemPromptOverride } from "../system-prompt.js";
|
|
54
|
+
import { applySystemPromptOverrideToSession, buildEmbeddedSystemPrompt, createSystemPromptOverride, } from "../system-prompt.js";
|
|
55
55
|
import { splitSdkTools } from "../tool-split.js";
|
|
56
56
|
import { describeUnknownError, mapThinkingLevel } from "../utils.js";
|
|
57
57
|
import { detectAndLoadPromptImages } from "./images.js";
|
|
@@ -325,7 +325,8 @@ export async function runEmbeddedAttempt(params) {
|
|
|
325
325
|
skillsPrompt,
|
|
326
326
|
tools,
|
|
327
327
|
});
|
|
328
|
-
const
|
|
328
|
+
const systemPromptOverride = createSystemPromptOverride(appendPrompt);
|
|
329
|
+
const systemPromptText = systemPromptOverride();
|
|
329
330
|
const sessionLock = await acquireSessionWriteLock({
|
|
330
331
|
sessionFile: params.sessionFile,
|
|
331
332
|
});
|
|
@@ -376,19 +377,12 @@ export async function runEmbeddedAttempt(params) {
|
|
|
376
377
|
const clientToolDefs = params.clientTools
|
|
377
378
|
? toClientToolDefinitions(params.clientTools, (toolName, toolParams) => {
|
|
378
379
|
clientToolCallDetected = { name: toolName, params: toolParams };
|
|
380
|
+
}, {
|
|
381
|
+
agentId: sessionAgentId,
|
|
382
|
+
sessionKey: params.sessionKey,
|
|
379
383
|
})
|
|
380
384
|
: [];
|
|
381
385
|
const allCustomTools = [...customTools, ...clientToolDefs];
|
|
382
|
-
const resourceLoader = new DefaultResourceLoader({
|
|
383
|
-
cwd: resolvedWorkspace,
|
|
384
|
-
agentDir,
|
|
385
|
-
settingsManager,
|
|
386
|
-
additionalExtensionPaths,
|
|
387
|
-
noSkills: true,
|
|
388
|
-
systemPromptOverride: systemPrompt,
|
|
389
|
-
agentsFilesOverride: () => ({ agentsFiles: [] }),
|
|
390
|
-
});
|
|
391
|
-
await resourceLoader.reload();
|
|
392
386
|
({ session } = await createAgentSession({
|
|
393
387
|
cwd: resolvedWorkspace,
|
|
394
388
|
agentDir,
|
|
@@ -398,10 +392,11 @@ export async function runEmbeddedAttempt(params) {
|
|
|
398
392
|
thinkingLevel: mapThinkingLevel(params.thinkLevel),
|
|
399
393
|
tools: builtInTools,
|
|
400
394
|
customTools: allCustomTools,
|
|
395
|
+
additionalExtensionPaths,
|
|
401
396
|
sessionManager,
|
|
402
397
|
settingsManager,
|
|
403
|
-
resourceLoader,
|
|
404
398
|
}));
|
|
399
|
+
applySystemPromptOverrideToSession(session, systemPromptOverride);
|
|
405
400
|
if (!session) {
|
|
406
401
|
throw new Error("Embedded agent session missing");
|
|
407
402
|
}
|
|
@@ -433,7 +428,7 @@ export async function runEmbeddedAttempt(params) {
|
|
|
433
428
|
if (cacheTrace) {
|
|
434
429
|
cacheTrace.recordStage("session:loaded", {
|
|
435
430
|
messages: activeSession.messages,
|
|
436
|
-
system:
|
|
431
|
+
system: systemPromptText,
|
|
437
432
|
note: "after session create",
|
|
438
433
|
});
|
|
439
434
|
activeSession.agent.streamFn = cacheTrace.wrapStreamFn(activeSession.agent.streamFn);
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { AgentTool } from "@mariozechner/pi-agent-core";
|
|
2
|
+
import type { AgentSession } from "@mariozechner/pi-coding-agent";
|
|
2
3
|
import type { ResolvedTimeFormat } from "../date-time.js";
|
|
3
4
|
import type { EmbeddedContextFile } from "../pi-embedded-helpers.js";
|
|
4
5
|
import type { EmbeddedSandboxInfo } from "./types.js";
|
|
@@ -45,3 +46,4 @@ export declare function buildEmbeddedSystemPrompt(params: {
|
|
|
45
46
|
contextFiles?: EmbeddedContextFile[];
|
|
46
47
|
}): string;
|
|
47
48
|
export declare function createSystemPromptOverride(systemPrompt: string): (defaultPrompt?: string) => string;
|
|
49
|
+
export declare function applySystemPromptOverrideToSession(session: AgentSession, override: (defaultPrompt?: string) => string): void;
|
|
@@ -31,3 +31,10 @@ export function createSystemPromptOverride(systemPrompt) {
|
|
|
31
31
|
const trimmed = systemPrompt.trim();
|
|
32
32
|
return () => trimmed;
|
|
33
33
|
}
|
|
34
|
+
export function applySystemPromptOverrideToSession(session, override) {
|
|
35
|
+
const prompt = override().trim();
|
|
36
|
+
session.agent.setSystemPrompt(prompt);
|
|
37
|
+
const mutableSession = session;
|
|
38
|
+
mutableSession._baseSystemPrompt = prompt;
|
|
39
|
+
mutableSession._rebuildSystemPrompt = () => prompt;
|
|
40
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export type CompactionSafeguardRuntimeValue = {
|
|
2
2
|
maxHistoryShare?: number;
|
|
3
|
+
contextWindowTokens?: number;
|
|
3
4
|
};
|
|
4
5
|
export declare function setCompactionSafeguardRuntime(sessionManager: unknown, value: CompactionSafeguardRuntimeValue | null): void;
|
|
5
6
|
export declare function getCompactionSafeguardRuntime(sessionManager: unknown): CompactionSafeguardRuntimeValue | null;
|
|
@@ -145,10 +145,11 @@ export default function compactionSafeguardExtension(api) {
|
|
|
145
145
|
};
|
|
146
146
|
}
|
|
147
147
|
try {
|
|
148
|
-
const
|
|
148
|
+
const runtime = getCompactionSafeguardRuntime(ctx.sessionManager);
|
|
149
|
+
const modelContextWindow = resolveContextWindowTokens(model);
|
|
150
|
+
const contextWindowTokens = runtime?.contextWindowTokens ?? modelContextWindow;
|
|
149
151
|
const turnPrefixMessages = preparation.turnPrefixMessages ?? [];
|
|
150
152
|
let messagesToSummarize = preparation.messagesToSummarize;
|
|
151
|
-
const runtime = getCompactionSafeguardRuntime(ctx.sessionManager);
|
|
152
153
|
const maxHistoryShare = runtime?.maxHistoryShare ?? 0.5;
|
|
153
154
|
const tokensBefore = typeof preparation.tokensBefore === "number" && Number.isFinite(preparation.tokensBefore)
|
|
154
155
|
? preparation.tokensBefore
|
|
@@ -3,5 +3,8 @@ import type { ToolDefinition } from "@mariozechner/pi-coding-agent";
|
|
|
3
3
|
import type { ClientToolDefinition } from "./pi-embedded-runner/run/params.js";
|
|
4
4
|
type AnyAgentTool = AgentTool<any, unknown>;
|
|
5
5
|
export declare function toToolDefinitions(tools: AnyAgentTool[]): ToolDefinition[];
|
|
6
|
-
export declare function toClientToolDefinitions(tools: ClientToolDefinition[], onClientToolCall?: (toolName: string, params: Record<string, unknown>) => void
|
|
6
|
+
export declare function toClientToolDefinitions(tools: ClientToolDefinition[], onClientToolCall?: (toolName: string, params: Record<string, unknown>) => void, hookContext?: {
|
|
7
|
+
agentId?: string;
|
|
8
|
+
sessionKey?: string;
|
|
9
|
+
}): ToolDefinition[];
|
|
7
10
|
export {};
|
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import { logDebug, logError } from "../logger.js";
|
|
2
|
+
import { runBeforeToolCallHook } from "./pi-tools.before-tool-call.js";
|
|
2
3
|
import { normalizeToolName } from "./tool-policy.js";
|
|
3
4
|
import { jsonResult } from "./tools/common.js";
|
|
5
|
+
function isPlainObject(value) {
|
|
6
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
7
|
+
}
|
|
4
8
|
function describeToolExecutionError(err) {
|
|
5
9
|
if (err instanceof Error) {
|
|
6
10
|
const message = err.message?.trim() ? err.message : String(err);
|
|
@@ -51,7 +55,7 @@ export function toToolDefinitions(tools) {
|
|
|
51
55
|
}
|
|
52
56
|
// Convert client tools (OpenResponses hosted tools) to ToolDefinition format
|
|
53
57
|
// These tools are intercepted to return a "pending" result instead of executing
|
|
54
|
-
export function toClientToolDefinitions(tools, onClientToolCall) {
|
|
58
|
+
export function toClientToolDefinitions(tools, onClientToolCall, hookContext) {
|
|
55
59
|
return tools.map((tool) => {
|
|
56
60
|
const func = tool.function;
|
|
57
61
|
return {
|
|
@@ -60,9 +64,20 @@ export function toClientToolDefinitions(tools, onClientToolCall) {
|
|
|
60
64
|
description: func.description ?? "",
|
|
61
65
|
parameters: func.parameters,
|
|
62
66
|
execute: async (toolCallId, params, _onUpdate, _ctx, _signal) => {
|
|
67
|
+
const outcome = await runBeforeToolCallHook({
|
|
68
|
+
toolName: func.name,
|
|
69
|
+
params,
|
|
70
|
+
toolCallId,
|
|
71
|
+
ctx: hookContext,
|
|
72
|
+
});
|
|
73
|
+
if (outcome.blocked) {
|
|
74
|
+
throw new Error(outcome.reason);
|
|
75
|
+
}
|
|
76
|
+
const adjustedParams = outcome.params;
|
|
77
|
+
const paramsRecord = isPlainObject(adjustedParams) ? adjustedParams : {};
|
|
63
78
|
// Notify handler that a client tool was called
|
|
64
79
|
if (onClientToolCall) {
|
|
65
|
-
onClientToolCall(func.name,
|
|
80
|
+
onClientToolCall(func.name, paramsRecord);
|
|
66
81
|
}
|
|
67
82
|
// Return a pending result - the client will execute this tool
|
|
68
83
|
return jsonResult({
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { AnyAgentTool } from "./tools/common.js";
|
|
2
|
+
type HookContext = {
|
|
3
|
+
agentId?: string;
|
|
4
|
+
sessionKey?: string;
|
|
5
|
+
};
|
|
6
|
+
type HookOutcome = {
|
|
7
|
+
blocked: true;
|
|
8
|
+
reason: string;
|
|
9
|
+
} | {
|
|
10
|
+
blocked: false;
|
|
11
|
+
params: unknown;
|
|
12
|
+
};
|
|
13
|
+
declare function isPlainObject(value: unknown): value is Record<string, unknown>;
|
|
14
|
+
export declare function runBeforeToolCallHook(args: {
|
|
15
|
+
toolName: string;
|
|
16
|
+
params: unknown;
|
|
17
|
+
toolCallId?: string;
|
|
18
|
+
ctx?: HookContext;
|
|
19
|
+
}): Promise<HookOutcome>;
|
|
20
|
+
export declare function wrapToolWithBeforeToolCallHook(tool: AnyAgentTool, ctx?: HookContext): AnyAgentTool;
|
|
21
|
+
export declare const __testing: {
|
|
22
|
+
runBeforeToolCallHook: typeof runBeforeToolCallHook;
|
|
23
|
+
isPlainObject: typeof isPlainObject;
|
|
24
|
+
};
|
|
25
|
+
export {};
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { createSubsystemLogger } from "../logging/subsystem.js";
|
|
2
|
+
import { getGlobalHookRunner } from "../plugins/hook-runner-global.js";
|
|
3
|
+
import { normalizeToolName } from "./tool-policy.js";
|
|
4
|
+
const log = createSubsystemLogger("agents/tools");
|
|
5
|
+
function isPlainObject(value) {
|
|
6
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
7
|
+
}
|
|
8
|
+
export async function runBeforeToolCallHook(args) {
|
|
9
|
+
const hookRunner = getGlobalHookRunner();
|
|
10
|
+
if (!hookRunner?.hasHooks("before_tool_call")) {
|
|
11
|
+
return { blocked: false, params: args.params };
|
|
12
|
+
}
|
|
13
|
+
const toolName = normalizeToolName(args.toolName || "tool");
|
|
14
|
+
const params = args.params;
|
|
15
|
+
try {
|
|
16
|
+
const normalizedParams = isPlainObject(params) ? params : {};
|
|
17
|
+
const hookResult = await hookRunner.runBeforeToolCall({
|
|
18
|
+
toolName,
|
|
19
|
+
params: normalizedParams,
|
|
20
|
+
}, {
|
|
21
|
+
toolName,
|
|
22
|
+
agentId: args.ctx?.agentId,
|
|
23
|
+
sessionKey: args.ctx?.sessionKey,
|
|
24
|
+
});
|
|
25
|
+
if (hookResult?.block) {
|
|
26
|
+
return {
|
|
27
|
+
blocked: true,
|
|
28
|
+
reason: hookResult.blockReason || "Tool call blocked by plugin hook",
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
if (hookResult?.params && isPlainObject(hookResult.params)) {
|
|
32
|
+
if (isPlainObject(params)) {
|
|
33
|
+
return { blocked: false, params: { ...params, ...hookResult.params } };
|
|
34
|
+
}
|
|
35
|
+
return { blocked: false, params: hookResult.params };
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
catch (err) {
|
|
39
|
+
const toolCallId = args.toolCallId ? ` toolCallId=${args.toolCallId}` : "";
|
|
40
|
+
log.warn(`before_tool_call hook failed: tool=${toolName}${toolCallId} error=${String(err)}`);
|
|
41
|
+
}
|
|
42
|
+
return { blocked: false, params };
|
|
43
|
+
}
|
|
44
|
+
export function wrapToolWithBeforeToolCallHook(tool, ctx) {
|
|
45
|
+
const execute = tool.execute;
|
|
46
|
+
if (!execute) {
|
|
47
|
+
return tool;
|
|
48
|
+
}
|
|
49
|
+
const toolName = tool.name || "tool";
|
|
50
|
+
return {
|
|
51
|
+
...tool,
|
|
52
|
+
execute: async (toolCallId, params, signal, onUpdate) => {
|
|
53
|
+
const outcome = await runBeforeToolCallHook({
|
|
54
|
+
toolName,
|
|
55
|
+
params,
|
|
56
|
+
toolCallId,
|
|
57
|
+
ctx,
|
|
58
|
+
});
|
|
59
|
+
if (outcome.blocked) {
|
|
60
|
+
throw new Error(outcome.reason);
|
|
61
|
+
}
|
|
62
|
+
return await execute(toolCallId, outcome.params, signal, onUpdate);
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
export const __testing = {
|
|
67
|
+
runBeforeToolCallHook,
|
|
68
|
+
isPlainObject,
|
|
69
|
+
};
|
package/dist/agents/pi-tools.js
CHANGED
|
@@ -8,6 +8,7 @@ import { createExecTool, createProcessTool, } from "./bash-tools.js";
|
|
|
8
8
|
import { listChannelAgentTools } from "./channel-tools.js";
|
|
9
9
|
import { createOpenClawTools } from "./openclaw-tools.js";
|
|
10
10
|
import { wrapToolWithAbortSignal } from "./pi-tools.abort.js";
|
|
11
|
+
import { wrapToolWithBeforeToolCallHook } from "./pi-tools.before-tool-call.js";
|
|
11
12
|
import { filterToolsByPolicy, isToolAllowedByPolicies, resolveEffectiveToolPolicy, resolveGroupToolPolicy, resolveSubagentToolPolicy, } from "./pi-tools.policy.js";
|
|
12
13
|
import { assertRequiredParams, CLAUDE_PARAM_GROUPS, createOpenClawReadTool, createSandboxedEditTool, createSandboxedReadTool, createSandboxedWriteTool, normalizeToolParams, patchToolSchemaForClaudeCompatibility, wrapToolParamNormalization, } from "./pi-tools.read.js";
|
|
13
14
|
import { cleanToolSchemaForGemini, normalizeToolParameters } from "./pi-tools.schema.js";
|
|
@@ -294,9 +295,13 @@ export function createOpenClawCodingTools(options) {
|
|
|
294
295
|
// Always normalize tool JSON Schemas before handing them to pi-agent/pi-ai.
|
|
295
296
|
// Without this, some providers (notably OpenAI) will reject root-level union schemas.
|
|
296
297
|
const normalized = subagentFiltered.map(normalizeToolParameters);
|
|
298
|
+
const withHooks = normalized.map((tool) => wrapToolWithBeforeToolCallHook(tool, {
|
|
299
|
+
agentId,
|
|
300
|
+
sessionKey: options?.sessionKey,
|
|
301
|
+
}));
|
|
297
302
|
const withAbort = options?.abortSignal
|
|
298
|
-
?
|
|
299
|
-
:
|
|
303
|
+
? withHooks.map((tool) => wrapToolWithAbortSignal(tool, options.abortSignal))
|
|
304
|
+
: withHooks;
|
|
300
305
|
// NOTE: Keep canonical (lowercase) tool names here.
|
|
301
306
|
// pi-ai's Anthropic OAuth transport remaps tool names to Claude Code-style names
|
|
302
307
|
// on the wire and maps them back for tool dispatch.
|