forked from anomalyco/opencode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshare-next.ts
More file actions
376 lines (332 loc) · 12.4 KB
/
share-next.ts
File metadata and controls
376 lines (332 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
import type * as SDK from "@opencode-ai/sdk/v2"
import { Effect, Exit, Layer, Option, Schema, Scope, Context, Stream } from "effect"
import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"
import { Account } from "@/account/account"
import { Bus } from "@/bus"
import { InstanceState } from "@/effect/instance-state"
import { Provider } from "@/provider/provider"
import { ModelID, ProviderID } from "@/provider/schema"
import { Session } from "@/session/session"
import { MessageV2 } from "@/session/message-v2"
import type { SessionID } from "@/session/schema"
import { Database } from "@/storage/db"
import { eq } from "drizzle-orm"
import { Config } from "@/config/config"
import * as Log from "@opencode-ai/core/util/log"
import { SessionShareTable } from "./share.sql"
const log = Log.create({ service: "share-next" })
const disabled = process.env["OPENCODE_DISABLE_SHARE"] === "true" || process.env["OPENCODE_DISABLE_SHARE"] === "1"
export type Api = {
create: string
sync: (shareID: string) => string
remove: (shareID: string) => string
data: (shareID: string) => string
}
export type Req = {
headers: Record<string, string>
api: Api
baseUrl: string
}
const ShareSchema = Schema.Struct({
id: Schema.String,
url: Schema.String,
secret: Schema.String,
})
export type Share = typeof ShareSchema.Type
type State = {
queue: Map<SessionID, Map<string, Data>>
scope: Scope.Closeable
shared: Map<SessionID, Share | null>
}
type Data =
| {
type: "session"
data: SDK.Session
}
| {
type: "message"
data: SDK.Message
}
| {
type: "part"
data: SDK.Part
}
| {
type: "session_diff"
data: SDK.SnapshotFileDiff[]
}
| {
type: "model"
data: SDK.Model[]
}
export interface Interface {
readonly init: () => Effect.Effect<void, unknown>
readonly url: () => Effect.Effect<string, unknown>
readonly request: () => Effect.Effect<Req, unknown>
readonly create: (sessionID: SessionID) => Effect.Effect<Share, unknown>
readonly remove: (sessionID: SessionID) => Effect.Effect<void, unknown>
}
export class Service extends Context.Service<Service, Interface>()("@opencode/ShareNext") {}
const db = <T>(fn: (d: Parameters<typeof Database.use>[0] extends (trx: infer D) => any ? D : never) => T) =>
Effect.sync(() => Database.use(fn))
function api(resource: string): Api {
return {
create: `/api/${resource}`,
sync: (shareID) => `/api/${resource}/${shareID}/sync`,
remove: (shareID) => `/api/${resource}/${shareID}`,
data: (shareID) => `/api/${resource}/${shareID}/data`,
}
}
const legacyApi = api("share")
const consoleApi = api("shares")
function key(item: Data) {
switch (item.type) {
case "session":
return "session"
case "message":
return `message/${item.data.id}`
case "part":
return `part/${item.data.messageID}/${item.data.id}`
case "session_diff":
return "session_diff"
case "model":
return "model"
}
}
export const layer = Layer.effect(
Service,
Effect.gen(function* () {
const account = yield* Account.Service
const bus = yield* Bus.Service
const cfg = yield* Config.Service
const http = yield* HttpClient.HttpClient
const httpOk = HttpClient.filterStatusOk(http)
const provider = yield* Provider.Service
const session = yield* Session.Service
function sync(sessionID: SessionID, data: Data[]): Effect.Effect<void> {
return Effect.gen(function* () {
if (disabled) return
const share = yield* getCached(sessionID)
if (!share) return
const s = yield* InstanceState.get(state)
const existing = s.queue.get(sessionID)
if (existing) {
for (const item of data) {
existing.set(key(item), item)
}
return
}
const next = new Map(data.map((item) => [key(item), item]))
s.queue.set(sessionID, next)
yield* flush(sessionID).pipe(
Effect.delay(1000),
Effect.catchCause((cause) =>
Effect.sync(() => {
log.error("share flush failed", { sessionID, cause })
}),
),
Effect.forkIn(s.scope),
)
})
}
const state: InstanceState.InstanceState<State> = yield* InstanceState.make<State>(
Effect.fn("ShareNext.state")(function* (_ctx) {
const cache: State = { queue: new Map(), scope: yield* Scope.make(), shared: new Map() }
yield* Effect.addFinalizer(() =>
Scope.close(cache.scope, Exit.void).pipe(
Effect.andThen(
Effect.sync(() => {
cache.queue.clear()
cache.shared.clear()
}),
),
),
)
if (disabled) return cache
const watch = <D extends { type: string }>(
def: D,
fn: (evt: { properties: any }) => Effect.Effect<void, unknown>,
) =>
bus.subscribe(def as never).pipe(
Stream.runForEach((evt) =>
fn(evt).pipe(
Effect.catchCause((cause) =>
Effect.sync(() => {
log.error("share subscriber failed", { type: def.type, cause })
}),
),
),
),
Effect.forkScoped,
)
yield* watch(Session.Event.Updated, (evt) =>
Effect.gen(function* () {
const info = evt.properties.info
yield* sync(info.id, [{ type: "session", data: info }])
}),
)
yield* watch(MessageV2.Event.Updated, (evt) =>
Effect.gen(function* () {
const info = evt.properties.info
yield* sync(info.sessionID, [{ type: "message", data: info }])
if (info.role !== "user") return
const model = yield* provider.getModel(info.model.providerID, info.model.modelID)
yield* sync(info.sessionID, [{ type: "model", data: [model] }])
}),
)
yield* watch(MessageV2.Event.PartUpdated, (evt) =>
sync(evt.properties.part.sessionID, [{ type: "part", data: evt.properties.part }]),
)
yield* watch(Session.Event.Diff, (evt) =>
sync(evt.properties.sessionID, [{ type: "session_diff", data: evt.properties.diff }]),
)
yield* watch(Session.Event.Deleted, (evt) => remove(evt.properties.sessionID))
return cache
}),
)
const request = Effect.fn("ShareNext.request")(function* () {
const headers: Record<string, string> = {}
const active = yield* account.active()
if (Option.isNone(active) || !active.value.active_org_id) {
const baseUrl = (yield* cfg.get()).enterprise?.url ?? "https://opncd.ai"
return { headers, api: legacyApi, baseUrl } satisfies Req
}
const token = yield* account.token(active.value.id)
if (Option.isNone(token)) {
throw new Error("No active account token available for sharing")
}
headers.authorization = `Bearer ${token.value}`
headers["x-org-id"] = active.value.active_org_id
return { headers, api: consoleApi, baseUrl: active.value.url } satisfies Req
})
const get = Effect.fnUntraced(function* (sessionID: SessionID) {
const row = yield* db((db) =>
db.select().from(SessionShareTable).where(eq(SessionShareTable.session_id, sessionID)).get(),
)
if (!row) return
return { id: row.id, secret: row.secret, url: row.url } satisfies Share
})
const getCached = Effect.fnUntraced(function* (sessionID: SessionID) {
const s = yield* InstanceState.get(state)
if (s.shared.has(sessionID)) {
const cached = s.shared.get(sessionID)
return cached === null ? undefined : cached
}
const share = yield* get(sessionID)
s.shared.set(sessionID, share ?? null)
return share
})
const flush = Effect.fn("ShareNext.flush")(function* (sessionID: SessionID) {
if (disabled) return
const s = yield* InstanceState.get(state)
const queued = s.queue.get(sessionID)
if (!queued) return
s.queue.delete(sessionID)
const share = yield* getCached(sessionID)
if (!share) return
const req = yield* request()
const res = yield* HttpClientRequest.post(`${req.baseUrl}${req.api.sync(share.id)}`).pipe(
HttpClientRequest.setHeaders(req.headers),
HttpClientRequest.bodyJson({ secret: share.secret, data: Array.from(queued.values()) }),
Effect.flatMap((r) => http.execute(r)),
)
if (res.status >= 400) {
log.warn("failed to sync share", { sessionID, shareID: share.id, status: res.status })
}
})
const full = Effect.fn("ShareNext.full")(function* (sessionID: SessionID) {
log.info("full sync", { sessionID })
const info = yield* session.get(sessionID)
const diffs = yield* session.diff(sessionID)
const messages = yield* session.messages({ sessionID })
const models = yield* Effect.forEach(
Array.from(
new Map(
messages
.filter((msg) => msg.info.role === "user")
.map((msg) => (msg.info as SDK.UserMessage).model)
.map((item) => [`${item.providerID}/${item.modelID}`, item] as const),
).values(),
),
(item) => provider.getModel(ProviderID.make(item.providerID), ModelID.make(item.modelID)),
{ concurrency: 8 },
)
yield* sync(sessionID, [
{ type: "session", data: info },
...messages.map((item) => ({ type: "message" as const, data: item.info })),
...messages.flatMap((item) => item.parts.map((part) => ({ type: "part" as const, data: part }))),
{ type: "session_diff", data: diffs },
{ type: "model", data: models },
])
})
const init = Effect.fn("ShareNext.init")(function* () {
if (disabled) return
yield* InstanceState.get(state)
})
const url = Effect.fn("ShareNext.url")(function* () {
return (yield* request()).baseUrl
})
const create = Effect.fn("ShareNext.create")(function* (sessionID: SessionID) {
if (disabled) return { id: "", url: "", secret: "" }
log.info("creating share", { sessionID })
const req = yield* request()
const result = yield* HttpClientRequest.post(`${req.baseUrl}${req.api.create}`).pipe(
HttpClientRequest.setHeaders(req.headers),
HttpClientRequest.bodyJson({ sessionID }),
Effect.flatMap((r) => httpOk.execute(r)),
Effect.flatMap(HttpClientResponse.schemaBodyJson(ShareSchema)),
)
yield* db((db) =>
db
.insert(SessionShareTable)
.values({ session_id: sessionID, id: result.id, secret: result.secret, url: result.url })
.onConflictDoUpdate({
target: SessionShareTable.session_id,
set: { id: result.id, secret: result.secret, url: result.url },
})
.run(),
)
const s = yield* InstanceState.get(state)
s.shared.set(sessionID, result)
yield* full(sessionID).pipe(
Effect.catchCause((cause) =>
Effect.sync(() => {
log.error("share full sync failed", { sessionID, cause })
}),
),
Effect.forkIn(s.scope),
)
return result
})
const remove = Effect.fn("ShareNext.remove")(function* (sessionID: SessionID) {
if (disabled) return
log.info("removing share", { sessionID })
const s = yield* InstanceState.get(state)
const share = yield* getCached(sessionID)
if (!share) {
s.shared.delete(sessionID)
s.queue.delete(sessionID)
return
}
const req = yield* request()
yield* HttpClientRequest.delete(`${req.baseUrl}${req.api.remove(share.id)}`).pipe(
HttpClientRequest.setHeaders(req.headers),
HttpClientRequest.bodyJson({ secret: share.secret }),
Effect.flatMap((r) => httpOk.execute(r)),
)
yield* db((db) => db.delete(SessionShareTable).where(eq(SessionShareTable.session_id, sessionID)).run())
s.shared.delete(sessionID)
s.queue.delete(sessionID)
})
return Service.of({ init, url, request, create, remove })
}),
)
export const defaultLayer = layer.pipe(
Layer.provide(Bus.layer),
Layer.provide(Account.defaultLayer),
Layer.provide(Config.defaultLayer),
Layer.provide(FetchHttpClient.layer),
Layer.provide(Provider.defaultLayer),
Layer.provide(Session.defaultLayer),
)
export * as ShareNext from "./share-next"