Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/desktop-electron/src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -615,7 +615,7 @@ registerAboutIpc()

function killSidecar() {
if (!server) return
server.stop()
server.stop(true)
server = null
}

Expand Down
96 changes: 89 additions & 7 deletions packages/opencode/src/pty/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,15 @@ import { envValueCaseInsensitive, withoutInternalServerAuthEnv } from "@/util/en
import { PtyID } from "./schema"
import { Effect, Layer, Context } from "effect"
import * as EffectLogger from "@opencode-ai/core/effect/logger"
import { setTimeout as sleep } from "node:timers/promises"

export namespace Pty {
const log = Log.create({ service: "pty" })

const BUFFER_LIMIT = 1024 * 1024 * 2
const BUFFER_CHUNK = 64 * 1024
const TERMINATION_GRACE_MS = 200
const EXIT_WAIT_MS = 1000
const encoder = new TextEncoder()

type Socket = {
Expand Down Expand Up @@ -121,10 +124,8 @@ export namespace Pty {
Effect.gen(function* () {
const bus = yield* Bus.Service
const plugin = yield* Plugin.Service
function teardown(session: Active) {
try {
session.process.kill()
} catch {}

function closeSubscribers(session: Active) {
for (const [sub, ws] of session.subscribers.entries()) {
try {
if (sock(ws) === sub) ws.close()
Expand All @@ -133,6 +134,87 @@ export namespace Pty {
session.subscribers.clear()
}

function waitForExit(session: Active) {
if (session.info.status === "exited") return Promise.resolve()
return new Promise<void>((resolve) => {
const timer = setTimeout(resolve, EXIT_WAIT_MS)
const sub = session.process.onExit(() => {
clearTimeout(timer)
sub.dispose()
resolve()
})
})
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

function processExists(pid: number) {
try {
process.kill(pid, 0)
return true
} catch {
return false
}
}

const hasExited = (session: Active) => session.info.status === "exited" || !processExists(session.process.pid)

async function descendantPids(pid: number) {
if (process.platform === "win32") return []
const seen = new Set<number>()
const pending = [pid]
while (pending.length) {
const parent = pending.pop()!
const out = await Bun.$`pgrep -P ${parent}`.quiet().nothrow().text()
for (const line of out.split(/\s+/)) {
const child = Number(line)
if (!Number.isInteger(child) || child <= 0 || seen.has(child)) continue
seen.add(child)
pending.push(child)
}
}
return Array.from(seen)
}

function signalProcess(session: Active, signal: string) {
if (session.info.status === "exited") return
try {
session.process.kill(signal)
} catch {}
}

const terminate = Effect.fn("Pty.terminate")(function* (session: Active) {
if (hasExited(session)) return
const exited = waitForExit(session)
if (process.platform === "win32") {
signalProcess(session, "SIGTERM")
yield* Effect.promise(() => exited)
return
}

const descendants = yield* Effect.promise(() => descendantPids(session.process.pid))
signalProcess(session, "SIGTERM")
for (const child of descendants) {
try {
if (processExists(child)) process.kill(child, "SIGTERM")
} catch {}
}
yield* Effect.promise(() =>
Promise.race([exited.then(() => true), sleep(TERMINATION_GRACE_MS).then(() => false)]),
)
if (hasExited(session)) return
signalProcess(session, "SIGKILL")
for (const child of descendants) {
try {
if (processExists(child)) process.kill(child, "SIGKILL")
} catch {}
}
yield* Effect.promise(() => exited)
})

const teardown = Effect.fn("Pty.teardown")(function* (session: Active) {
closeSubscribers(session)
yield* terminate(session)
})

const state = yield* InstanceState.make<State>(
Effect.fn("Pty.state")(function* (ctx) {
const state = {
Expand All @@ -141,9 +223,9 @@ export namespace Pty {
}

yield* Effect.addFinalizer(() =>
Effect.sync(() => {
Effect.gen(function* () {
for (const session of state.sessions.values()) {
teardown(session)
yield* teardown(session)
}
state.sessions.clear()
}),
Expand All @@ -159,7 +241,7 @@ export namespace Pty {
if (!session) return
s.sessions.delete(id)
log.info("removing session", { id })
teardown(session)
yield* teardown(session)
yield* bus.publish(Event.Deleted, { id: session.info.id })
})

Expand Down
4 changes: 3 additions & 1 deletion packages/opencode/src/session/llm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,9 @@ const live: Layer.Layer<

const result = yield* run({ ...input, abort: ctrl.signal })

return Stream.fromAsyncIterable(result.fullStream, (e) => (e instanceof Error ? e : new Error(String(e))))
return Stream.fromAsyncIterable(result.fullStream, (e) => (e instanceof Error ? e : new Error(String(e)))).pipe(
Stream.timeout("10 minutes"),
)
}),
),
)
Expand Down
116 changes: 114 additions & 2 deletions packages/opencode/src/session/processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,24 @@ type ToolCall = {
done: Deferred.Deferred<void>
}

type PendingLoopAction = {
loopAction: "block" | "stop"
tool: string
sigKey: string
kind: SessionDiagnostics.SignatureKind
outcome: SessionDiagnostics.LoopOutcome
completedCount: number
completedFailures?: number
nextOccurrenceCount: number
attemptedInput?: unknown
errorMessage: string
renderedText?: string
}

interface ProcessorContext extends Input {
toolcalls: Record<string, ToolCall>
pendingLoopActions: Record<string, PendingLoopAction>
pendingToolUpdates: Record<string, Array<(part: MessageV2.ToolPart) => MessageV2.ToolPart>>
shouldBreak: boolean
snapshot: string | undefined
blocked: boolean
Expand Down Expand Up @@ -150,6 +166,8 @@ export const layer: Layer.Layer<
sessionID: input.sessionID,
model: input.model,
toolcalls: {},
pendingLoopActions: {},
pendingToolUpdates: {},
shouldBreak: false,
snapshot: initialSnapshot,
blocked: false,
Expand Down Expand Up @@ -192,7 +210,10 @@ export const layer: Layer.Layer<
update: (part: MessageV2.ToolPart) => MessageV2.ToolPart,
) {
const match = yield* readToolCall(toolCallID)
if (!match) return
if (!match) {
;(ctx.pendingToolUpdates[toolCallID] ??= []).push(update)
return
}
const part = yield* session.updatePart(update(match.part))
ctx.toolcalls[toolCallID] = {
...match.call,
Expand All @@ -203,6 +224,22 @@ export const layer: Layer.Layer<
return part
})

const applyPendingToolUpdates = Effect.fn("SessionProcessor.applyPendingToolUpdates")(function* (toolCallID: string) {
const pending = ctx.pendingToolUpdates[toolCallID]
if (!pending?.length) return
delete ctx.pendingToolUpdates[toolCallID]
const match = yield* readToolCall(toolCallID)
if (!match) return
const next = pending.reduce((part, update) => update(part), match.part)
const part = yield* session.updatePart(next)
ctx.toolcalls[toolCallID] = {
...match.call,
partID: part.id,
messageID: part.messageID,
sessionID: part.sessionID,
}
})
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

const toolStateMetadata = (part: MessageV2.ToolPart) =>
"metadata" in part.state && isRecord(part.state.metadata) ? part.state.metadata : undefined

Expand Down Expand Up @@ -440,6 +477,50 @@ export const layer: Layer.Layer<
const failToolCall = Effect.fn("SessionProcessor.failToolCall")(function* (toolCallID: string, error: unknown) {
const match = yield* readToolCall(toolCallID)
if (!match) return false
const pending = ctx.pendingLoopActions[toolCallID]
if (pending) {
delete ctx.pendingLoopActions[toolCallID]
const existingMeta = toolStateMetadata(match.part)
const metadata = SessionDiagnostics.mergeMetadata(existingMeta, {
diagnostics: {
loop: {
loopAction: pending.loopAction,
loopType: pending.kind,
loopSigKey: pending.sigKey,
outcome: pending.outcome,
loopCompletedCount: pending.completedCount,
loopCompletedFailures: pending.completedFailures,
loopOccurrenceCount: pending.nextOccurrenceCount,
attemptedInput: pending.attemptedInput,
},
},
})
const end = Date.now()
const start = "time" in match.part.state ? match.part.state.time.start : end
yield* session.updatePart({
...match.part,
state: {
status: "error",
input: match.part.state.input,
error: pending.errorMessage,
metadata,
time: { start, end },
},
})
if (pending.loopAction === "stop" && pending.renderedText) {
yield* session.updatePart({
id: PartID.ascending(),
sessionID: ctx.sessionID,
messageID: ctx.assistantMessage.id,
type: "text",
text: pending.renderedText,
synthetic: true,
})
ctx.blocked = true
}
yield* settleToolCall(toolCallID)
return true
}
if (match.part.state.status !== "running") {
yield* settleToolCall(toolCallID)
return false
Expand Down Expand Up @@ -539,6 +620,7 @@ export const layer: Layer.Layer<
messageID: part.messageID,
sessionID: part.sessionID,
}
yield* applyPendingToolUpdates(value.id)
return
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

case "tool-input-delta":
Expand All @@ -551,7 +633,7 @@ export const layer: Layer.Layer<
if (ctx.assistantMessage.summary) {
throw new Error(`Tool call not allowed while generating summary: ${value.toolName}`)
}
const running = yield* updateToolCall(value.toolCallId, (match) => ({
let running = yield* updateToolCall(value.toolCallId, (match) => ({
...match,
tool: value.toolName,
state: {
Expand All @@ -564,6 +646,9 @@ export const layer: Layer.Layer<
? { ...value.providerMetadata, providerExecuted: true }
: value.providerMetadata,
}))
yield* applyPendingToolUpdates(value.toolCallId)
const refreshed = yield* readToolCall(value.toolCallId)
if (refreshed) running = refreshed.part
if (!running || !ctx.assistantMessage.parentID) return
const info = yield* session.get(ctx.sessionID)
const observed = SessionDiagnostics.observeToolCall({
Expand Down Expand Up @@ -860,8 +945,21 @@ export const layer: Layer.Layer<
attemptedInput?: unknown
errorMessage: string
}) {
ctx.pendingLoopActions[input.toolCallId] = {
loopAction: "block",
tool: input.tool,
sigKey: input.sigKey,
kind: input.kind,
outcome: input.outcome,
completedCount: input.completedCount,
completedFailures: input.completedFailures,
nextOccurrenceCount: input.nextOccurrenceCount,
attemptedInput: input.attemptedInput,
errorMessage: input.errorMessage,
}
const match = yield* readToolCall(input.toolCallId)
if (!match) return
delete ctx.pendingLoopActions[input.toolCallId]
// Idempotence guard: if the model emits multiple parallel tool calls of the same
// sigKey within one assistant step, applyLoopGate can decide block for several of
// them before any has persisted. Re-check existing block sigKeys here so we record
Expand Down Expand Up @@ -935,8 +1033,22 @@ export const layer: Layer.Layer<
renderedText: string
toolErrorMessage: string
}) {
ctx.pendingLoopActions[input.toolCallId] = {
loopAction: "stop",
tool: input.tool,
sigKey: input.sigKey,
kind: input.kind,
outcome: input.outcome,
completedCount: input.completedCount,
completedFailures: input.completedFailures,
nextOccurrenceCount: input.nextOccurrenceCount,
attemptedInput: input.attemptedInput,
errorMessage: input.toolErrorMessage,
renderedText: input.renderedText,
}
const match = yield* readToolCall(input.toolCallId)
if (!match) return
delete ctx.pendingLoopActions[input.toolCallId]
// Idempotence guard (see recordSyntheticBlock for the full rationale): re-check
// hasStopped here. The duplicate-stop case writes two Chinese summaries which is
// visible UX noise; this guard closes the most common parallel-call window.
Expand Down
2 changes: 2 additions & 0 deletions packages/opencode/src/session/retry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export const RETRY_INITIAL_DELAY = 2000
export const RETRY_BACKOFF_FACTOR = 2
export const RETRY_MAX_DELAY_NO_HEADERS = 30_000 // 30 seconds
export const RETRY_MAX_DELAY = 2_147_483_647 // max 32-bit signed integer for setTimeout
export const RETRY_MAX_ATTEMPTS = 10

function cap(ms: number) {
return Math.min(ms, RETRY_MAX_DELAY)
Expand Down Expand Up @@ -112,6 +113,7 @@ export function policy(opts: {
const error = opts.parse(meta.input)
const message = retryable(error)
if (!message) return Cause.done(meta.attempt)
if (meta.attempt >= RETRY_MAX_ATTEMPTS) return Cause.done(meta.attempt)
Comment thread
Astro-Han marked this conversation as resolved.
Resolved
return Effect.gen(function* () {
const wait = delay(meta.attempt, MessageV2.APIError.isInstance(error) ? error : undefined)
const now = yield* Clock.currentTimeMillis
Expand Down
Loading
Loading