Merge pull request #1953 from maximharizanov/fix/copilot-initiator-attribution

fix(copilot): mark internal hook injections as agent-initiated
This commit is contained in:
YeonGyu-Kim
2026-02-20 11:54:01 +09:00
committed by GitHub
19 changed files with 292 additions and 22 deletions

View File

@@ -13,6 +13,7 @@ import {
normalizeSDKResponse,
promptWithModelSuggestionRetry,
resolveInheritedPromptTools,
createInternalAgentTextPart,
} from "../../shared"
import { setSessionTools } from "../../shared/session-tools-store"
import { ConcurrencyManager } from "./concurrency"
@@ -1311,7 +1312,7 @@ Use \`background_output(task_id="${task.id}")\` to retrieve this result when rea
...(agent !== undefined ? { agent } : {}),
...(model !== undefined ? { model } : {}),
...(tools ? { tools } : {}),
parts: [{ type: "text", text: notification }],
parts: [createInternalAgentTextPart(notification)],
},
})
log("[background-agent] Sent notification to parent session:", {

View File

@@ -1,7 +1,7 @@
import type { BackgroundTask } from "./types"
import type { ResultHandlerContext } from "./result-handler-context"
import { TASK_CLEANUP_DELAY_MS } from "./constants"
import { log } from "../../shared"
import { createInternalAgentTextPart, log } from "../../shared"
import { getTaskToastManager } from "../task-toast-manager"
import { formatDuration } from "./duration-formatter"
import { buildBackgroundTaskNotificationText } from "./background-task-notification-template"
@@ -72,7 +72,7 @@ export async function notifyParentSession(
...(agent !== undefined ? { agent } : {}),
...(model !== undefined ? { model } : {}),
...(tools ? { tools } : {}),
parts: [{ type: "text", text: notification }],
parts: [createInternalAgentTextPart(notification)],
},
})

View File

@@ -5,7 +5,7 @@ import { MESSAGE_STORAGE, PART_STORAGE } from "./constants"
import type { MessageMeta, OriginalMessageContext, TextPart, ToolPermission } from "./types"
import { log } from "../../shared/logger"
import { isSqliteBackend } from "../../shared/opencode-storage-detection"
import { normalizeSDKResponse } from "../../shared"
import { createInternalAgentTextPart, normalizeSDKResponse } from "../../shared"
export interface StoredMessage {
agent?: string
@@ -331,7 +331,7 @@ export function injectHookMessage(
const textPart: TextPart = {
id: partID,
type: "text",
text: hookContent,
text: createInternalAgentTextPart(hookContent).text,
synthetic: true,
time: {
start: now,

View File

@@ -1,7 +1,7 @@
import type { PluginInput } from "@opencode-ai/plugin"
import type { BackgroundManager } from "../../features/background-agent"
import { log } from "../../shared/logger"
import { resolveInheritedPromptTools } from "../../shared"
import { createInternalAgentTextPart, resolveInheritedPromptTools } from "../../shared"
import { HOOK_NAME } from "./hook-name"
import { BOULDER_CONTINUATION_PROMPT } from "./system-reminder-templates"
import { resolveRecentPromptContextForSession } from "./recent-model-resolver"
@@ -53,7 +53,7 @@ export async function injectBoulderContinuation(input: {
agent: agent ?? "atlas",
...(promptContext.model !== undefined ? { model: promptContext.model } : {}),
...(inheritedTools ? { tools: inheritedTools } : {}),
parts: [{ type: "text", text: prompt }],
parts: [createInternalAgentTextPart(prompt)],
},
query: { directory: ctx.directory },
})

View File

@@ -3,7 +3,7 @@ import { loadClaudeHooksConfig } from "../config"
import { loadPluginExtendedConfig } from "../config-loader"
import { executeStopHooks, type StopContext } from "../stop"
import type { PluginConfig } from "../types"
import { isHookDisabled, log } from "../../../shared"
import { createInternalAgentTextPart, isHookDisabled, log } from "../../../shared"
import {
clearSessionHookState,
sessionErrorState,
@@ -94,7 +94,7 @@ export function createSessionEventHandler(ctx: PluginInput, config: PluginConfig
.prompt({
path: { id: sessionID },
body: {
parts: [{ type: "text", text: stopResult.injectPrompt }],
parts: [createInternalAgentTextPart(stopResult.injectPrompt)],
},
query: { directory: ctx.directory },
})

View File

@@ -3,7 +3,11 @@ import { log } from "../../shared/logger"
import { findNearestMessageWithFields } from "../../features/hook-message-injector"
import { getMessageDir } from "./message-storage-directory"
import { withTimeout } from "./with-timeout"
import { normalizeSDKResponse, resolveInheritedPromptTools } from "../../shared"
import {
createInternalAgentTextPart,
normalizeSDKResponse,
resolveInheritedPromptTools,
} from "../../shared"
type MessageInfo = {
agent?: string
@@ -64,7 +68,7 @@ export async function injectContinuationPrompt(
...(agent !== undefined ? { agent } : {}),
...(model !== undefined ? { model } : {}),
...(inheritedTools ? { tools: inheritedTools } : {}),
parts: [{ type: "text", text: options.prompt }],
parts: [createInternalAgentTextPart(options.prompt)],
},
query: { directory: options.directory },
})

View File

@@ -1,6 +1,7 @@
declare const require: (name: string) => any
const { describe, expect, test } = require("bun:test")
import { extractResumeConfig, resumeSession } from "./resume"
import { OMO_INTERNAL_INITIATOR_MARKER } from "../../shared/internal-initiator-marker"
import type { MessageData } from "./types"
describe("session-recovery resume", () => {
@@ -44,5 +45,8 @@ describe("session-recovery resume", () => {
// then
expect(ok).toBe(true)
expect(promptBody?.tools).toEqual({ question: false, bash: true })
expect(Array.isArray(promptBody?.parts)).toBe(true)
const firstPart = (promptBody?.parts as Array<{ text?: string }>)?.[0]
expect(firstPart?.text).toContain(OMO_INTERNAL_INITIATOR_MARKER)
})
})

View File

@@ -1,6 +1,6 @@
import type { createOpencodeClient } from "@opencode-ai/sdk"
import type { MessageData, ResumeConfig } from "./types"
import { resolveInheritedPromptTools } from "../../shared"
import { createInternalAgentTextPart, resolveInheritedPromptTools } from "../../shared"
const RECOVERY_RESUME_TEXT = "[session recovered - continuing previous task]"
@@ -30,7 +30,7 @@ export async function resumeSession(client: Client, config: ResumeConfig): Promi
await client.session.promptAsync({
path: { id: config.sessionID },
body: {
parts: [{ type: "text", text: RECOVERY_RESUME_TEXT }],
parts: [createInternalAgentTextPart(RECOVERY_RESUME_TEXT)],
agent: config.agent,
model: config.model,
...(inheritedTools ? { tools: inheritedTools } : {}),

View File

@@ -2,18 +2,26 @@ declare const require: (name: string) => any
const { describe, expect, test } = require("bun:test")
import { injectContinuation } from "./continuation-injection"
import { OMO_INTERNAL_INITIATOR_MARKER } from "../../shared/internal-initiator-marker"
describe("injectContinuation", () => {
test("inherits tools from resolved message info when reinjecting", async () => {
// given
let capturedTools: Record<string, boolean> | undefined
let capturedText: string | undefined
const ctx = {
directory: "/tmp/test",
client: {
session: {
todo: async () => ({ data: [{ id: "1", content: "todo", status: "pending", priority: "high" }] }),
promptAsync: async (input: { body: { tools?: Record<string, boolean> } }) => {
promptAsync: async (input: {
body: {
tools?: Record<string, boolean>
parts?: Array<{ type: string; text: string }>
}
}) => {
capturedTools = input.body.tools
capturedText = input.body.parts?.[0]?.text
return {}
},
},
@@ -37,5 +45,6 @@ describe("injectContinuation", () => {
// then
expect(capturedTools).toEqual({ question: false, bash: true })
expect(capturedText).toContain(OMO_INTERNAL_INITIATOR_MARKER)
})
})

View File

@@ -1,7 +1,11 @@
import type { PluginInput } from "@opencode-ai/plugin"
import type { BackgroundManager } from "../../features/background-agent"
import { normalizeSDKResponse, resolveInheritedPromptTools } from "../../shared"
import {
createInternalAgentTextPart,
normalizeSDKResponse,
resolveInheritedPromptTools,
} from "../../shared"
import {
findNearestMessageWithFields,
findNearestMessageWithFieldsFromSDK,
@@ -151,7 +155,7 @@ ${todoList}`
agent: agentName,
...(model !== undefined ? { model } : {}),
...(inheritedTools ? { tools: inheritedTools } : {}),
parts: [{ type: "text", text: prompt }],
parts: [createInternalAgentTextPart(prompt)],
},
query: { directory: ctx.directory },
})

View File

@@ -1,6 +1,7 @@
import { afterEach, describe, expect, test } from "bun:test"
import { _resetForTesting, setMainSession } from "../../features/claude-code-session-state"
import type { BackgroundTask } from "../../features/background-agent"
import { OMO_INTERNAL_INITIATOR_MARKER } from "../../shared/internal-initiator-marker"
import { createUnstableAgentBabysitterHook } from "./index"
const projectDir = process.cwd()
@@ -93,6 +94,7 @@ describe("unstable-agent-babysitter hook", () => {
expect(text).toContain("background_output")
expect(text).toContain("background_cancel")
expect(text).toContain("deep thought")
expect(text).toContain(OMO_INTERNAL_INITIATOR_MARKER)
})
test("fires reminder for hung minimax task", async () => {
@@ -128,6 +130,7 @@ describe("unstable-agent-babysitter hook", () => {
expect(text).toContain("background_output")
expect(text).toContain("background_cancel")
expect(text).toContain("minimax thought")
expect(text).toContain(OMO_INTERNAL_INITIATOR_MARKER)
})
test("does not remind stable model tasks", async () => {

View File

@@ -1,7 +1,7 @@
import type { BackgroundManager } from "../../features/background-agent"
import { getMainSessionID, getSessionAgent } from "../../features/claude-code-session-state"
import { log } from "../../shared/logger"
import { resolveInheritedPromptTools } from "../../shared"
import { createInternalAgentTextPart, resolveInheritedPromptTools } from "../../shared"
import {
buildReminder,
extractMessages,
@@ -158,7 +158,7 @@ export function createUnstableAgentBabysitterHook(ctx: BabysitterContext, option
...(agent ? { agent } : {}),
...(model ? { model } : {}),
...(tools ? { tools } : {}),
parts: [{ type: "text", text: reminder }],
parts: [createInternalAgentTextPart(reminder)],
},
query: { directory: ctx.directory },
})

View File

@@ -2,6 +2,7 @@ import type { PluginContext, PluginInterface, ToolsRecord } from "./plugin/types
import type { OhMyOpenCodeConfig } from "./config"
import { createChatParamsHandler } from "./plugin/chat-params"
import { createChatHeadersHandler } from "./plugin/chat-headers"
import { createChatMessageHandler } from "./plugin/chat-message"
import { createMessagesTransformHandler } from "./plugin/messages-transform"
import { createEventHandler } from "./plugin/event"
@@ -30,11 +31,13 @@ export function createPluginInterface(args: {
return {
tool: tools,
"chat.params": async (input, output) => {
"chat.params": async (input: unknown, output: unknown) => {
const handler = createChatParamsHandler({ anthropicEffort: hooks.anthropicEffort })
await handler(input, output)
},
"chat.headers": createChatHeadersHandler({ ctx }),
"chat.message": createChatMessageHandler({
ctx,
pluginConfig,

View File

@@ -0,0 +1,109 @@
import { describe, expect, test } from "bun:test"
import { OMO_INTERNAL_INITIATOR_MARKER } from "../shared"
import { createChatHeadersHandler } from "./chat-headers"
describe("createChatHeadersHandler", () => {
test("sets x-initiator=agent for Copilot internal marker messages", async () => {
const handler = createChatHeadersHandler({
ctx: {
client: {
session: {
message: async () => ({
data: {
parts: [
{
type: "text",
text: `notification\n${OMO_INTERNAL_INITIATOR_MARKER}`,
},
],
},
}),
},
},
} as never,
})
const output: { headers: Record<string, string> } = { headers: {} }
await handler(
{
sessionID: "ses_1",
provider: { id: "github-copilot" },
message: {
id: "msg_1",
role: "user",
},
},
output,
)
expect(output.headers["x-initiator"]).toBe("agent")
})
test("does not override non-copilot providers", async () => {
const handler = createChatHeadersHandler({
ctx: {
client: {
session: {
message: async () => ({
data: {
parts: [
{
type: "text",
text: `notification\n${OMO_INTERNAL_INITIATOR_MARKER}`,
},
],
},
}),
},
},
} as never,
})
const output: { headers: Record<string, string> } = { headers: {} }
await handler(
{
sessionID: "ses_1",
provider: { id: "openai" },
message: {
id: "msg_1",
role: "user",
},
},
output,
)
expect(output.headers["x-initiator"]).toBeUndefined()
})
test("does not override regular user messages", async () => {
const handler = createChatHeadersHandler({
ctx: {
client: {
session: {
message: async () => ({
data: {
parts: [{ type: "text", text: "normal user message" }],
},
}),
},
},
} as never,
})
const output: { headers: Record<string, string> } = { headers: {} }
await handler(
{
sessionID: "ses_1",
provider: { id: "github-copilot" },
message: {
id: "msg_1",
role: "user",
},
},
output,
)
expect(output.headers["x-initiator"]).toBeUndefined()
})
})

104
src/plugin/chat-headers.ts Normal file
View File

@@ -0,0 +1,104 @@
import { OMO_INTERNAL_INITIATOR_MARKER } from "../shared"
import type { PluginContext } from "./types"
type ChatHeadersInput = {
sessionID: string
provider: { id: string }
message: {
id?: string
role?: string
}
}
type ChatHeadersOutput = {
headers: Record<string, string>
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null
}
function buildChatHeadersInput(raw: unknown): ChatHeadersInput | null {
if (!isRecord(raw)) return null
const sessionID = raw.sessionID
const provider = raw.provider
const message = raw.message
if (typeof sessionID !== "string") return null
if (!isRecord(provider) || typeof provider.id !== "string") return null
if (!isRecord(message)) return null
return {
sessionID,
provider: { id: provider.id },
message: {
id: typeof message.id === "string" ? message.id : undefined,
role: typeof message.role === "string" ? message.role : undefined,
},
}
}
function isChatHeadersOutput(raw: unknown): raw is ChatHeadersOutput {
if (!isRecord(raw)) return false
if (!isRecord(raw.headers)) {
raw.headers = {}
}
return isRecord(raw.headers)
}
function isCopilotProvider(providerID: string): boolean {
return providerID === "github-copilot" || providerID === "github-copilot-enterprise"
}
async function hasInternalMarker(
client: PluginContext["client"],
sessionID: string,
messageID: string,
): Promise<boolean> {
try {
const response = await client.session.message({
path: { id: sessionID, messageID },
})
const data = response.data
if (!isRecord(data) || !Array.isArray(data.parts)) return false
return data.parts.some((part) => {
if (!isRecord(part) || part.type !== "text" || typeof part.text !== "string") {
return false
}
return part.text.includes(OMO_INTERNAL_INITIATOR_MARKER)
})
} catch {
return false
}
}
async function isOmoInternalMessage(input: ChatHeadersInput, client: PluginContext["client"]): Promise<boolean> {
if (input.message.role !== "user") {
return false
}
if (!input.message.id) {
return false
}
return hasInternalMarker(client, input.sessionID, input.message.id)
}
export function createChatHeadersHandler(args: { ctx: PluginContext }): (input: unknown, output: unknown) => Promise<void> {
const { ctx } = args
return async (input, output): Promise<void> => {
const normalizedInput = buildChatHeadersInput(input)
if (!normalizedInput) return
if (!isChatHeadersOutput(output)) return
if (!isCopilotProvider(normalizedInput.provider.id)) return
if (!(await isOmoInternalMessage(normalizedInput, ctx.client))) return
output.headers["x-initiator"] = "agent"
}
}

View File

@@ -2,7 +2,17 @@ import type { Plugin, ToolDefinition } from "@opencode-ai/plugin"
export type PluginContext = Parameters<Plugin>[0]
export type PluginInstance = Awaited<ReturnType<Plugin>>
export type PluginInterface = Omit<PluginInstance, "experimental.session.compacting">
type ChatHeadersHook = PluginInstance extends { "chat.headers"?: infer T }
? T
: (input: unknown, output: unknown) => Promise<void>
export type PluginInterface = Omit<
PluginInstance,
"experimental.session.compacting" | "chat.headers"
> & {
"chat.headers"?: ChatHeadersHook
}
export type ToolsRecord = Record<string, ToolDefinition>

View File

@@ -57,3 +57,4 @@ export * from "./opencode-message-dir"
export * from "./normalize-sdk-response"
export * from "./session-directory-resolver"
export * from "./prompt-tools"
export * from "./internal-initiator-marker"

View File

@@ -0,0 +1,11 @@
export const OMO_INTERNAL_INITIATOR_MARKER = "<!-- OMO_INTERNAL_INITIATOR -->"
export function createInternalAgentTextPart(text: string): {
type: "text"
text: string
} {
return {
type: "text",
text: `${text}\n${OMO_INTERNAL_INITIATOR_MARKER}`,
}
}

View File

@@ -16,6 +16,10 @@ type ToolContextWithCallID = ToolContext & {
call_id?: string
}
type ToolContextWithMetadata = ToolContextWithCallID & {
metadata?: (value: unknown) => void
}
function resolveToolCallID(ctx: ToolContextWithCallID): string | undefined {
if (typeof ctx.callID === "string" && ctx.callID.trim() !== "") return ctx.callID
if (typeof ctx.callId === "string" && ctx.callId.trim() !== "") return ctx.callId
@@ -145,6 +149,7 @@ CONTENT FORMAT:
},
execute: async (args: HashlineEditArgs, context: ToolContext) => {
try {
const metadataContext = context as ToolContextWithMetadata
const filePath = args.filePath
const { edits } = args
@@ -188,9 +193,11 @@ CONTENT FORMAT:
},
}
context.metadata(meta)
if (typeof metadataContext.metadata === "function") {
metadataContext.metadata(meta)
}
const callID = resolveToolCallID(context)
const callID = resolveToolCallID(metadataContext)
if (callID) {
storeToolMetadata(context.sessionID, callID, meta)
}