diff --git a/packages/core/src/aisdk.ts b/packages/core/src/aisdk.ts index a392273dad7..ffe9425d9f8 100644 --- a/packages/core/src/aisdk.ts +++ b/packages/core/src/aisdk.ts @@ -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["content"] @@ -420,11 +422,8 @@ function modelFromLanguage(info: RuntimeInfo, language: LanguageModelV3) { }) } -function gatewayProviderOptions(modelID: ID, settings: Readonly>) { - 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>) { + 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) } } diff --git a/packages/core/src/config/plugin/skill-file.ts b/packages/core/src/config/plugin/skill-file.ts index 95782512b9f..6d1672bdb8e 100644 --- a/packages/core/src/config/plugin/skill-file.ts +++ b/packages/core/src/config/plugin/skill-file.ts @@ -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)[key]) + if (!isRecord(metadata)) return undefined + return booleanValue(metadata[key]) } const booleanValue = (value: unknown) => { diff --git a/packages/core/src/formatter/builtins.ts b/packages/core/src/formatter/builtins.ts index 86b3714add5..8609451c66b 100644 --- a/packages/core/src/formatter/builtins.ts +++ b/packages/core/src/formatter/builtins.ts @@ -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 { - return Boolean(input && typeof input === "object" && !Array.isArray(input)) -} diff --git a/packages/core/src/plugin/provider/github-copilot.ts b/packages/core/src/plugin/provider/github-copilot.ts index 19de498c5e8..4b449d024f5 100644 --- a/packages/core/src/plugin/provider/github-copilot.ts +++ b/packages/core/src/plugin/provider/github-copilot.ts @@ -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 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 { - return typeof input === "object" && input !== null && !Array.isArray(input) -} diff --git a/packages/core/src/session/runner/publish-llm-event.ts b/packages/core/src/session/runner/publish-llm-event.ts index e61309d7ab8..93db097c480 100644 --- a/packages/core/src/session/runner/publish-llm-event.ts +++ b/packages/core/src/session/runner/publish-llm-event.ts @@ -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 => - typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record) : { value } +const asRecord = (value: unknown): Record => (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) }] diff --git a/packages/core/src/tool/runtime.ts b/packages/core/src/tool/runtime.ts index d1c5e29caf1..da38823c44c 100644 --- a/packages/core/src/tool/runtime.ts +++ b/packages/core/src/tool/runtime.ts @@ -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 => - typeof value === "object" && value !== null && !Array.isArray(value) - const canFlattenAllOf = (allOf: ReadonlyArray>, parent: Record) => { 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 | 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) diff --git a/packages/core/src/v1/config/provider-options.ts b/packages/core/src/v1/config/provider-options.ts index 8602acadfb0..16d2097d346 100644 --- a/packages/core/src/v1/config/provider-options.ts +++ b/packages/core/src/v1/config/provider-options.ts @@ -1,5 +1,7 @@ export * as ConfigProviderOptionsV1 from "./provider-options.js" +import { isRecord } from "@opencode/ai/utils/record" + type Options = Readonly> 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,