Repository navigation
Expand file tree
/
Copy pathsession-target.ts
More file actions
199 lines (185 loc) · 6.45 KB
/
Copy pathsession-target.ts
File metadata and controls
199 lines (185 loc) · 6.45 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
import type { LocationGetOutput, ModelRef, OpenCodeClient, SessionInfo } from "@opencode/client/promise"
import { Model } from "@opencode/schema/model"
import path from "node:path"
import { errorMessage } from "./util/error"
const SESSION_PAGE_LIMIT = 50
export type SessionTarget = {
session: SessionInfo
location: LocationGetOutput
model: ModelRef | undefined
agent: string | undefined
resume: boolean
}
export type SessionTargetPreparation = (input: {
client: OpenCodeClient
location: LocationGetOutput
session: SessionInfo | undefined
model: ModelRef | undefined
agent: string | undefined
signal?: AbortSignal
}) => Promise<{ model: ModelRef | undefined; agent: string | undefined }>
export class SessionTargetMutationError extends Error {
override readonly name = "SessionTargetMutationError"
constructor(cause: unknown) {
super(errorMessage(cause), { cause })
}
}
export async function resolveSessionTarget(input: {
client: OpenCodeClient
location?: { directory?: string; workspace?: string }
continue?: boolean
session?: string
fork?: boolean
model?: ModelRef
agent?: string
environment?: Readonly<Record<string, string>>
prepare: SessionTargetPreparation
signal?: AbortSignal
}): Promise<SessionTarget> {
const selection = await selectSession(input)
const selected = selection.session
const location =
selection.location ??
(await resolveLocation(
input.client,
selected ? { directory: selected.location.directory } : input.location,
input.signal,
))
const prepared = await input.prepare({
client: input.client,
location,
session: selected,
model: input.model ?? selected?.model,
agent: input.agent ?? selected?.agent,
signal: input.signal,
})
const session =
selected ??
(await input.client.session
.create(
{
id: input.session,
agent: prepared.agent,
model: prepared.model,
location: { directory: location.directory },
},
...requestOptions(input.signal),
)
.catch((error) => {
throw new SessionTargetMutationError(error)
}))
if (input.environment !== undefined)
await input.client.session
.environment({ sessionID: session.id, variables: input.environment }, ...requestOptions(input.signal))
.catch((error) => {
throw new SessionTargetMutationError(error)
})
return {
session,
location,
model: prepared.model,
agent: prepared.agent ?? session.agent,
resume: selected !== undefined,
}
}
export function parseSessionTargetModel(value?: string): ModelRef | undefined {
if (!value) return
const model = Model.Ref.parse(value)
return { providerID: model.providerID, id: model.id, variant: model.variant }
}
async function selectSession(input: {
client: OpenCodeClient
location?: { directory?: string }
continue?: boolean
session?: string
fork?: boolean
signal?: AbortSignal
}) {
const explicit = input.session ? await findSession(input.client, input.session, input.signal) : undefined
if (input.session && !explicit) {
if (input.fork) throw new Error("Session not found")
return { session: undefined }
}
if (explicit)
return {
session: input.fork
? await input.client.session
.fork({ sessionID: explicit.id }, ...requestOptions(input.signal))
.catch((error) => {
throw new SessionTargetMutationError(error)
})
: explicit,
}
if (!input.continue) return { session: undefined }
const location = await resolveLocation(input.client, input.location, input.signal)
const selected = await latestSession(input.client, location, undefined, input.signal)
if (!selected) return { session: undefined, location }
return {
session: input.fork
? await input.client.session.fork({ sessionID: selected.id }, ...requestOptions(input.signal)).catch((error) => {
throw new SessionTargetMutationError(error)
})
: selected,
}
}
/** Create a new worktree of the location's project, keeping the caller's subfolder when the worktree has it. */
export async function createWorktreeLocation(input: {
client: OpenCodeClient
location?: { directory?: string }
name?: string
signal?: AbortSignal
}) {
const base = await resolveLocation(input.client, input.location, input.signal)
const created = await input.client.worktree
.create(
{ projectID: base.project.id, from: base.project.directory, name: input.name },
...requestOptions(input.signal),
)
.catch((error) => {
throw new SessionTargetMutationError(error)
})
const subfolder = path.relative(base.project.directory, base.directory)
if (!subfolder || subfolder.startsWith("..") || path.isAbsolute(subfolder))
return { root: created.directory, directory: created.directory }
const directory = path.join(created.directory, subfolder)
return resolveLocation(input.client, { directory }, input.signal).then(
() => ({ root: created.directory, directory }),
() => ({ root: created.directory, directory: created.directory }),
)
}
export function findSession(client: OpenCodeClient, sessionID: string, signal?: AbortSignal) {
return client.session.get({ sessionID }, ...requestOptions(signal)).catch((error) => {
if (error && typeof error === "object" && "_tag" in error && error._tag === "SessionNotFoundError") return undefined
throw error
})
}
async function latestSession(
client: OpenCodeClient,
location: LocationGetOutput,
cursor?: string,
signal?: AbortSignal,
): Promise<SessionInfo | undefined> {
const page = await client.session.list(
{
directory: location.directory,
parentID: null,
archived: false,
limit: SESSION_PAGE_LIMIT,
order: "desc",
...(cursor ? { cursor } : {}),
},
...requestOptions(signal),
)
const selected = page.data.find((session) => session.location.directory === location.directory)
if (selected) return selected
if (!page.cursor.next || page.data.length === 0) return
return latestSession(client, location, page.cursor.next, signal)
}
function resolveLocation(client: OpenCodeClient, location?: { directory?: string }, signal?: AbortSignal) {
if (!location && !signal) return client.location.get()
if (!location) return client.location.get(undefined, { signal })
return client.location.get({ location }, ...requestOptions(signal))
}
function requestOptions(signal?: AbortSignal): [] | [{ signal: AbortSignal }] {
return signal ? [{ signal }] : []
}