Skip to content

Commit bb68ad0

Browse files
authored
refactor(types): drain chained-assertion ledger β€” agents (#124354)
* refactor(types): drain chained-assertion ledger β€” agents * fix(agents): preserve non-configurable stream iterators * refactor(agents): call provider failover hook directly
1 parent 527d155 commit bb68ad0

8 files changed

Lines changed: 155 additions & 41 deletions

File tree

β€Žscripts/oxlint-boundary-guards.mjsβ€Ž

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -666,7 +666,17 @@ export default {
666666
"packages/ai",
667667
"src/acp/client.ts", // Node and Web ReadableStream types live in separate namespaces.
668668
"src/acp/server.ts", // Node and Web ReadableStream types live in separate namespaces.
669-
"src/agents",
669+
"src/agents/agent-hooks/compaction-safeguard.ts", // AgentMessage custom roles exceed the Copilot header message contract.
670+
"src/agents/agent-model-discovery.ts", // Persisted registry rows need a fully resolved model parser owner.
671+
"src/agents/embedded-agent-helpers/images.ts", // Assistant blocks cross the tool-image sanitizer's narrower block namespace.
672+
"src/agents/embedded-agent-runner/run/attempt-stream.ts", // Synthetic yield stream metadata is wider than the provider model contract.
673+
"src/agents/embedded-agent-runner/run/images.ts", // Provider-only video blocks cross the canonical AgentMessage namespace.
674+
"src/agents/mcp-http-fetch.ts", // Undici Response crosses the DOM FetchLike type namespace.
675+
"src/agents/model-auth-model.ts", // Null Authorization sentinel crosses the SDK's string-only header type.
676+
"src/agents/model-provider-auth.ts", // Route-fact cache keys cross a config-only hash API.
677+
"src/agents/modes/interactive/theme/theme.ts", // Global symbol registry and Proxy receiver bridge duplicate module copies.
678+
"src/agents/subagents/spawn/subagent-depth.ts", // Generic session projections cross the fixed accessor entry type.
679+
"src/agents/tool-search-transcript.ts", // Synthetic target turns omit provider-owned assistant metadata.
670680
"src/channels/plugins/config-schema.ts", // Public SDK Zod generics preserve caller schema identity.
671681
"src/commands/channel-test-registry.ts", // Test support.
672682
"src/commands/doctor/cron/legacy-repair.ts", // Partially validated legacy rows cross the canonical cron store type.
@@ -683,7 +693,9 @@ export default {
683693
"src/infra/net/runtime-fetch.ts", // Undici and DOM fetch types live in separate namespaces.
684694
"src/infra/state-migrations.meeting-transcripts-files.ts", // Legacy summary validation does not prove element types.
685695
"src/infra/unhandled-rejections.ts", // Global symbol registry crosses module copies.
686-
"src/meeting-bot",
696+
"src/meeting-bot/browser-controller.ts", // Generic health fallbacks cannot construct arbitrary platform subtypes.
697+
"src/meeting-bot/platform-adapter.ts", // Generic parsers add adapter-owned health and transcript fields.
698+
"src/meeting-bot/plugin-shell.ts", // Type-only plugin namespace factory has no runtime value.
687699
"src/plugin-sdk/channel-config-helpers.ts", // Public SDK accessor generics are intentionally decoupled.
688700
"src/plugin-sdk/provider-stream-shared.ts", // Untyped normalizer events need a transport stream API redesign.
689701
"src/plugin-sdk/qa-runtime.ts", // Public SDK lazy module exposes a narrower runtime surface.

β€Žsrc/agents/agent-tools.read.tsβ€Ž

Lines changed: 58 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import path from "node:path";
77
import { URL } from "node:url";
88
import { detectMime } from "@openclaw/media-core/mime";
99
import { formatByteSize } from "@openclaw/normalization-core";
10+
import type { Static, TSchema } from "typebox";
11+
import { Value } from "typebox/value";
1012
import { isWindowsDrivePath } from "../infra/archive-path.js";
1113
import { isMissingPathError, toErrorObject } from "../infra/errors.js";
1214
import {
@@ -38,7 +40,7 @@ import {
3840
withMemoryWriteProvenance,
3941
} from "./memory-write-provenance.js";
4042
import { toRelativeWorkspacePath } from "./path-policy.js";
41-
import type { AgentToolResult } from "./runtime/index.js";
43+
import type { AgentTool, AgentToolResult } from "./runtime/index.js";
4244
import { assertSandboxPath } from "./sandbox-paths.js";
4345
import type { SandboxFsBridge } from "./sandbox/fs-bridge.js";
4446
import {
@@ -73,6 +75,27 @@ type SkillReadContent = {
7375
readContent?: string;
7476
};
7577

78+
/** Erase a schema-specific session tool only after its input passes that owned schema. */
79+
function eraseSessionFileTool<TParameters extends TSchema, TDetails>(
80+
tool: AgentTool<TParameters, TDetails>,
81+
): AnyAgentTool {
82+
return {
83+
...tool,
84+
execute: async (toolCallId, params, signal, onUpdate) => {
85+
if (!Value.Check(tool.parameters, params)) {
86+
throw new Error(`Invalid parameters for ${tool.name}`);
87+
}
88+
const typedParams = params as Static<TParameters>;
89+
return await tool.execute(
90+
toolCallId,
91+
typedParams,
92+
signal,
93+
onUpdate ? (update) => onUpdate(update) : undefined,
94+
);
95+
},
96+
};
97+
}
98+
7699
type ReadTruncationDetails = {
77100
truncated: boolean;
78101
outputLines: number;
@@ -885,9 +908,11 @@ type SandboxToolParams = {
885908
export function createSandboxedReadTool(
886909
params: SandboxToolParams & { createTool?: typeof createReadTool },
887910
) {
888-
const base = (params.createTool ?? createReadTool)(params.root, {
889-
operations: createSandboxReadOperations(params),
890-
}) as unknown as AnyAgentTool;
911+
const base = eraseSessionFileTool(
912+
(params.createTool ?? createReadTool)(params.root, {
913+
operations: createSandboxReadOperations(params),
914+
}),
915+
);
891916
return createOpenClawReadTool(base, {
892917
modelContextWindowTokens: params.modelContextWindowTokens,
893918
imageSanitization: params.imageSanitization,
@@ -898,19 +923,23 @@ export function createSandboxedReadTool(
898923
export function createSandboxedWriteTool(
899924
params: SandboxToolParams & { createTool?: typeof createWriteTool },
900925
) {
901-
const base = (params.createTool ?? createWriteTool)(params.root, {
902-
operations: createSandboxWriteOperations(params),
903-
}) as unknown as AnyAgentTool;
926+
const base = eraseSessionFileTool(
927+
(params.createTool ?? createWriteTool)(params.root, {
928+
operations: createSandboxWriteOperations(params),
929+
}),
930+
);
904931
return wrapToolParamValidation(base, REQUIRED_PARAM_GROUPS.write);
905932
}
906933

907934
/** Create a sandbox-backed edit tool with required-parameter validation. */
908935
export function createSandboxedEditTool(
909936
params: SandboxToolParams & { createTool?: typeof createEditTool },
910937
) {
911-
const base = (params.createTool ?? createEditTool)(params.root, {
912-
operations: createSandboxEditOperations(params),
913-
}) as unknown as AnyAgentTool;
938+
const base = eraseSessionFileTool(
939+
(params.createTool ?? createEditTool)(params.root, {
940+
operations: createSandboxEditOperations(params),
941+
}),
942+
);
914943
return wrapToolParamValidation(base, REQUIRED_PARAM_GROUPS.edit);
915944
}
916945

@@ -923,9 +952,11 @@ export function createHostWorkspaceWriteTool(
923952
createTool?: typeof createWriteTool;
924953
},
925954
) {
926-
const base = (options?.createTool ?? createWriteTool)(root, {
927-
operations: createHostWriteOperations(root, options),
928-
}) as unknown as AnyAgentTool;
955+
const base = eraseSessionFileTool(
956+
(options?.createTool ?? createWriteTool)(root, {
957+
operations: createHostWriteOperations(root, options),
958+
}),
959+
);
929960
return wrapToolParamValidation(base, REQUIRED_PARAM_GROUPS.write);
930961
}
931962

@@ -938,9 +969,11 @@ export function createHostWorkspaceEditTool(
938969
createTool?: typeof createEditTool;
939970
},
940971
) {
941-
const base = (options?.createTool ?? createEditTool)(root, {
942-
operations: createHostEditOperations(root, options),
943-
}) as unknown as AnyAgentTool;
972+
const base = eraseSessionFileTool(
973+
(options?.createTool ?? createEditTool)(root, {
974+
operations: createHostEditOperations(root, options),
975+
}),
976+
);
944977
return wrapToolParamValidation(base, REQUIRED_PARAM_GROUPS.edit);
945978
}
946979

@@ -1003,13 +1036,15 @@ export function wrapReadToolWithSkillContent(
10031036
}
10041037
return content;
10051038
};
1006-
const virtualBase = createReadTool("/", {
1007-
operations: {
1008-
resolvePath: (filePath) => filePath,
1009-
access: async (filePath) => void readContent(filePath),
1010-
readFile: async (filePath) => Buffer.from(readContent(filePath), "utf8"),
1011-
},
1012-
}) as unknown as AnyAgentTool;
1039+
const virtualBase = eraseSessionFileTool(
1040+
createReadTool("/", {
1041+
operations: {
1042+
resolvePath: (filePath) => filePath,
1043+
access: async (filePath) => void readContent(filePath),
1044+
readFile: async (filePath) => Buffer.from(readContent(filePath), "utf8"),
1045+
},
1046+
}),
1047+
);
10131048
const virtualRead = createOpenClawReadTool(virtualBase, options);
10141049
return {
10151050
...tool,

β€Žsrc/agents/embedded-agent-runner/run/attempt-prompt-support.tsβ€Ž

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,13 @@ type PromptBuildToolPolicyBaseline = {
5252
catalogEntries: readonly ToolSearchCatalogEntry[];
5353
};
5454

55+
function readNamedToolPluginMeta(tool: NamedTool): { pluginId: string } | undefined {
56+
if (!("execute" in tool) || typeof tool.execute !== "function") {
57+
return undefined;
58+
}
59+
return getPluginToolMeta(tool as AnyAgentTool);
60+
}
61+
5562
export function applyResolvedToolPromptFinalizer(params: {
5663
prompt: string;
5764
activeToolNames: readonly string[];
@@ -71,8 +78,7 @@ export function applyResolvedToolPromptFinalizer(params: {
7178
function filterTools<T extends NamedTool>(
7279
tools: readonly T[],
7380
toolsAllow: string[],
74-
toolMeta: (tool: T) => { pluginId: string } | undefined = (tool) =>
75-
getPluginToolMeta(tool as unknown as AnyAgentTool),
81+
toolMeta: (tool: T) => { pluginId: string } | undefined = readNamedToolPluginMeta,
7682
): T[] {
7783
return applyEmbeddedAttemptToolsAllow([...tools], toolsAllow, {
7884
toolMeta,

β€Žsrc/agents/embedded-agent-runner/run/attempt-tool-call-text-promotion.test.tsβ€Ž

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,37 @@ async function collectStreamEvents(stream: AsyncIterable<unknown>): Promise<unkn
4040
const requireRecord = createRequireRecord("object", "expected-label");
4141

4242
describe("wrapStreamFnPromoteStandaloneTextToolCalls", () => {
43+
it("supports writable non-configurable stream iterators", async () => {
44+
const resultMessage = {
45+
role: "assistant",
46+
content: [{ type: "text", text: "plain response" }],
47+
stopReason: "stop",
48+
};
49+
const baseStream = createFakeStream({
50+
events: [{ type: "done", reason: "stop", message: resultMessage }],
51+
resultMessage,
52+
});
53+
const iterator = baseStream[Symbol.asyncIterator];
54+
Object.defineProperty(baseStream, Symbol.asyncIterator, {
55+
configurable: false,
56+
value: iterator,
57+
writable: true,
58+
});
59+
const wrapped = wrapStreamFnPromoteStandaloneTextToolCalls(
60+
(() => baseStream) as never,
61+
new Set(["exec"]),
62+
);
63+
64+
const stream = (await Promise.resolve(
65+
wrapped({} as never, {} as never, {} as never),
66+
)) as FakeWrappedStream;
67+
68+
await expect(collectStreamEvents(stream)).resolves.toEqual([
69+
{ type: "done", reason: "stop", message: resultMessage },
70+
]);
71+
await expect(stream.result()).resolves.toEqual(resultMessage);
72+
});
73+
4374
it("preserves a fenced allowed-tool example in live and terminal output", async () => {
4475
const parts = ["`", "``json\n", "[re", 'ad]\n{"path":"example.txt"}\n[/read]\n', "```"];
4576
const rawText = parts.join("");

β€Žsrc/agents/embedded-agent-runner/run/attempt-tool-call-text-promotion.tsβ€Ž

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -112,9 +112,7 @@ function wrapStreamPromoteStandaloneTextToolCalls(
112112
};
113113

114114
const originalAsyncIterator = stream[Symbol.asyncIterator].bind(stream);
115-
(stream as unknown as { [Symbol.asyncIterator]: () => AsyncIterator<unknown> })[
116-
Symbol.asyncIterator
117-
] = async function* () {
115+
const wrappedAsyncIterator = async function* () {
118116
const source = {
119117
[Symbol.asyncIterator]: originalAsyncIterator,
120118
} as AsyncIterable<unknown>;
@@ -125,6 +123,9 @@ function wrapStreamPromoteStandaloneTextToolCalls(
125123
resolveProtectedRanges: findCodeRegions,
126124
});
127125
};
126+
if (!Reflect.set(stream, Symbol.asyncIterator, wrappedAsyncIterator)) {
127+
throw new TypeError("Cannot replace stream async iterator");
128+
}
128129

129130
return stream;
130131
}

β€Žsrc/agents/failover/provider-patterns.tsβ€Ž

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import { matchesContextOverflowMessage } from "@openclaw/ai/internal/runtime";
2+
import { isRecord } from "@openclaw/normalization-core/record-coerce";
23
import { resolveNodeRequireFromMeta } from "../../logging/node-require.js";
34
import { isRateLimitErrorMessage } from "./message-patterns.js";
4-
import type { FailoverReason } from "./signal.js";
5+
import { FAILOVER_REASONS, type FailoverReason } from "./signal.js";
56
type ProviderErrorPattern = {
67
/** Regex to match against the raw error message. */
78
test: RegExp;
@@ -43,6 +44,10 @@ const PROVIDER_CONTEXT_OVERFLOW_SIGNAL_RE =
4344
const PROVIDER_CONTEXT_OVERFLOW_ACTION_RE =
4445
/\b(?:too\s+(?:large|long|many)|exceed(?:s|ed|ing)?|overflow|limit|maximum|max)\b/i;
4546

47+
function isFailoverReason(value: unknown): value is FailoverReason {
48+
return typeof value === "string" && FAILOVER_REASONS.some((reason) => reason === value);
49+
}
50+
4651
function resolveProviderRuntimeHooks(): ProviderRuntimeHooks | null {
4752
if (cachedProviderRuntimeHooks !== undefined) {
4853
return cachedProviderRuntimeHooks;
@@ -52,9 +57,20 @@ function resolveProviderRuntimeHooks(): ProviderRuntimeHooks | null {
5257
return cachedProviderRuntimeHooks;
5358
}
5459
try {
55-
cachedProviderRuntimeHooks = requireProviderRuntime(
56-
"../../plugins/provider-runtime.js",
57-
) as unknown as ProviderRuntimeHooks;
60+
const runtime: unknown = requireProviderRuntime("../../plugins/provider-runtime.js");
61+
const classify = isRecord(runtime) ? runtime.classifyProviderFailoverSignalWithPlugin : null;
62+
if (typeof classify !== "function") {
63+
cachedProviderRuntimeHooks = null;
64+
return cachedProviderRuntimeHooks;
65+
}
66+
cachedProviderRuntimeHooks = {
67+
classifyProviderFailoverSignalWithPlugin: (params) => {
68+
const result: unknown = classify(params);
69+
return result === null || result === undefined || isFailoverReason(result)
70+
? result
71+
: undefined;
72+
},
73+
};
5874
} catch {
5975
cachedProviderRuntimeHooks = null;
6076
}

β€Žsrc/agents/mcp-pagination.tsβ€Ž

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ type McpPaginationRequest = {
1919
signal: AbortSignal;
2020
};
2121

22-
type CollectMcpPaginatedItemsParams<TInput, TOutput = TInput> = {
22+
type CollectMcpPaginatedItemsBaseParams<TInput> = {
2323
label: string;
2424
itemLabel: string;
2525
timeoutMs: number;
@@ -28,9 +28,14 @@ type CollectMcpPaginatedItemsParams<TInput, TOutput = TInput> = {
2828
maxBytes: number;
2929
signal?: AbortSignal;
3030
loadPage: (request: McpPaginationRequest) => Promise<McpPaginationPage<TInput>>;
31-
mapItem?: (item: TInput) => TOutput | undefined;
3231
};
3332

33+
type CollectMcpPaginatedItemsParams<TInput, TOutput> =
34+
| (CollectMcpPaginatedItemsBaseParams<TInput> & {
35+
mapItem: (item: TInput) => TOutput | undefined;
36+
})
37+
| (CollectMcpPaginatedItemsBaseParams<TInput> & { mapItem?: undefined });
38+
3439
function positiveInteger(value: number, label: string): number {
3540
if (!Number.isSafeInteger(value) || value <= 0) {
3641
throw new Error(`${label} must be a positive safe integer`);
@@ -43,9 +48,17 @@ function abortError(signal: AbortSignal, label: string): Error {
4348
}
4449

4550
/** Collects one complete MCP list under a single bounded lifecycle. */
46-
export async function collectMcpPaginatedItems<TInput, TOutput = TInput>(
51+
export function collectMcpPaginatedItems<TInput>(
52+
params: CollectMcpPaginatedItemsBaseParams<TInput> & { mapItem?: undefined },
53+
): Promise<TInput[]>;
54+
export function collectMcpPaginatedItems<TInput, TOutput>(
55+
params: CollectMcpPaginatedItemsBaseParams<TInput> & {
56+
mapItem: (item: TInput) => TOutput | undefined;
57+
},
58+
): Promise<TOutput[]>;
59+
export async function collectMcpPaginatedItems<TInput, TOutput>(
4760
params: CollectMcpPaginatedItemsParams<TInput, TOutput>,
48-
): Promise<TOutput[]> {
61+
): Promise<Array<TInput | TOutput>> {
4962
const timeoutMs = clampPositiveTimerTimeoutMs(params.timeoutMs);
5063
if (timeoutMs === undefined) {
5164
throw new Error(`${params.label} requires a positive timeout`);
@@ -81,7 +94,7 @@ export async function collectMcpPaginatedItems<TInput, TOutput = TInput>(
8194
signal.addEventListener("abort", onAbort, { once: true });
8295
});
8396

84-
const items: TOutput[] = [];
97+
const items: Array<TInput | TOutput> = [];
8598
const seenCursors = new Set<string>();
8699
let collectedBytes = 0;
87100
let cursor: string | undefined;
@@ -104,7 +117,7 @@ export async function collectMcpPaginatedItems<TInput, TOutput = TInput>(
104117
collectedBytes += measured.bytes;
105118

106119
for (const item of page.items) {
107-
const mapped = params.mapItem ? params.mapItem(item) : (item as unknown as TOutput);
120+
const mapped = params.mapItem ? params.mapItem(item) : item;
108121
if (mapped === undefined) {
109122
continue;
110123
}

β€Žsrc/agents/sessions/session-manager-codec.tsβ€Ž

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -406,7 +406,7 @@ export function partitionSessionFileEntries(entries: readonly FileEntry[]): {
406406
for (const [originalIndex, rawEntry] of entries.entries()) {
407407
const entry = normalizePersistedLegacyHookMessage(rawEntry) as FileEntry;
408408
if (!hasHeader && isRecord(entry) && entry.type === "session" && typeof entry.id === "string") {
409-
fileEntries.push(entry as unknown as SessionHeader);
409+
fileEntries.push(entry);
410410
fileEntriesByOriginalIndex[originalIndex] = entry;
411411
hasHeader = true;
412412
continue;

0 commit comments

Comments
Β (0)