pi-branch-out 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +148 -0
- package/THIRD-PARTY-NOTICES.md +9 -0
- package/extensions/branch-out/config.json.example +5 -0
- package/extensions/branch-out/index.ts +1252 -0
- package/package.json +33 -0
|
@@ -0,0 +1,1252 @@
|
|
|
1
|
+
import * as fs from "node:fs"
|
|
2
|
+
import * as os from "node:os"
|
|
3
|
+
import * as path from "node:path"
|
|
4
|
+
import { spawn } from "node:child_process"
|
|
5
|
+
import { fileURLToPath } from "node:url"
|
|
6
|
+
|
|
7
|
+
import type {
|
|
8
|
+
ExtensionAPI,
|
|
9
|
+
ExtensionCommandContext,
|
|
10
|
+
ExtensionContext,
|
|
11
|
+
SessionEntry,
|
|
12
|
+
} from "@mariozechner/pi-coding-agent"
|
|
13
|
+
import { SessionManager } from "@mariozechner/pi-coding-agent"
|
|
14
|
+
import { Key, matchesKey } from "@mariozechner/pi-tui"
|
|
15
|
+
|
|
16
|
+
const TERMINAL_FLAG = "branch-out-terminal"
|
|
17
|
+
const STATUS_KEY = "branch-out-terminal"
|
|
18
|
+
const BRANCH_LAUNCH_CUSTOM_TYPE = "branch-out-launch"
|
|
19
|
+
const BRANCH_LAUNCH_APPLIED_CUSTOM_TYPE = "branch-out-launch-applied"
|
|
20
|
+
const AUTO_SUBMIT_SECONDS = 10
|
|
21
|
+
const THINKING_LEVELS = new Set(["off", "minimal", "low", "medium", "high", "xhigh"])
|
|
22
|
+
const EXTENSION_DIR = path.dirname(fileURLToPath(import.meta.url))
|
|
23
|
+
const CONFIG_PATH = path.join(EXTENSION_DIR, "config.json")
|
|
24
|
+
|
|
25
|
+
type LaunchMode = "tab" | "split"
|
|
26
|
+
type StaticSplitDirection = "left" | "right" | "up" | "down"
|
|
27
|
+
type RotatingSplitDirection = "clockwise" | "counterclockwise"
|
|
28
|
+
type SplitDirection = StaticSplitDirection | RotatingSplitDirection
|
|
29
|
+
type TerminalBackend = "cmux" | "tmux" | "iterm" | "terminal" | "ghostty" | "unknown"
|
|
30
|
+
|
|
31
|
+
type ModelRef = {
|
|
32
|
+
provider: string
|
|
33
|
+
id: string
|
|
34
|
+
name?: string
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
type ScopedModelCandidate = {
|
|
38
|
+
model: ModelRef
|
|
39
|
+
thinkingLevel?: string
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
type BranchLaunchData = {
|
|
43
|
+
launchId: string
|
|
44
|
+
message?: string
|
|
45
|
+
autoSubmitSeconds: number
|
|
46
|
+
modelNotice?: string
|
|
47
|
+
targetModel?: ModelRef
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
type ExtensionConfig = {
|
|
51
|
+
launchMode: LaunchMode
|
|
52
|
+
splitDirection: SplitDirection
|
|
53
|
+
splitDirectionPreferences: SplitDirection[]
|
|
54
|
+
preserveFocus: boolean
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
type LayoutLeafState = {
|
|
58
|
+
ref: string
|
|
59
|
+
direction: StaticSplitDirection
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
type LayoutWorkspaceState = {
|
|
63
|
+
backend: "cmux" | "tmux"
|
|
64
|
+
workspaceKey: string
|
|
65
|
+
policy: RotatingSplitDirection
|
|
66
|
+
queue: LayoutLeafState[]
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
type PendingAutoSubmit = {
|
|
70
|
+
ctx: ExtensionContext
|
|
71
|
+
sessionFile: string
|
|
72
|
+
interval: ReturnType<typeof setInterval>
|
|
73
|
+
unsubscribeInput: () => void
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const DEFAULT_CONFIG: ExtensionConfig = {
|
|
77
|
+
launchMode: "split",
|
|
78
|
+
splitDirection: "right",
|
|
79
|
+
splitDirectionPreferences: ["right"],
|
|
80
|
+
preserveFocus: true,
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const LAYOUT_STATE_PATH = path.join(os.tmpdir(), "pi-branch-out-layout-state.json")
|
|
84
|
+
|
|
85
|
+
let pending: PendingAutoSubmit | undefined
|
|
86
|
+
|
|
87
|
+
function normalizeTerminalFlag(value: unknown): string | undefined {
|
|
88
|
+
if (typeof value !== "string") return undefined
|
|
89
|
+
const trimmed = value.trim()
|
|
90
|
+
return trimmed.length > 0 ? trimmed : undefined
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function renderTerminalCommand(template: string, sessionFile: string): string {
|
|
94
|
+
if (template.includes("{session}")) {
|
|
95
|
+
return template.split("{session}").join(sessionFile)
|
|
96
|
+
}
|
|
97
|
+
return `${template} ${sessionFile}`
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function shellQuote(value: string): string {
|
|
101
|
+
return `'${value.replace(/'/g, "'\\''")}'`
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function spawnDetached(command: string, args: string[], onError?: (error: Error) => void): void {
|
|
105
|
+
const child = spawn(command, args, { detached: true, stdio: "ignore" })
|
|
106
|
+
child.unref()
|
|
107
|
+
if (onError) child.on("error", onError)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function loadConfig(): ExtensionConfig {
|
|
111
|
+
try {
|
|
112
|
+
const raw = fs.readFileSync(CONFIG_PATH, "utf8")
|
|
113
|
+
const parsed = JSON.parse(raw) as Partial<ExtensionConfig>
|
|
114
|
+
const launchMode = parsed.launchMode === "tab" || parsed.launchMode === "split"
|
|
115
|
+
? parsed.launchMode
|
|
116
|
+
: DEFAULT_CONFIG.launchMode
|
|
117
|
+
const splitDirectionPreferences = parseSplitDirectionPreferences(parsed.splitDirection)
|
|
118
|
+
const preserveFocus = typeof parsed.preserveFocus === "boolean"
|
|
119
|
+
? parsed.preserveFocus
|
|
120
|
+
: DEFAULT_CONFIG.preserveFocus
|
|
121
|
+
return {
|
|
122
|
+
launchMode,
|
|
123
|
+
splitDirection: splitDirectionPreferences[0],
|
|
124
|
+
splitDirectionPreferences,
|
|
125
|
+
preserveFocus,
|
|
126
|
+
}
|
|
127
|
+
} catch {
|
|
128
|
+
return {
|
|
129
|
+
...DEFAULT_CONFIG,
|
|
130
|
+
splitDirectionPreferences: [DEFAULT_CONFIG.splitDirection],
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function isStaticSplitDirection(value: string): value is StaticSplitDirection {
|
|
136
|
+
return value === "left" || value === "right" || value === "up" || value === "down"
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function isSplitDirection(value: string): value is SplitDirection {
|
|
140
|
+
return isStaticSplitDirection(value) || value === "clockwise" || value === "counterclockwise"
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function parseSplitDirectionPreferences(value: unknown): SplitDirection[] {
|
|
144
|
+
if (typeof value !== "string") return [DEFAULT_CONFIG.splitDirection]
|
|
145
|
+
|
|
146
|
+
const directions = value
|
|
147
|
+
.split(",")
|
|
148
|
+
.map((part) => part.trim())
|
|
149
|
+
.filter(isSplitDirection)
|
|
150
|
+
|
|
151
|
+
return directions.length > 0 ? directions : [DEFAULT_CONFIG.splitDirection]
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function resolveSupportedSplitDirection(
|
|
155
|
+
backend: TerminalBackend,
|
|
156
|
+
preferences: SplitDirection[],
|
|
157
|
+
): SplitDirection | undefined {
|
|
158
|
+
switch (backend) {
|
|
159
|
+
case "cmux":
|
|
160
|
+
case "tmux":
|
|
161
|
+
return preferences[0]
|
|
162
|
+
case "iterm":
|
|
163
|
+
return preferences.find((direction) => direction === "right" || direction === "down")
|
|
164
|
+
default:
|
|
165
|
+
return undefined
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function detectTerminalBackend(): TerminalBackend {
|
|
170
|
+
if (process.env.CMUX_SOCKET_PATH) return "cmux"
|
|
171
|
+
if (process.env.TMUX) return "tmux"
|
|
172
|
+
if (process.env.TERM_PROGRAM === "iTerm.app") return "iterm"
|
|
173
|
+
if (process.env.TERM_PROGRAM === "Apple_Terminal") return "terminal"
|
|
174
|
+
if (process.env.GHOSTTY_RESOURCES_DIR || normalizeModelText(process.env.TERM_PROGRAM ?? "").includes("ghostty")) {
|
|
175
|
+
return "ghostty"
|
|
176
|
+
}
|
|
177
|
+
return "unknown"
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function isRotatingSplitDirection(direction: SplitDirection): direction is RotatingSplitDirection {
|
|
181
|
+
return direction === "clockwise" || direction === "counterclockwise"
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function loadLayoutStates(): LayoutWorkspaceState[] {
|
|
185
|
+
try {
|
|
186
|
+
const raw = fs.readFileSync(LAYOUT_STATE_PATH, "utf8")
|
|
187
|
+
const parsed = JSON.parse(raw)
|
|
188
|
+
return Array.isArray(parsed) ? parsed as LayoutWorkspaceState[] : []
|
|
189
|
+
} catch {
|
|
190
|
+
return []
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function saveLayoutStates(states: LayoutWorkspaceState[]): void {
|
|
195
|
+
try {
|
|
196
|
+
fs.writeFileSync(LAYOUT_STATE_PATH, JSON.stringify(states, null, 2))
|
|
197
|
+
} catch {
|
|
198
|
+
// Ignore layout-state persistence failures
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function upsertLayoutState(state: LayoutWorkspaceState): void {
|
|
203
|
+
const states = loadLayoutStates().filter((candidate) => !(
|
|
204
|
+
candidate.backend === state.backend && candidate.workspaceKey === state.workspaceKey
|
|
205
|
+
))
|
|
206
|
+
states.push(state)
|
|
207
|
+
saveLayoutStates(states)
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function getLayoutState(
|
|
211
|
+
backend: "cmux" | "tmux",
|
|
212
|
+
workspaceKey: string,
|
|
213
|
+
policy: RotatingSplitDirection,
|
|
214
|
+
): LayoutWorkspaceState | undefined {
|
|
215
|
+
return loadLayoutStates().find((candidate) => (
|
|
216
|
+
candidate.backend === backend
|
|
217
|
+
&& candidate.workspaceKey === workspaceKey
|
|
218
|
+
&& candidate.policy === policy
|
|
219
|
+
))
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function resolveClockwiseChildDirections(direction: StaticSplitDirection): [StaticSplitDirection, StaticSplitDirection] {
|
|
223
|
+
switch (direction) {
|
|
224
|
+
case "right": return ["up", "down"]
|
|
225
|
+
case "down": return ["right", "left"]
|
|
226
|
+
case "left": return ["down", "up"]
|
|
227
|
+
case "up": return ["left", "right"]
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function resolveCounterclockwiseChildDirections(direction: StaticSplitDirection): [StaticSplitDirection, StaticSplitDirection] {
|
|
232
|
+
switch (direction) {
|
|
233
|
+
case "right": return ["down", "up"]
|
|
234
|
+
case "up": return ["right", "left"]
|
|
235
|
+
case "left": return ["up", "down"]
|
|
236
|
+
case "down": return ["left", "right"]
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function buildRotatingChildren(
|
|
241
|
+
policy: RotatingSplitDirection,
|
|
242
|
+
direction: StaticSplitDirection,
|
|
243
|
+
existingRef: string,
|
|
244
|
+
createdRef: string,
|
|
245
|
+
): LayoutLeafState[] {
|
|
246
|
+
const [existingDirection, createdDirection] = policy === "clockwise"
|
|
247
|
+
? resolveClockwiseChildDirections(direction)
|
|
248
|
+
: resolveCounterclockwiseChildDirections(direction)
|
|
249
|
+
return [
|
|
250
|
+
{ ref: createdRef, direction: createdDirection },
|
|
251
|
+
{ ref: existingRef, direction: existingDirection },
|
|
252
|
+
]
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function normalizeModelText(value: string): string {
|
|
256
|
+
return value.trim().toLowerCase()
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function collapseModelText(value: string): string {
|
|
260
|
+
return normalizeModelText(value).replace(/[^a-z0-9]+/g, "")
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function expandUserPath(p: string): string {
|
|
264
|
+
if (p === "~") return os.homedir()
|
|
265
|
+
if (p.startsWith("~/")) return path.join(os.homedir(), p.slice(2))
|
|
266
|
+
return p
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function splitPatternThinkingLevel(pattern: string): { pattern: string; thinkingLevel?: string } {
|
|
270
|
+
const lastColonIndex = pattern.lastIndexOf(":")
|
|
271
|
+
if (lastColonIndex === -1) return { pattern }
|
|
272
|
+
|
|
273
|
+
const suffix = pattern.slice(lastColonIndex + 1).trim().toLowerCase()
|
|
274
|
+
if (!THINKING_LEVELS.has(suffix)) return { pattern }
|
|
275
|
+
|
|
276
|
+
return {
|
|
277
|
+
pattern: pattern.slice(0, lastColonIndex),
|
|
278
|
+
thinkingLevel: suffix,
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function matchesGlob(pattern: string, value: string): boolean {
|
|
283
|
+
const escaped = pattern
|
|
284
|
+
.replace(/[.+^${}()|\\]/g, "\\$&")
|
|
285
|
+
.replace(/\*/g, ".*")
|
|
286
|
+
.replace(/\?/g, ".")
|
|
287
|
+
return new RegExp(`^${escaped}$`, "i").test(value)
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function loadEnabledModelPatterns(cwd: string): string[] | undefined {
|
|
291
|
+
const agentDir = process.env.PI_CODING_AGENT_DIR
|
|
292
|
+
? expandUserPath(process.env.PI_CODING_AGENT_DIR)
|
|
293
|
+
: path.join(os.homedir(), ".pi", "agent")
|
|
294
|
+
const globalSettingsPath = path.join(agentDir, "settings.json")
|
|
295
|
+
const projectSettingsPath = path.join(cwd, ".pi", "settings.json")
|
|
296
|
+
|
|
297
|
+
const readEnabledModels = (settingsPath: string): string[] | undefined => {
|
|
298
|
+
try {
|
|
299
|
+
const raw = fs.readFileSync(settingsPath, "utf8")
|
|
300
|
+
const parsed = JSON.parse(raw)
|
|
301
|
+
return Array.isArray(parsed?.enabledModels)
|
|
302
|
+
? parsed.enabledModels.filter((value: unknown): value is string => typeof value === "string")
|
|
303
|
+
: undefined
|
|
304
|
+
} catch {
|
|
305
|
+
return undefined
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
const globalModels = readEnabledModels(globalSettingsPath)
|
|
310
|
+
const projectModels = readEnabledModels(projectSettingsPath)
|
|
311
|
+
return projectModels ?? globalModels
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function scoreModelCandidate(
|
|
315
|
+
query: string,
|
|
316
|
+
candidate: ScopedModelCandidate,
|
|
317
|
+
options?: { preferredProvider?: string },
|
|
318
|
+
): number {
|
|
319
|
+
const normalizedQuery = normalizeModelText(query)
|
|
320
|
+
if (!normalizedQuery) return 0
|
|
321
|
+
|
|
322
|
+
const fullId = normalizeModelText(`${candidate.model.provider}/${candidate.model.id}`)
|
|
323
|
+
const id = normalizeModelText(candidate.model.id)
|
|
324
|
+
const name = normalizeModelText(candidate.model.name ?? "")
|
|
325
|
+
const providerBonus = options?.preferredProvider
|
|
326
|
+
&& normalizeModelText(candidate.model.provider) === normalizeModelText(options.preferredProvider)
|
|
327
|
+
? 750
|
|
328
|
+
: 0
|
|
329
|
+
|
|
330
|
+
if (fullId === normalizedQuery) return 12000 + providerBonus
|
|
331
|
+
if (id === normalizedQuery) return 11500 + providerBonus
|
|
332
|
+
if (fullId.endsWith(`/${normalizedQuery}`)) return 11000 + providerBonus
|
|
333
|
+
if (id.startsWith(normalizedQuery)) return 10000 - (id.length - normalizedQuery.length) + providerBonus
|
|
334
|
+
if (fullId.startsWith(normalizedQuery)) return 9500 - (fullId.length - normalizedQuery.length) + providerBonus
|
|
335
|
+
|
|
336
|
+
const idIndex = id.indexOf(normalizedQuery)
|
|
337
|
+
if (idIndex !== -1) return 9000 - idIndex * 10 - (id.length - normalizedQuery.length) + providerBonus
|
|
338
|
+
|
|
339
|
+
const fullIdIndex = fullId.indexOf(normalizedQuery)
|
|
340
|
+
if (fullIdIndex !== -1) {
|
|
341
|
+
return 8000 - fullIdIndex * 10 - (fullId.length - normalizedQuery.length) + providerBonus
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
const nameIndex = name.indexOf(normalizedQuery)
|
|
345
|
+
if (nameIndex !== -1) return 7000 - nameIndex * 10 - (name.length - normalizedQuery.length) + providerBonus
|
|
346
|
+
|
|
347
|
+
const collapsedQuery = collapseModelText(query)
|
|
348
|
+
if (!collapsedQuery) return 0
|
|
349
|
+
|
|
350
|
+
const collapsedId = collapseModelText(candidate.model.id)
|
|
351
|
+
const collapsedFullId = collapseModelText(`${candidate.model.provider}/${candidate.model.id}`)
|
|
352
|
+
const collapsedName = collapseModelText(candidate.model.name ?? "")
|
|
353
|
+
|
|
354
|
+
if (collapsedId === collapsedQuery) return 6500 + providerBonus
|
|
355
|
+
if (collapsedFullId === collapsedQuery) return 6250 + providerBonus
|
|
356
|
+
if (collapsedId.startsWith(collapsedQuery)) {
|
|
357
|
+
return 6000 - (collapsedId.length - collapsedQuery.length) + providerBonus
|
|
358
|
+
}
|
|
359
|
+
if (collapsedFullId.startsWith(collapsedQuery)) {
|
|
360
|
+
return 5500 - (collapsedFullId.length - collapsedQuery.length) + providerBonus
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
const collapsedIdIndex = collapsedId.indexOf(collapsedQuery)
|
|
364
|
+
if (collapsedIdIndex !== -1) {
|
|
365
|
+
return 5000 - collapsedIdIndex * 10 - (collapsedId.length - collapsedQuery.length) + providerBonus
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
const collapsedFullIdIndex = collapsedFullId.indexOf(collapsedQuery)
|
|
369
|
+
if (collapsedFullIdIndex !== -1) {
|
|
370
|
+
return 4500 - collapsedFullIdIndex * 10 - (collapsedFullId.length - collapsedQuery.length) + providerBonus
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
const collapsedNameIndex = collapsedName.indexOf(collapsedQuery)
|
|
374
|
+
if (collapsedNameIndex !== -1) {
|
|
375
|
+
return 4000 - collapsedNameIndex * 10 - (collapsedName.length - collapsedQuery.length) + providerBonus
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
return 0
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function resolveClosestModelCandidate(
|
|
382
|
+
modelQuery: string,
|
|
383
|
+
candidates: ScopedModelCandidate[],
|
|
384
|
+
options?: { preferredProvider?: string },
|
|
385
|
+
): ScopedModelCandidate | undefined {
|
|
386
|
+
const normalizedQuery = normalizeModelText(modelQuery)
|
|
387
|
+
if (!normalizedQuery) return undefined
|
|
388
|
+
|
|
389
|
+
const slashIndex = normalizedQuery.indexOf("/")
|
|
390
|
+
const providerQuery = slashIndex > 0 ? normalizedQuery.slice(0, slashIndex) : undefined
|
|
391
|
+
const idQuery = slashIndex > 0 ? normalizedQuery.slice(slashIndex + 1) : normalizedQuery
|
|
392
|
+
|
|
393
|
+
const searchSpace = providerQuery
|
|
394
|
+
? candidates.filter((candidate) => normalizeModelText(candidate.model.provider) === providerQuery)
|
|
395
|
+
: candidates
|
|
396
|
+
if (searchSpace.length === 0) return undefined
|
|
397
|
+
|
|
398
|
+
return searchSpace
|
|
399
|
+
.map((candidate) => ({
|
|
400
|
+
candidate,
|
|
401
|
+
score: Math.max(
|
|
402
|
+
scoreModelCandidate(normalizedQuery, candidate, options),
|
|
403
|
+
providerQuery ? scoreModelCandidate(idQuery, candidate, options) + 50 : 0,
|
|
404
|
+
),
|
|
405
|
+
}))
|
|
406
|
+
.filter((entry) => entry.score > 0)
|
|
407
|
+
.sort((a, b) => (
|
|
408
|
+
b.score - a.score
|
|
409
|
+
|| a.candidate.model.id.length - b.candidate.model.id.length
|
|
410
|
+
|| `${a.candidate.model.provider}/${a.candidate.model.id}`.localeCompare(
|
|
411
|
+
`${b.candidate.model.provider}/${b.candidate.model.id}`,
|
|
412
|
+
)
|
|
413
|
+
))[0]?.candidate
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
function resolveScopedCandidatesFromSettings(ctx: ExtensionContext): ScopedModelCandidate[] {
|
|
417
|
+
const patterns = loadEnabledModelPatterns(ctx.cwd)
|
|
418
|
+
if (!patterns || patterns.length === 0) return []
|
|
419
|
+
|
|
420
|
+
const availableModels = ctx.modelRegistry.getAvailable().map((model: any) => ({
|
|
421
|
+
model: {
|
|
422
|
+
provider: model.provider,
|
|
423
|
+
id: model.id,
|
|
424
|
+
name: model.name,
|
|
425
|
+
},
|
|
426
|
+
}))
|
|
427
|
+
const preferredProvider = ctx.model?.provider
|
|
428
|
+
const resolved: ScopedModelCandidate[] = []
|
|
429
|
+
const seen = new Set<string>()
|
|
430
|
+
|
|
431
|
+
const addCandidate = (candidate: ScopedModelCandidate) => {
|
|
432
|
+
const key = `${candidate.model.provider}/${candidate.model.id}`
|
|
433
|
+
if (seen.has(key)) return
|
|
434
|
+
seen.add(key)
|
|
435
|
+
resolved.push(candidate)
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
for (const rawPattern of patterns) {
|
|
439
|
+
const { pattern, thinkingLevel } = splitPatternThinkingLevel(rawPattern.trim())
|
|
440
|
+
if (!pattern) continue
|
|
441
|
+
|
|
442
|
+
if (pattern.includes("*") || pattern.includes("?")) {
|
|
443
|
+
for (const candidate of availableModels) {
|
|
444
|
+
const fullId = `${candidate.model.provider}/${candidate.model.id}`
|
|
445
|
+
if (matchesGlob(pattern, fullId) || matchesGlob(pattern, candidate.model.id)) {
|
|
446
|
+
addCandidate({ model: candidate.model, thinkingLevel })
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
continue
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
const match = resolveClosestModelCandidate(pattern, availableModels, { preferredProvider })
|
|
453
|
+
if (match) {
|
|
454
|
+
addCandidate({ model: match.model, thinkingLevel })
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
return resolved
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
function getModelCandidates(ctx: ExtensionContext): ScopedModelCandidate[] {
|
|
462
|
+
const settingsScopedModels = resolveScopedCandidatesFromSettings(ctx)
|
|
463
|
+
if (settingsScopedModels.length > 0) return settingsScopedModels
|
|
464
|
+
|
|
465
|
+
if (ctx.model) {
|
|
466
|
+
return ctx.modelRegistry.getAvailable()
|
|
467
|
+
.filter((model: any) => model.provider === ctx.model?.provider)
|
|
468
|
+
.map((model: any) => ({
|
|
469
|
+
model: {
|
|
470
|
+
provider: model.provider,
|
|
471
|
+
id: model.id,
|
|
472
|
+
name: model.name,
|
|
473
|
+
},
|
|
474
|
+
}))
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
return []
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
function parseBranchArgs(rawArgs: string): { modelQuery?: string; message: string } {
|
|
481
|
+
let remaining = rawArgs.trim()
|
|
482
|
+
let modelQuery: string | undefined
|
|
483
|
+
|
|
484
|
+
const modelMatch = remaining.match(/^--model\s+(\S+)(?:\s+|$)/)
|
|
485
|
+
if (modelMatch) {
|
|
486
|
+
modelQuery = modelMatch[1]
|
|
487
|
+
remaining = remaining.slice(modelMatch[0].length).trimStart()
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
return { modelQuery, message: remaining }
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
function isEditableInput(data: string): boolean {
|
|
494
|
+
if (!data) return false
|
|
495
|
+
|
|
496
|
+
if (data.length === 1) {
|
|
497
|
+
const charCode = data.charCodeAt(0)
|
|
498
|
+
if (charCode >= 32 && charCode !== 127) return true
|
|
499
|
+
if (charCode === 8 || charCode === 13) return true
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
if (data === "\n" || data === "\r" || data === "\x7f") return true
|
|
503
|
+
if (data.length > 1 && !data.startsWith("\x1b")) return true
|
|
504
|
+
return false
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
function getStatusLine(ctx: ExtensionContext, seconds: number): string {
|
|
508
|
+
const accent = ctx.ui.theme.fg("accent", `branch auto-submit in ${seconds}s`)
|
|
509
|
+
const hint = ctx.ui.theme.fg("dim", "(type or Esc to cancel)")
|
|
510
|
+
return `${accent} ${hint}`
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
function clearPending(ctx?: ExtensionContext, notice?: string): void {
|
|
514
|
+
if (!pending) return
|
|
515
|
+
clearInterval(pending.interval)
|
|
516
|
+
pending.unsubscribeInput()
|
|
517
|
+
pending.ctx.ui.setStatus(STATUS_KEY, undefined)
|
|
518
|
+
const active = pending
|
|
519
|
+
pending = undefined
|
|
520
|
+
if (ctx && notice) {
|
|
521
|
+
ctx.ui.notify(notice, "info")
|
|
522
|
+
} else if (!ctx && notice) {
|
|
523
|
+
active.ctx.ui.notify(notice, "info")
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
function autoSubmitDraft(pi: ExtensionAPI): void {
|
|
528
|
+
if (!pending) return
|
|
529
|
+
|
|
530
|
+
const active = pending
|
|
531
|
+
const currentSession = active.ctx.sessionManager.getSessionFile()
|
|
532
|
+
if (!currentSession || currentSession !== active.sessionFile) {
|
|
533
|
+
clearPending(undefined)
|
|
534
|
+
return
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
const draft = active.ctx.ui.getEditorText().trim()
|
|
538
|
+
clearPending(undefined)
|
|
539
|
+
if (!draft) {
|
|
540
|
+
active.ctx.ui.notify("Draft is empty", "warning")
|
|
541
|
+
return
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
active.ctx.ui.setEditorText("")
|
|
545
|
+
try {
|
|
546
|
+
if (active.ctx.isIdle()) {
|
|
547
|
+
pi.sendUserMessage(draft)
|
|
548
|
+
} else {
|
|
549
|
+
pi.sendUserMessage(draft, { deliverAs: "followUp" })
|
|
550
|
+
}
|
|
551
|
+
} catch {
|
|
552
|
+
pi.sendUserMessage(draft)
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
function startCountdown(pi: ExtensionAPI, ctx: ExtensionContext, secondsTotal: number): void {
|
|
557
|
+
clearPending(ctx)
|
|
558
|
+
|
|
559
|
+
const sessionFile = ctx.sessionManager.getSessionFile()
|
|
560
|
+
if (!sessionFile) {
|
|
561
|
+
ctx.ui.notify("Auto-submit disabled: could not determine session identity", "warning")
|
|
562
|
+
return
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
let secondsRemaining = secondsTotal
|
|
566
|
+
ctx.ui.setStatus(STATUS_KEY, getStatusLine(ctx, secondsRemaining))
|
|
567
|
+
|
|
568
|
+
const unsubscribeInput = ctx.ui.onTerminalInput((data) => {
|
|
569
|
+
if (matchesKey(data, Key.escape)) {
|
|
570
|
+
clearPending(ctx, "Auto-submit cancelled")
|
|
571
|
+
return { consume: true }
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
if (data === "\r" || data === "\n" || data === "\r\n") {
|
|
575
|
+
clearPending(ctx)
|
|
576
|
+
return undefined
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
if (isEditableInput(data)) {
|
|
580
|
+
clearPending(ctx, "Auto-submit cancelled")
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
return undefined
|
|
584
|
+
})
|
|
585
|
+
|
|
586
|
+
const interval = setInterval(() => {
|
|
587
|
+
if (!pending) return
|
|
588
|
+
|
|
589
|
+
secondsRemaining -= 1
|
|
590
|
+
if (secondsRemaining <= 0) {
|
|
591
|
+
autoSubmitDraft(pi)
|
|
592
|
+
return
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
ctx.ui.setStatus(STATUS_KEY, getStatusLine(ctx, secondsRemaining))
|
|
596
|
+
}, 1000)
|
|
597
|
+
|
|
598
|
+
pending = {
|
|
599
|
+
ctx,
|
|
600
|
+
sessionFile,
|
|
601
|
+
interval,
|
|
602
|
+
unsubscribeInput,
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
function readBranchLaunchData(entries: SessionEntry[]): BranchLaunchData | undefined {
|
|
607
|
+
let latestLaunch: BranchLaunchData | undefined
|
|
608
|
+
const applied = new Set<string>()
|
|
609
|
+
|
|
610
|
+
for (const entry of entries) {
|
|
611
|
+
if (entry.type !== "custom") continue
|
|
612
|
+
if (entry.customType === BRANCH_LAUNCH_APPLIED_CUSTOM_TYPE) {
|
|
613
|
+
const launchId = typeof entry.data === "object" && entry.data && "launchId" in entry.data
|
|
614
|
+
? (entry.data as any).launchId
|
|
615
|
+
: undefined
|
|
616
|
+
if (typeof launchId === "string" && launchId) applied.add(launchId)
|
|
617
|
+
continue
|
|
618
|
+
}
|
|
619
|
+
if (entry.customType !== BRANCH_LAUNCH_CUSTOM_TYPE) continue
|
|
620
|
+
const data = entry.data
|
|
621
|
+
if (!data || typeof data !== "object") continue
|
|
622
|
+
const launchId = typeof (data as any).launchId === "string" ? (data as any).launchId : undefined
|
|
623
|
+
if (!launchId) continue
|
|
624
|
+
latestLaunch = data as BranchLaunchData
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
if (!latestLaunch) return undefined
|
|
628
|
+
return applied.has(latestLaunch.launchId) ? undefined : latestLaunch
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
async function isMacAppAvailable(pi: ExtensionAPI, appName: string): Promise<boolean> {
|
|
632
|
+
const result = await pi.exec("open", ["-Ra", appName])
|
|
633
|
+
return result.code === 0
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
function buildBranchCommand(forkFile: string): string {
|
|
637
|
+
return `pi --session ${shellQuote(forkFile)}`
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
function extractCmuxSurface(output: string): string | undefined {
|
|
641
|
+
return output.match(/surface:\d+/)?.[0]
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
function extractCmuxPane(output: string): string | undefined {
|
|
645
|
+
return output.match(/pane:\d+/)?.[0]
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
function extractCmuxPanes(output: string): string[] {
|
|
649
|
+
return Array.from(new Set(output.match(/pane:\d+/g) ?? []))
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
function extractTmuxPanes(output: string): string[] {
|
|
653
|
+
return output
|
|
654
|
+
.split("\n")
|
|
655
|
+
.map((line) => line.trim())
|
|
656
|
+
.filter(Boolean)
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
function extractCmuxSurfaces(output: string): string[] {
|
|
660
|
+
return Array.from(new Set(output.match(/surface:\d+/g) ?? []))
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
function extractTmuxPane(output: string): string | undefined {
|
|
664
|
+
return output.trim().split("\n").map((line) => line.trim()).find(Boolean)
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
function parseCmuxCallerPane(output: string): string | undefined {
|
|
668
|
+
try {
|
|
669
|
+
const parsed = JSON.parse(output)
|
|
670
|
+
return parsed?.caller?.pane_ref
|
|
671
|
+
} catch {
|
|
672
|
+
return undefined
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
function parseCmuxCallerSurface(output: string): string | undefined {
|
|
677
|
+
try {
|
|
678
|
+
const parsed = JSON.parse(output)
|
|
679
|
+
return parsed?.caller?.surface_ref
|
|
680
|
+
} catch {
|
|
681
|
+
return undefined
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
async function listCmuxSurfaceRefs(pi: ExtensionAPI): Promise<string[]> {
|
|
686
|
+
const result = await pi.exec("cmux", ["--json", "tree"])
|
|
687
|
+
if (result.code !== 0) {
|
|
688
|
+
throw new Error(result.stderr || result.stdout || "cmux tree failed")
|
|
689
|
+
}
|
|
690
|
+
return extractCmuxSurfaces(`${result.stdout || result.stderr}`)
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
async function listTmuxPaneRefs(pi: ExtensionAPI): Promise<string[]> {
|
|
694
|
+
const result = await pi.exec("tmux", ["list-panes", "-F", "#{pane_id}"])
|
|
695
|
+
if (result.code !== 0) {
|
|
696
|
+
throw new Error(result.stderr || result.stdout || "tmux list-panes failed")
|
|
697
|
+
}
|
|
698
|
+
return extractTmuxPanes(`${result.stdout || result.stderr}`)
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
async function getTmuxWorkspaceKey(pi: ExtensionAPI): Promise<string> {
|
|
702
|
+
const result = await pi.exec("tmux", ["display-message", "-p", "#{session_id}:#{window_id}"])
|
|
703
|
+
if (result.code !== 0) {
|
|
704
|
+
throw new Error(result.stderr || result.stdout || "tmux display-message failed")
|
|
705
|
+
}
|
|
706
|
+
return `${result.stdout || result.stderr}`.trim()
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
async function resolveRotatingTarget(
|
|
710
|
+
backend: "cmux" | "tmux",
|
|
711
|
+
workspaceKey: string,
|
|
712
|
+
policy: RotatingSplitDirection,
|
|
713
|
+
currentRef: string,
|
|
714
|
+
existingRefs: string[],
|
|
715
|
+
): Promise<LayoutLeafState> {
|
|
716
|
+
const existingRefSet = new Set(existingRefs)
|
|
717
|
+
const state = getLayoutState(backend, workspaceKey, policy)
|
|
718
|
+
const queue = state?.queue.filter((candidate) => existingRefSet.has(candidate.ref)) ?? []
|
|
719
|
+
if (queue.length === 0) {
|
|
720
|
+
return { ref: currentRef, direction: "right" }
|
|
721
|
+
}
|
|
722
|
+
return queue[0]
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
function updateRotatingState(
|
|
726
|
+
backend: "cmux" | "tmux",
|
|
727
|
+
workspaceKey: string,
|
|
728
|
+
policy: RotatingSplitDirection,
|
|
729
|
+
queue: LayoutLeafState[],
|
|
730
|
+
): void {
|
|
731
|
+
upsertLayoutState({ backend, workspaceKey, policy, queue })
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
async function openInCmux(
|
|
735
|
+
pi: ExtensionAPI,
|
|
736
|
+
forkFile: string,
|
|
737
|
+
config: ExtensionConfig,
|
|
738
|
+
): Promise<{ opened: boolean; error?: string }> {
|
|
739
|
+
if (!process.env.CMUX_SOCKET_PATH) return { opened: false }
|
|
740
|
+
|
|
741
|
+
if (config.launchMode === "tab") {
|
|
742
|
+
const createResult = await pi.exec("cmux", ["new-surface", "--type", "terminal"])
|
|
743
|
+
if (createResult.code !== 0) {
|
|
744
|
+
return { opened: false, error: createResult.stderr || createResult.stdout || "cmux new-surface failed" }
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
const surface = extractCmuxSurface(`${createResult.stdout || createResult.stderr}`)
|
|
748
|
+
if (!surface) {
|
|
749
|
+
return {
|
|
750
|
+
opened: false,
|
|
751
|
+
error: `Unexpected cmux output: ${(createResult.stdout || createResult.stderr || "").trim()}`,
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
const sendResult = await pi.exec("cmux", ["send", "--surface", surface, `${buildBranchCommand(forkFile)}\n`])
|
|
756
|
+
if (sendResult.code !== 0) {
|
|
757
|
+
return { opened: false, error: sendResult.stderr || sendResult.stdout || "cmux send failed" }
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
return { opened: true }
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
const identifyResult = await pi.exec("cmux", ["identify", "--json"])
|
|
764
|
+
if (identifyResult.code !== 0) {
|
|
765
|
+
return { opened: false, error: identifyResult.stderr || identifyResult.stdout || "cmux identify failed" }
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
const identifyOutput = `${identifyResult.stdout || identifyResult.stderr}`
|
|
769
|
+
const currentPane = parseCmuxCallerPane(identifyOutput)
|
|
770
|
+
const currentSurface = parseCmuxCallerSurface(identifyOutput) ?? process.env.CMUX_SURFACE_ID
|
|
771
|
+
if (!currentSurface) {
|
|
772
|
+
return { opened: false, error: "Could not determine current cmux surface" }
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
const resolvedSplitDirection = resolveSupportedSplitDirection("cmux", config.splitDirectionPreferences)
|
|
776
|
+
if (!resolvedSplitDirection) {
|
|
777
|
+
return { opened: false, error: `Split direction '${config.splitDirection}' is not supported in cmux` }
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
const panesBeforeResult = await pi.exec("cmux", ["list-panes", "--json"])
|
|
781
|
+
const policy = isRotatingSplitDirection(resolvedSplitDirection) ? resolvedSplitDirection : undefined
|
|
782
|
+
const workspaceKey = process.env.CMUX_WORKSPACE_ID ?? "cmux"
|
|
783
|
+
const existingRefs = policy ? await listCmuxSurfaceRefs(pi) : []
|
|
784
|
+
const leaf = policy
|
|
785
|
+
? await resolveRotatingTarget("cmux", workspaceKey, policy, currentSurface, existingRefs)
|
|
786
|
+
: undefined
|
|
787
|
+
const queue = policy
|
|
788
|
+
? (getLayoutState("cmux", workspaceKey, policy)?.queue.filter((candidate) => existingRefs.includes(candidate.ref)) ?? [])
|
|
789
|
+
: []
|
|
790
|
+
const activeLeaf = leaf ?? { ref: currentSurface, direction: resolvedSplitDirection as StaticSplitDirection }
|
|
791
|
+
const createResult = await pi.exec("cmux", ["new-split", activeLeaf.direction, "--surface", activeLeaf.ref])
|
|
792
|
+
if (createResult.code !== 0) {
|
|
793
|
+
return { opened: false, error: createResult.stderr || createResult.stdout || "cmux new-split failed" }
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
const createOutput = `${createResult.stdout || createResult.stderr}`
|
|
797
|
+
const surface = extractCmuxSurface(createOutput)
|
|
798
|
+
const pane = extractCmuxPane(createOutput)
|
|
799
|
+
if (!surface) {
|
|
800
|
+
return {
|
|
801
|
+
opened: false,
|
|
802
|
+
error: `Unexpected cmux output: ${(createResult.stdout || createResult.stderr || "").trim()}`,
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
const sendResult = await pi.exec("cmux", ["send", "--surface", surface, `${buildBranchCommand(forkFile)}\n`])
|
|
807
|
+
if (sendResult.code !== 0) {
|
|
808
|
+
return { opened: false, error: sendResult.stderr || sendResult.stdout || "cmux send failed" }
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
if (policy) {
|
|
812
|
+
updateRotatingState(
|
|
813
|
+
"cmux",
|
|
814
|
+
workspaceKey,
|
|
815
|
+
policy,
|
|
816
|
+
[...(queue.length === 0 ? [] : queue.slice(1)), ...buildRotatingChildren(policy, activeLeaf.direction, activeLeaf.ref, surface)],
|
|
817
|
+
)
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
if (config.preserveFocus && currentPane) {
|
|
821
|
+
const focusResult = await pi.exec("cmux", ["focus-pane", "--pane", currentPane])
|
|
822
|
+
if (focusResult.code !== 0) {
|
|
823
|
+
return { opened: false, error: focusResult.stderr || focusResult.stdout || "cmux focus-pane failed" }
|
|
824
|
+
}
|
|
825
|
+
} else if (!config.preserveFocus) {
|
|
826
|
+
const panesBefore = panesBeforeResult.code === 0
|
|
827
|
+
? extractCmuxPanes(`${panesBeforeResult.stdout || panesBeforeResult.stderr}`)
|
|
828
|
+
: []
|
|
829
|
+
const panesAfterResult = await pi.exec("cmux", ["list-panes", "--json"])
|
|
830
|
+
const panesAfter = panesAfterResult.code === 0
|
|
831
|
+
? extractCmuxPanes(`${panesAfterResult.stdout || panesAfterResult.stderr}`)
|
|
832
|
+
: []
|
|
833
|
+
const newPane = panesAfter.find((candidate) => !panesBefore.includes(candidate)) ?? pane
|
|
834
|
+
if (newPane) {
|
|
835
|
+
const focusResult = await pi.exec("cmux", ["focus-pane", "--pane", newPane])
|
|
836
|
+
if (focusResult.code !== 0) {
|
|
837
|
+
return { opened: false, error: focusResult.stderr || focusResult.stdout || "cmux focus-pane failed" }
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
return { opened: true }
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
async function openInTmux(
|
|
846
|
+
pi: ExtensionAPI,
|
|
847
|
+
forkFile: string,
|
|
848
|
+
config: ExtensionConfig,
|
|
849
|
+
): Promise<{ opened: boolean; error?: string }> {
|
|
850
|
+
if (!process.env.TMUX) return { opened: false }
|
|
851
|
+
|
|
852
|
+
if (config.launchMode === "tab") {
|
|
853
|
+
const result = await pi.exec("tmux", ["new-window", "-n", "branch", "pi", "--session", forkFile])
|
|
854
|
+
if (result.code !== 0) {
|
|
855
|
+
return { opened: false, error: result.stderr || result.stdout || "tmux new-window failed" }
|
|
856
|
+
}
|
|
857
|
+
return { opened: true }
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
const currentPane = process.env.TMUX_PANE
|
|
861
|
+
if (!currentPane) {
|
|
862
|
+
return { opened: false, error: "Could not determine current tmux pane" }
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
const resolvedSplitDirection = resolveSupportedSplitDirection("tmux", config.splitDirectionPreferences)
|
|
866
|
+
if (!resolvedSplitDirection) {
|
|
867
|
+
return { opened: false, error: `Split direction '${config.splitDirection}' is not supported in tmux` }
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
const policy = isRotatingSplitDirection(resolvedSplitDirection) ? resolvedSplitDirection : undefined
|
|
871
|
+
const workspaceKey = await getTmuxWorkspaceKey(pi)
|
|
872
|
+
const existingRefs = policy ? await listTmuxPaneRefs(pi) : []
|
|
873
|
+
const leaf = policy
|
|
874
|
+
? await resolveRotatingTarget("tmux", workspaceKey, policy, currentPane, existingRefs)
|
|
875
|
+
: undefined
|
|
876
|
+
const queue = policy
|
|
877
|
+
? (getLayoutState("tmux", workspaceKey, policy)?.queue.filter((candidate) => existingRefs.includes(candidate.ref)) ?? [])
|
|
878
|
+
: []
|
|
879
|
+
const activeLeaf = leaf ?? { ref: currentPane, direction: resolvedSplitDirection as StaticSplitDirection }
|
|
880
|
+
|
|
881
|
+
const splitArgs = [
|
|
882
|
+
"split-window",
|
|
883
|
+
"-t",
|
|
884
|
+
activeLeaf.ref,
|
|
885
|
+
activeLeaf.direction === "left" || activeLeaf.direction === "right" ? "-h" : "-v",
|
|
886
|
+
"-P",
|
|
887
|
+
"-F",
|
|
888
|
+
"#{pane_id}",
|
|
889
|
+
]
|
|
890
|
+
if (activeLeaf.direction === "left" || activeLeaf.direction === "up") splitArgs.push("-b")
|
|
891
|
+
if (config.preserveFocus) splitArgs.push("-d")
|
|
892
|
+
splitArgs.push(buildBranchCommand(forkFile))
|
|
893
|
+
|
|
894
|
+
const result = await pi.exec("tmux", splitArgs)
|
|
895
|
+
if (result.code !== 0) {
|
|
896
|
+
return { opened: false, error: result.stderr || result.stdout || "tmux split-window failed" }
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
const newPane = extractTmuxPane(`${result.stdout || result.stderr}`)
|
|
900
|
+
if (policy && newPane) {
|
|
901
|
+
updateRotatingState(
|
|
902
|
+
"tmux",
|
|
903
|
+
workspaceKey,
|
|
904
|
+
policy,
|
|
905
|
+
[...(queue.length === 0 ? [] : queue.slice(1)), ...buildRotatingChildren(policy, activeLeaf.direction, activeLeaf.ref, newPane)],
|
|
906
|
+
)
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
return { opened: true }
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
async function resolveITermApp(pi: ExtensionAPI): Promise<string | undefined> {
|
|
913
|
+
for (const candidate of ["iTerm2", "iTerm"]) {
|
|
914
|
+
if (await isMacAppAvailable(pi, candidate)) return candidate
|
|
915
|
+
}
|
|
916
|
+
return undefined
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
async function openInITerm(
|
|
920
|
+
pi: ExtensionAPI,
|
|
921
|
+
forkFile: string,
|
|
922
|
+
config: ExtensionConfig,
|
|
923
|
+
): Promise<{ opened: boolean; error?: string }> {
|
|
924
|
+
if (process.platform !== "darwin") return { opened: false }
|
|
925
|
+
|
|
926
|
+
const availableApp = await resolveITermApp(pi)
|
|
927
|
+
if (!availableApp) return { opened: false }
|
|
928
|
+
|
|
929
|
+
const resolvedSplitDirection = config.launchMode === "split"
|
|
930
|
+
? resolveSupportedSplitDirection("iterm", config.splitDirectionPreferences)
|
|
931
|
+
: undefined
|
|
932
|
+
if (config.launchMode === "split" && !resolvedSplitDirection) {
|
|
933
|
+
return { opened: false, error: `Split direction '${config.splitDirection}' is not supported in iTerm2` }
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
const command = buildBranchCommand(forkFile)
|
|
937
|
+
const splitCommand = resolvedSplitDirection === "down"
|
|
938
|
+
? "set newSession to (split horizontally with default profile)"
|
|
939
|
+
: "set newSession to (split vertically with default profile)"
|
|
940
|
+
const scriptLines = config.launchMode === "split"
|
|
941
|
+
? [
|
|
942
|
+
`tell application "${availableApp}"`,
|
|
943
|
+
"activate",
|
|
944
|
+
"if (count of windows) is 0 then",
|
|
945
|
+
"create window with default profile",
|
|
946
|
+
"tell current session of current window",
|
|
947
|
+
`write text ${JSON.stringify(command)}`,
|
|
948
|
+
"end tell",
|
|
949
|
+
"else",
|
|
950
|
+
"tell current tab of current window",
|
|
951
|
+
"set originalSession to current session",
|
|
952
|
+
"tell originalSession",
|
|
953
|
+
splitCommand,
|
|
954
|
+
"end tell",
|
|
955
|
+
"tell newSession",
|
|
956
|
+
`write text ${JSON.stringify(command)}`,
|
|
957
|
+
"end tell",
|
|
958
|
+
...(config.preserveFocus ? ["select originalSession"] : ["select newSession"]),
|
|
959
|
+
"end tell",
|
|
960
|
+
"end if",
|
|
961
|
+
"end tell",
|
|
962
|
+
]
|
|
963
|
+
: [
|
|
964
|
+
`tell application "${availableApp}"`,
|
|
965
|
+
"activate",
|
|
966
|
+
"if (count of windows) is 0 then",
|
|
967
|
+
"create window with default profile",
|
|
968
|
+
"else",
|
|
969
|
+
"tell current window to create tab with default profile",
|
|
970
|
+
"end if",
|
|
971
|
+
"tell current session of current window",
|
|
972
|
+
`write text ${JSON.stringify(command)}`,
|
|
973
|
+
"end tell",
|
|
974
|
+
"end tell",
|
|
975
|
+
]
|
|
976
|
+
|
|
977
|
+
const osascriptArgs = scriptLines.flatMap((line) => ["-e", line])
|
|
978
|
+
const result = await pi.exec("osascript", osascriptArgs)
|
|
979
|
+
if (result.code !== 0) {
|
|
980
|
+
return { opened: false, error: result.stderr || result.stdout || "osascript failed" }
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
return { opened: true }
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
async function openInMacOSTerminal(
|
|
987
|
+
pi: ExtensionAPI,
|
|
988
|
+
forkFile: string,
|
|
989
|
+
config: ExtensionConfig,
|
|
990
|
+
): Promise<{ opened: boolean; error?: string }> {
|
|
991
|
+
if (process.platform !== "darwin") return { opened: false }
|
|
992
|
+
if (!(await isMacAppAvailable(pi, "Terminal"))) return { opened: false }
|
|
993
|
+
if (config.launchMode === "split") {
|
|
994
|
+
return { opened: false, error: "Split launch is not supported in Terminal.app" }
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
const command = buildBranchCommand(forkFile)
|
|
998
|
+
const scriptLines = [
|
|
999
|
+
'tell application "Terminal"',
|
|
1000
|
+
"activate",
|
|
1001
|
+
"if (count of windows) is 0 then",
|
|
1002
|
+
`do script ${JSON.stringify(command)}`,
|
|
1003
|
+
"else",
|
|
1004
|
+
`do script ${JSON.stringify(command)} in front window`,
|
|
1005
|
+
"end if",
|
|
1006
|
+
"end tell",
|
|
1007
|
+
]
|
|
1008
|
+
|
|
1009
|
+
const osascriptArgs = scriptLines.flatMap((line) => ["-e", line])
|
|
1010
|
+
const result = await pi.exec("osascript", osascriptArgs)
|
|
1011
|
+
if (result.code !== 0) {
|
|
1012
|
+
return { opened: false, error: result.stderr || result.stdout || "osascript failed" }
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
return { opened: true }
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
function openInGhostty(ctx: ExtensionCommandContext, forkFile: string): void {
|
|
1019
|
+
spawnDetached("ghostty", ["-e", "pi", "--session", forkFile], (error) => {
|
|
1020
|
+
if (ctx.hasUI) {
|
|
1021
|
+
ctx.ui.notify(`Ghostty failed to open: ${error.message}`, "warning")
|
|
1022
|
+
ctx.ui.notify(`Run: pi --session ${forkFile}`, "info")
|
|
1023
|
+
}
|
|
1024
|
+
})
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
async function openForkInTerminal(pi: ExtensionAPI, ctx: ExtensionCommandContext, forkFile: string): Promise<void> {
|
|
1028
|
+
const terminalFlag = normalizeTerminalFlag(pi.getFlag(`--${TERMINAL_FLAG}`))
|
|
1029
|
+
if (terminalFlag) {
|
|
1030
|
+
const command = renderTerminalCommand(terminalFlag, forkFile)
|
|
1031
|
+
spawnDetached("bash", ["-lc", command], (error) => {
|
|
1032
|
+
if (ctx.hasUI) ctx.ui.notify(`Terminal command failed: ${error.message}`, "error")
|
|
1033
|
+
})
|
|
1034
|
+
return
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
const config = loadConfig()
|
|
1038
|
+
const activeBackend = detectTerminalBackend()
|
|
1039
|
+
|
|
1040
|
+
if (activeBackend === "cmux") {
|
|
1041
|
+
const cmuxAttempt = await openInCmux(pi, forkFile, config)
|
|
1042
|
+
if (!cmuxAttempt.opened) throw new Error(cmuxAttempt.error || "cmux launch failed")
|
|
1043
|
+
return
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
if (activeBackend === "tmux") {
|
|
1047
|
+
const tmuxAttempt = await openInTmux(pi, forkFile, config)
|
|
1048
|
+
if (!tmuxAttempt.opened) throw new Error(tmuxAttempt.error || "tmux launch failed")
|
|
1049
|
+
return
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
if (activeBackend === "iterm") {
|
|
1053
|
+
const iTermAttempt = await openInITerm(pi, forkFile, config)
|
|
1054
|
+
if (!iTermAttempt.opened) throw new Error(iTermAttempt.error || "iTerm failed to open")
|
|
1055
|
+
return
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
if (activeBackend === "terminal") {
|
|
1059
|
+
const terminalAttempt = await openInMacOSTerminal(pi, forkFile, config)
|
|
1060
|
+
if (!terminalAttempt.opened) throw new Error(terminalAttempt.error || "Terminal.app failed to open")
|
|
1061
|
+
return
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
if (activeBackend === "ghostty") {
|
|
1065
|
+
if (config.launchMode === "split") {
|
|
1066
|
+
throw new Error("Split launch is not supported in Ghostty")
|
|
1067
|
+
}
|
|
1068
|
+
openInGhostty(ctx, forkFile)
|
|
1069
|
+
return
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
if (config.launchMode === "split") {
|
|
1073
|
+
throw new Error("Split launch requires an active cmux, tmux, or iTerm2 session")
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
if (process.platform === "darwin") {
|
|
1077
|
+
const iTermAttempt = await openInITerm(pi, forkFile, config)
|
|
1078
|
+
if (iTermAttempt.opened) return
|
|
1079
|
+
if (iTermAttempt.error && ctx.hasUI) ctx.ui.notify(`iTerm failed to open: ${iTermAttempt.error}`, "warning")
|
|
1080
|
+
|
|
1081
|
+
const terminalAttempt = await openInMacOSTerminal(pi, forkFile, config)
|
|
1082
|
+
if (terminalAttempt.opened) return
|
|
1083
|
+
if (terminalAttempt.error && ctx.hasUI) {
|
|
1084
|
+
ctx.ui.notify(`macOS Terminal failed to open: ${terminalAttempt.error}`, "warning")
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
spawnDetached("alacritty", ["-e", "pi", "--session", forkFile], (error) => {
|
|
1089
|
+
if (ctx.hasUI) {
|
|
1090
|
+
ctx.ui.notify(`Alacritty failed to open: ${error.message}`, "warning")
|
|
1091
|
+
ctx.ui.notify(`Run: pi --session ${forkFile}`, "info")
|
|
1092
|
+
}
|
|
1093
|
+
})
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
async function applyPendingBranchLaunch(pi: ExtensionAPI, ctx: ExtensionContext): Promise<void> {
|
|
1097
|
+
const launch = readBranchLaunchData(ctx.sessionManager.getBranch())
|
|
1098
|
+
if (!launch) return
|
|
1099
|
+
|
|
1100
|
+
pi.appendEntry(BRANCH_LAUNCH_APPLIED_CUSTOM_TYPE, { launchId: launch.launchId })
|
|
1101
|
+
|
|
1102
|
+
if (launch.targetModel) {
|
|
1103
|
+
const match = typeof ctx.modelRegistry.find === "function"
|
|
1104
|
+
? ctx.modelRegistry.find(launch.targetModel.provider, launch.targetModel.id)
|
|
1105
|
+
: ctx.modelRegistry.getAvailable().find(
|
|
1106
|
+
(model: any) => model.provider === launch.targetModel?.provider && model.id === launch.targetModel?.id,
|
|
1107
|
+
)
|
|
1108
|
+
if (match && (!ctx.model || ctx.model.provider !== match.provider || ctx.model.id !== match.id)) {
|
|
1109
|
+
const switched = await pi.setModel(match)
|
|
1110
|
+
if (!switched && ctx.hasUI) {
|
|
1111
|
+
ctx.ui.notify(`Could not switch branch model to ${match.provider}/${match.id}`, "warning")
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
if (ctx.hasUI && launch.modelNotice) {
|
|
1117
|
+
ctx.ui.notify(launch.modelNotice, launch.targetModel ? "info" : "warning")
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
const message = launch.message?.trim()
|
|
1121
|
+
if (!ctx.hasUI || !message) return
|
|
1122
|
+
|
|
1123
|
+
ctx.ui.setEditorText(message)
|
|
1124
|
+
if (launch.autoSubmitSeconds > 0) {
|
|
1125
|
+
startCountdown(pi, ctx, launch.autoSubmitSeconds)
|
|
1126
|
+
} else {
|
|
1127
|
+
ctx.ui.notify("Draft ready in editor (auto-submit disabled)", "info")
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
function resolveBranchModel(
|
|
1132
|
+
ctx: ExtensionContext,
|
|
1133
|
+
modelQuery: string | undefined,
|
|
1134
|
+
): { targetModel?: ModelRef; notice?: string } {
|
|
1135
|
+
const currentModel = ctx.model
|
|
1136
|
+
? {
|
|
1137
|
+
provider: ctx.model.provider,
|
|
1138
|
+
id: ctx.model.id,
|
|
1139
|
+
name: ctx.model.name,
|
|
1140
|
+
}
|
|
1141
|
+
: undefined
|
|
1142
|
+
|
|
1143
|
+
if (!currentModel) {
|
|
1144
|
+
return modelQuery
|
|
1145
|
+
? { notice: `Model '${modelQuery}' did not resolve; branch will use the session model.` }
|
|
1146
|
+
: {}
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
if (!modelQuery) {
|
|
1150
|
+
return { targetModel: currentModel }
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
const match = resolveClosestModelCandidate(modelQuery, getModelCandidates(ctx), {
|
|
1154
|
+
preferredProvider: ctx.model.provider,
|
|
1155
|
+
})
|
|
1156
|
+
if (!match) {
|
|
1157
|
+
return {
|
|
1158
|
+
targetModel: currentModel,
|
|
1159
|
+
notice: `Model '${modelQuery}' did not resolve safely; using ${ctx.model.provider}/${ctx.model.id}`,
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
return {
|
|
1164
|
+
targetModel: match.model,
|
|
1165
|
+
notice: `Branch model: ${match.model.provider}/${match.model.id}`,
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
export default function (pi: ExtensionAPI) {
|
|
1170
|
+
pi.registerFlag(TERMINAL_FLAG, {
|
|
1171
|
+
description: "Command to open a new terminal. Use {session} placeholder for the session file path.",
|
|
1172
|
+
type: "string",
|
|
1173
|
+
})
|
|
1174
|
+
|
|
1175
|
+
for (const eventName of [
|
|
1176
|
+
"session_before_switch",
|
|
1177
|
+
"session_switch",
|
|
1178
|
+
"session_before_fork",
|
|
1179
|
+
"session_fork",
|
|
1180
|
+
"session_before_tree",
|
|
1181
|
+
"session_tree",
|
|
1182
|
+
"session_shutdown",
|
|
1183
|
+
] as const) {
|
|
1184
|
+
pi.on(eventName as any, (_event: any, eventCtx: any) => {
|
|
1185
|
+
if (pending) clearPending(eventCtx)
|
|
1186
|
+
})
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
1190
|
+
await applyPendingBranchLaunch(pi, ctx)
|
|
1191
|
+
})
|
|
1192
|
+
|
|
1193
|
+
pi.registerCommand("branch", {
|
|
1194
|
+
description: "Fork current session into a new terminal tab or split pane, optionally queueing --model <query> and a draft message",
|
|
1195
|
+
handler: async (args, ctx) => {
|
|
1196
|
+
await ctx.waitForIdle()
|
|
1197
|
+
|
|
1198
|
+
const sessionFile = ctx.sessionManager.getSessionFile()
|
|
1199
|
+
if (!sessionFile) {
|
|
1200
|
+
if (ctx.hasUI) ctx.ui.notify("Session is not persisted. Restart without --no-session.", "error")
|
|
1201
|
+
return
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
const leafId = ctx.sessionManager.getLeafId()
|
|
1205
|
+
if (!leafId) {
|
|
1206
|
+
if (ctx.hasUI) ctx.ui.notify("No messages yet. Nothing to branch.", "error")
|
|
1207
|
+
return
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
const { modelQuery, message } = parseBranchArgs(args)
|
|
1211
|
+
const forkManager = SessionManager.open(sessionFile)
|
|
1212
|
+
const forkFile = forkManager.createBranchedSession(leafId)
|
|
1213
|
+
if (!forkFile) {
|
|
1214
|
+
throw new Error("Failed to create branched session")
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
const trimmedMessage = message.trim()
|
|
1218
|
+
const hasLaunchCustomization = Boolean(modelQuery || trimmedMessage)
|
|
1219
|
+
let launchData: BranchLaunchData | undefined
|
|
1220
|
+
|
|
1221
|
+
if (hasLaunchCustomization) {
|
|
1222
|
+
const launchSession = SessionManager.open(forkFile)
|
|
1223
|
+
const modelResolution = resolveBranchModel(ctx, modelQuery)
|
|
1224
|
+
launchData = {
|
|
1225
|
+
launchId: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
|
|
1226
|
+
message: trimmedMessage || undefined,
|
|
1227
|
+
autoSubmitSeconds: AUTO_SUBMIT_SECONDS,
|
|
1228
|
+
modelNotice: modelResolution.notice,
|
|
1229
|
+
targetModel: modelResolution.targetModel,
|
|
1230
|
+
}
|
|
1231
|
+
launchSession.appendCustomEntry(BRANCH_LAUNCH_CUSTOM_TYPE, launchData)
|
|
1232
|
+
}
|
|
1233
|
+
|
|
1234
|
+
await openForkInTerminal(pi, ctx, forkFile)
|
|
1235
|
+
|
|
1236
|
+
if (ctx.hasUI) {
|
|
1237
|
+
if (!launchData) {
|
|
1238
|
+
ctx.ui.notify("Opened fork", "info")
|
|
1239
|
+
return
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
const details = [
|
|
1243
|
+
launchData.targetModel
|
|
1244
|
+
? `${launchData.targetModel.provider}/${launchData.targetModel.id}`
|
|
1245
|
+
: ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined,
|
|
1246
|
+
launchData.message ? "draft queued" : undefined,
|
|
1247
|
+
].filter(Boolean).join(" · ")
|
|
1248
|
+
ctx.ui.notify(details ? `Opened fork (${details})` : "Opened fork", "info")
|
|
1249
|
+
}
|
|
1250
|
+
},
|
|
1251
|
+
})
|
|
1252
|
+
}
|