pi-branch-out 0.1.9 → 0.1.11

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/README.md CHANGED
@@ -114,7 +114,7 @@ Routing is automatic and tried in this order:
114
114
 
115
115
  If no backend is detected, macOS tries iTerm2 and Terminal.app before falling back to an Alacritty window; other platforms fall back to Alacritty. These fallbacks require `launchMode: "tab"`.
116
116
 
117
- The Orca backend opens the fork beside the terminal that ran `/branch` and uses Pi's current working directory. Orca supports `right` (horizontal) and `down` (vertical) splits and requires `launchMode: "split"`.
117
+ The Orca backend opens the fork beside the terminal that ran `/branch` and uses Pi's current working directory. Direction values describe the desired placement: `right` creates a left/right split (Orca `vertical`), while `down` creates a top/bottom split (Orca `horizontal`). Orca requires `launchMode: "split"`.
118
118
 
119
119
  The Warp backend opens the fork in a new tab in Warp's active window and uses Pi's current working directory. It works with Warp Stable on macOS and Linux when Pi runs on the same machine as Warp, not in an SSH session. It requires `launchMode: "tab"`; for splits inside Warp, run Pi in tmux with `launchMode: "split"`. Each launch writes a temporary [Tab Config](https://docs.warp.dev/terminal/windows/tab-configs/) named `tmp_pi_branch_*.toml`, which the new tab deletes as it starts. If a launch never opens a tab, delete the leftover file from `~/.warp/tab_configs/` on macOS or `${XDG_DATA_HOME:-$HOME/.local/share}/warp-terminal/tab_configs/` on Linux.
120
120
 
@@ -154,6 +154,20 @@ Fork using a fuzzy model query. If the current provider is Anthropic, `flash` w
154
154
  ```
155
155
  Fork with both a target model and a queued message.
156
156
 
157
+ ## Building and publishing
158
+
159
+ To release from a dot314 repository checkout, use Node.js 24 or newer and `trash` on your PATH. Update the version in `packages/pi-branch-out/package.json`, then run these commands from the repository root:
160
+
161
+ ```bash
162
+ cd packages/pi-branch-out
163
+ npm run test:package
164
+ npm pack
165
+ ```
166
+
167
+ The package-local `.npmrc` enables npm lifecycle scripts. Packing runs `prepack` to copy the current extension source and check for local JSON configs. The package test checks the tarball against the source and runs the Orca tests on its extracted implementation.
168
+
169
+ Publish the resulting tarball with `npm publish <tarball-path>`.
170
+
157
171
  ## Upstream credit
158
172
 
159
173
  An earlier version of this extension began as an iteration on davidgasquez's [`branch-term.ts`](https://github.com/davidgasquez/dotfiles/blob/main/agents/pi/extensions/branch-term.ts), MIT license.
@@ -26,7 +26,7 @@ type LaunchMode = "tab" | "split"
26
26
  type StaticSplitDirection = "left" | "right" | "up" | "down"
27
27
  type RotatingSplitDirection = "clockwise" | "counterclockwise"
28
28
  type SplitDirection = StaticSplitDirection | RotatingSplitDirection
29
- type TerminalBackend = "cmux" | "tmux" | "iterm" | "terminal" | "ghostty" | "unknown"
29
+ type TerminalBackend = "orca" | "cmux" | "tmux" | "iterm" | "terminal" | "ghostty" | "unknown" | "warp"
30
30
 
31
31
  type ModelRef = {
32
32
  provider: string
@@ -159,6 +159,8 @@ function resolveSupportedSplitDirection(
159
159
  case "cmux":
160
160
  case "tmux":
161
161
  return preferences[0]
162
+ case "orca":
163
+ return preferences.find((direction) => direction === "right" || direction === "down") ?? "right"
162
164
  case "iterm":
163
165
  return preferences.find((direction) => direction === "right" || direction === "down")
164
166
  default:
@@ -167,6 +169,7 @@ function resolveSupportedSplitDirection(
167
169
  }
168
170
 
169
171
  function detectTerminalBackend(): TerminalBackend {
172
+ if (process.env.ORCA_WORKTREE_ID && (process.env.ORCA_TERMINAL_HANDLE || process.env.ORCA_PANE_KEY)) return "orca"
170
173
  if (process.env.CMUX_SOCKET_PATH) return "cmux"
171
174
  if (process.env.TMUX) return "tmux"
172
175
  if (process.env.TERM_PROGRAM === "iTerm.app") return "iterm"
@@ -174,6 +177,7 @@ function detectTerminalBackend(): TerminalBackend {
174
177
  if (process.env.GHOSTTY_RESOURCES_DIR || normalizeModelText(process.env.TERM_PROGRAM ?? "").includes("ghostty")) {
175
178
  return "ghostty"
176
179
  }
180
+ if (process.env.TERM_PROGRAM === "WarpTerminal") return "warp"
177
181
  return "unknown"
178
182
  }
179
183
 
@@ -637,6 +641,31 @@ function buildBranchCommand(forkFile: string): string {
637
641
  return `pi --session ${shellQuote(forkFile)}`
638
642
  }
639
643
 
644
+ function resolveOrcaCommand(): string {
645
+ return normalizeTerminalFlag(process.env.ORCA_CLI_COMMAND)
646
+ ?? (process.env.ORCA_DEV_REPO_ROOT ? "orca-dev" : "orca")
647
+ }
648
+
649
+ function parseOrcaTerminalHandle(output: string, paneKey?: string, terminalHandle?: string): string | undefined {
650
+ try {
651
+ const parsed = JSON.parse(output) as {
652
+ result?: {
653
+ terminals?: Array<{ handle?: unknown; tabId?: unknown; leafId?: unknown }>
654
+ }
655
+ }
656
+ const terminal = parsed.result?.terminals?.find((candidate) => terminalHandle
657
+ ? candidate.handle === terminalHandle
658
+ : (
659
+ typeof candidate.tabId === "string"
660
+ && typeof candidate.leafId === "string"
661
+ && `${candidate.tabId}:${candidate.leafId}` === paneKey
662
+ ))
663
+ return typeof terminal?.handle === "string" && terminal.handle ? terminal.handle : undefined
664
+ } catch {
665
+ return undefined
666
+ }
667
+ }
668
+
640
669
  function extractCmuxSurface(output: string): string | undefined {
641
670
  return output.match(/surface:\d+/)?.[0]
642
671
  }
@@ -731,6 +760,62 @@ function updateRotatingState(
731
760
  upsertLayoutState({ backend, workspaceKey, policy, queue })
732
761
  }
733
762
 
763
+ async function openInOrca(
764
+ pi: ExtensionAPI,
765
+ forkFile: string,
766
+ config: ExtensionConfig,
767
+ cwd: string,
768
+ ): Promise<{ opened: boolean; error?: string }> {
769
+ const worktreeId = process.env.ORCA_WORKTREE_ID
770
+ const paneKey = process.env.ORCA_PANE_KEY
771
+ const terminalHandle = process.env.ORCA_TERMINAL_HANDLE
772
+ if (!worktreeId || (!paneKey && !terminalHandle)) return { opened: false }
773
+ if (config.launchMode !== "split") {
774
+ return { opened: false, error: "Orca branch launch requires launchMode 'split'" }
775
+ }
776
+
777
+ const resolvedSplitDirection = resolveSupportedSplitDirection("orca", config.splitDirectionPreferences)
778
+ if (!resolvedSplitDirection) {
779
+ return { opened: false, error: `Split direction '${config.splitDirection}' is not supported in Orca` }
780
+ }
781
+
782
+ const orcaCommand = resolveOrcaCommand()
783
+ const listResult = await pi.exec(orcaCommand, ["terminal", "list", "--worktree", `id:${worktreeId}`, "--json"])
784
+ if (listResult.code !== 0) {
785
+ return { opened: false, error: listResult.stderr || listResult.stdout || "orca terminal list failed" }
786
+ }
787
+
788
+ const currentHandle = parseOrcaTerminalHandle(`${listResult.stdout || listResult.stderr}`, paneKey, terminalHandle)
789
+ if (!currentHandle) {
790
+ return { opened: false, error: `Could not resolve Orca terminal '${terminalHandle || paneKey}' in the current worktree` }
791
+ }
792
+
793
+ const direction = resolvedSplitDirection === "right" ? "vertical" : "horizontal"
794
+ const splitResult = await pi.exec(orcaCommand, [
795
+ "terminal",
796
+ "split",
797
+ "--terminal",
798
+ currentHandle,
799
+ "--direction",
800
+ direction,
801
+ "--command",
802
+ `cd ${shellQuote(cwd)} && ${buildBranchCommand(forkFile)}`,
803
+ "--json",
804
+ ])
805
+ if (splitResult.code !== 0) {
806
+ return { opened: false, error: splitResult.stderr || splitResult.stdout || "orca terminal split failed" }
807
+ }
808
+
809
+ if (config.preserveFocus) {
810
+ const focusResult = await pi.exec(orcaCommand, ["terminal", "switch", "--terminal", currentHandle, "--json"])
811
+ if (focusResult.code !== 0) {
812
+ return { opened: false, error: focusResult.stderr || focusResult.stdout || "orca terminal switch failed" }
813
+ }
814
+ }
815
+
816
+ return { opened: true }
817
+ }
818
+
734
819
  async function openInCmux(
735
820
  pi: ExtensionAPI,
736
821
  forkFile: string,
@@ -1024,6 +1109,61 @@ function openInGhostty(ctx: ExtensionCommandContext, forkFile: string): void {
1024
1109
  })
1025
1110
  }
1026
1111
 
1112
+ async function openInWarp(
1113
+ pi: ExtensionAPI,
1114
+ forkFile: string,
1115
+ config: ExtensionConfig,
1116
+ cwd: string,
1117
+ ): Promise<{ opened: boolean; error?: string }> {
1118
+ if (config.launchMode !== "tab") {
1119
+ return { opened: false, error: "Warp cannot split an existing pane; set launchMode to 'tab' (or use tmux inside Warp)" }
1120
+ }
1121
+ if (process.platform !== "darwin" && process.platform !== "linux") {
1122
+ return { opened: false, error: "Warp branch launch is supported on macOS and Linux only" }
1123
+ }
1124
+
1125
+ // Ordinary new_tab URIs cannot run commands. A unique Tab Config avoids
1126
+ // concurrent launches racing over a shared file that Warp reads asynchronously.
1127
+ const configDir = process.platform === "darwin"
1128
+ ? path.join(os.homedir(), ".warp", "tab_configs")
1129
+ : path.join(process.env.XDG_DATA_HOME || path.join(os.homedir(), ".local", "share"), "warp-terminal", "tab_configs")
1130
+ const name = `tmp_pi_branch_${path.basename(forkFile, ".jsonl").replace(/[^a-zA-Z0-9_-]/g, "_")}`
1131
+ const configFile = path.join(configDir, `${name}.toml`)
1132
+ // Remove only once Warp has read the config and started its shell, not when
1133
+ // the URI opener returns. No startup command depends on the file afterward.
1134
+ const command = `rm -f -- ${shellQuote(configFile)}; ${buildBranchCommand(forkFile)}`
1135
+ // Warp substitutes this reserved variable in `directory` and `commands` even when a
1136
+ // config declares no params, so a path containing it cannot be passed through literally.
1137
+ const reservedTemplate = "{{autogenerated_branch_name}}"
1138
+ if (cwd.includes(reservedTemplate) || command.includes(reservedTemplate)) {
1139
+ return { opened: false, error: `Warp substitutes ${reservedTemplate} in Tab Configs; cannot launch from a path containing it` }
1140
+ }
1141
+ // A JSON string literal is a valid TOML basic string once raw DEL (U+007F) is escaped.
1142
+ const tomlString = (value: string) => JSON.stringify(value).replaceAll("\x7f", "\\u007f")
1143
+ fs.mkdirSync(configDir, { recursive: true, mode: 0o700 })
1144
+ fs.writeFileSync(configFile, [
1145
+ 'name = "Pi branch"',
1146
+ "",
1147
+ "[[panes]]",
1148
+ 'id = "main"',
1149
+ 'type = "terminal"',
1150
+ `directory = ${tomlString(cwd)}`,
1151
+ `commands = [${tomlString(command)}]`,
1152
+ "",
1153
+ ].join("\n"), { flag: "wx", mode: 0o600 })
1154
+
1155
+ let opened = false
1156
+ try {
1157
+ const result = await pi.exec(process.platform === "darwin" ? "open" : "xdg-open", [
1158
+ `warp://tab_config/${encodeURIComponent(name)}`,
1159
+ ])
1160
+ opened = result.code === 0
1161
+ return { opened, error: opened ? undefined : result.stderr || result.stdout || "Warp URI launch failed" }
1162
+ } finally {
1163
+ if (!opened) fs.rmSync(configFile, { force: true })
1164
+ }
1165
+ }
1166
+
1027
1167
  async function openForkInTerminal(pi: ExtensionAPI, ctx: ExtensionCommandContext, forkFile: string): Promise<void> {
1028
1168
  const terminalFlag = normalizeTerminalFlag(pi.getFlag(TERMINAL_FLAG))
1029
1169
  if (terminalFlag) {
@@ -1037,6 +1177,12 @@ async function openForkInTerminal(pi: ExtensionAPI, ctx: ExtensionCommandContext
1037
1177
  const config = loadConfig()
1038
1178
  const activeBackend = detectTerminalBackend()
1039
1179
 
1180
+ if (activeBackend === "orca") {
1181
+ const orcaAttempt = await openInOrca(pi, forkFile, config, ctx.cwd)
1182
+ if (!orcaAttempt.opened) throw new Error(orcaAttempt.error || "Orca launch failed")
1183
+ return
1184
+ }
1185
+
1040
1186
  if (activeBackend === "cmux") {
1041
1187
  const cmuxAttempt = await openInCmux(pi, forkFile, config)
1042
1188
  if (!cmuxAttempt.opened) throw new Error(cmuxAttempt.error || "cmux launch failed")
@@ -1069,6 +1215,12 @@ async function openForkInTerminal(pi: ExtensionAPI, ctx: ExtensionCommandContext
1069
1215
  return
1070
1216
  }
1071
1217
 
1218
+ if (activeBackend === "warp") {
1219
+ const warpAttempt = await openInWarp(pi, forkFile, config, ctx.cwd)
1220
+ if (!warpAttempt.opened) throw new Error(warpAttempt.error || "Warp launch failed")
1221
+ return
1222
+ }
1223
+
1072
1224
  if (config.launchMode === "split") {
1073
1225
  throw new Error("Split launch requires an active cmux, tmux, or iTerm2 session")
1074
1226
  }
@@ -1166,6 +1318,40 @@ function resolveBranchModel(
1166
1318
  }
1167
1319
  }
1168
1320
 
1321
+ function writeBranchSnapshot(
1322
+ session: ExtensionContext["sessionManager"],
1323
+ parentSession: string,
1324
+ branch: SessionEntry[],
1325
+ ): string {
1326
+ const child = SessionManager.create(session.getCwd(), path.dirname(parentSession), { parentSession })
1327
+ const file = child.getSessionFile()
1328
+ const header = child.getHeader()
1329
+ if (!file || !header) throw new Error("Failed to create branched session")
1330
+
1331
+ // Labels are session-wide in Pi. Carry over the latest update (including a
1332
+ // clear) for each retained target if that update lies outside the active path.
1333
+ const branchIds = new Set(branch.map((entry) => entry.id))
1334
+ const latestLabels = new Map<string, Extract<SessionEntry, { type: "label" }>>()
1335
+ for (const entry of session.getEntries()) {
1336
+ if (entry.type === "label" && branchIds.has(entry.targetId)) {
1337
+ latestLabels.set(entry.targetId, entry)
1338
+ }
1339
+ }
1340
+ const entries = [...branch]
1341
+ let parentId = branch[branch.length - 1].id
1342
+ for (const label of latestLabels.values()) {
1343
+ if (branchIds.has(label.id)) continue
1344
+ entries.push({ ...label, parentId })
1345
+ parentId = label.id
1346
+ }
1347
+
1348
+ fs.writeFileSync(file, [header, ...entries].map((entry) => JSON.stringify(entry) + "\n").join(""), {
1349
+ flag: "wx",
1350
+ mode: 0o600,
1351
+ })
1352
+ return file
1353
+ }
1354
+
1169
1355
  export default function (pi: ExtensionAPI) {
1170
1356
  pi.registerFlag(TERMINAL_FLAG, {
1171
1357
  description: "Command to open a new terminal. Use {session} placeholder for the session file path.",
@@ -1191,26 +1377,22 @@ export default function (pi: ExtensionAPI) {
1191
1377
  pi.registerCommand("branch", {
1192
1378
  description: "Fork current session into a new terminal tab or split pane, optionally queueing --model <query> and a draft message",
1193
1379
  handler: async (args, ctx) => {
1194
- await ctx.waitForIdle()
1195
-
1196
1380
  const sessionFile = ctx.sessionManager.getSessionFile()
1197
1381
  if (!sessionFile) {
1198
1382
  if (ctx.hasUI) ctx.ui.notify("Session is not persisted. Restart without --no-session.", "error")
1199
1383
  return
1200
1384
  }
1201
1385
 
1202
- const leafId = ctx.sessionManager.getLeafId()
1203
- if (!leafId) {
1386
+ // Snapshot the live path before the first await. The active leaf need not
1387
+ // exist in the on-disk file, and must not be replaced by a different leaf.
1388
+ const branch = ctx.sessionManager.getBranch()
1389
+ if (!branch.some((entry) => entry.type === "message" && (entry.message.role === "user" || entry.message.role === "assistant"))) {
1204
1390
  if (ctx.hasUI) ctx.ui.notify("No messages yet. Nothing to branch.", "error")
1205
1391
  return
1206
1392
  }
1207
1393
 
1208
1394
  const { modelQuery, message } = parseBranchArgs(args)
1209
- const forkManager = SessionManager.open(sessionFile)
1210
- const forkFile = forkManager.createBranchedSession(leafId)
1211
- if (!forkFile) {
1212
- throw new Error("Failed to create branched session")
1213
- }
1395
+ const forkFile = writeBranchSnapshot(ctx.sessionManager, sessionFile, branch)
1214
1396
 
1215
1397
  const trimmedMessage = message.trim()
1216
1398
  const hasLaunchCustomization = Boolean(modelQuery || trimmedMessage)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-branch-out",
3
- "version": "0.1.9",
3
+ "version": "0.1.11",
4
4
  "description": "Fork the current Pi session into a split terminal pane or new tab with rotating layout policies, and with optional model and message queuing, and support for cmux, tmux, iTerm2, Terminal.app, Ghostty, Warp, and Orca.",
5
5
  "keywords": ["pi-package", "pi", "pi-coding-agent"],
6
6
  "license": "MIT",
@@ -20,7 +20,8 @@
20
20
  "@earendil-works/pi-coding-agent": ">=0.74.0"
21
21
  },
22
22
  "scripts": {
23
- "prepack": "node ../../scripts/pi-package-prepack.mjs"
23
+ "prepack": "node ../../scripts/pi-package-prepack.mjs",
24
+ "test:package": "node --test test/package-smoke.mjs"
24
25
  },
25
26
  "files": ["extensions/**", "README.md", "LICENSE", "THIRD-PARTY-NOTICES.md", "package.json"],
26
27
  "dot314Prepack": {