GeezerVison is showing github.com — refactor(core): run GitHub Copilot on native ai protocols by rekram1-node · Pull Request #62034 · anomalyco/opencode
refactor(core): run GitHub Copilot on native ai protocols
#62034
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Uh oh!
There was an error while loading. Please reload this page.
Show file tree
Hide file tree
Changes from all commits
Commits
File filter
Filter by extension
.json
(1)
.lock
(1)
.md
(1)
.ts
(42)
All 4 file types selected
Only manifest files
Deleted files
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
There are no files selected for viewing
7 changes: 2 additions & 5 deletions
7
bun.lock
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Original file line number
Diff line number
Diff line change
Expand Up
@@ -1032,7 +1032,11 @@ const mapFinishReason = (reason: string | null | undefined): FinishReason => {
// inclusive `inputTokens` the rest of the contract expects. Extended
// thinking tokens are included in `output_tokens`; newer responses also
// expose that subset through `output_tokens_details.thinking_tokens`.
const mapUsage = (usage: AnthropicUsage | undefined, providerMetadataKey: string): Usage | undefined => {
const mapUsage = (
usage: AnthropicUsage | undefined,
providerMetadataKey: string,
frame?: AnthropicEvent,
): Usage | undefined => {
if (!usage) return undefined
const iterations = usage.iterations?.length ? usage.iterations : [usage]
const last = usage.iterations?.at(-1)
Expand All
@@ -1059,7 +1063,7 @@ const mapUsage = (usage: AnthropicUsage | undefined, providerMetadataKey: string
cacheWriteInputTokens: cacheWrite,
reasoningTokens: ProviderShared.sumTokens(...iterations.map((item) => item.output_tokens_details?.thinking_tokens)),
totalTokens: ProviderShared.totalTokens(inputTokens, outputTokens, undefined),
...ProviderShared.reportedBilling(usage),
...ProviderShared.reportedBilling(usage, frame ),
providerMetadata: { [providerMetadataKey]: usage },
})
}
Expand Down
Expand Up
@@ -1331,7 +1335,11 @@ const onMessageDelta = (
state: ParserState,
event: AnthropicEvent & { readonly delta?: AnthropicStreamDelta },
): StepResult => {
const usage = mergeUsage(state.usage, mapUsage(event.usage, state.providerMetadataKey), state.providerMetadataKey)
const usage = mergeUsage(
state.usage,
mapUsage(event.usage, state.providerMetadataKey, event),
state.providerMetadataKey,
)
const pendingFinish = (() => {
const stopReason = event.delta?.stop_reason
if (stopReason === null || stopReason === undefined) return state.pendingFinish
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -890,7 +890,11 @@ export const fromRequest = (request: LLMRequest) => fromRequestWithAdapter(reque
// cached-read and cache-write subsets, and `output_tokens` (inclusive total)
// with a `reasoning_tokens` subset. Pass the totals through and derive the
// non-cached breakdown.
export const mapUsage = (usage: OpenResponsesUsage | null | undefined, providerMetadataKey: string) => {
export const mapUsage = (
usage: OpenResponsesUsage | null | undefined,
providerMetadataKey: string,
...frames: ReadonlyArray<unknown>
) => {
if (!usage) return undefined
const cached = usage.input_tokens_details?.cached_tokens
const cacheWrite = usage.input_tokens_details?.cache_write_tokens
Expand All
@@ -904,11 +908,41 @@ export const mapUsage = (usage: OpenResponsesUsage | null | undefined, providerM
cacheWriteInputTokens: cacheWrite,
reasoningTokens: reasoning,
totalTokens: ProviderShared.totalTokens(usage.input_tokens, usage.output_tokens, usage.total_tokens),
...ProviderShared.reportedBilling(usage),
...ProviderShared.reportedBilling(usage, ...frames ),
providerMetadata: { [providerMetadataKey]: usage },
})
}
// GitHub Copilot lists the filters that ran; the blocking one names its rule in `content_filter_raw`.
const decodeContentFilters = Schema.decodeUnknownOption(
Schema.Array(
Schema.Struct({
source_type: Schema.optional(Schema.String),
blocked: Schema.optional(Schema.Boolean),
content_filter_raw: Schema.optional(
Schema.Array(
Schema.Struct({
action: Schema.optional(Schema.String),
label: Schema.optional(Schema.String),
result: Schema.optional(Schema.Unknown),
}),
),
),
content_filter_results: Schema.optional(Schema.Unknown),
}),
),
)
const contentFilterCategory = (raw: unknown) => {
const blocked = Option.getOrElse(decodeContentFilters(raw), () => []).filter((filter) => filter.blocked)
const filter = blocked.find((item) => item.source_type === "completion") ?? blocked[0]
if (!filter) return undefined
return (
filter.content_filter_raw?.find((rule) => rule.action === "BLOCK" && rule.result === true)?.label ??
ProviderShared.contentFilterCategory(filter.content_filter_results)
)
}
const mapFinishReason = (event: Event, hasFunctionCall: boolean): FinishReason => {
const reason = event.response?.incomplete_details?.reason
if (reason === undefined) {
Expand Down
Expand Up
@@ -981,17 +1015,18 @@ const ITEM_ID_PREFIX: Readonly<Record<string, string>> = {
compaction: "cmp",
}
// An item without an id adopts the id already open in its output slot,
// otherwise it gets a locally minted one.
// An item adopts the id already open in its output slot, since GitHub Copilot
// sends a different id on every event, including the item's own done event.
// Otherwise it keeps its id or gets a locally minted one.
const resolveItem = (
state: Pick<ParserState, "outputItems">,
item: StreamItem,
index: number | undefined,
): OutputItem => ({
...item,
id:
item.id ??
(index === undefined ? undefined : state.outputItems[index]) ??
item.id ??
`${ITEM_ID_PREFIX[item.type] ?? "item"}_${crypto.randomUUID().replaceAll("-", "")}`,
})
Expand Down
Expand Up
@@ -1392,12 +1427,15 @@ const onResponseFinish = Effect.fnUntraced(function* (state: ParserState, event:
}
events.push(...pending.events)
}
const normalized = mapFinishReason(event, current.hasFunctionCall)
const lifecycle = Lifecycle.finish(current.lifecycle, events, {
reason: {
normalized: mapFinishReason(event, current.hasFunctionCall) ,
normalized,
raw: event.response?.incomplete_details?.reason,
...(normalized === "content-filter" ? { category: contentFilterCategory(event.response?.content_filters) } : {}),
},
usage: mapUsage(event.response?.usage, current.providerMetadataKey),
// Copilot reports its billing on the terminal event, beside `response`.
usage: mapUsage(event.response?.usage, current.providerMetadataKey, event, event.response),
providerMetadata:
event.response?.id || event.response?.service_tier
? providerMetadata(current, {
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -195,6 +195,7 @@ export const OpenAIChatMessage = Schema.Union([
reasoning: Schema.optional(Schema.String),
reasoning_text: Schema.optional(Schema.String),
reasoning_details: Schema.optional(Schema.Unknown),
reasoning_opaque: Schema.optional(Schema.String),
}),
[Schema.Record(Schema.String, Schema.Unknown)],
),
Expand Down
Expand Up
@@ -264,6 +265,8 @@ export const OpenAIChatUsage = Schema.StructWithRest(
prompt_cache_hit_tokens: optionalNull(Schema.Number),
cache_read_input_tokens: optionalNull(Schema.Number),
cache_created_input_tokens: optionalNull(Schema.Number),
// GitHub Copilot reports reasoning at the top level instead of in `completion_tokens_details`.
reasoning_tokens: optionalNull(Schema.Number),
prompt_tokens_details: optionalNull(
Schema.StructWithRest(
Schema.Struct({
Expand Down
Expand Up
@@ -309,6 +312,8 @@ export const OpenAIChatDelta = Schema.StructWithRest(
reasoning: optionalNull(Schema.String),
reasoning_text: optionalNull(Schema.String),
reasoning_details: optionalNull(Schema.Unknown),
// GitHub Copilot's opaque reasoning state, which must be replayed for multi-turn reasoning.
reasoning_opaque: optionalNull(Schema.String),
tool_calls: optionalNull(Schema.Array(OpenAIChatToolCallDelta)),
}),
[Schema.Record(Schema.String, Schema.Unknown)],
Expand Down
Expand Up
@@ -368,6 +373,8 @@ export interface ParserState {
readonly reasoningTextObserved: boolean
readonly reasoningDetails: Array<ReasoningDetail>
readonly reasoningDetailsObserved: boolean
/** Latest `reasoning_opaque`; interleaved reasoning sends a new one before each tool call. */
readonly reasoningOpaque?: string
readonly reasoningEmitted: boolean
readonly latestToolIndex?: number
readonly nextToolIndex: number
Expand Down
Expand Up
@@ -496,6 +503,13 @@ const lowerReasoningDetail = (detail: ReasoningDetail) => {
return detail
}
// Interleaved reasoning yields one opaque value per segment; like the Copilot VS Code
// client, replay the latest one with the concatenated reasoning text.
const reasoningOpaque = (parts: ReadonlyArray<ReasoningPart>, providerMetadataKey: string) =>
parts
.map((part) => part.providerMetadata?.[providerMetadataKey]?.reasoningOpaque)
.findLast((value) => typeof value === "string")
const isKimiDetail = (detail: { readonly type: string }) => detail.type === "summary" || detail.type === "encrypted"
const lowerUserMessage = Effect.fnUntraced(function* (message: UserMessage, options: LoweringOptions) {
Expand Down
Expand Up
@@ -560,7 +574,9 @@ const lowerAssistantMessage = Effect.fnUntraced(function* (
// even when thinking arrived only through structured details.
if (details?.some(isKimiDetail)) return "reasoning_content"
})()
const reasoningText = reasoning.length === 0 ? (requireReasoning ? "" : undefined) : text
const opaque = reasoningOpaque(reasoning, options.providerMetadataKey)
const reasoningText =
reasoning.length === 0 || (opaque !== undefined && text === "") ? (requireReasoning ? "" : undefined) : text
const result = {
role: "assistant" as const,
content: (() => {
Expand All
@@ -570,6 +586,7 @@ const lowerAssistantMessage = Effect.fnUntraced(function* (
})(),
...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
...(details !== undefined ? { reasoning_details: details } : {}),
...(opaque !== undefined ? { reasoning_opaque: opaque } : {}),
}
if (field === undefined || reasoningText === undefined) return result
return { ...result, [field]: reasoningText }
Expand Down
Expand Up
@@ -945,18 +962,29 @@ const mapFinishReason = Effect.fnUntraced(function* (event: OpenAIChatEvent, rea
// `prompt_tokens_details.cached_tokens`, DeepSeek uses
// `prompt_cache_hit_tokens`, Zai uses top-level `cached_tokens`, and
// DigitalOcean uses top-level `cache_read_input_tokens` / `cache_created_input_tokens`.
const mapUsage = (usage: OpenAIChatEvent["usage"], providerMetadataKey: string): Usage | undefined => {
const mapUsage = (
usage: OpenAIChatEvent["usage"],
providerMetadataKey: string,
frame: OpenAIChatEvent,
): Usage | undefined => {
if (!usage) return undefined
const input = usage.prompt_tokens ?? undefined
const output = usage.completion_tokens ?? undefined
const completion = usage.completion_tokens ?? undefined
const cached =
usage.prompt_tokens_details?.cached_tokens ??
usage.prompt_cache_hit_tokens ??
usage.cached_tokens ??
usage.cache_read_input_tokens ??
undefined
const cacheWrite = usage.prompt_tokens_details?.cache_write_tokens ?? usage.cache_created_input_tokens ?? undefined
const reasoning = usage.completion_tokens_details?.reasoning_tokens ?? undefined
const reasoning = usage.completion_tokens_details?.reasoning_tokens ?? usage.reasoning_tokens ?? undefined
// Copilot's Gemini counts reasoning beside `completion_tokens` rather than inside it; the total tells which.
const output =
completion !== undefined &&
reasoning !== undefined &&
usage.total_tokens === ProviderShared.sumTokens(input, completion, reasoning)
? completion + reasoning
: completion
const nonCached = ProviderShared.subtractTokens(input, ProviderShared.sumTokens(cached, cacheWrite))
return new Usage({
inputTokens: input,
Expand All
@@ -966,7 +994,7 @@ const mapUsage = (usage: OpenAIChatEvent["usage"], providerMetadataKey: string):
cacheWriteInputTokens: cacheWrite,
reasoningTokens: reasoning,
totalTokens: ProviderShared.totalTokens(input, output, usage.total_tokens ?? undefined),
...ProviderShared.reportedBilling(usage),
...ProviderShared.reportedBilling(usage, frame ),
providerMetadata: { [providerMetadataKey]: usage },
})
}
Expand Down
Expand Up
@@ -1075,10 +1103,12 @@ const reasoningMetadata = (
providerMetadataKey: string,
field: ParserState["reasoningField"],
details?: ReadonlyArray<ReasoningDetail>,
opaque?: string,
) => ({
[providerMetadataKey]: {
...(field ? { reasoningField: field } : {}),
...(details ? { reasoningDetails: details } : {}),
...(opaque ? { reasoningOpaque: opaque } : {}),
},
})
Expand All
@@ -1099,14 +1129,22 @@ const step = (state: ParserState, event: OpenAIChatEvent) =>
// Moonshot (and a few other OpenAI-compatible providers) attach usage to
// `choice.usage` instead of the top-level `usage` field.
const usage =
mapUsage(event.usage, state.providerMetadataKey) ??
mapUsage(choice?.usage, state.providerMetadataKey) ??
mapUsage(event.usage, state.providerMetadataKey, event ) ??
mapUsage(choice?.usage, state.providerMetadataKey, event ) ??
state.usage
const rawFinishReason = choice?.finish_reason
const finishReason = rawFinishReason
? {
normalized: yield* mapFinishReason(event, rawFinishReason),
raw: choice?.native_finish_reason ?? rawFinishReason,
...(rawFinishReason === "content_filter"
? {
category: ProviderShared.contentFilterCategory(
choice?.delta?.copilot_annotations,
choice?.content_filter_results,
),
}
: {}),
}
: state.finishReason
const delta = choice?.delta
Expand Down
Expand Up
@@ -1143,13 +1181,14 @@ const step = (state: ParserState, event: OpenAIChatEvent) =>
: undefined
if (detailDelta !== undefined) appendReasoningDetails(state.reasoningDetails, detailDelta)
const reasoningDetailsObserved = state.reasoningDetailsObserved || detailDelta !== undefined
const reasoningOpaque = delta?.reasoning_opaque || state.reasoningOpaque
const deltaMetadata = reasoningMetadata(state.providerMetadataKey, reasoningField)
const text = detailDelta?.length
? (detailText(detailDelta, reasoningTextObserved) ?? reasoning?.text)
: reasoning?.text
if (text !== undefined) lifecycle = Lifecycle.reasoningDelta(lifecycle, events, "reasoning-0", text, deltaMetadata)
else if (
reasoningDetailsObserved &&
( reasoningDetailsObserved || reasoningOpaque !== undefined) &&
!lifecycle.reasoning.has("reasoning-0") &&
(Boolean(delta?.content) || Boolean(delta?.refusal) || toolDeltas.length > 0)
)
Expand Down
Expand Up
@@ -1262,6 +1301,7 @@ const step = (state: ParserState, event: OpenAIChatEvent) =>
reasoningTextObserved,
reasoningDetails: state.reasoningDetails,
reasoningDetailsObserved,
reasoningOpaque,
reasoningEmitted,
latestToolIndex,
nextToolIndex,
Expand Down
Expand Up
@@ -1306,9 +1346,10 @@ export const finishEvents = Effect.fnUntraced(function* (state: ParserState) {
state.providerMetadataKey,
state.reasoningField,
state.reasoningDetailsObserved ? [...state.reasoningDetails] : undefined,
state.reasoningOpaque,
)
const started =
state.reasoningDetailsObserved && !state.reasoningEmitted
( state.reasoningDetailsObserved || state.reasoningOpaque !== undefined) && !state.reasoningEmitted
? Lifecycle.reasoningStart(
state.lifecycle,
events,
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -54,12 +54,36 @@ export const ReportedBilling = Schema.Struct({
cost: billedAmount,
})
/** Reads `ReportedBilling` from a raw usage object, which provider metadata keeps as the endpoint sent it. */
export const reportedBilling = (usage: unknown) =>
Option.match(Schema.decodeUnknownOption(ReportedBilling)(usage), {
onNone: () => ({}),
onSome: (billing) => ({ cost: billing.cost }),
})
/**
* GitHub Copilot reports its charge beside usage on the frame that carries it, as `copilot_usage.total_nano_aiu`:
* billionths of an AI credit, which costs $0.01.
*/
const CopilotBilling = Schema.Struct({
copilot_usage: Schema.Struct({ total_nano_aiu: Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0)) }),
})
const decodeCopilotBilling = Schema.decodeUnknownOption(CopilotBilling)
/**
* Reads `ReportedBilling` from a raw usage object, which provider metadata keeps as the endpoint sent it, or
* Copilot's billing from the frames that carry the usage.
*/
export const reportedBilling = (usage: unknown, ...frames: ReadonlyArray<unknown>) => {
const reported = Option.getOrUndefined(Schema.decodeUnknownOption(ReportedBilling)(usage))?.cost
if (reported !== undefined) return { cost: reported }
const nanoAiu = frames
.map((frame) => Option.getOrUndefined(decodeCopilotBilling(frame))?.copilot_usage.total_nano_aiu)
.find((value) => value !== undefined)
return nanoAiu === undefined ? {} : { cost: nanoAiu / 100_000_000_000 }
}
/**
* The filter that blocked a response, from maps keyed by filter name: Azure's `content_filter_results`
* (`{ hate: { filtered: true } }`) or GitHub Copilot's `copilot_annotations` (`{ TextCopyright: [...] }`).
*/
export const contentFilterCategory = (...sources: ReadonlyArray<unknown>) =>
sources
.flatMap((source) => (isRecord(source) ? Object.entries(source) : []))
.find(([, value]) => (isRecord(value) && "filtered" in value ? value.filtered === true : Boolean(value)))?.[0]
/**
* Accepts stream frames that carry no `type`, alongside the typed event schema. Gateways inject such frames as
Expand Down
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.