Skip to content

Commit c8de424

Browse files
agustifivanmilevtues
authored andcommitted
feat(server): restart approval intent protocol and endpoints
(cherry picked from commit 87a27cf) Co-authored-by: Ivan Milev <ivanmilevtues@gmail.com>
1 parent a9904a2 commit c8de424

10 files changed

Lines changed: 211 additions & 6 deletions

File tree

‎packages/client/src/effect/api/api.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
// Generated by @opencode/httpapi-codegen. Do not edit.
22
import type { Effect, Stream } from "effect"
3+
import type { Session } from "@opencode/schema/session"
34
import type { Location } from "@opencode/schema/location"
45
import type { Agent } from "@opencode/schema/agent"
56
import type { Plugin } from "@opencode/schema/plugin"
6-
import type { Session } from "@opencode/schema/session"
77
import type { AbsolutePath } from "@opencode/schema/schema"
88
import type { Project } from "@opencode/schema/project"
99
import type { RelativePath } from "@opencode/schema/schema"
@@ -59,10 +59,23 @@ export type ServerConnectInput = { readonly code: string }
5959
export type ServerConnectOutput = { readonly token: string }
6060
export type ServerConnectOperation<E = never> = (input: ServerConnectInput) => Effect.Effect<ServerConnectOutput, E>
6161

62+
export type ServerRestartRequestOutput = { readonly active: ReadonlyArray<Session.ID> }
63+
export type ServerRestartRequestOperation<E = never> = () => Effect.Effect<ServerRestartRequestOutput, E>
64+
65+
export type ServerRestartResolveInput = { readonly decision: "now" | "idle" | "cancel" }
66+
export type ServerRestartResolveOutput = { readonly decision: "now" | "idle" | "cancel" }
67+
export type ServerRestartResolveOperation<E = never> = (
68+
input: ServerRestartResolveInput,
69+
) => Effect.Effect<ServerRestartResolveOutput, E>
70+
6271
export interface ServerApi<E = never> {
6372
readonly info: ServerInfoOperation<E>
6473
readonly pair: ServerPairOperation<E>
6574
readonly connect: ServerConnectOperation<E>
75+
readonly restart: {
76+
readonly request: ServerRestartRequestOperation<E>
77+
readonly resolve: ServerRestartResolveOperation<E>
78+
}
6679
}
6780

6881
export type LocationGetInput = { readonly location?: { readonly directory?: string | undefined } | undefined }

‎packages/client/src/effect/generated/client.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@ import type {
99
ServerPairOutput,
1010
ServerConnectInput,
1111
ServerConnectOutput,
12+
ServerRestartRequestOutput,
13+
ServerRestartResolveInput,
14+
ServerRestartResolveOutput,
1215
LocationGetInput,
1316
LocationGetOutput,
1417
LocationReloadOutput,
@@ -310,10 +313,19 @@ const EndpointServerConnect = (raw: RawClient["server.server"]) => (input: Serve
310313
raw["server.connect"]({ params: { code: input["code"] } }).pipe(Effect.mapError(mapClientError)),
311314
)
312315

316+
const EndpointServerRestartRequest = (raw: RawClient["server.server"]) => () =>
317+
preserveEffect<ServerRestartRequestOutput>()(raw["server.restart.request"]({}).pipe(Effect.mapError(mapClientError)))
318+
319+
const EndpointServerRestartResolve = (raw: RawClient["server.server"]) => (input: ServerRestartResolveInput) =>
320+
preserveEffect<ServerRestartResolveOutput>()(
321+
raw["server.restart.resolve"]({ payload: { decision: input["decision"] } }).pipe(Effect.mapError(mapClientError)),
322+
)
323+
313324
const adaptGroupServer = (raw: RawClient["server.server"]) => ({
314325
info: EndpointServerInfo(raw),
315326
pair: EndpointServerPair(raw),
316327
connect: EndpointServerConnect(raw),
328+
restart: { request: EndpointServerRestartRequest(raw), resolve: EndpointServerRestartResolve(raw) },
317329
})
318330

319331
const EndpointLocationGet = (raw: RawClient["server.location"]) => (input?: LocationGetInput) =>

‎packages/client/src/promise/generated/client.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@ import type {
33
ServerPairOutput,
44
ServerConnectInput,
55
ServerConnectOutput,
6+
ServerRestartRequestOutput,
7+
ServerRestartResolveInput,
8+
ServerRestartResolveOutput,
69
LocationGetInput,
710
LocationGetOutput,
811
LocationReloadOutput,
@@ -443,6 +446,31 @@ export function make(options: ClientOptions) {
443446
},
444447
requestOptions,
445448
),
449+
restart: {
450+
request: (requestOptions?: RequestOptions) =>
451+
request<ServerRestartRequestOutput>(
452+
{
453+
method: "POST",
454+
path: `/api/server/restart/request`,
455+
successStatus: 200,
456+
declaredStatuses: [400, 401],
457+
empty: false,
458+
},
459+
requestOptions,
460+
),
461+
resolve: (input: ServerRestartResolveInput, requestOptions?: RequestOptions) =>
462+
request<ServerRestartResolveOutput>(
463+
{
464+
method: "POST",
465+
path: `/api/server/restart/resolve`,
466+
body: { decision: input["decision"] },
467+
successStatus: 200,
468+
declaredStatuses: [400, 401],
469+
empty: false,
470+
},
471+
requestOptions,
472+
),
473+
},
446474
},
447475
location: {
448476
get: (input?: LocationGetInput, requestOptions?: RequestOptions) =>

‎packages/client/src/promise/generated/types.ts‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ export type PairingCode = { code: string; expires_in: number }
1212

1313
export type PairingSession = { token: string }
1414

15+
export type SessionID = string
16+
1517
export type AbsolutePath = string
1618

1719
export type ProjectID = string
@@ -40,8 +42,6 @@ export type PluginFeatures = { server?: true; tui?: true; rpc?: true }
4042

4143
export type PluginState = { status: "active" } | { status: "failed"; error: string; ref?: string }
4244

43-
export type SessionID = string
44-
4545
export type SessionMessageID = string
4646

4747
export type MoneyUSD = number
@@ -1741,6 +1741,24 @@ export type SessionIdle = {
17411741
data: { sessionID: SessionID }
17421742
}
17431743

1744+
export type ServerRestartRequested = {
1745+
id: EventID
1746+
created: number
1747+
metadata?: { [x: string]: any }
1748+
type: "server.restart.requested"
1749+
location?: LocationRef
1750+
data: { active: Array<SessionID> }
1751+
}
1752+
1753+
export type ServerRestartResolved = {
1754+
id: EventID
1755+
created: number
1756+
metadata?: { [x: string]: any }
1757+
type: "server.restart.resolved"
1758+
location?: LocationRef
1759+
data: { decision: "now" | "idle" | "cancel" }
1760+
}
1761+
17441762
export type TuiPromptAppend = {
17451763
id: EventID
17461764
created: number
@@ -2627,6 +2645,8 @@ export type V2Event =
26272645
| WebsearchUpdated
26282646
| SessionStatusUpdated
26292647
| SessionIdle
2648+
| ServerRestartRequested
2649+
| ServerRestartResolved
26302650
| TuiPromptAppend
26312651
| TuiCommandExecute
26322652
| TuiToastShow
@@ -2895,6 +2915,14 @@ export type ServerConnectInput = { readonly code: { readonly code: string }["cod
28952915

28962916
export type ServerConnectOutput = PairingSession
28972917

2918+
export type ServerRestartRequestOutput = { active: Array<SessionID> }
2919+
2920+
export type ServerRestartResolveInput = {
2921+
readonly decision: { readonly decision: "now" | "idle" | "cancel" }["decision"]
2922+
}
2923+
2924+
export type ServerRestartResolveOutput = { decision: "now" | "idle" | "cancel" }
2925+
28982926
export type LocationGetInput = {
28992927
readonly location?: { readonly location?: { readonly directory?: string | undefined } | undefined }["location"]
29002928
}

‎packages/protocol/src/groups/server.ts‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { Schema } from "effect"
22
import { HttpApiEndpoint, HttpApiGroup, OpenApi } from "effect/http-api"
3-
import { UnauthorizedError } from "../errors.js"
3+
import { ServiceEvent } from "@opencode/schema/service-event"
4+
import { Session } from "@opencode/schema/session"
5+
import { InvalidRequestError, UnauthorizedError } from "../errors.js"
46

57
export const ServerInfo = Schema.Struct({
68
version: Schema.String,
@@ -75,4 +77,36 @@ export const ServerGroup = HttpApiGroup.make("server.server")
7577
}),
7678
),
7779
)
80+
.add(
81+
HttpApiEndpoint.post("server.restart.request", "/api/server/restart/request", {
82+
success: Schema.Struct({
83+
active: Schema.Array(Session.ID),
84+
}),
85+
}).annotateMerge(
86+
OpenApi.annotations({
87+
identifier: "server.restart.request",
88+
summary: "Request service restart approval",
89+
description:
90+
"Register a pending service restart. Returns the sessions with running agents so the requester can seek approval. Resolving the request is reported through server.restart events.",
91+
}),
92+
),
93+
)
94+
.add(
95+
HttpApiEndpoint.post("server.restart.resolve", "/api/server/restart/resolve", {
96+
payload: Schema.Struct({
97+
decision: ServiceEvent.Decision,
98+
}),
99+
success: Schema.Struct({
100+
decision: ServiceEvent.Decision,
101+
}),
102+
error: InvalidRequestError,
103+
}).annotateMerge(
104+
OpenApi.annotations({
105+
identifier: "server.restart.resolve",
106+
summary: "Resolve pending service restart",
107+
description:
108+
"Approve the pending service restart (now or once sessions go idle) or cancel it. Only the first resolution wins.",
109+
}),
110+
),
111+
)
78112
.annotateMerge(OpenApi.annotations({ title: "server" }))

‎packages/schema/src/event-manifest.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import { Worktree } from "./worktree.js"
2727
import { Pty } from "./pty.js"
2828
import { Reference } from "./reference.js"
2929
import { ServerEvent } from "./server-event.js"
30+
import { ServiceEvent } from "./service-event.js"
3031
import { Shell } from "./shell.js"
3132
import { Skill } from "./skill.js"
3233
import { SessionCompactionEvent } from "./session-compaction-event.js"
@@ -73,6 +74,7 @@ export const ServerDefinitions = Event.inventory(
7374
...featureDefinitions,
7475
// Current events the TUI consumes from the public stream.
7576
...SessionStatusEvent.Definitions,
77+
...ServiceEvent.Definitions,
7678
...TuiEvent.Definitions,
7779
...InstallationEvent.Definitions,
7880
...VcsEvent.Definitions,
@@ -94,6 +96,7 @@ export const Definitions = Event.inventory(
9496
...FileSystemV1.Event.Definitions,
9597
...SessionStatusEvent.Definitions,
9698
...SessionCompactionEvent.Definitions,
99+
...ServiceEvent.Definitions,
97100
...VcsEvent.Definitions,
98101
...WorkspaceEvent.Definitions,
99102
...WorktreeEvent.Definitions,
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
export * as ServiceEvent from "./service-event.js"
2+
3+
import { Schema } from "effect"
4+
import { Event } from "./event.js"
5+
import { SessionID } from "./session-id.js"
6+
7+
export const Requested = Event.ephemeral({
8+
type: "server.restart.requested",
9+
schema: {
10+
active: Schema.Array(SessionID),
11+
},
12+
})
13+
14+
export const Decision = Schema.Union([
15+
Schema.Literal("now"),
16+
Schema.Literal("idle"),
17+
Schema.Literal("cancel"),
18+
])
19+
export type Decision = typeof Decision.Type
20+
21+
export const Resolved = Event.ephemeral({
22+
type: "server.restart.resolved",
23+
schema: {
24+
decision: Decision,
25+
},
26+
})
27+
28+
export const Definitions = Event.inventory(Requested, Resolved)

‎packages/server/src/handlers.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { EventHandler } from "./handlers/event"
1414
import { AgentHandler } from "./handlers/agent"
1515
import { PluginHandler } from "./handlers/plugin"
1616
import { ServerHandler } from "./handlers/server"
17+
import { RestartIntent } from "./restart-intent"
1718
import { DebugHandler } from "./handlers/debug"
1819
import { PtyHandler } from "./handlers/pty"
1920
import { PersistentPtyHandler } from "./handlers/persistent-pty"
@@ -32,7 +33,7 @@ import { MigrationHandler } from "./handlers/migration"
3233
import { ConfigHandler } from "./handlers/config"
3334

3435
export const handlers = Layer.mergeAll(
35-
ServerHandler,
36+
ServerHandler.pipe(Layer.provide(RestartIntent.layer)),
3637
DebugHandler,
3738
MigrationHandler,
3839
LocationHandler,

‎packages/server/src/handlers/server.ts‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,23 @@ import { Duration, Effect } from "effect"
22
import { HttpServerRequest, HttpServerResponse } from "effect/http"
33
import { HttpApiBuilder } from "effect/http-api"
44
import { PersistentPty } from "@opencode/core/persistent-pty"
5-
import { UnauthorizedError } from "@opencode/protocol/errors"
5+
import { Session } from "@opencode/core/session"
6+
import { Bus } from "@opencode/core/bus"
7+
import { ServiceEvent } from "@opencode/schema/service-event"
8+
import { InvalidRequestError, UnauthorizedError } from "@opencode/protocol/errors"
69
import { Api } from "../api"
710
import { ServerAuth } from "../auth"
811
import { ServerInfo } from "../server-info"
912
import { ServerPairing } from "../pairing"
13+
import { RestartIntent } from "../restart-intent"
1014

1115
export const ServerHandler = HttpApiBuilder.group(Api, "server.server", (handlers) =>
1216
Effect.gen(function* () {
1317
const pairing = yield* ServerPairing.Service
1418
const auth = yield* ServerAuth.Config
19+
const session = yield* Session.Service
20+
const intent = yield* RestartIntent.Service
21+
const bus = yield* Bus.Service
1522

1623
return handlers
1724
.handle("server.info", () =>
@@ -27,6 +34,26 @@ export const ServerHandler = HttpApiBuilder.group(Api, "server.server", (handler
2734
}),
2835
)
2936
.handle("server.pair", () => pairing.issue())
37+
.handle(
38+
"server.restart.request",
39+
Effect.fn(function* () {
40+
const active = Array.from(yield* session.active)
41+
yield* intent.request()
42+
yield* bus.publish(ServiceEvent.Requested, { active }, { global: true })
43+
return { active }
44+
}),
45+
)
46+
.handle(
47+
"server.restart.resolve",
48+
Effect.fn(function* (ctx) {
49+
const winner = yield* intent.resolve(ctx.payload.decision)
50+
if (winner === undefined) {
51+
return yield* new InvalidRequestError({ message: "No pending service restart request" })
52+
}
53+
yield* bus.publish(ServiceEvent.Resolved, { decision: winner }, { global: true })
54+
return { decision: winner }
55+
}),
56+
)
3057
.handle(
3158
"server.connect",
3259
Effect.fn(function* (ctx) {
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
export * as RestartIntent from "./restart-intent"
2+
3+
import { ServiceEvent } from "@opencode/schema/service-event"
4+
import { Context, Effect, Layer, Ref } from "effect"
5+
6+
export class Service extends Context.Service<Service, {
7+
/** Record a pending intent unless one exists. */
8+
readonly request: () => Effect.Effect<void>
9+
/**
10+
* Resolve the pending intent with first-wins semantics. Returns the winning
11+
* decision, or undefined when no intent is pending.
12+
*/
13+
readonly resolve: (decision: ServiceEvent.Decision) => Effect.Effect<ServiceEvent.Decision | undefined>
14+
}>()("@opencode/server/RestartIntent") {}
15+
16+
export const layer = Layer.effect(
17+
Service,
18+
Effect.gen(function* () {
19+
const state = yield* Ref.make<{ readonly pending: boolean; readonly last?: ServiceEvent.Decision }>({
20+
pending: false,
21+
})
22+
return Service.of({
23+
request: () => Ref.update(state, (current) => (current.pending ? current : { pending: true })),
24+
resolve: (decision) =>
25+
Ref.modify(state, (current) => {
26+
if (!current.pending) return [current.last, current] as const
27+
return [decision, { pending: false, last: decision }] as const
28+
}),
29+
})
30+
}),
31+
)

0 commit comments

Comments
 (0)