@termwire/cli 0.1.2 → 0.2.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,30 @@
1
1
  # @termwire/cli
2
2
 
3
+ ## 0.2.1
4
+
5
+ ### Patch Changes
6
+
7
+ - eec1451: Termwire new sessions now set the outer terminal title from the tmux session name, and the tmux adapter exposes built-in layout selection.
8
+ - Updated dependencies [eec1451]
9
+ - @termwire/tmux@0.2.1
10
+ - @termwire/nvim@0.2.1
11
+
12
+ ## 0.2.0
13
+
14
+ ### Minor Changes
15
+
16
+ - 6f485f3: Add configurable tmux window and pane layouts for new workspaces.
17
+
18
+ Support optional global and project JSONC configuration, strict Zod validation,
19
+ explicit editor pane selection, and deferred pane command startup with complete
20
+ workspace environment variables.
21
+
22
+ ### Patch Changes
23
+
24
+ - Updated dependencies [6f485f3]
25
+ - @termwire/tmux@0.2.0
26
+ - @termwire/nvim@0.2.0
27
+
3
28
  ## 0.1.2
4
29
 
5
30
  ### Patch Changes
package/README.md CHANGED
@@ -8,9 +8,10 @@ termwire --help
8
8
  termwire up dev
9
9
  ```
10
10
 
11
- The project's main entry point — the `termwire` command. Orchestrates the
12
- other packages. Fully **stateless**: no config files, no state files —
13
- workspace identity lives in environment variables set by `termwire up <name>`.
11
+ The project's main entry point — the `termwire` command. It orchestrates the
12
+ other packages. Runtime workspace identity is stateless and lives in the
13
+ environment variables set by `termwire up <name>`; layout configuration is
14
+ optional JSONC, not persistent workspace state.
14
15
 
15
16
  ## Why it exists
16
17
 
@@ -33,22 +34,287 @@ the explicit `termwire_open({ path, line? })` OpenCode plugin tool.
33
34
  selects the directory key; otherwise `<name>` does. `--branch` selects the exact Git branch when
34
35
  present; otherwise the worktree directory key is also the branch name. Slashes are preserved in
35
36
  Git branch names and replaced only in filesystem-safe worktree directory names. Without `-w`, Git
36
- is changed only when `--branch` is present. Existing tmux sessions attach without Git mutations.
37
+ is changed only when `--branch` is present. Existing tmux sessions attach without Git mutations or
38
+ rereading/reconciling configuration.
37
39
 
38
- ## How it works
40
+ ## Layout configuration
39
41
 
40
- - `up <name>` creates `editor` (`nvim --listen <socket>`) and free `shell`
41
- windows. Final processes receive `TERMWIRE_SESSION`, `TERMWIRE_SOCKET`,
42
- and `TERMWIRE_EDITOR_PANE`.
43
- - OpenCode is not started automatically. Users may start it in the shell and
44
- reshape the workspace with tmux.
45
- - Existing sessions attach immediately without branch or worktree mutation.
46
- - There are no config files or persistent state.
42
+ TermWire discovers optional JSONC files in this order:
43
+
44
+ 1. Global: `$XDG_CONFIG_HOME/termwire/config.jsonc`, or
45
+ `~/.config/termwire/config.jsonc` when `XDG_CONFIG_HOME` is unset.
46
+ 2. Project: `<resolved-workspace-git-root>/.termwire.jsonc`. For `up -w`, this
47
+ is the resolved target worktree's file, not the invoking checkout's file.
48
+
49
+ Both present files are validated. Project `windows` fully replace global
50
+ `windows`; they are never merged. A version-only project file falls through to
51
+ global windows, and a version-only global file falls through to the exact
52
+ default layout:
53
+
54
+ ```json
55
+ {
56
+ "windows": [
57
+ { "name": "editor", "panes": [{ "id": "editor", "role": "editor" }] },
58
+ { "name": "shell", "panes": [{ "id": "shell" }] }
59
+ ]
60
+ }
61
+ ```
62
+
63
+ When neither source provides `windows`, that same editor-then-shell two-window
64
+ default is used.
65
+
66
+ ### Schema
67
+
68
+ Each configuration root is an object with required numeric `"version": 1`,
69
+ optional nonempty-string `"$schema"` for future compatibility, and optional
70
+ `windows`; unknown keys are rejected at every level. `windows`, when provided,
71
+ is a nonempty array of uniquely named window objects. Each window has only
72
+ `name` and a nonempty `panes` array. Pane ids are nonempty and unique within
73
+ their window.
74
+
75
+ A pane may contain only `id`, `role`, `command`, `splitFrom`, `direction`, and
76
+ `sizePercent`:
77
+
78
+ - `role`, when present, is only `"editor"`. Exactly one editor exists across
79
+ the effective layout, and it cannot have a `command`.
80
+ - `command`, when present, is a nonempty argv array of nonempty strings. Shell
81
+ command strings are not supported.
82
+ - The first pane of a window has no split fields. Every later pane must name an
83
+ earlier pane in the same window with `splitFrom` and set `direction` to
84
+ `"horizontal"` or `"vertical"`. An optional `sizePercent` is an integer from
85
+ 1 through 99.
86
+
87
+ This release provides no official JSON Schema file or URL, generation command,
88
+ publishing, autocomplete, or editor integration. `$schema` is accepted for
89
+ future compatibility only; it does not point to a TermWire-provided artifact.
90
+
91
+ Panes are created in declaration order. This valid multi-window example has one
92
+ editor and demonstrates argv commands and ordered splits:
93
+
94
+ ```jsonc
95
+ // ~/.config/termwire/config.jsonc or .termwire.jsonc
96
+ {
97
+ "version": 1,
98
+ "windows": [
99
+ {
100
+ "name": "editor",
101
+ "panes": [
102
+ { "id": "editor", "role": "editor" },
103
+ {
104
+ "id": "watch",
105
+ "splitFrom": "editor",
106
+ "direction": "vertical",
107
+ "sizePercent": 35,
108
+ "command": ["bun", "run", "dev"],
109
+ },
110
+ ],
111
+ },
112
+ {
113
+ "name": "shell",
114
+ "panes": [
115
+ { "id": "shell", "command": ["zsh", "-l"] },
116
+ {
117
+ "id": "tests",
118
+ "splitFrom": "shell",
119
+ "direction": "horizontal",
120
+ "sizePercent": 40,
121
+ "command": ["bun", "test"],
122
+ },
123
+ ],
124
+ },
125
+ ],
126
+ }
127
+ ```
128
+
129
+ JSONC comments and trailing commas are accepted. There is no interpolation,
130
+ custom pane cwd, custom pane environment, shell-string command syntax, or
131
+ configuration/state persistence beyond reading these optional files for a new
132
+ session.
133
+
134
+ ### Layout cookbook
135
+
136
+ #### Default: editor and shell
137
+
138
+ Use two simple windows when you want the editor and an ordinary shell kept separate.
139
+
140
+ ```text
141
+ [editor] [shell]
142
+ ┌──────────────────┐ ┌──────────────────┐
143
+ │ editor │ │ shell │
144
+ └──────────────────┘ └──────────────────┘
145
+ ```
146
+
147
+ ```jsonc
148
+ {
149
+ "version": 1,
150
+ "windows": [
151
+ {
152
+ "name": "editor",
153
+ "panes": [{ "id": "editor", "role": "editor" }],
154
+ },
155
+ {
156
+ "name": "shell",
157
+ "panes": [{ "id": "shell" }],
158
+ },
159
+ ],
160
+ }
161
+ ```
162
+
163
+ #### Three-window workflow
164
+
165
+ Use independent windows when you want to move between editing, AI work, and a shell.
166
+ The `ai` window is an ordinary shell and does not start a command automatically.
167
+
168
+ ```text
169
+ [editor] [ai] [shell]
170
+ ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐
171
+ │ editor │ │ ai (shell) │ │ shell │
172
+ └──────────────────┘ └──────────────────┘ └──────────────────┘
173
+ ```
174
+
175
+ ```jsonc
176
+ {
177
+ "version": 1,
178
+ "windows": [
179
+ {
180
+ "name": "editor",
181
+ "panes": [{ "id": "editor", "role": "editor" }],
182
+ },
183
+ {
184
+ "name": "ai",
185
+ "panes": [{ "id": "ai" }],
186
+ },
187
+ {
188
+ "name": "shell",
189
+ "panes": [{ "id": "shell" }],
190
+ },
191
+ ],
192
+ }
193
+ ```
194
+
195
+ #### Focused coding
196
+
197
+ Keep editing, OpenCode, and watched tests visible together in one `work` window.
198
+
199
+ ```text
200
+ [work]
201
+ ┌───────────────────────────┬──────────────────┐
202
+ │ editor │ ai │
203
+ │ │ opencode │
204
+ │ │ │
205
+ │ ├──────────────────┤
206
+ │ │ tests (new: 40%) │
207
+ │ │ bun test --watch │
208
+ └───────────────────────────┴──────────────────┘
209
+ right side: 40%
210
+ ```
211
+
212
+ ```jsonc
213
+ {
214
+ "version": 1,
215
+ "windows": [
216
+ {
217
+ "name": "work",
218
+ "panes": [
219
+ { "id": "editor", "role": "editor" },
220
+ {
221
+ "id": "ai",
222
+ "splitFrom": "editor",
223
+ "direction": "horizontal",
224
+ "sizePercent": 40,
225
+ "command": ["opencode"],
226
+ },
227
+ {
228
+ "id": "tests",
229
+ "splitFrom": "ai",
230
+ "direction": "vertical",
231
+ "sizePercent": 40,
232
+ "command": ["bun", "test", "--watch"],
233
+ },
234
+ ],
235
+ },
236
+ ],
237
+ }
238
+ ```
239
+
240
+ #### Full-stack
241
+
242
+ Separate code, the development server, and a spare shell while keeping watched tests under the
243
+ editor.
244
+
245
+ ```text
246
+ [code] [server] [shell]
247
+ ┌──────────────────┐ ┌────────────────────┐ ┌──────────────────┐
248
+ │ editor │ │ server │ │ shell │
249
+ │ │ │ bun run dev │ │ │
250
+ │ │ │ │ │ │
251
+ │ │ │ │ │ │
252
+ │ │ │ │ │ │
253
+ ├──────────────────┤ │ │ │ │
254
+ │ tests (new: 35%) │ │ │ │ │
255
+ │ bun test --watch │ │ │ │ │
256
+ │ │ │ │ │ │
257
+ └──────────────────┘ └────────────────────┘ └──────────────────┘
258
+ ```
259
+
260
+ ```jsonc
261
+ {
262
+ "version": 1,
263
+ "windows": [
264
+ {
265
+ "name": "code",
266
+ "panes": [
267
+ { "id": "editor", "role": "editor" },
268
+ {
269
+ "id": "tests",
270
+ "splitFrom": "editor",
271
+ "direction": "vertical",
272
+ "sizePercent": 35,
273
+ "command": ["bun", "test", "--watch"],
274
+ },
275
+ ],
276
+ },
277
+ {
278
+ "name": "server",
279
+ "panes": [{ "id": "server", "command": ["bun", "run", "dev"] }],
280
+ },
281
+ {
282
+ "name": "shell",
283
+ "panes": [{ "id": "shell" }],
284
+ },
285
+ ],
286
+ }
287
+ ```
288
+
289
+ `horizontal` means left/right, `vertical` means top/bottom, and `sizePercent` applies to the new
290
+ pane. Layouts affect only newly created sessions; attaches are unchanged. The OpenCode and Bun
291
+ commands are replaceable examples.
292
+
293
+ ### Errors and session behavior
294
+
295
+ JSONC parse errors identify the source and one-based line and column. Schema
296
+ errors identify the source and JSON path; unreadable existing files retain their
297
+ original error as the cause. After workspace/worktree resolution, configuration
298
+ is loaded and validated before socket or tmux session side effects. Once a new
299
+ session exists, layout or attach failure triggers best-effort session cleanup
300
+ while preserving the original failure.
301
+
302
+ ## Runtime behavior
303
+
304
+ - `up <name>` starts the editor as `nvim --listen <socket>` and uses a pane's
305
+ argv command, or tmux's default shell when an ordinary pane has no command.
306
+ Final processes receive `TERMWIRE_SESSION`, `TERMWIRE_SOCKET`, and
307
+ `TERMWIRE_EDITOR_PANE`.
308
+ - The default layout does not start OpenCode automatically. Users may start it manually in an
309
+ ordinary shell pane, or configure `["opencode"]` as a pane command. They may also reshape the
310
+ workspace with tmux after creation.
47
311
  - The CLI has no shell-facing `open` command and does not need to be in `PATH`
48
312
  for the plugin: the plugin composes the nvim and tmux adapters directly.
49
313
 
50
314
  ## Dependencies
51
315
 
52
- Commander 15 is the CLI runtime dependency for parsing `up`. `@termwire/tmux`
53
- and `@termwire/nvim` are thin adapters over their binaries; the CLI owns
54
- workspace policy and orchestration.
316
+ Commander 15 parses `up`; `jsonc-parser` handles JSONC parsing and diagnostics;
317
+ Zod 4 provides strict structural config validation. All three are direct runtime
318
+ dependencies.
319
+ `@termwire/tmux` and `@termwire/nvim` are thin adapters over their binaries;
320
+ the CLI owns workspace policy and orchestration.
@@ -0,0 +1,11 @@
1
+ import type { LoadedConfig } from "./config-types";
2
+ export interface ConfigLoaderDependencies {
3
+ env: Record<string, string | undefined>;
4
+ homedir: () => string;
5
+ exists: (path: string) => Promise<boolean>;
6
+ readFile: (path: string, encoding: "utf8") => Promise<string>;
7
+ }
8
+ export declare function createConfigLoader(dependencies: ConfigLoaderDependencies): {
9
+ loadGlobal(): Promise<LoadedConfig | undefined>;
10
+ loadProject(gitRoot: string): Promise<LoadedConfig | undefined>;
11
+ };
@@ -0,0 +1,62 @@
1
+ import { isAbsolute, join } from "node:path";
2
+ import { parse } from "jsonc-parser";
3
+ export function createConfigLoader(dependencies) {
4
+ return {
5
+ async loadGlobal() {
6
+ return loadFile(dependencies, globalConfigPath(dependencies));
7
+ },
8
+ async loadProject(gitRoot) {
9
+ return loadFile(dependencies, join(gitRoot, ".termwire.jsonc"));
10
+ },
11
+ };
12
+ }
13
+ function globalConfigPath(dependencies) {
14
+ const xdgConfigHome = dependencies.env.XDG_CONFIG_HOME;
15
+ const configHome = xdgConfigHome && isAbsolute(xdgConfigHome)
16
+ ? xdgConfigHome
17
+ : join(dependencies.homedir(), ".config");
18
+ return join(configHome, "termwire", "config.jsonc");
19
+ }
20
+ function lineColumn(text, offset) {
21
+ let line = 1;
22
+ let column = 1;
23
+ for (let index = 0; index < offset; index += 1) {
24
+ if (text[index] === "\r") {
25
+ if (text[index + 1] === "\n" && index + 1 < offset) {
26
+ index += 1;
27
+ }
28
+ line += 1;
29
+ column = 1;
30
+ }
31
+ else if (text[index] === "\n") {
32
+ line += 1;
33
+ column = 1;
34
+ }
35
+ else {
36
+ column += 1;
37
+ }
38
+ }
39
+ return { line, column };
40
+ }
41
+ async function loadFile(dependencies, path) {
42
+ if (!(await dependencies.exists(path))) {
43
+ return undefined;
44
+ }
45
+ let text;
46
+ try {
47
+ text = await dependencies.readFile(path, "utf8");
48
+ }
49
+ catch (error) {
50
+ if (error.code === "ENOENT") {
51
+ return undefined;
52
+ }
53
+ throw new Error(`Failed to read config ${path}`, { cause: error });
54
+ }
55
+ const errors = [];
56
+ const value = parse(text, errors, { allowTrailingComma: true, disallowComments: false });
57
+ if (errors.length > 0) {
58
+ const { line, column } = lineColumn(text, errors[0].offset);
59
+ throw new Error(`${path}:${line}:${column}: ${errors[0].error}`);
60
+ }
61
+ return { source: path, value };
62
+ }
@@ -0,0 +1,50 @@
1
+ import { z } from "zod";
2
+ export declare const paneSchema: z.ZodObject<{
3
+ id: z.ZodString;
4
+ role: z.ZodOptional<z.ZodLiteral<"editor">>;
5
+ command: z.ZodOptional<z.ZodArray<z.ZodString>>;
6
+ splitFrom: z.ZodOptional<z.ZodString>;
7
+ direction: z.ZodOptional<z.ZodEnum<{
8
+ horizontal: "horizontal";
9
+ vertical: "vertical";
10
+ }>>;
11
+ sizePercent: z.ZodOptional<z.ZodNumber>;
12
+ }, z.core.$strict>;
13
+ export declare const windowSchema: z.ZodObject<{
14
+ name: z.ZodString;
15
+ panes: z.ZodArray<z.ZodObject<{
16
+ id: z.ZodString;
17
+ role: z.ZodOptional<z.ZodLiteral<"editor">>;
18
+ command: z.ZodOptional<z.ZodArray<z.ZodString>>;
19
+ splitFrom: z.ZodOptional<z.ZodString>;
20
+ direction: z.ZodOptional<z.ZodEnum<{
21
+ horizontal: "horizontal";
22
+ vertical: "vertical";
23
+ }>>;
24
+ sizePercent: z.ZodOptional<z.ZodNumber>;
25
+ }, z.core.$strict>>;
26
+ }, z.core.$strict>;
27
+ export declare const configV1Schema: z.ZodObject<{
28
+ version: z.ZodLiteral<1>;
29
+ $schema: z.ZodOptional<z.ZodString>;
30
+ windows: z.ZodOptional<z.ZodArray<z.ZodObject<{
31
+ name: z.ZodString;
32
+ panes: z.ZodArray<z.ZodObject<{
33
+ id: z.ZodString;
34
+ role: z.ZodOptional<z.ZodLiteral<"editor">>;
35
+ command: z.ZodOptional<z.ZodArray<z.ZodString>>;
36
+ splitFrom: z.ZodOptional<z.ZodString>;
37
+ direction: z.ZodOptional<z.ZodEnum<{
38
+ horizontal: "horizontal";
39
+ vertical: "vertical";
40
+ }>>;
41
+ sizePercent: z.ZodOptional<z.ZodNumber>;
42
+ }, z.core.$strict>>;
43
+ }, z.core.$strict>>>;
44
+ }, z.core.$strict>;
45
+ export type PaneConfig = z.infer<typeof paneSchema>;
46
+ export type WindowConfig = z.infer<typeof windowSchema>;
47
+ export type ConfigV1 = z.infer<typeof configV1Schema>;
48
+ export type LayoutConfig = {
49
+ windows: NonNullable<ConfigV1["windows"]>;
50
+ };
@@ -0,0 +1,18 @@
1
+ import { z } from "zod";
2
+ export const paneSchema = z.strictObject({
3
+ id: z.string().min(1),
4
+ role: z.literal("editor").optional(),
5
+ command: z.array(z.string().min(1)).min(1).optional(),
6
+ splitFrom: z.string().optional(),
7
+ direction: z.enum(["horizontal", "vertical"]).optional(),
8
+ sizePercent: z.number().int().min(1).max(99).optional(),
9
+ });
10
+ export const windowSchema = z.strictObject({
11
+ name: z.string().min(1),
12
+ panes: z.array(paneSchema).min(1),
13
+ });
14
+ export const configV1Schema = z.strictObject({
15
+ version: z.literal(1),
16
+ $schema: z.string().min(1).optional(),
17
+ windows: z.array(windowSchema).min(1).optional(),
18
+ });
@@ -0,0 +1,4 @@
1
+ export interface LoadedConfig {
2
+ source: string;
3
+ value: unknown;
4
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,3 @@
1
+ import { type LayoutConfig } from "./config-schema";
2
+ import type { LoadedConfig } from "./config-types";
3
+ export declare function resolveLayout(globalConfig?: LoadedConfig, projectConfig?: LoadedConfig): LayoutConfig;
@@ -0,0 +1,117 @@
1
+ import { configV1Schema, } from "./config-schema";
2
+ const defaultLayout = {
3
+ windows: [
4
+ { name: "editor", panes: [{ id: "editor", role: "editor" }] },
5
+ { name: "shell", panes: [{ id: "shell" }] },
6
+ ],
7
+ };
8
+ export function resolveLayout(globalConfig, projectConfig) {
9
+ const global = globalConfig ? validateConfig(globalConfig) : undefined;
10
+ const project = projectConfig ? validateConfig(projectConfig) : undefined;
11
+ const globalWindows = global?.windows;
12
+ const projectWindows = project?.windows;
13
+ return copyLayout(projectWindows ?? globalWindows ?? defaultLayout.windows);
14
+ }
15
+ function expectUnique(source, path, values, value) {
16
+ if (values.has(value)) {
17
+ throw new Error(`${source}: ${path}: must be unique`);
18
+ }
19
+ values.add(value);
20
+ }
21
+ function copyLayout(windows) {
22
+ return {
23
+ windows: windows.map((window) => ({
24
+ ...window,
25
+ panes: window.panes.map((pane) => pane.command === undefined ? { ...pane } : { ...pane, command: [...pane.command] }),
26
+ })),
27
+ };
28
+ }
29
+ function validateWindow(source, path, value, names, editors) {
30
+ expectUnique(source, `${path}.name`, names, value.name);
31
+ validatePanes(source, path, value.panes, editors);
32
+ }
33
+ function validatePanes(source, windowPath, value, editors) {
34
+ const ids = new Set();
35
+ const earlierIds = new Set();
36
+ for (let paneIndex = 0; paneIndex < value.length; paneIndex += 1) {
37
+ const panePath = `${windowPath}.panes[${paneIndex}]`;
38
+ const id = validatePane(source, panePath, value[paneIndex], paneIndex, ids, earlierIds, editors);
39
+ earlierIds.add(id);
40
+ }
41
+ }
42
+ function validatePane(source, path, value, index, ids, earlierIds, editors) {
43
+ expectUnique(source, `${path}.id`, ids, value.id);
44
+ validateEditor(source, path, value, editors);
45
+ validateSplitRules(source, path, value, index, earlierIds);
46
+ return value.id;
47
+ }
48
+ function validateEditor(source, path, pane, editors) {
49
+ if (pane.role === "editor") {
50
+ if (pane.command !== undefined) {
51
+ throw new Error(`${source}: ${path}.command: is not allowed for the editor`);
52
+ }
53
+ editors.count += 1;
54
+ if (editors.count > 1) {
55
+ throw new Error(`${source}: ${path}.role: exactly one editor is required`);
56
+ }
57
+ }
58
+ }
59
+ function validateSplitRules(source, path, pane, index, earlierIds) {
60
+ if (index === 0) {
61
+ for (const key of ["splitFrom", "direction", "sizePercent"]) {
62
+ if (pane[key] !== undefined) {
63
+ throw new Error(`${source}: ${path}.${key}: is not allowed on the first pane`);
64
+ }
65
+ }
66
+ }
67
+ else {
68
+ if (pane.splitFrom === undefined || !earlierIds.has(pane.splitFrom)) {
69
+ throw new Error(`${source}: ${path}.splitFrom: must reference an earlier pane`);
70
+ }
71
+ if (pane.direction === undefined) {
72
+ throw new Error(`${source}: ${path}.direction: must be horizontal or vertical`);
73
+ }
74
+ }
75
+ }
76
+ function expectSingleEditor(source, editors) {
77
+ if (editors.count !== 1) {
78
+ throw new Error(`${source}: $.windows: exactly one editor is required`);
79
+ }
80
+ }
81
+ function validateWindows(source, value) {
82
+ const names = new Set();
83
+ const editors = { count: 0 };
84
+ for (let index = 0; index < value.length; index += 1) {
85
+ validateWindow(source, `$.windows[${index}]`, value[index], names, editors);
86
+ }
87
+ expectSingleEditor(source, editors);
88
+ }
89
+ function validateConfig(config) {
90
+ const result = configV1Schema.safeParse(config.value);
91
+ if (!result.success) {
92
+ throw configError(config.source, result.error.issues[0]);
93
+ }
94
+ if (result.data.windows !== undefined) {
95
+ validateWindows(config.source, result.data.windows);
96
+ }
97
+ return result.data;
98
+ }
99
+ function configError(source, issue) {
100
+ const path = issue.code === "unrecognized_keys" ? [...issue.path, issue.keys[0]] : issue.path;
101
+ return new Error(`${source}: ${jsonPath(path)}: ${issue.message}`);
102
+ }
103
+ function jsonPath(path) {
104
+ let result = "$";
105
+ for (const segment of path) {
106
+ if (typeof segment === "number") {
107
+ result += `[${segment}]`;
108
+ }
109
+ else if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(String(segment))) {
110
+ result += `.${String(segment)}`;
111
+ }
112
+ else {
113
+ result += `[${JSON.stringify(String(segment))}]`;
114
+ }
115
+ }
116
+ return result;
117
+ }
@@ -0,0 +1,19 @@
1
+ import type { createTmux } from "@termwire/tmux";
2
+ import type { LayoutConfig } from "./config-schema";
3
+ export declare function createLayout(options: {
4
+ tmux: ReturnType<typeof createTmux>;
5
+ session: string;
6
+ workspace: string;
7
+ socket: string;
8
+ layout: LayoutConfig;
9
+ initial: {
10
+ windowId: string;
11
+ paneId: string;
12
+ };
13
+ }): Promise<{
14
+ editor: {
15
+ windowId: string;
16
+ paneId: string;
17
+ };
18
+ environment: Record<string, string>;
19
+ }>;
package/dist/layout.js ADDED
@@ -0,0 +1,106 @@
1
+ export async function createLayout(options) {
2
+ const paneMappings = await createPaneMappings(options);
3
+ const editor = findEditor(options.layout, paneMappings);
4
+ const environment = createWorkspaceEnvironment(options.session, options.socket, editor.paneId);
5
+ await setSessionEnvironment(options.tmux, options.session, environment);
6
+ await respawnPanes({
7
+ tmux: options.tmux,
8
+ workspace: options.workspace,
9
+ socket: options.socket,
10
+ layout: options.layout,
11
+ paneMappings,
12
+ environment,
13
+ });
14
+ await focusEditor(options.tmux, editor);
15
+ return { editor, environment };
16
+ }
17
+ function setPaneMapping(mappings, windowName, paneId, mappedPane) {
18
+ let windowMappings = mappings.get(windowName);
19
+ if (!windowMappings) {
20
+ windowMappings = new Map();
21
+ mappings.set(windowName, windowMappings);
22
+ }
23
+ windowMappings.set(paneId, mappedPane);
24
+ }
25
+ function getPaneMapping(mappings, windowName, paneId) {
26
+ return mappings.get(windowName)?.get(paneId);
27
+ }
28
+ function createWorkspaceEnvironment(session, socket, editorPane) {
29
+ return {
30
+ TERMWIRE_SESSION: session,
31
+ TERMWIRE_SOCKET: socket,
32
+ TERMWIRE_EDITOR_PANE: editorPane,
33
+ };
34
+ }
35
+ function commandForPane(pane, socket) {
36
+ return pane.role === "editor" ? ["nvim", "--listen", socket] : pane.command;
37
+ }
38
+ async function createPaneMappings(options) {
39
+ const paneMappings = new Map();
40
+ const firstWindow = options.layout.windows[0];
41
+ const firstPane = firstWindow.panes[0];
42
+ setPaneMapping(paneMappings, firstWindow.name, firstPane.id, options.initial);
43
+ for (const [windowIndex, window] of options.layout.windows.entries()) {
44
+ let windowId = windowIndex === 0 ? options.initial.windowId : undefined;
45
+ for (const [paneIndex, pane] of window.panes.entries()) {
46
+ if (windowIndex === 0 && paneIndex === 0)
47
+ continue;
48
+ if (paneIndex === 0) {
49
+ const created = await options.tmux.newWindow({
50
+ target: options.session,
51
+ name: window.name,
52
+ cwd: options.workspace,
53
+ });
54
+ windowId = created.windowId;
55
+ setPaneMapping(paneMappings, window.name, pane.id, created);
56
+ continue;
57
+ }
58
+ const target = getPaneMapping(paneMappings, window.name, pane.splitFrom ?? "");
59
+ const paneId = await options.tmux.splitPane({
60
+ target: target?.paneId ?? "",
61
+ direction: pane.direction ?? "horizontal",
62
+ sizePercent: pane.sizePercent,
63
+ cwd: options.workspace,
64
+ });
65
+ setPaneMapping(paneMappings, window.name, pane.id, { windowId: windowId ?? "", paneId });
66
+ }
67
+ }
68
+ return paneMappings;
69
+ }
70
+ function findEditor(layout, paneMappings) {
71
+ let editor;
72
+ for (const window of layout.windows) {
73
+ for (const pane of window.panes) {
74
+ const mappedPane = getPaneMapping(paneMappings, window.name, pane.id);
75
+ if (pane.role === "editor")
76
+ editor = mappedPane;
77
+ }
78
+ }
79
+ if (!editor)
80
+ throw new Error("layout does not contain an editor pane");
81
+ return editor;
82
+ }
83
+ async function setSessionEnvironment(tmux, session, environment) {
84
+ for (const [key, value] of Object.entries(environment)) {
85
+ await tmux.setEnvironment(session, key, value);
86
+ }
87
+ }
88
+ async function respawnPanes(options) {
89
+ for (const window of options.layout.windows) {
90
+ for (const pane of window.panes) {
91
+ const mappedPane = getPaneMapping(options.paneMappings, window.name, pane.id);
92
+ if (!mappedPane)
93
+ throw new Error(`layout pane is not mapped: ${pane.id}`);
94
+ await options.tmux.respawnPane({
95
+ target: mappedPane.paneId,
96
+ cwd: options.workspace,
97
+ environment: options.environment,
98
+ command: commandForPane(pane, options.socket),
99
+ });
100
+ }
101
+ }
102
+ }
103
+ async function focusEditor(tmux, editor) {
104
+ await tmux.selectWindow(editor.windowId);
105
+ await tmux.selectPane(editor.paneId);
106
+ }
package/dist/program.d.ts CHANGED
@@ -10,6 +10,9 @@ export interface ProgramDependencies {
10
10
  export interface RuntimeDependencies {
11
11
  createTmux: () => ReturnType<typeof createTmux>;
12
12
  cwd: () => string;
13
+ env: Record<string, string | undefined>;
14
+ homedir: () => string;
15
+ readFile: (path: string, encoding: "utf8") => Promise<string>;
13
16
  gitExec: GitExec;
14
17
  mkdir: (path: string, options: {
15
18
  recursive: true;
package/dist/program.js CHANGED
@@ -1,7 +1,11 @@
1
- import { mkdir as mkdirDirectory, stat, unlink as unlinkFile } from "node:fs/promises";
1
+ import { mkdir as mkdirDirectory, readFile as readFileFromDisk, stat, unlink as unlinkFile, } from "node:fs/promises";
2
+ import { homedir as getHomeDirectory } from "node:os";
2
3
  import { createTmux } from "@termwire/tmux";
3
4
  import { Command, CommanderError } from "commander";
4
5
  import { prepareBranch } from "./branch";
6
+ import { createConfigLoader } from "./config-loader";
7
+ import { resolveLayout } from "./config-validation";
8
+ import { createLayout } from "./layout";
5
9
  import { up } from "./up";
6
10
  import { findGitRoot, prepareWorktree } from "./worktree";
7
11
  export const executeGit = async (argv, options) => {
@@ -33,6 +37,9 @@ export async function removeStaleSocket(path, unlink) {
33
37
  export function createRuntimeUp(dependencies = {}) {
34
38
  const tmux = (dependencies.createTmux ?? (() => createTmux()))();
35
39
  const cwd = dependencies.cwd ?? (() => process.cwd());
40
+ const env = dependencies.env ?? process.env;
41
+ const homedir = dependencies.homedir ?? getHomeDirectory;
42
+ const readFile = dependencies.readFile ?? ((path, encoding) => readFileFromDisk(path, encoding));
36
43
  const gitExec = dependencies.gitExec ?? executeGit;
37
44
  const mkdir = dependencies.mkdir ?? mkdirDirectory;
38
45
  const pathExists = dependencies.pathExists ??
@@ -48,6 +55,9 @@ export function createRuntimeUp(dependencies = {}) {
48
55
  }
49
56
  });
50
57
  const unlink = dependencies.unlink ?? unlinkFile;
58
+ const loader = createConfigLoader({ env, homedir, exists: pathExists, readFile });
59
+ const loadGlobalConfig = loader.loadGlobal;
60
+ const loadProjectConfig = loader.loadProject;
51
61
  return (request) => up(request, {
52
62
  cwd,
53
63
  findGitRoot: (directory) => findGitRoot(gitExec, directory),
@@ -58,6 +68,10 @@ export function createRuntimeUp(dependencies = {}) {
58
68
  },
59
69
  removeFile: (path) => removeStaleSocket(path, unlink),
60
70
  tmux,
71
+ loadGlobalConfig,
72
+ loadProjectConfig,
73
+ resolveLayout,
74
+ createLayout,
61
75
  });
62
76
  }
63
77
  export function createProgram(dependencies) {
package/dist/up.d.ts CHANGED
@@ -1,4 +1,7 @@
1
1
  import type { createTmux } from "@termwire/tmux";
2
+ import type { LayoutConfig } from "./config-schema";
3
+ import type { LoadedConfig } from "./config-types";
4
+ import type { createLayout } from "./layout";
2
5
  export interface UpRequest {
3
6
  name: string;
4
7
  worktree?: true | string;
@@ -20,5 +23,9 @@ export interface UpDependencies {
20
23
  mkdir: (path: string) => Promise<void>;
21
24
  removeFile: (path: string) => Promise<void>;
22
25
  tmux: ReturnType<typeof createTmux>;
26
+ loadGlobalConfig: () => Promise<LoadedConfig | undefined>;
27
+ loadProjectConfig: (gitRoot: string) => Promise<LoadedConfig | undefined>;
28
+ resolveLayout: (globalConfig: LoadedConfig | undefined, projectConfig: LoadedConfig | undefined) => LayoutConfig;
29
+ createLayout: typeof createLayout;
23
30
  }
24
31
  export declare function up(request: UpRequest, dependencies: UpDependencies): Promise<void>;
package/dist/up.js CHANGED
@@ -14,28 +14,36 @@ export async function up(request, dependencies) {
14
14
  return;
15
15
  }
16
16
  const workspace = await resolveWorkspace(request, dependencies, identity, gitRoot, cwd);
17
+ const layout = await loadEffectiveLayout(workspace, dependencies);
17
18
  await dependencies.mkdir("/tmp/termwire");
18
19
  await dependencies.removeFile(identity.socket);
19
- const editor = await dependencies.tmux.newSession({
20
+ const initial = await dependencies.tmux.newSession({
20
21
  session: identity.session,
21
- name: "editor",
22
+ name: layout.windows[0].name,
22
23
  cwd: workspace,
23
24
  });
24
- const environment = createWorkspaceEnvironment(identity, editor.paneId);
25
25
  try {
26
- await configureWorkspaceSession({
26
+ await dependencies.tmux.setSessionTitle(identity.session);
27
+ await dependencies.createLayout({
27
28
  tmux: dependencies.tmux,
28
- identity,
29
+ session: identity.session,
29
30
  workspace,
30
- editor,
31
- environment,
31
+ socket: identity.socket,
32
+ layout,
33
+ initial,
32
34
  });
35
+ await dependencies.tmux.attach(identity.session);
33
36
  }
34
37
  catch (error) {
35
38
  await bestEffortKillSession(dependencies.tmux, identity.session);
36
39
  throw error;
37
40
  }
38
- await dependencies.tmux.attach(identity.session);
41
+ }
42
+ async function loadEffectiveLayout(workspace, dependencies) {
43
+ const globalConfig = await dependencies.loadGlobalConfig();
44
+ const gitRoot = await dependencies.findGitRoot(workspace);
45
+ const projectConfig = gitRoot === undefined ? undefined : await dependencies.loadProjectConfig(gitRoot);
46
+ return dependencies.resolveLayout(globalConfig, projectConfig);
39
47
  }
40
48
  async function resolveWorkspace(request, dependencies, identity, gitRoot, cwd) {
41
49
  if (request.worktree === undefined) {
@@ -58,32 +66,6 @@ async function resolveWorkspace(request, dependencies, identity, gitRoot, cwd) {
58
66
  branch: request.branch ?? name,
59
67
  });
60
68
  }
61
- function createWorkspaceEnvironment(identity, editorPane) {
62
- return {
63
- TERMWIRE_SESSION: identity.session,
64
- TERMWIRE_SOCKET: identity.socket,
65
- TERMWIRE_EDITOR_PANE: editorPane,
66
- };
67
- }
68
- async function configureWorkspaceSession(options) {
69
- for (const [key, value] of Object.entries(options.environment)) {
70
- await options.tmux.setEnvironment(options.identity.session, key, value);
71
- }
72
- await options.tmux.respawnPane({
73
- target: options.editor.paneId,
74
- cwd: options.workspace,
75
- command: ["nvim", "--listen", options.identity.socket],
76
- environment: options.environment,
77
- });
78
- await options.tmux.newWindow({
79
- target: options.identity.session,
80
- name: "shell",
81
- cwd: options.workspace,
82
- environment: options.environment,
83
- });
84
- await options.tmux.selectWindow(options.editor.windowId);
85
- await options.tmux.selectPane(options.editor.paneId);
86
- }
87
69
  async function bestEffortKillSession(tmux, session) {
88
70
  try {
89
71
  await tmux.killSession(session);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@termwire/cli",
3
- "version": "0.1.2",
3
+ "version": "0.2.1",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -37,8 +37,10 @@
37
37
  "url": "https://github.com/max-konin/termwire/issues"
38
38
  },
39
39
  "dependencies": {
40
- "@termwire/nvim": "^0.1.2",
41
- "@termwire/tmux": "^0.1.2",
42
- "commander": "^15.0.0"
40
+ "@termwire/nvim": "^0.2.1",
41
+ "@termwire/tmux": "^0.2.1",
42
+ "commander": "^15.0.0",
43
+ "jsonc-parser": "^3.3.1",
44
+ "zod": "^4.0.0"
43
45
  }
44
46
  }