Skip to content

Commit aaa509b

Browse files
authored
refactor(types): remove chained type assertions in core and ui (#124073)
* refactor(types): remove chained assertions in core and ui * fix(types): preserve legacy cron migration identity * fix(types): preserve settings patch key types
1 parent 26ff3c9 commit aaa509b

29 files changed

Lines changed: 205 additions & 163 deletions

‎packages/acp-core/src/runtime/errors.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -128,12 +128,12 @@ export function formatAcpErrorChain(error: unknown): string {
128128
return redactSensitiveText(String(error));
129129
}
130130
const segments: string[] = [renderSingleError(error)];
131-
let current: unknown = (error as unknown as { cause?: unknown }).cause;
131+
let current: unknown = error.cause;
132132
let depth = 0;
133133
while (current !== undefined && current !== null && depth < 8) {
134134
if (current instanceof Error) {
135135
segments.push(renderSingleError(current));
136-
current = (current as unknown as { cause?: unknown }).cause;
136+
current = current.cause;
137137
} else {
138138
segments.push(stringifyNonErrorCause(current));
139139
current = undefined;
@@ -144,7 +144,7 @@ export function formatAcpErrorChain(error: unknown): string {
144144
}
145145

146146
function renderSingleError(error: Error): string {
147-
const codeValue = (error as unknown as { code?: unknown }).code;
147+
const codeValue = "code" in error ? error.code : undefined;
148148
const codeSuffix =
149149
typeof codeValue === "string" || typeof codeValue === "number" ? ` [${codeValue}]` : "";
150150
return `${error.name}${codeSuffix}: ${error.message}`;

‎packages/agent-core/src/agent-loop.ts‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1873,8 +1873,17 @@ type TurnTaintMetadata = {
18731873
};
18741874

18751875
function readTurnTaintMetadata(message: AgentMessage): TurnTaintMetadata | undefined {
1876-
const metadata = (message as unknown as Record<string, unknown>)["__openclaw"];
1877-
return asOptionalRecord(metadata) as TurnTaintMetadata | undefined;
1876+
const metadata = Reflect.get(message, "__openclaw");
1877+
const record = asOptionalRecord(metadata);
1878+
if (!record) {
1879+
return undefined;
1880+
}
1881+
return {
1882+
...(record.resultContentSource === "network"
1883+
? { resultContentSource: record.resultContentSource }
1884+
: {}),
1885+
...(record.turnTainted === true ? { turnTainted: true } : {}),
1886+
};
18781887
}
18791888

18801889
function toolResultTaintsTurn(message: ToolResultMessage): boolean {
@@ -1898,10 +1907,11 @@ function withAssistantTurnTaint(message: AssistantMessage, tainted: boolean): As
18981907
if (!tainted) {
18991908
return message;
19001909
}
1901-
return {
1910+
const taintedMessage = {
19021911
...message,
19031912
__openclaw: { ...readTurnTaintMetadata(message), turnTainted: true },
1904-
} as unknown as AssistantMessage;
1913+
} satisfies AssistantMessage & { __openclaw: TurnTaintMetadata };
1914+
return taintedMessage;
19051915
}
19061916

19071917
function withToolResultContentSource(

‎packages/ai/src/providers/anthropic.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import type {
99
RawMessageStreamEvent,
1010
TextBlockParam,
1111
} from "@anthropic-ai/sdk/resources/messages.js";
12+
import { isRecord } from "@openclaw/normalization-core/record-coerce";
1213
import { getEnvApiKey } from "../env-api-keys.js";
1314
import { getAiTransportHost, resolveAiTransportHeaderSentinels } from "../host.js";
1415
import {
@@ -448,7 +449,7 @@ export const streamAnthropic: StreamFunction<"anthropic-messages", AnthropicComp
448449
// and allowing the thinking-block recovery retry to fire.
449450
eventSink.push({ type: "start", partial: output });
450451
} else if (event.type === "content_block_start") {
451-
const rawContentBlock = event.content_block as unknown as Record<string, unknown>;
452+
const rawContentBlock = isRecord(event.content_block) ? event.content_block : undefined;
452453
if (
453454
requestOptions?.anthropicServerCompaction === true &&
454455
compactionCapture.begin(event.index, rawContentBlock, output.content.length)
@@ -566,7 +567,7 @@ export const streamAnthropic: StreamFunction<"anthropic-messages", AnthropicComp
566567
});
567568
}
568569
} else if (event.type === "content_block_delta") {
569-
const rawDelta = event.delta as unknown as Record<string, unknown>;
570+
const rawDelta = isRecord(event.delta) ? event.delta : undefined;
570571
if (compactionCapture.delta(event.index, rawDelta)) {
571572
continue;
572573
} else if (event.delta.type === "text_delta") {

‎packages/ai/src/transports/anthropic-compaction-replay.ts‎

Lines changed: 31 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { AssistantMessage, Context, Model, ProviderReplayState } from "@openclaw/llm-core";
2+
import { isRecord } from "@openclaw/normalization-core/record-coerce";
23
import { shortHash } from "../utils/hash.js";
34

45
const ANTHROPIC_COMPACTION_REPLAY_TYPE = "anthropic-compaction";
@@ -85,40 +86,39 @@ function buildAnthropicReplayContext(model: Model, options?: ReplayOpts): Anthro
8586
};
8687
}
8788

88-
function readAnthropicCompactionState(
89-
value: unknown,
90-
): AnthropicCompactionReplayState | AnthropicCompactionSuppressionState | undefined {
91-
if (!value || typeof value !== "object" || Array.isArray(value)) {
92-
return undefined;
93-
}
94-
const state = value as Record<string, unknown>;
95-
const validEnvelope =
96-
state.v === 1 &&
97-
typeof state.data === "string" &&
98-
typeof state.provider === "string" &&
99-
typeof state.api === "string" &&
100-
typeof state.model === "string" &&
101-
typeof state.baseUrlHash === "string" &&
102-
(state.sessionHash === undefined || typeof state.sessionHash === "string") &&
103-
(state.authProfileHash === undefined || typeof state.authProfileHash === "string");
104-
if (!validEnvelope) {
105-
return undefined;
106-
}
107-
const replayState = state as unknown as
108-
| AnthropicCompactionReplayState
109-
| AnthropicCompactionSuppressionState;
110-
if (replayState.type === ANTHROPIC_COMPACTION_SUPPRESSION_TYPE) {
111-
return replayState.data === ANTHROPIC_COMPACTION_SUPPRESSION_DATA ? replayState : undefined;
112-
}
89+
function isAnthropicCompactionState(
90+
state: Record<string, unknown>,
91+
): state is Record<string, unknown> &
92+
(AnthropicCompactionReplayState | AnthropicCompactionSuppressionState) {
11393
if (
114-
replayState.type !== ANTHROPIC_COMPACTION_REPLAY_TYPE ||
115-
replayState.data.length === 0 ||
116-
(replayState.replayIndex !== undefined &&
117-
(!Number.isSafeInteger(replayState.replayIndex) || replayState.replayIndex < 0))
94+
state.v !== 1 ||
95+
typeof state.data !== "string" ||
96+
typeof state.provider !== "string" ||
97+
typeof state.api !== "string" ||
98+
typeof state.model !== "string" ||
99+
typeof state.baseUrlHash !== "string" ||
100+
(state.sessionHash !== undefined && typeof state.sessionHash !== "string") ||
101+
(state.authProfileHash !== undefined && typeof state.authProfileHash !== "string")
118102
) {
119-
return undefined;
103+
return false;
104+
}
105+
if (state.type === ANTHROPIC_COMPACTION_SUPPRESSION_TYPE) {
106+
return state.data === ANTHROPIC_COMPACTION_SUPPRESSION_DATA;
120107
}
121-
return replayState;
108+
return (
109+
state.type === ANTHROPIC_COMPACTION_REPLAY_TYPE &&
110+
state.data.length > 0 &&
111+
(state.replayIndex === undefined ||
112+
(typeof state.replayIndex === "number" &&
113+
Number.isSafeInteger(state.replayIndex) &&
114+
state.replayIndex >= 0))
115+
);
116+
}
117+
118+
function readAnthropicCompactionState(
119+
value: unknown,
120+
): AnthropicCompactionReplayState | AnthropicCompactionSuppressionState | undefined {
121+
return isRecord(value) && isAnthropicCompactionState(value) ? value : undefined;
122122
}
123123

124124
function replayContextMatches(

‎packages/ai/src/transports/openai-completions-transport.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ import {
3434
import {
3535
failTransportStream,
3636
finalizeTransportStream,
37+
type WritableTransportStream,
3738
withProviderResponseHook,
3839
} from "./transport-stream-shared.js";
3940

@@ -173,7 +174,7 @@ function buildOpenAICompletionsClientConfig(
173174
export function createOpenAICompletionsTransportStreamFn(): StreamFn {
174175
return (model, context, options) => {
175176
const eventStream = createAssistantMessageEventStream();
176-
const stream = eventStream as unknown as { push(event: unknown): void; end(): void };
177+
const stream = eventStream as unknown as WritableTransportStream;
177178
void (async () => {
178179
const output: MutableAssistantOutput = {
179180
role: "assistant" as const,
@@ -293,6 +294,6 @@ export function createOpenAICompletionsTransportStreamFn(): StreamFn {
293294
firstEventAbort?.dispose();
294295
}
295296
})();
296-
return eventStream as unknown as ReturnType<StreamFn>;
297+
return eventStream;
297298
};
298299
}

‎packages/ai/src/transports/openai-responses-client.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ import { sanitizeResponsesImagePayload } from "./responses-image-payload-sanitiz
7676
import {
7777
mergeTransportMetadata,
7878
transportAbortError,
79+
type WritableTransportStream,
7980
withProviderResponseHook,
8081
} from "./transport-stream-shared.js";
8182
import { redactIdentifier } from "./transport-utils.js";
@@ -240,7 +241,7 @@ function createResponsesTransportExecutor(config: ResponsesTransportExecutorOpti
240241
const responsesOptions = options as OpenAIResponsesOptions | undefined;
241242
const compactRequest = claimResponsesCompactRequest(responsesOptions);
242243
const eventStream = createAssistantMessageEventStream();
243-
const stream = eventStream as unknown as { push(event: unknown): void; end(): void };
244+
const stream = eventStream as unknown as WritableTransportStream;
244245
void (async () => {
245246
const output = createOpenAIResponsesAssistantOutput(model, config.outputApi);
246247
let firstEventAbort: ReturnType<typeof createFirstStreamEventAbortController> | undefined;
@@ -590,7 +591,7 @@ function createResponsesTransportExecutor(config: ResponsesTransportExecutorOpti
590591
firstEventAbort?.dispose();
591592
}
592593
})();
593-
return eventStream as unknown as ReturnType<StreamFn>;
594+
return eventStream;
594595
};
595596
}
596597

‎packages/ai/src/transports/openai-responses-compaction-replay.ts‎

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -62,29 +62,35 @@ export function isOpenAIResponsesReplayContext(
6262
);
6363
}
6464

65-
function readOpenAIResponsesCompactionReplayState(
66-
value: unknown,
67-
): OpenAIResponsesCompactionReplayState | OpenAIResponsesCompactionSuppressionState | undefined {
68-
if (
69-
!isOpenAIResponsesReplayContext(value) ||
70-
typeof value.baseUrlHash !== "string" ||
71-
(value as Record<string, unknown>).v !== 1
72-
) {
73-
return undefined;
65+
function isOpenAIResponsesCompactionState(
66+
state: OpenAIResponsesReplayContext & Record<string, unknown>,
67+
): state is Record<string, unknown> &
68+
(OpenAIResponsesCompactionReplayState | OpenAIResponsesCompactionSuppressionState) {
69+
if (typeof state.baseUrlHash !== "string" || state.v !== 1) {
70+
return false;
7471
}
75-
const state = value as OpenAIResponsesReplayContext & Record<string, unknown>;
7672
if (state.type === OPENAI_RESPONSES_COMPACTION_SUPPRESSION_TYPE) {
77-
return state.data === OPENAI_RESPONSES_COMPACTION_SUPPRESSION_DATA
78-
? (state as unknown as OpenAIResponsesCompactionSuppressionState)
79-
: undefined;
73+
return state.data === OPENAI_RESPONSES_COMPACTION_SUPPRESSION_DATA;
8074
}
81-
return state.type === OPENAI_RESPONSES_COMPACTION_REPLAY_TYPE &&
75+
return (
76+
state.type === OPENAI_RESPONSES_COMPACTION_REPLAY_TYPE &&
8277
typeof state.data === "string" &&
8378
state.data.length > 0 &&
8479
(state.id === undefined || typeof state.id === "string") &&
8580
(state.replayIndex === undefined ||
86-
(Number.isSafeInteger(state.replayIndex) && (state.replayIndex as number) >= 0))
87-
? (state as unknown as OpenAIResponsesCompactionReplayState)
81+
(typeof state.replayIndex === "number" &&
82+
Number.isSafeInteger(state.replayIndex) &&
83+
state.replayIndex >= 0))
84+
);
85+
}
86+
87+
function readOpenAIResponsesCompactionReplayState(
88+
value: unknown,
89+
): OpenAIResponsesCompactionReplayState | OpenAIResponsesCompactionSuppressionState | undefined {
90+
return isRecord(value) &&
91+
isOpenAIResponsesReplayContext(value) &&
92+
isOpenAIResponsesCompactionState(value)
93+
? value
8894
: undefined;
8995
}
9096

‎packages/ai/src/transports/openai-responses-replay-messages-internal.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { Api, AssistantMessage, Context, Model } from "@openclaw/llm-core";
2+
import { isRecord } from "@openclaw/normalization-core/record-coerce";
23
import type {
34
ResponseFunctionCallOutputItemList,
45
ResponseInput,
@@ -369,9 +370,7 @@ function convertResponsesMessagesWithStyle(
369370
const replayableReasoningItem = prepareOpenAIResponsesReasoningItemForReplay(
370371
reasoningItem,
371372
replayContext,
372-
readOpenAIResponsesReasoningReplayBlockMetadata(
373-
block as unknown as Record<string, unknown>,
374-
),
373+
readOpenAIResponsesReasoningReplayBlockMetadata(isRecord(block) ? block : {}),
375374
providerStyle ? { preserveUnattributedEncryptedContent: true } : undefined,
376375
);
377376
if (!shouldReplayResponsesItemIds) {

‎packages/ai/src/transports/openai-responses-stream-internal.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { isRecord } from "@openclaw/normalization-core/record-coerce";
12
import type {
23
ResponseCreateParamsStreaming,
34
ResponseOutputItem,
@@ -705,10 +706,7 @@ export async function processResponsesStream<TApi extends Api>(
705706
event.message ? `Error Code ${event.code}: ${event.message}` : "Unknown error",
706707
);
707708
} else if (event.type === "response.failed") {
708-
const failure = normalizeResponsesFailedEvent(
709-
event as unknown as Record<string, unknown>,
710-
model,
711-
);
709+
const failure = normalizeResponsesFailedEvent(isRecord(event) ? event : {}, model);
712710
finalizeFailedResponse(event.response, failure.responseId);
713711
throw new ResponsesStreamFailure(failure, event.response);
714712
}

‎packages/markdown-core/src/ir.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1578,7 +1578,7 @@ export function markdownToIRWithMeta(
15781578
assistantTranscriptRolePreserveLinks: options.assistantTranscriptRoleHeaders === true,
15791579
};
15801580
const md = createMarkdownIt(options);
1581-
const tokens = md.parse(source, env as unknown as object);
1581+
const tokens = md.parse(source, env);
15821582

15831583
const tableMode = options.tableMode ?? "off";
15841584

0 commit comments

Comments
 (0)