Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
24 changes: 20 additions & 4 deletions packages/opencode/src/kilo-sessions/kilo-sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -454,10 +454,7 @@ export namespace KiloSessions {
// Same-title Updated (setTitle no-op / double session.renamed): still
// consume a matching rename adoption after sync so the mark cannot
// stick and swallow a later real local rename (Decision 8).
const outcome = (():
| { kind: "same" }
| { kind: "adopted" }
| { kind: "report"; generated: boolean } => {
const outcome = ((): { kind: "same" } | { kind: "adopted" } | { kind: "report"; generated: boolean } => {
if (sameTitle) return { kind: "same" }
// Consume marks before the network hop so the 60s TTL does not span
// token resolution + ingest.sync. Checks run even when prev is
Expand Down Expand Up @@ -832,6 +829,25 @@ export namespace KiloSessions {
])
await AppRuntime.runPromise(SessionPrompt.Service.use((svc) => svc.cancel(id)))
},
// kilocode_change - K1 W1 clone: import a cloud session in-process. The
// dynamic import keeps the HTTP handler graph out of the remote-sender
// module graph, mirroring the lazy cancelPrompt pattern.
importFromCloud: async (cloneId) => {
const [{ CloudSessionImportInProcess }, { AppRuntime }] = await Promise.all([
import("@/kilocode/server/import-cloud-session-in-process"),
import("@/effect/app-runtime"),
])
const { session, diffs, directory } = await AppRuntime.runPromise(
CloudSessionImportInProcess.importSessionWithoutRestore(cloneId),
)
return {
session,
finalize: () =>
AppRuntime.runPromise(
CloudSessionImportInProcess.finalizeSessionImport({ sessionId: session.id, diffs, directory }),
),
}
},
})

if (seq !== remoteSeq) {
Expand Down
5 changes: 5 additions & 0 deletions packages/opencode/src/kilo-sessions/remote-protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@ export namespace RemoteProtocol {
export const Capabilities = z
.object({
attachments: z.boolean().optional(),
// kilocode_change - sessionClone: present only when the CLI accepts a
// cloud-session clone (create_session.cloneFromKiloSessionId). The old
// wire form omits sessionClone; remove the mobile fail-closed check
// when every shipped CLI advertises it.
sessionClone: z.boolean().optional(),
})
.optional()
export const Heartbeat = z.object({
Expand Down
86 changes: 86 additions & 0 deletions packages/opencode/src/kilo-sessions/remote-sender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ const CreateSessionRequest = z
agent: z.string().min(1).optional(),
model: CreateSessionModel.optional(),
orgId: z.string().uuid().optional(),
// kilocode_change - cloneFromKiloSessionId: optional cloud-session import.
// The old wire form omits this field and performs a fresh sessionCreate;
// remove the fresh-create branch when every shipped CLI advertises sessionClone.
cloneFromKiloSessionId: z.string().min(1).optional(),
})
.strict()

Expand Down Expand Up @@ -90,6 +94,20 @@ function errorName(error: unknown): string {
}
// kilocode_change end

// kilocode_change - create_session cloud-import error mapping. The import seam
// rejects with a tagged error carrying the upstream `status` (or a
// "CloudSessionImportUnauthorized" tag for missing credentials). Map those to
// the exact wire literals; never surface the upstream message (it may embed
// credentials) and never fall back to a fresh sessionCreate.
function importErrorText(error: unknown): string {
const value = error as { status?: unknown; _tag?: unknown } | null | undefined
if (value?._tag === "CloudSessionImportUnauthorized") return "cloud session import unauthorized"
if (value?.status === 404) return "cloud session not found"
if (value?.status === 401) return "cloud session import unauthorized"
if (value?.status === 403) return "cloud session import access denied"
return "cloud session import failed"
}

// kilocode_change start — lazy init to avoid circular dependency
// (Server → RemoteRoutes → RemoteSender → SessionPrompt at module load time)
type RemotePromptInput = Omit<SessionPrompt.PromptInput, "model"> & {
Expand Down Expand Up @@ -173,6 +191,14 @@ export namespace RemoteSender {
hasSession?: (sessionID: SessionID) => boolean
ownedCount?: () => number
cancelPrompt?: (sessionID: SessionID) => Promise<void>
// kilocode_change - injectable cloud-session import seam for create_session
// clone requests. Takes the cloud session id and returns the imported
// local Session.Info plus a `finalize` closure that restores workspace
// files and writes session_diff storage keys; the caller must run
// `finalize` only after a successful attach. Production wires this to the
// in-process import helper (dynamic import + AppRuntime.runPromise); a
// missing seam is a wiring bug, never a fallback to sessionCreate.
importFromCloud?: (cloneId: string) => Promise<{ session: Session.Info; finalize: () => Promise<void> }>
catalog?: {
readonly get: (sessionID: SessionID) => Promise<Session.Info>
readonly messages: (sessionID: SessionID) => Promise<MessageV2.WithParts[]>
Expand Down Expand Up @@ -799,6 +825,10 @@ export namespace RemoteSender {
// (a) accepts an absent `sessionId` (instance-picker path), (b)
// resolves the target directory from that session or options.directory,
// (c) attaches in-process; attach failures roll back via sessionRemove.
// kilocode_change - clone: an optional cloneFromKiloSessionId imports a
// cloud session in-process (importFromCloud) instead of a fresh
// sessionCreate; a missing importFromCloud seam is a wiring bug, never
// a fallback to sessionCreate.
const parsed = CreateSessionRequest.safeParse(msg.data)
if (!parsed.success) {
options.conn.send({
Expand All @@ -817,6 +847,16 @@ export namespace RemoteSender {
})
return
}
const cloneId = parsed.data.cloneFromKiloSessionId
const importFromCloud = options.importFromCloud
if (cloneId && !importFromCloud) {
options.conn.send({
type: "response",
id: msg.id,
error: "invalid create_session command",
})
return
}
const createInput: CreateSessionInput = {
...(parsed.data.agent ? { agent: parsed.data.agent } : {}),
...(parsed.data.model
Expand All @@ -842,6 +882,52 @@ export namespace RemoteSender {
Option.map((p) => p.then((info) => info.directory)),
Option.getOrElse(() => Promise.resolve(options.directory)),
)
if (cloneId) {
// Clone path: import in-process, then attach. Import failures
// map to the exact literals and never fall back to a fresh
// sessionCreate; attach failures roll back the imported session.
const outcome = await run({
directory: targetDirectory,
fn: async (): Promise<{ id: string } | { error: string }> => {
let imported: { session: Session.Info; finalize: () => Promise<void> }
try {
imported = await importFromCloud!(cloneId)
} catch (importError) {
return { error: importErrorText(importError) }
}
try {
await attachSession(imported.session.id)
} catch (attachError) {
// Roll back the imported root session so the DB does not
// keep an orphan the relay never learned about. Swallow
// the cleanup error; re-throw the original attach error.
try {
await sessionRemove(imported.session.id)
} catch (cleanupError) {
options.log.error("create session cleanup failed", {
id: msg.id,
error: errorName(cleanupError),
})
}
throw attachError
}
// Restore workspace files and write storage keys only after
// the attach succeeded. finalize never rejects.
await imported.finalize()
return { id: imported.session.id }
},
})
if ("error" in outcome) {
options.conn.send({ type: "response", id: msg.id, error: outcome.error })
return
}
options.conn.send({
type: "response",
id: msg.id,
result: { protocolVersion: 1, sessionID: outcome.id },
})
return
}
const result = await run({
directory: targetDirectory,
fn: async () => {
Expand Down
29 changes: 20 additions & 9 deletions packages/opencode/src/kilo-sessions/remote-ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,12 @@ export namespace RemoteWS {
let lastGood: SessionInfo[] | undefined
let outstanding = 0
let degradedCount = 0
type Waiter = { resolve: () => void; reject: (err: unknown) => void; requireSessionId?: string; detachSessionId?: string }
type Waiter = {
resolve: () => void
reject: (err: unknown) => void
requireSessionId?: string
detachSessionId?: string
}
let waiters: Waiter[] = []

function makeWaiter(): { promise: Promise<void>; waiter: Waiter } {
Expand All @@ -151,7 +156,9 @@ export namespace RemoteWS {
// One bounded gather. Never throws. Returns the fresh session list (and
// optional instance advertisement), or undefined to signal a degraded
// cycle (caller sends last known-good).
async function gatherOnce(): Promise<{ sessions: SessionInfo[]; instance?: RemoteProtocol.Heartbeat["instance"] } | undefined> {
async function gatherOnce(): Promise<
{ sessions: SessionInfo[]; instance?: RemoteProtocol.Heartbeat["instance"] } | undefined
> {
if (outstanding >= maxOutstandingGathers) {
degradedCount++
options.log.warn("remote-ws heartbeat gather cap reached, degraded heartbeat", {
Expand Down Expand Up @@ -183,7 +190,9 @@ export namespace RemoteWS {
},
)
const outcome = await new Promise<
{ kind: "ok"; sessions: SessionInfo[]; instance?: RemoteProtocol.Heartbeat["instance"] } | { kind: "err"; error: unknown } | { kind: "timeout" }
| { kind: "ok"; sessions: SessionInfo[]; instance?: RemoteProtocol.Heartbeat["instance"] }
| { kind: "err"; error: unknown }
| { kind: "timeout" }
>((resolve) => {
let done = false
const t = timers.setTimeout(() => {
Expand All @@ -196,9 +205,7 @@ export namespace RemoteWS {
done = true
timers.clearTimeout(t)
resolve(
res.ok
? { kind: "ok", sessions: res.sessions, instance: res.instance }
: { kind: "err", error: res.error },
res.ok ? { kind: "ok", sessions: res.sessions, instance: res.instance } : { kind: "err", error: res.error },
)
})
})
Expand Down Expand Up @@ -261,7 +268,7 @@ export namespace RemoteWS {
send({
type: "heartbeat",
protocolVersion: InstallationVersion,
capabilities: { attachments: true },
capabilities: { attachments: true, sessionClone: true },
sessions: fresh.sessions,
...(fresh.instance ? { instance: fresh.instance } : {}),
})
Expand Down Expand Up @@ -306,7 +313,7 @@ export namespace RemoteWS {
send({
type: "heartbeat",
protocolVersion: InstallationVersion,
capabilities: { attachments: true },
capabilities: { attachments: true, sessionClone: true },
sessions: lastGood ?? [],
})
waiters = cycleWaiters.concat(waiters)
Expand Down Expand Up @@ -428,7 +435,11 @@ export namespace RemoteWS {
return
}
const endpoint = `${options.url}/api/user/cli?token=${encodeURIComponent(token)}&connectionId=${connectionId}`
options.log.info("remote-ws connecting", { connectionId, gen: g.id, endpoint: endpoint.replace(/token=[^&]+/, "token=***") })
options.log.info("remote-ws connecting", {
connectionId,
gen: g.id,
endpoint: endpoint.replace(/token=[^&]+/, "token=***"),
})
let socket: WebSocket
try {
socket = new WebSocket(endpoint)
Expand Down
Loading
Loading