fix(continuation): auto-continue GPT permission-seeking replies

Resume GPT sessions when the last assistant reply ends in a permission-seeking tail, while honoring stop-continuation and avoiding duplicate continuation across todo and atlas flows.

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
This commit is contained in:
YeonGyu-Kim
2026-03-11 21:19:29 +09:00
parent 3f364cc8df
commit a1b060841f
22 changed files with 617 additions and 4 deletions
@@ -0,0 +1,44 @@
type TextPart = {
type?: string
text?: string
}
type MessageInfo = {
id?: string
role?: string
error?: unknown
model?: {
providerID?: string
modelID?: string
}
providerID?: string
modelID?: string
}
export type SessionMessage = {
info?: MessageInfo
parts?: TextPart[]
}
export function getLastAssistantMessage(messages: SessionMessage[]): SessionMessage | null {
for (let index = messages.length - 1; index >= 0; index--) {
if (messages[index].info?.role === "assistant") {
return messages[index]
}
}
return null
}
export function extractAssistantText(message: SessionMessage): string {
return (message.parts ?? [])
.filter((part) => part.type === "text" && typeof part.text === "string")
.map((part) => part.text?.trim() ?? "")
.filter(Boolean)
.join("\n")
}
export function isGptAssistantMessage(message: SessionMessage): boolean {
const modelID = message.info?.model?.modelID ?? message.info?.modelID
return typeof modelID === "string" && modelID.toLowerCase().includes("gpt")
}
@@ -0,0 +1,10 @@
export const HOOK_NAME = "gpt-permission-continuation"
export const CONTINUATION_PROMPT = "continue"
export const DEFAULT_STALL_PATTERNS = [
"if you want",
"would you like",
"shall i",
"do you want me to",
"let me know if",
] as const
@@ -0,0 +1,23 @@
import { DEFAULT_STALL_PATTERNS } from "./constants"
function getTrailingSegment(text: string): string {
const normalized = text.trim().replace(/\s+/g, " ")
if (!normalized) return ""
const sentenceParts = normalized.split(/(?<=[.!?])\s+/)
return sentenceParts[sentenceParts.length - 1]?.trim().toLowerCase() ?? ""
}
export function detectStallPattern(
text: string,
patterns: readonly string[] = DEFAULT_STALL_PATTERNS,
): boolean {
if (!text.trim()) return false
const tail = text.slice(-800)
const lines = tail.split("\n").map((line) => line.trim()).filter(Boolean)
const hotZone = lines.slice(-3).join(" ")
const trailingSegment = getTrailingSegment(hotZone)
return patterns.some((pattern) => trailingSegment.startsWith(pattern.toLowerCase()))
}
@@ -0,0 +1,150 @@
import { describe, expect, test } from "bun:test"
import { createGptPermissionContinuationHook } from "."
type SessionMessage = {
info: {
id: string
role: "user" | "assistant"
model?: {
providerID?: string
modelID?: string
}
modelID?: string
}
parts?: Array<{ type: string; text?: string }>
}
function createMockPluginInput(messages: SessionMessage[]) {
const promptCalls: string[] = []
const ctx = {
directory: "/tmp/test",
client: {
session: {
messages: async () => ({ data: messages }),
prompt: async (input: { body: { parts: Array<{ text: string }> } }) => {
promptCalls.push(input.body.parts[0]?.text ?? "")
return {}
},
promptAsync: async (input: { body: { parts: Array<{ text: string }> } }) => {
promptCalls.push(input.body.parts[0]?.text ?? "")
return {}
},
},
},
} as any
return { ctx, promptCalls }
}
describe("gpt-permission-continuation", () => {
test("injects continue when the last GPT assistant reply asks for permission", async () => {
// given
const { ctx, promptCalls } = createMockPluginInput([
{
info: { id: "msg-1", role: "assistant", modelID: "gpt-5.4" },
parts: [{ type: "text", text: "I finished the analysis. If you want, I can apply the changes next." }],
},
])
const hook = createGptPermissionContinuationHook(ctx)
// when
await hook.handler({ event: { type: "session.idle", properties: { sessionID: "ses-1" } } })
// then
expect(promptCalls).toEqual(["continue"])
})
test("does not inject when the last assistant model is not GPT", async () => {
// given
const { ctx, promptCalls } = createMockPluginInput([
{
info: {
id: "msg-1",
role: "assistant",
model: { providerID: "anthropic", modelID: "claude-sonnet-4" },
},
parts: [{ type: "text", text: "If you want, I can keep going." }],
},
])
const hook = createGptPermissionContinuationHook(ctx)
// when
await hook.handler({ event: { type: "session.idle", properties: { sessionID: "ses-1" } } })
// then
expect(promptCalls).toEqual([])
})
test("does not inject when the last assistant reply is not a stall pattern", async () => {
// given
const { ctx, promptCalls } = createMockPluginInput([
{
info: { id: "msg-1", role: "assistant", modelID: "gpt-5.4" },
parts: [{ type: "text", text: "I completed the refactor and all tests pass." }],
},
])
const hook = createGptPermissionContinuationHook(ctx)
// when
await hook.handler({ event: { type: "session.idle", properties: { sessionID: "ses-1" } } })
// then
expect(promptCalls).toEqual([])
})
test("does not inject when a permission phrase appears before the final sentence", async () => {
// given
const { ctx, promptCalls } = createMockPluginInput([
{
info: { id: "msg-1", role: "assistant", modelID: "gpt-5.4" },
parts: [{ type: "text", text: "If you want, I can keep going. The current work is complete." }],
},
])
const hook = createGptPermissionContinuationHook(ctx)
// when
await hook.handler({ event: { type: "session.idle", properties: { sessionID: "ses-1" } } })
// then
expect(promptCalls).toEqual([])
})
test("does not inject when continuation is stopped for the session", async () => {
// given
const { ctx, promptCalls } = createMockPluginInput([
{
info: { id: "msg-1", role: "assistant", modelID: "gpt-5.4" },
parts: [{ type: "text", text: "If you want, I can continue with the fix." }],
},
])
const hook = createGptPermissionContinuationHook(ctx, {
isContinuationStopped: (sessionID) => sessionID === "ses-1",
})
// when
await hook.handler({ event: { type: "session.idle", properties: { sessionID: "ses-1" } } })
// then
expect(promptCalls).toEqual([])
})
test("does not inject twice for the same assistant message", async () => {
// given
const { ctx, promptCalls } = createMockPluginInput([
{
info: { id: "msg-1", role: "assistant", modelID: "gpt-5.4" },
parts: [{ type: "text", text: "Would you like me to continue with the fix?" }],
},
])
const hook = createGptPermissionContinuationHook(ctx)
// when
await hook.handler({ event: { type: "session.idle", properties: { sessionID: "ses-1" } } })
await hook.handler({ event: { type: "session.idle", properties: { sessionID: "ses-1" } } })
// then
expect(promptCalls).toEqual(["continue"])
})
})
@@ -0,0 +1,116 @@
import type { PluginInput } from "@opencode-ai/plugin"
import { normalizeSDKResponse } from "../../shared"
import { log } from "../../shared/logger"
import {
extractAssistantText,
getLastAssistantMessage,
isGptAssistantMessage,
type SessionMessage,
} from "./assistant-message"
import { CONTINUATION_PROMPT, HOOK_NAME } from "./constants"
import { detectStallPattern } from "./detector"
import type { SessionStateStore } from "./session-state"
async function promptContinuation(
ctx: PluginInput,
sessionID: string,
): Promise<void> {
const payload = {
path: { id: sessionID },
body: {
parts: [{ type: "text" as const, text: CONTINUATION_PROMPT }],
},
query: { directory: ctx.directory },
}
if (typeof ctx.client.session.promptAsync === "function") {
await ctx.client.session.promptAsync(payload)
return
}
await ctx.client.session.prompt(payload)
}
export function createGptPermissionContinuationHandler(args: {
ctx: PluginInput
sessionStateStore: SessionStateStore
isContinuationStopped?: (sessionID: string) => boolean
}): (input: { event: { type: string; properties?: unknown } }) => Promise<void> {
const { ctx, sessionStateStore, isContinuationStopped } = args
return async ({ event }: { event: { type: string; properties?: unknown } }): Promise<void> => {
const properties = event.properties as Record<string, unknown> | undefined
if (event.type === "session.deleted") {
const sessionID = (properties?.info as { id?: string } | undefined)?.id
if (sessionID) {
sessionStateStore.cleanup(sessionID)
}
return
}
if (event.type !== "session.idle") return
const sessionID = properties?.sessionID as string | undefined
if (!sessionID) return
if (isContinuationStopped?.(sessionID)) {
log(`[${HOOK_NAME}] Skipped: continuation stopped for session`, { sessionID })
return
}
const state = sessionStateStore.getState(sessionID)
if (state.inFlight) {
log(`[${HOOK_NAME}] Skipped: prompt already in flight`, { sessionID })
return
}
try {
const messagesResponse = await ctx.client.session.messages({
path: { id: sessionID },
query: { directory: ctx.directory },
})
const messages = normalizeSDKResponse(messagesResponse, [] as SessionMessage[], {
preferResponseOnMissingData: true,
})
const lastAssistantMessage = getLastAssistantMessage(messages)
if (!lastAssistantMessage) return
const messageID = lastAssistantMessage.info?.id
if (messageID && state.lastHandledMessageID === messageID) {
log(`[${HOOK_NAME}] Skipped: already handled assistant message`, { sessionID, messageID })
return
}
if (lastAssistantMessage.info?.error) {
log(`[${HOOK_NAME}] Skipped: last assistant message has error`, { sessionID, messageID })
return
}
if (!isGptAssistantMessage(lastAssistantMessage)) {
log(`[${HOOK_NAME}] Skipped: last assistant model is not GPT`, { sessionID, messageID })
return
}
const assistantText = extractAssistantText(lastAssistantMessage)
if (!detectStallPattern(assistantText)) {
return
}
state.inFlight = true
await promptContinuation(ctx, sessionID)
state.lastHandledMessageID = messageID
state.lastInjectedAt = Date.now()
log(`[${HOOK_NAME}] Injected continuation prompt`, { sessionID, messageID })
} catch (error) {
log(`[${HOOK_NAME}] Failed to inject continuation prompt`, {
sessionID,
error: String(error),
})
} finally {
state.inFlight = false
}
}
}
@@ -0,0 +1,29 @@
import type { PluginInput } from "@opencode-ai/plugin"
import { createGptPermissionContinuationHandler } from "./handler"
import { createSessionStateStore } from "./session-state"
export type GptPermissionContinuationHook = {
handler: (input: { event: { type: string; properties?: unknown } }) => Promise<void>
wasRecentlyInjected: (sessionID: string) => boolean
}
export function createGptPermissionContinuationHook(
ctx: PluginInput,
options?: {
isContinuationStopped?: (sessionID: string) => boolean
},
): GptPermissionContinuationHook {
const sessionStateStore = createSessionStateStore()
return {
handler: createGptPermissionContinuationHandler({
ctx,
sessionStateStore,
isContinuationStopped: options?.isContinuationStopped,
}),
wasRecentlyInjected(sessionID: string): boolean {
return sessionStateStore.wasRecentlyInjected(sessionID, 5_000)
},
}
}
@@ -0,0 +1,34 @@
type SessionState = {
inFlight: boolean
lastHandledMessageID?: string
lastInjectedAt?: number
}
export type SessionStateStore = ReturnType<typeof createSessionStateStore>
export function createSessionStateStore() {
const states = new Map<string, SessionState>()
const getState = (sessionID: string): SessionState => {
const existing = states.get(sessionID)
if (existing) return existing
const created: SessionState = {
inFlight: false,
}
states.set(sessionID, created)
return created
}
return {
getState,
wasRecentlyInjected(sessionID: string, windowMs: number): boolean {
const state = states.get(sessionID)
if (!state?.lastInjectedAt) return false
return Date.now() - state.lastInjectedAt <= windowMs
},
cleanup(sessionID: string): void {
states.delete(sessionID)
},
}
}
@@ -0,0 +1,62 @@
import { describe, expect, test } from "bun:test"
import { createTodoContinuationEnforcer } from "../todo-continuation-enforcer"
import { createGptPermissionContinuationHook } from "."
describe("gpt-permission-continuation coordination", () => {
test("injects only once when GPT permission continuation and todo continuation are both eligible", async () => {
// given
const promptCalls: string[] = []
const toastCalls: string[] = []
const sessionID = "ses-dual-continuation"
const ctx = {
directory: "/tmp/test",
client: {
session: {
messages: async () => ({
data: [
{
info: { id: "msg-1", role: "assistant", modelID: "gpt-5.4" },
parts: [{ type: "text", text: "If you want, I can implement the fix next." }],
},
],
}),
todo: async () => ({
data: [{ id: "1", content: "Task 1", status: "pending", priority: "high" }],
}),
prompt: async (input: { body: { parts: Array<{ text: string }> } }) => {
promptCalls.push(input.body.parts[0]?.text ?? "")
return {}
},
promptAsync: async (input: { body: { parts: Array<{ text: string }> } }) => {
promptCalls.push(input.body.parts[0]?.text ?? "")
return {}
},
},
tui: {
showToast: async (input: { body: { title: string } }) => {
toastCalls.push(input.body.title)
return {}
},
},
},
} as any
const gptPermissionContinuation = createGptPermissionContinuationHook(ctx)
const todoContinuationEnforcer = createTodoContinuationEnforcer(ctx, {
shouldSkipContinuation: (id) => gptPermissionContinuation.wasRecentlyInjected(id),
})
// when
await gptPermissionContinuation.handler({
event: { type: "session.idle", properties: { sessionID } },
})
await todoContinuationEnforcer.handler({
event: { type: "session.idle", properties: { sessionID } },
})
// then
expect(promptCalls).toEqual(["continue"])
expect(toastCalls).toEqual([])
})
})