Skip to content

Commit 0ab6578

Browse files
authored
fix: preserve source code in tool results (#127697)
Preserve opaque source strings across tool-result replay while retaining masking for direct .env reads, registered or recognizable secrets, structured sensitive fields, and payment data.
1 parent 460f5b6 commit 0ab6578

20 files changed

Lines changed: 577 additions & 85 deletions

‎docs/gateway/logging.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,15 @@ Tune console verbosity independently:
5858

5959
OpenClaw masks sensitive tokens before log or transcript output leaves the process. This redaction policy applies at console, file-log, OTLP log-record, and session transcript text sinks, so matching secret values are masked before JSONL lines or messages are written to disk.
6060

61+
Model-visible tool-result text preserves ambiguous source assignments such as
62+
`token = timeObserverToken`. Registered secrets and explicit credential forms,
63+
including structured fields, authorization headers, URL credentials, and known
64+
token formats, remain masked. Direct reads of `.env`
65+
files apply broader assignment masking before their content becomes a tool
66+
result. Other config and source reads preserve opaque values; register actual
67+
secrets instead of relying on key-name matching. Other transcript fields and
68+
diagnostic sinks retain broad assignment matching.
69+
6170
- Sensitive-value redaction is always enabled.
6271
- `logging.redactPatterns`: array of regex strings (overrides defaults)
6372
- Use raw regex strings (auto `gi`), or `/pattern/flags` for custom flags.

‎docs/logging.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,15 @@ masked before the line or message is written to disk. Redaction is best-effort:
315315
it applies to text-bearing message content and log strings, not every
316316
identifier or binary payload field.
317317

318+
Model-visible tool-result text uses narrower assignment matching so source code
319+
remains intact. Registered secrets and explicit credential forms, including
320+
structured fields, authorization headers, URL credentials, and known token
321+
formats, remain masked. Direct reads of `.env` files apply
322+
broader assignment masking before their content becomes a tool result. Other
323+
config and source reads preserve opaque values; register actual secrets instead
324+
of relying on key-name matching. Bare source assignments such as
325+
`token = timeObserverToken` remain unchanged.
326+
318327
The built-in defaults cover common API credentials and payment-credential field
319328
names such as card number, CVC/CVV, shared payment token, and payment credential
320329
when they appear as JSON fields, URL parameters, CLI flags, or assignments.

‎packages/ai/src/host.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -140,8 +140,8 @@ export interface AiTransportHost {
140140
): typeof fetch | undefined;
141141
/** Resolves host-owned process-local secret sentinel substrings immediately before egress. */
142142
resolveSecretSentinel(value: string): string;
143-
/** Redacts secrets inside structured tool-result payloads. */
144-
redactSecrets<T>(value: T): T;
143+
/** Redacts model-visible tool results without treating ordinary source assignments as secrets. */
144+
redactModelVisibleSecrets<T>(value: T): T;
145145
/** Redacts secret-bearing text in tool payload strings. */
146146
redactToolPayloadText(text: string): string;
147147
/** Normalizes Anthropic inline image blocks before provider payload construction. */
@@ -228,7 +228,7 @@ type ActiveAiTransportHost = Omit<AiTransportHost, "normalizeAnthropicInlineCont
228228
const inertAiTransportHost: ActiveAiTransportHost = {
229229
buildModelFetch: () => undefined,
230230
resolveSecretSentinel: (value) => value,
231-
redactSecrets: (value) => value,
231+
redactModelVisibleSecrets: (value) => value,
232232
redactToolPayloadText: (text) => text,
233233
normalizeAnthropicInlineContentBlocks: async (content) => [...content],
234234
resolveOpenAIStrictToolSetting: (_model, options) =>

‎packages/ai/src/providers/mistral.test.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -805,7 +805,8 @@ describe("Mistral provider", () => {
805805
it("serializes structured non-image blocks in tool results as JSON text", async () => {
806806
// Prove the host redaction port is applied to structured tool-result text.
807807
configureAiTransportHost({
808-
redactToolPayloadText: (text) => text.replaceAll('"value"', '"***"'),
808+
redactModelVisibleSecrets: <T>(value: T): T =>
809+
JSON.parse(JSON.stringify(value).replaceAll('"value"', '"***"')) as T,
809810
});
810811
const testContext = makeMistralToolResultContext("fetch", [
811812
{
@@ -827,8 +828,7 @@ describe("Mistral provider", () => {
827828
const toolContent = Array.isArray(toolMessage?.content) ? toolMessage.content : [];
828829
const textBlock = toolContent.find((block) => block.type === "text");
829830
expect(textBlock?.text).toEqual(expect.stringContaining('{"type":"resource"'));
830-
expect(textBlock?.text).toContain('{\\"key\\":\\"***\\"}');
831-
expect(textBlock?.text).not.toContain('{\\"key\\":\\"value\\"}');
831+
expect(textBlock?.text).toContain('{\\"key\\":\\"value\\"}');
832832
});
833833

834834
it("does not emit image chunks or placeholders for payload-less tool media", async () => {

‎packages/ai/src/providers/tool-result-text.ts‎

Lines changed: 5 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -54,25 +54,13 @@ function redactInlineDataUris(value: string): string {
5454
);
5555
}
5656

57-
function redactStructuredTextValue(value: string): string {
58-
const host = getAiTransportHost();
59-
const redacted = host.redactToolPayloadText(value);
60-
const trimmed = redacted.trim();
61-
if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) {
62-
return redacted;
63-
}
64-
try {
65-
const redactedWrapper = host.redactSecrets({ structuredTextValue: JSON.parse(redacted) });
66-
return JSON.stringify(redactedWrapper.structuredTextValue);
67-
} catch {
68-
return redacted;
69-
}
70-
}
71-
7257
function stringifyStructuredBlock(block: Record<string, unknown>): string | undefined {
7358
const seen = new WeakSet<object>();
7459
try {
75-
const redactedWrapper = getAiTransportHost().redactSecrets({ structuredToolResult: block });
60+
const host = getAiTransportHost();
61+
const redactedWrapper = host.redactModelVisibleSecrets({
62+
structuredToolResult: block,
63+
});
7664
const redactedBlock = redactedWrapper.structuredToolResult;
7765
const serialized = JSON.stringify(
7866
redactedBlock,
@@ -90,7 +78,7 @@ function stringifyStructuredBlock(block: Record<string, unknown>): string | unde
9078
return value.toString();
9179
}
9280
if (typeof value === "string") {
93-
return redactInlineDataUris(redactStructuredTextValue(value));
81+
return redactInlineDataUris(host.redactModelVisibleSecrets(value));
9482
}
9583
if (typeof value === "function" || typeof value === "symbol" || value === undefined) {
9684
return undefined;

‎packages/ai/src/transports/anthropic-transport-stream.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -340,7 +340,7 @@ describe("anthropic transport stream", () => {
340340
configureAiTransportHost({
341341
...coreTransportHost,
342342
buildModelFetch: buildGuardedModelFetchMock,
343-
redactSecrets: redactTestSecrets,
343+
redactModelVisibleSecrets: redactTestSecrets,
344344
resolveProviderRequestCapabilities: (input) => {
345345
const endpointClass = resolveTestEndpointClass(input.baseUrl);
346346
return {
@@ -3780,7 +3780,7 @@ describe("anthropic transport stream", () => {
37803780
// No images → returns sanitized text string, not array
37813781
expect(typeof toolResult.content).toBe("string");
37823782
expect(toolResult.content).toContain('"type":"resource"');
3783-
expect(toolResult.content).toContain('{\\"key\\":\\"***\\"}');
3783+
expect(toolResult.content).toContain('{\\"key\\":\\"value\\"}');
37843784
expect(toolResult.is_error).toBe(false);
37853785
});
37863786

‎src/agents/agent-tools.create-openclaw-coding-tools.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3089,6 +3089,38 @@ describe("createOpenClawCodingTools read behavior", () => {
30893089
expect(details?.truncation?.firstLineExceedsLimit).toBe(false);
30903090
expect(details?.truncation).not.toHaveProperty("content");
30913091
});
3092+
3093+
it("redacts env files while preserving config and source reads", async () => {
3094+
const credential = "unquoted-config-credential-1234567890";
3095+
const source = "API_TOKEN = computeToken()";
3096+
const execute = vi.fn(async (_toolCallId: string, args: { path: string }) => {
3097+
const text =
3098+
args.path.endsWith(".ts") || args.path.endsWith(".envrc")
3099+
? source
3100+
: `api_key: ${credential}`;
3101+
return {
3102+
content: [{ type: "text" as const, text }],
3103+
details: { kind: "text", content: text },
3104+
};
3105+
});
3106+
const readTool = createOpenClawReadTool({
3107+
name: "read",
3108+
label: "read",
3109+
description: "test read",
3110+
parameters: Type.Object({ path: Type.String() }),
3111+
execute,
3112+
});
3113+
3114+
const yamlResult = await readTool.execute("read-yaml", { path: "settings.yaml" });
3115+
const envResult = await readTool.execute("read-env", { path: "production.env" });
3116+
const sourceResult = await readTool.execute("read-source", { path: "settings.ts" });
3117+
const envrcResult = await readTool.execute("read-envrc", { path: ".envrc" });
3118+
3119+
expect(extractToolText(yamlResult)).toBe(`api_key: ${credential}`);
3120+
expect(extractToolText(envResult)).not.toContain(credential);
3121+
expect(extractToolText(sourceResult)).toBe(source);
3122+
expect(extractToolText(envrcResult)).toBe(source);
3123+
});
30923124
});
30933125

30943126
const DEFAULT_TOOLS = [

‎src/agents/agent-tools.read.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
} from "../infra/fs-safe.js";
1919
import { hasEncodedFileUrlSeparator, trySafeFileURLToPath } from "../infra/local-file-access.js";
2020
import { decodeWindowsTextFileBuffer } from "../infra/windows-encoding.js";
21+
import { redactSecrets } from "../logging/redact.js";
2122
import {
2223
classifyMediaReferenceSource,
2324
normalizeMediaReferenceSource,
@@ -69,6 +70,8 @@ const MAX_ADAPTIVE_READ_MAX_BYTES = 128 * 1024;
6970
const ADAPTIVE_READ_CONTEXT_SHARE = 0.1;
7071
const CHARS_PER_TOKEN_ESTIMATE = 4;
7172
const MAX_ADAPTIVE_READ_PAGES = 4;
73+
// `.env` files are credential stores; `.envrc` and general config files remain source-shaped.
74+
const ENV_FILE_PATH_RE = /(?:^|[/\\])(?:\.env(?:\.[^/\\]+)?|[^/\\]+\.env)$/i;
7275

7376
type OpenClawReadToolOptions = {
7477
modelContextWindowTokens?: number;
@@ -1055,7 +1058,10 @@ export function createOpenClawReadTool(
10551058
`read:${filePath}`,
10561059
options?.imageSanitization,
10571060
);
1058-
return normalizeReadResultDetails(sanitizedResult);
1061+
const modelVisibleResult = ENV_FILE_PATH_RE.test(filePath)
1062+
? { ...sanitizedResult, content: redactSecrets(sanitizedResult.content) }
1063+
: sanitizedResult;
1064+
return normalizeReadResultDetails(modelVisibleResult);
10591065
},
10601066
};
10611067
}

‎src/agents/embedded-agent-subscribe.tools.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -391,9 +391,29 @@ describe("sanitizeToolResult", () => {
391391

392392
it("redacts primitive string results", () => {
393393
const sanitized = sanitizeToolResult("OPENROUTER_API_KEY=sk-or-v1-abcdef0123456789") as string;
394+
const source = "if let token = timeObserverToken {";
394395

395396
expect(sanitized).not.toContain("sk-or-v1-abcdef0123456789");
396397
expect(sanitized).toContain("OPENROUTER_API_KEY=");
398+
expect(sanitizeToolResult(source)).toBe(source);
399+
});
400+
401+
it("preserves source assignments in structured results while redacting credential fields", () => {
402+
const source = "if let token = timeObserverToken {";
403+
const credential = "sk-1234567890abcdefXYZ";
404+
const sanitized = sanitizeToolResult({
405+
content: [{ type: "text", text: source }],
406+
detail: source,
407+
token: credential,
408+
}) as {
409+
content: Array<{ text: string }>;
410+
detail: string;
411+
token: string;
412+
};
413+
414+
expect(sanitized.content[0]?.text).toBe(source);
415+
expect(sanitized.detail).toBe(source);
416+
expect(sanitized.token).not.toContain(credential);
397417
});
398418

399419
it("preserves top-level arrays while redacting nested strings", () => {

‎src/agents/embedded-agent-tool-results.ts‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@ import {
77
readStringValue,
88
} from "@openclaw/normalization-core/string-coerce";
99
import {
10-
redactSecrets,
10+
redactModelVisibleSecrets,
11+
redactModelVisibleSensitiveFieldValueWithConfig,
12+
redactModelVisibleToolPayloadText,
1113
redactSensitiveFieldValue,
1214
redactToolPayloadText,
1315
} from "../logging/redact.js";
@@ -248,10 +250,10 @@ export function sanitizeToolArgs(args: unknown): unknown {
248250

249251
export function sanitizeToolResult(result: unknown): unknown {
250252
if (typeof result === "string") {
251-
return redactToolPayloadText(result);
253+
return redactModelVisibleToolPayloadText(result);
252254
}
253255
if (Array.isArray(result)) {
254-
return redactSecrets(result);
256+
return redactModelVisibleSecrets(result);
255257
}
256258
if (!result || typeof result !== "object") {
257259
return result;
@@ -280,7 +282,7 @@ export function sanitizeToolResult(result: unknown): unknown {
280282
}
281283
// Deep-redact the entire result so any top-level or nested string is
282284
// protected, not just `details` and text content blocks.
283-
const baseline = redactSecrets(preCleaned);
285+
const baseline = redactModelVisibleSecrets(preCleaned);
284286
const out: Record<string, unknown> = { ...baseline };
285287
const content = Array.isArray(baseline.content) ? baseline.content : null;
286288
if (content) {
@@ -340,7 +342,9 @@ function sanitizeStructuredToolResultValue(
340342
if (OPAQUE_STRUCTURED_RESULT_FIELDS.has(key)) {
341343
return `[opaque data omitted: ${value.length} chars]`;
342344
}
343-
return truncateToolText(redactInlineDataUriValue(redactSensitiveFieldValue(key, value)));
345+
return truncateToolText(
346+
redactInlineDataUriValue(redactModelVisibleSensitiveFieldValueWithConfig(key, value)),
347+
);
344348
}
345349
if (typeof value === "bigint") {
346350
return value.toString();
@@ -379,7 +383,7 @@ function stringifyStructuredToolResultContent(block: unknown): string | undefine
379383
}
380384
try {
381385
const serialized = JSON.stringify(sanitizeStructuredToolResultValue(record));
382-
const redacted = serialized ? redactToolPayloadText(serialized) : serialized;
386+
const redacted = serialized ? redactModelVisibleToolPayloadText(serialized) : serialized;
383387
return redacted && redacted !== "{}" ? redacted : undefined;
384388
} catch {
385389
return undefined;
@@ -406,7 +410,7 @@ function resolveToolResultContentBlocks(result: object): unknown[] {
406410

407411
export function extractToolResultText(result: unknown): string | undefined {
408412
if (typeof result === "string") {
409-
const trimmed = redactToolPayloadText(redactInlineDataUriValue(result)).trim();
413+
const trimmed = redactModelVisibleToolPayloadText(redactInlineDataUriValue(result)).trim();
410414
return trimmed ? truncateToolText(trimmed) : undefined;
411415
}
412416
if (!result || typeof result !== "object") {

0 commit comments

Comments
 (0)