refactor(core): reuse shared isRecord and stringify helpers (#57826)

This commit is contained in:
Aiden Cline
2026-10-21 11:18:38 -05:00
committed by GitHub
Unverified
parent ab249a9684
commit 93bf002401
7 changed files with 36 additions and 62 deletions
+6 -16
View File
@@ -32,6 +32,7 @@ import {
} from "@opencode/ai"
import { Auth, Endpoint, RequestExecutor, type AnyRoute, type HttpMiddleware } from "@opencode/ai/route"
import { ProviderShared } from "@opencode/ai/protocols/shared"
import { isRecord } from "@opencode/ai/utils/record"
import { Cause, Context, Effect, Layer, Option, Schema, Scope, Stream } from "effect"
import { makeParser } from "effect/encoding/Sse"
import { HttpClientRequest, HttpClientResponse } from "effect/http"
@@ -39,6 +40,7 @@ import { AsyncLocalStorage } from "node:async_hooks"
import type { ID, RuntimeInfo } from "./model.js"
import { Provider } from "./provider.js"
import { State } from "./state.js"
import { stringify } from "./tool/runtime.js"
type SDK = any
type UserContent = Extract<LanguageModelV3Message, { role: "user" }>["content"]
@@ -420,11 +422,8 @@ function modelFromLanguage(info: RuntimeInfo, language: LanguageModelV3) {
})
}
function gatewayProviderOptions(modelID: ID, settings: Readonly<Record<string, unknown>>) {
const gateway =
typeof settings.gateway === "object" && settings.gateway !== null && !Array.isArray(settings.gateway)
? Object.fromEntries(Object.entries(settings.gateway))
: undefined
function gatewayProviderOptions(modelID: ID, settings: Readonly<Record<string, JSONValue>>) {
const gateway = isRecord(settings.gateway) ? Object.fromEntries(Object.entries(settings.gateway)) : undefined
const model = Object.fromEntries(Object.entries(settings).filter(([key]) => key !== "gateway"))
if (Object.keys(model).length === 0) return gateway === undefined ? undefined : { gateway }
@@ -666,7 +665,7 @@ function toolOutput(result: ToolResultValue) {
switch (result.type) {
case "text":
case "error":
return { type: "text" as const, value: messageValue(result.value) }
return { type: "text" as const, value: stringify(result.value) }
case "content":
return {
type: "content" as const,
@@ -924,16 +923,7 @@ function jsonValue(input: unknown): JSONValue {
const encoded = JSON.stringify(input)
return encoded === undefined ? null : (JSON.parse(encoded) as JSONValue)
} catch {
return messageValue(input)
}
}
function messageValue(input: unknown) {
if (typeof input === "string") return input
try {
return JSON.stringify(input) ?? String(input)
} catch {
return String(input)
return stringify(input)
}
}
@@ -1,6 +1,7 @@
export * as SkillFile from "./skill-file.js"
import path from "path"
import { isRecord } from "@opencode/ai/utils/record"
import { Result, Schema, type SchemaIssue, SchemaParser } from "effect"
import { ConfigMarkdown } from "../markdown.js"
import { AbsolutePath } from "../../schema.js"
@@ -20,10 +21,8 @@ export type ParseResult =
| { readonly _tag: "Skipped"; readonly reason: "frontmatter"; readonly issue: SchemaIssue.Issue }
const metadataBoolean = (metadata: unknown, key: string) => {
if (metadata === undefined || metadata === null || typeof metadata !== "object" || Array.isArray(metadata)) {
return undefined
}
return booleanValue((metadata as Record<string, unknown>)[key])
if (!isRecord(metadata)) return undefined
return booleanValue(metadata[key])
}
const booleanValue = (value: unknown) => {
+1 -4
View File
@@ -1,5 +1,6 @@
import { Effect } from "effect"
import { ChildProcess } from "effect/process"
import { isRecord } from "@opencode/ai/utils/record"
import { FSUtil } from "@opencode/util/fs-util"
import { Npm } from "@opencode/util/npm"
import { AppProcess } from "@opencode/util/process"
@@ -291,7 +292,3 @@ function hasRecordKey(input: unknown, field: string, key: string) {
if (!isRecord(input)) return false
return isRecord(input[field]) && key in input[field]
}
function isRecord(input: unknown): input is Record<string, unknown> {
return Boolean(input && typeof input === "object" && !Array.isArray(input))
}
@@ -1,5 +1,6 @@
import type { IntegrationOAuthMethodRegistration } from "@opencode/plugin/effect/integration"
import type { SessionRequestKind, SessionTitle } from "@opencode/plugin/effect/session"
import { isRecord } from "@opencode/ai/utils/record"
import { Effect, Option, Schema, Semaphore, Stream } from "effect"
import { IntegrationConnection } from "../../integration/connection.js"
import { Credential } from "../../credential.js"
@@ -519,16 +520,16 @@ export function interactionType(kind: SessionRequestKind, child: boolean) {
type RequestMetadata = ReturnType<typeof requestMetadata>
function requestMetadata(url: string, body: unknown) {
if (!record(body)) return { agent: false, vision: false }
if (!isRecord(body)) return { agent: false, vision: false }
if (Array.isArray(body.input)) {
const last = body.input.at(-1)
return {
agent: !record(last) || last.role !== "user",
agent: !isRecord(last) || last.role !== "user",
vision: body.input.some(
(item) =>
record(item) &&
isRecord(item) &&
Array.isArray(item.content) &&
item.content.some((part) => record(part) && part.type === "input_image"),
item.content.some((part) => isRecord(part) && part.type === "input_image"),
),
}
}
@@ -536,35 +537,31 @@ function requestMetadata(url: string, body: unknown) {
const last = body.messages.at(-1)
if (url.includes("completions")) {
return {
agent: !record(last) || last.role !== "user",
agent: !isRecord(last) || last.role !== "user",
vision: body.messages.some(
(message) =>
record(message) &&
isRecord(message) &&
Array.isArray(message.content) &&
message.content.some((part) => record(part) && part.type === "image_url"),
message.content.some((part) => isRecord(part) && part.type === "image_url"),
),
}
}
const content = record(last) && Array.isArray(last.content) ? last.content : []
const content = isRecord(last) && Array.isArray(last.content) ? last.content : []
return {
agent:
!record(last) || last.role !== "user" || !content.some((part) => record(part) && part.type !== "tool_result"),
!isRecord(last) || last.role !== "user" || !content.some((part) => isRecord(part) && part.type !== "tool_result"),
vision: body.messages.some(
(message) =>
record(message) &&
isRecord(message) &&
Array.isArray(message.content) &&
message.content.some(
(part) =>
record(part) &&
isRecord(part) &&
(part.type === "image" ||
(part.type === "tool_result" &&
Array.isArray(part.content) &&
part.content.some((nested) => record(nested) && nested.type === "image"))),
part.content.some((nested) => isRecord(nested) && nested.type === "image"))),
),
),
}
}
function record(input: unknown): input is Record<string, unknown> {
return typeof input === "object" && input !== null && !Array.isArray(input)
}
@@ -1,4 +1,5 @@
import { type LLMEvent, type ProviderMetadata, type ToolResultValue } from "@opencode/ai"
import { isRecord } from "@opencode/ai/utils/record"
import type { Agent } from "@opencode/schema/agent"
import type { Model } from "@opencode/schema/model"
import type { RelativePath } from "@opencode/schema/schema"
@@ -14,6 +15,7 @@ import { Money } from "@opencode/schema/money"
import { SessionUsage } from "../usage.js"
import { contentFilterError } from "../to-session-error.js"
import type { Tool } from "../../tool.js"
import { stringify } from "../../tool/runtime.js"
type Input = {
readonly sessionID: SessionSchema.ID
@@ -26,8 +28,7 @@ type Input = {
readonly assistantMessageID: SessionMessage.ID
}
const asRecord = (value: unknown): Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : { value }
const asRecord = (value: unknown): Record<string, unknown> => (isRecord(value) ? value : { value })
const INPUT_EXCERPT_LIMIT = 2048
@@ -75,15 +76,6 @@ export interface StepRecord {
/** Derives canonical model content from a provider-hosted tool result. */
type NonEmptyContent = readonly [Tool.Content, ...Tool.Content[]]
const stringify = (value: unknown) => {
if (typeof value === "string") return value
try {
return JSON.stringify(value) ?? String(value)
} catch {
return String(value)
}
}
const hostedContent = (result: ToolResultValue): NonEmptyContent => {
if (result.type === "content" && isReadonlyArrayNonEmpty(result.value)) return result.value
return [{ type: "text", text: stringify(result.value) }]
+2 -4
View File
@@ -1,5 +1,6 @@
import type { ToolDefinition } from "@opencode/ai"
import { emptyInputJsonSchema } from "@opencode/ai/tool"
import { isRecord } from "@opencode/ai/utils/record"
import { Tool } from "@opencode/schema/tool"
import type { StandardJSONSchemaV1, StandardSchemaV1 } from "@standard-schema/spec"
import { Cache, Effect, JsonPointer, JsonSchema, Schema, SchemaIssue, SchemaRepresentation } from "effect"
@@ -198,9 +199,6 @@ const flattenAllOf = (value: unknown): unknown => {
return flattenAllOf({ ...Object.assign({}, ...allOf), ...rest })
}
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value)
const canFlattenAllOf = (allOf: ReadonlyArray<Record<string, unknown>>, parent: Record<string, unknown>) => {
const keys = new Set(Object.keys(parent).filter((key) => key !== "allOf"))
return allOf.every((item) =>
@@ -264,7 +262,7 @@ export const normalizeContent = (value: string | ReadonlyArray<Tool.Content> | u
return [{ type: "text" as const, text: stringify(output) }]
}
const stringify = (value: unknown) => {
export const stringify = (value: unknown) => {
if (typeof value === "string") return value
try {
return JSON.stringify(value) ?? String(value)
@@ -1,5 +1,7 @@
export * as ConfigProviderOptionsV1 from "./provider-options.js"
import { isRecord } from "@opencode/ai/utils/record"
type Options = Readonly<Record<string, unknown>>
export interface ProviderResult {
@@ -12,13 +14,12 @@ export function provider(options: Options): ProviderResult {
const headers = options.headers
const body = options.body
const settings = Object.fromEntries(Object.entries(options).filter(([key]) => key !== "headers" && key !== "body"))
const headerOverlay =
typeof headers === "object" && headers !== null && !Array.isArray(headers)
? Object.fromEntries(
Object.entries(headers).filter((entry): entry is [string, string] => typeof entry[1] === "string"),
)
: undefined
const bodyOverlay = typeof body === "object" && body !== null && !Array.isArray(body) ? { ...body } : undefined
const headerOverlay = isRecord(headers)
? Object.fromEntries(
Object.entries(headers).filter((entry): entry is [string, string] => typeof entry[1] === "string"),
)
: undefined
const bodyOverlay = isRecord(body) ? { ...body } : undefined
return {
settings,
headers: headerOverlay,