Skip to content

Commit 5d60123

Browse files
authored
refactor(types): remove chained type assertions in extensions (#124079)
* refactor(types): remove chained assertions in extensions * fix(codex): preserve canonical binding identity
1 parent f4beff1 commit 5d60123

34 files changed

Lines changed: 138 additions & 163 deletions

‎extensions/amazon-bedrock/stream.runtime.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1108,7 +1108,7 @@ function convertToolConfig(
11081108
toolSpec: {
11091109
name: tool.name,
11101110
description: tool.description,
1111-
inputSchema: { json: tool.parameters as unknown as DocumentType },
1111+
inputSchema: { json: { ...tool.parameters } },
11121112
},
11131113
}));
11141114

‎extensions/anthropic/session-catalog-history.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -70,10 +70,10 @@ export async function importClaudeHistory(params: {
7070
continue;
7171
}
7272
// The idempotency key rides on the message so recovery re-imports dedupe.
73-
const message = {
74-
...(imported as unknown as Record<string, unknown>),
73+
const message: AgentMessage & { idempotencyKey: string } = {
74+
...imported,
7575
idempotencyKey: `claude-catalog:${params.threadId}:${item.uuid ?? index}`,
76-
} as unknown as AgentMessage;
76+
};
7777
await transcript.appendMessage({
7878
message,
7979
idempotencyLookup: "scan",

‎extensions/browser/src/browser/chrome.ts‎

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,7 @@
44
* Builds launch args, starts/stops managed Chrome, probes CDP readiness, and
55
* resolves WebSocket endpoints for browser control.
66
*/
7-
import {
8-
type ChildProcess,
9-
type ChildProcessWithoutNullStreams,
10-
execFileSync,
11-
spawn,
12-
} from "node:child_process";
7+
import { type ChildProcess, execFileSync, spawn } from "node:child_process";
138
import { once } from "node:events";
149
import fs from "node:fs";
1510
import os from "node:os";
@@ -1080,15 +1075,13 @@ export async function launchOpenClawChrome(
10801075
}
10811076
// stdio tuple: discard stdout to prevent buffer saturation in constrained
10821077
// environments (e.g. Docker), while keeping stderr piped for diagnostics.
1083-
// Cast to ChildProcessWithoutNullStreams so callers can use .stderr safely;
1084-
// the tuple overload resolution varies across @types/node versions.
10851078
const preparedSpawn = prepareOomScoreAdjustedSpawn(exe.path, args, {
10861079
env,
10871080
});
10881081
const proc = spawn(preparedSpawn.command, preparedSpawn.args, {
10891082
stdio: ["ignore", "ignore", "pipe"],
10901083
env: preparedSpawn.env,
1091-
}) as unknown as ChildProcessWithoutNullStreams;
1084+
});
10921085
const onAbort = () => {
10931086
try {
10941087
proc.kill("SIGKILL");
@@ -1218,7 +1211,7 @@ export async function launchOpenClawChrome(
12181211
const onStderr = (chunk: Buffer | string) => {
12191212
stderrDiagnostics.append(chunk);
12201213
};
1221-
let proc: ChildProcessWithoutNullStreams | undefined;
1214+
let proc: ChildProcess | undefined;
12221215
let releaseSpawnAbort: (() => void) | undefined;
12231216

12241217
try {

‎extensions/codex/src/app-server/approval-bridge.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1182,7 +1182,7 @@ function approvalKindForMethod(method: string): AgentApprovalEventData["kind"] {
11821182
function emitApprovalEvent(params: EmbeddedRunAttemptParams, data: AgentApprovalEventData): void {
11831183
void params.onAgentEvent?.({
11841184
stream: "approval",
1185-
data: data as unknown as Record<string, unknown>,
1185+
data: { ...data },
11861186
});
11871187
}
11881188

‎extensions/codex/src/app-server/client-runtime.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import { embeddedAgentLog, formatErrorMessage } from "openclaw/plugin-sdk/agent-harness-runtime";
33
import { refreshCodexAppServerAuthTokens } from "./auth-bridge.js";
44
import type { CodexAppServerClient } from "./client.js";
5-
import type { CodexServiceTier, JsonValue } from "./protocol.js";
5+
import type { CodexServiceTier } from "./protocol.js";
66
import { mergeCodexRateLimitsUpdate } from "./rate-limit-cache.js";
77
import type { CodexAppServerAuthProfileLookup } from "./session-binding.js";
88

@@ -104,14 +104,15 @@ export function ensureCodexAppServerClientRuntime(
104104
if (runtime.context.authMode === "prepared-api-key") {
105105
throw new Error("ChatGPT token refresh is unavailable for prepared Codex API-key auth.");
106106
}
107-
return (await refreshCodexAppServerAuthTokens({
107+
const tokens = await refreshCodexAppServerAuthTokens({
108108
agentDir: runtime.context.agentDir,
109109
authProfileId: runtime.context.authProfileId,
110110
...(runtime.context.authProfileStore
111111
? { authProfileStore: runtime.context.authProfileStore }
112112
: {}),
113113
config: runtime.context.config,
114-
})) as unknown as JsonValue;
114+
});
115+
return { ...tokens };
115116
});
116117
client.addNotificationHandler((notification) => {
117118
if (notification.method === "account/rateLimits/updated") {

‎extensions/codex/src/app-server/event-projector-assistant-message.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,9 @@ export function createAssistantCommentaryMessage(
103103
timestamp: number,
104104
): AssistantMessage {
105105
const attribution = resolveCodexLocalRuntimeAttribution(params);
106-
return {
106+
const message: AssistantMessage & {
107+
openclawStreamFallback: { replacementText: string; source: "segment"; itemId: string };
108+
} = {
107109
role: "assistant",
108110
content: [{ type: "text", text }],
109111
api: attribution.api ?? "openai-chatgpt-responses",
@@ -119,7 +121,8 @@ export function createAssistantCommentaryMessage(
119121
source: "segment",
120122
itemId,
121123
},
122-
} as unknown as AssistantMessage;
124+
};
125+
return message;
123126
}
124127

125128
export function createAssistantMirrorMessage(

‎extensions/codex/src/app-server/event-projector-snapshot.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,10 @@ import { attachCodexMirrorIdentity } from "./upstream-prompt-provenance.js";
99
import { promptSnapshot } from "./user-prompt-message.js";
1010

1111
type TurnTaintMetadata = { resultContentSource?: "network"; turnTainted?: true };
12+
const CODEX_META_KEY = "__openclaw";
1213

1314
function readTurnTaintMetadata(message: AgentMessage): TurnTaintMetadata | undefined {
14-
const metadata = (message as unknown as Record<string, unknown>)["__openclaw"];
15+
const metadata = CODEX_META_KEY in message ? message[CODEX_META_KEY] : undefined;
1516
return metadata && typeof metadata === "object" && !Array.isArray(metadata)
1617
? (metadata as TurnTaintMetadata)
1718
: undefined;

‎extensions/codex/src/app-server/event-projector-tool-transcript.ts‎

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -313,9 +313,8 @@ export class CodexToolTranscriptProjection {
313313
}
314314
this.rawNativeToolOutputByCallId.set(callId, text);
315315
const result = this.messages.find(
316-
(message) =>
317-
message.role === "toolResult" &&
318-
(message as unknown as { toolCallId?: unknown }).toolCallId === callId,
316+
(message): message is Extract<AgentMessage, { role: "toolResult" }> =>
317+
message.role === "toolResult" && message.toolCallId === callId,
319318
);
320319
if (!result) {
321320
if (NATIVE_PATCH_REJECTION_RE.test(text)) {
@@ -336,11 +335,9 @@ export class CodexToolTranscriptProjection {
336335
id: callId,
337336
name: "apply_patch",
338337
text,
339-
isError: (result as unknown as { isError?: unknown }).isError === true,
338+
isError: result.isError,
340339
});
341-
(result as unknown as { content: unknown }).content = (
342-
replacement as unknown as { content: unknown }
343-
).content;
340+
result.content = replacement.content;
344341
}
345342

346343
async recordNativeToolResultWithDetails(item: CodexThreadItem | undefined): Promise<void> {
@@ -599,7 +596,9 @@ export class CodexToolTranscriptProjection {
599596
} as unknown as AgentMessage;
600597
}
601598

602-
private createToolResultMessage(params: ToolTranscriptResultInput): AgentMessage {
599+
private createToolResultMessage(
600+
params: ToolTranscriptResultInput,
601+
): Extract<AgentMessage, { role: "toolResult" }> {
603602
const text = truncateToolTranscriptText(params.text?.trim() || toolResultStatusText(params));
604603
return {
605604
role: "toolResult",
@@ -624,7 +623,7 @@ export class CodexToolTranscriptProjection {
624623
? { __openclaw: { resultContentSource: params.resultContentSource } }
625624
: {}),
626625
timestamp: this.nextTranscriptTimestamp(),
627-
} as unknown as AgentMessage;
626+
} as unknown as Extract<AgentMessage, { role: "toolResult" }>;
628627
}
629628
}
630629

‎extensions/codex/src/app-server/run-attempt-active-turn.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import {
1414
} from "./attempt-steering.js";
1515
import { CodexAppServerEventProjector } from "./event-projector.js";
1616
import { createCodexNativeMcpAppResultDetailsPreparer } from "./native-mcp-app.js";
17-
import type { CodexTurnStartResponse, JsonObject } from "./protocol.js";
17+
import { isJsonObject, type CodexTurnStartResponse } from "./protocol.js";
1818
import { readRecentCodexRateLimits } from "./rate-limit-cache.js";
1919
import { readBoundedCodexRemoteWorkspaceFile } from "./remote-workspace-media.js";
2020
import type { CodexAttemptLifecycleController } from "./run-attempt-lifecycle-controller.js";
@@ -165,13 +165,16 @@ export async function activateCodexAttemptTurn(
165165
}
166166
}
167167
if (!state.completed && isTerminalTurnStatus(turn.turn.status)) {
168+
if (!isJsonObject(turn.turn)) {
169+
throw new Error("Codex turn completion payload is not a JSON object");
170+
}
168171
await enqueueNotification(
169172
{
170173
method: "turn/completed",
171174
params: {
172175
threadId: resourceState.thread.threadId,
173176
turnId: activeTurnId,
174-
turn: turn.turn as unknown as JsonObject,
177+
turn: turn.turn,
175178
},
176179
},
177180
{ threadId: resourceState.thread.threadId, turnId: activeTurnId },

‎extensions/codex/src/app-server/run-attempt-prompt.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ import {
3333
codexLegacyDynamicToolsFingerprint,
3434
} from "./thread-lifecycle.js";
3535

36+
const CODEX_META_KEY = "__openclaw";
37+
3638
function isRestrictivePromptToolsAllow(toolsAllow: string[] | undefined): boolean {
3739
return toolsAllow !== undefined && !toolsAllow.some((name) => name.trim() === "*");
3840
}
@@ -327,8 +329,7 @@ export async function prepareCodexAttemptPrompt(context: CodexAttemptContext) {
327329
if (message.role !== "user" && message.role !== "assistant") {
328330
return false;
329331
}
330-
const record = message as unknown as Record<string, unknown>;
331-
const meta = record["__openclaw"];
332+
const meta = CODEX_META_KEY in message ? message[CODEX_META_KEY] : undefined;
332333
const mirrorIdentity =
333334
meta && typeof meta === "object" && !Array.isArray(meta)
334335
? (meta as Record<string, unknown>).mirrorIdentity
@@ -345,8 +346,9 @@ export async function prepareCodexAttemptPrompt(context: CodexAttemptContext) {
345346
: Number.NaN;
346347
return (
347348
!(
348-
typeof record.idempotencyKey === "string" &&
349-
record.idempotencyKey.startsWith("codex-app-server:")
349+
"idempotencyKey" in message &&
350+
typeof message.idempotencyKey === "string" &&
351+
message.idempotencyKey.startsWith("codex-app-server:")
350352
) &&
351353
mirrorOrigin !== "codex-app-server" &&
352354
!(typeof mirrorIdentity === "string" && mirrorIdentity.startsWith("codex-app-server:")) &&

0 commit comments

Comments
 (0)