@cotal-ai/tmux 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 ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,37 @@
1
+ # @cotal-ai/tmux
2
+
3
+ The tmux integration: a thin driver over the tmux CLI (open/close a window, send keys) plus a
4
+ self-registering `tmux` `Runtime` and `TerminalLayout` provider. Importing it registers both
5
+ with the core `Registry`, so the manager can spawn agents into tmux windows without depending
6
+ on this package.
7
+
8
+ **Tier:** `extensions/`. Peer-depends [`@cotal-ai/core`](../../packages/core); self-registers on
9
+ import.
10
+
11
+ ## What it does
12
+
13
+ - **`Runtime` (`tmux`)** — each agent gets its own window in a shared per-space tmux session
14
+ (`cotal-<space>`). Spawned unfocused; switch to `session:name` to watch it. Env is isolated
15
+ (`env -i`) so the tmux server's environment doesn't reach agents. Graceful stop types `/exit`
16
+ then kills the window; hard stop kills immediately.
17
+
18
+ - **`TerminalLayout` (`tmux`)** — opens/closes tmux windows for host-side orchestration
19
+ (e.g. `cotal setup`). Detects the current session from `$TMUX`; must be called from inside
20
+ a tmux session. Supports multi-pane tabs via `split-window`.
21
+
22
+ ## Usage
23
+
24
+ ```ts
25
+ import "@cotal-ai/tmux"; // self-registers; no other setup needed
26
+ ```
27
+
28
+ Then select via the manager: `cotal supervise --runtime tmux`.
29
+
30
+ ## Differences from `@cotal-ai/cmux`
31
+
32
+ cmux opens a per-agent **workspace (tab)** in the cmux app; this package opens a per-agent
33
+ **window** in a tmux session. Both are native-watch (no PTY streaming). No `cli.ts` helper is
34
+ included — tmux is always on PATH and needs no bundled binary path.
35
+
36
+ See [docs/architecture.md](../../docs/architecture.md) (*Manager*) and the
37
+ [root AGENTS.md](../../AGENTS.md) for the tier rules.
@@ -0,0 +1,55 @@
1
+ /** True if tmux is installed and reachable on PATH. */
2
+ export declare function available(): boolean;
3
+ /** Session name from the surrounding tmux environment. Throws if not inside tmux. */
4
+ export declare function currentSession(): string;
5
+ /** Ensure a detached tmux session exists; creates it if absent. A detached session has no client
6
+ * to size it, and some tmux builds then treat its window as sizeless — so `split-window` fails
7
+ * with "size missing". Give it an explicit initial size; tmux resizes to the real client on attach. */
8
+ export declare function ensureSession(session: string, cwd: string): void;
9
+ /** True if a window named `name` exists in `session`. Name-based — fragile under renames; prefer
10
+ * {@link windowAliveRef} when you hold a stable `@N` ID. Kept for name-based discovery/cleanup. */
11
+ export declare function windowAlive(session: string, name: string): boolean;
12
+ /** True if a window with the stable ID `windowId` (`@N`) still exists. Window IDs are server-global,
13
+ * so we test exact membership in the full window list — surviving renames, unlike {@link windowAlive}
14
+ * (name match). (Don't use `display-message -t`: for a stale target it silently falls back to the
15
+ * current window instead of erroring, so it can't detect a closed window.) */
16
+ export declare function windowAliveRef(windowId: string): boolean;
17
+ /** The stable refs for a freshly-opened window: its window ID (`@N`) and the ID of its initial
18
+ * (only) pane (`%N`). Both survive renames/reorders — drive later close/split/send/refs calls off
19
+ * these, not the mutable `session:name` target or pane indexes. */
20
+ export interface WindowRefs {
21
+ windowId: string;
22
+ paneId: string;
23
+ }
24
+ /** Open a new tmux window `name` in `session` running `command` (a shell string).
25
+ * Created detached (unfocused) by default; pass `focus: true` to switch to it.
26
+ * Returns the stable window ID (`@N`) and its initial pane ID (`%N`). */
27
+ export declare function openWindow(session: string, name: string, command: string, cwd: string, opts?: {
28
+ focus?: boolean;
29
+ }): WindowRefs;
30
+ /** Split `target` (a window ID `@N`, or session:window) creating a new pane running `command`.
31
+ * Returns the new pane's stable ID (`%N`). Direction convention matches {@link Tab.split.direction}:
32
+ * `"horizontal"` → stacked top/bottom rows (tmux `-v`, the default);
33
+ * `"vertical"` → side-by-side columns (tmux `-h`).
34
+ * `ratio` is the first pane's fraction — the new pane gets `(1 - ratio)`. */
35
+ export declare function splitWindow(target: string, command: string, cwd: string, direction: "vertical" | "horizontal", ratio?: number): string;
36
+ /** Focus a window by target (`session:name` or window ID). */
37
+ export declare function selectWindow(target: string): void;
38
+ /** Kill a tmux window by target (window ID `@N`, or `session:name`). Idempotent: already-gone is a no-op. */
39
+ export declare function closeWindow(target: string): void;
40
+ /** Window names open in `session`, or `[]` if unreachable. */
41
+ export declare function listWindows(session: string): string[];
42
+ /** Stable window IDs (`@N`) of every window in `session` whose name is exactly `label`. */
43
+ export declare function windowRefs(session: string, label: string): string[];
44
+ /** Shell command string that runs `command args` with `env -i` isolation — only the given
45
+ * `env` entries reach the process (the tmux server's inherited env is stripped). */
46
+ export declare function isolatedCommand(env: Record<string, string>, command: string, args: string[]): string;
47
+ /** Shell command string that runs `command args` with extra `env` merged into the inherited env. */
48
+ export declare function mergedCommand(env: Record<string, string>, command: string, args: string[]): string;
49
+ /** Type literal text into a tmux target.
50
+ * `-l` bypasses tmux's key-name lookup; `--` guards against text starting with `-`. */
51
+ export declare function send(text: string, target: string): void;
52
+ /** Send a named key sequence (e.g. `"Enter"`, `"C-c"`) to a tmux target.
53
+ * `--` guards against key names starting with `-`. */
54
+ export declare function sendKey(key: string, target: string): void;
55
+ //# sourceMappingURL=driver.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"driver.d.ts","sourceRoot":"","sources":["../src/driver.ts"],"names":[],"mappings":"AAEA,uDAAuD;AACvD,wBAAgB,SAAS,IAAI,OAAO,CAOnC;AAMD,qFAAqF;AACrF,wBAAgB,cAAc,IAAI,MAAM,CAQvC;AAWD;;wGAEwG;AACxG,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,IAAI,CAKhE;AAED;oGACoG;AACpG,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CASlE;AAED;;;+EAG+E;AAC/E,wBAAgB,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CASxD;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AE,MAAM,EAAE,MAAM,GAAG,IAAI,CAEvD;AAED;uDACuD;AACvD,wBAAgB,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,CAEzD"}
package/dist/driver.js ADDED
@@ -0,0 +1,187 @@
1
+ import { execFileSync } from "node:child_process";
2
+ /** True if tmux is installed and reachable on PATH. */
3
+ export function available() {
4
+ try {
5
+ execFileSync("tmux", ["-V"], { stdio: "ignore" });
6
+ return true;
7
+ }
8
+ catch {
9
+ return false;
10
+ }
11
+ }
12
+ function shellQuote(s) {
13
+ return `'${s.replace(/'/g, "'\\''")}'`;
14
+ }
15
+ /** Session name from the surrounding tmux environment. Throws if not inside tmux. */
16
+ export function currentSession() {
17
+ if (!process.env.TMUX)
18
+ throw new Error("tmux: not inside a tmux session ($TMUX is not set)");
19
+ try {
20
+ return execFileSync("tmux", ["display-message", "-p", "#S"], { encoding: "utf8" }).trim();
21
+ }
22
+ catch (err) {
23
+ throw new Error(`tmux: couldn't read current session name: ${err}`);
24
+ }
25
+ }
26
+ function hasSession(session) {
27
+ try {
28
+ execFileSync("tmux", ["has-session", "-t", session], { stdio: "ignore" });
29
+ return true;
30
+ }
31
+ catch {
32
+ return false;
33
+ }
34
+ }
35
+ /** Ensure a detached tmux session exists; creates it if absent. A detached session has no client
36
+ * to size it, and some tmux builds then treat its window as sizeless — so `split-window` fails
37
+ * with "size missing". Give it an explicit initial size; tmux resizes to the real client on attach. */
38
+ export function ensureSession(session, cwd) {
39
+ if (!hasSession(session))
40
+ execFileSync("tmux", ["new-session", "-d", "-s", session, "-x", "200", "-y", "50", "-c", cwd], {
41
+ stdio: "ignore",
42
+ });
43
+ }
44
+ /** True if a window named `name` exists in `session`. Name-based — fragile under renames; prefer
45
+ * {@link windowAliveRef} when you hold a stable `@N` ID. Kept for name-based discovery/cleanup. */
46
+ export function windowAlive(session, name) {
47
+ try {
48
+ const out = execFileSync("tmux", ["list-windows", "-t", session, "-F", "#W"], {
49
+ encoding: "utf8",
50
+ });
51
+ return out.split("\n").map((l) => l.trim()).includes(name);
52
+ }
53
+ catch {
54
+ return false;
55
+ }
56
+ }
57
+ /** True if a window with the stable ID `windowId` (`@N`) still exists. Window IDs are server-global,
58
+ * so we test exact membership in the full window list — surviving renames, unlike {@link windowAlive}
59
+ * (name match). (Don't use `display-message -t`: for a stale target it silently falls back to the
60
+ * current window instead of erroring, so it can't detect a closed window.) */
61
+ export function windowAliveRef(windowId) {
62
+ try {
63
+ return execFileSync("tmux", ["list-windows", "-a", "-F", "#{window_id}"], { encoding: "utf8" })
64
+ .split("\n")
65
+ .map((l) => l.trim())
66
+ .includes(windowId);
67
+ }
68
+ catch {
69
+ return false;
70
+ }
71
+ }
72
+ function isWindowGone(err) {
73
+ // Use both stderr (captured when stdio:"pipe") and message (contains the command + code).
74
+ const e = err;
75
+ const msg = `${String(e.stderr ?? "")}${String(e.message ?? "")}`;
76
+ return /can't find window|can't find session|no current window|session not found/i.test(msg);
77
+ }
78
+ /** Open a new tmux window `name` in `session` running `command` (a shell string).
79
+ * Created detached (unfocused) by default; pass `focus: true` to switch to it.
80
+ * Returns the stable window ID (`@N`) and its initial pane ID (`%N`). */
81
+ export function openWindow(session, name, command, cwd, opts = {}) {
82
+ const args = ["new-window", "-t", session, "-n", name, "-c", cwd];
83
+ if (!(opts.focus ?? false))
84
+ args.push("-d");
85
+ // -P -F prints the new window + pane IDs before returning — stable across renames and reorders.
86
+ args.push("-P", "-F", "#{window_id} #{pane_id}", command);
87
+ const out = execFileSync("tmux", args, { encoding: "utf8" }).trim();
88
+ const [windowId, paneId] = out.split(/\s+/);
89
+ if (!windowId || !paneId)
90
+ throw new Error(`tmux: couldn't read window/pane IDs from new-window ("${out}")`);
91
+ return { windowId, paneId };
92
+ }
93
+ /** Split `target` (a window ID `@N`, or session:window) creating a new pane running `command`.
94
+ * Returns the new pane's stable ID (`%N`). Direction convention matches {@link Tab.split.direction}:
95
+ * `"horizontal"` → stacked top/bottom rows (tmux `-v`, the default);
96
+ * `"vertical"` → side-by-side columns (tmux `-h`).
97
+ * `ratio` is the first pane's fraction — the new pane gets `(1 - ratio)`. */
98
+ export function splitWindow(target, command, cwd, direction, ratio) {
99
+ const args = ["split-window", "-t", target, "-c", cwd];
100
+ if (direction === "vertical")
101
+ args.push("-h"); // side-by-side columns = tmux -h
102
+ // `-l <n>%` is the modern size syntax; the old `-p <n>` is deprecated and errors "size missing"
103
+ // on tmux 3.4. The new pane gets (1 - ratio); the first keeps `ratio`.
104
+ if (ratio !== undefined)
105
+ args.push("-l", `${Math.round((1 - ratio) * 100)}%`);
106
+ // -P -F prints the new pane's ID — use it as a stable target (pane indexes shift under
107
+ // `pane-base-index` and renumber on close).
108
+ args.push("-P", "-F", "#{pane_id}", command);
109
+ return execFileSync("tmux", args, { encoding: "utf8" }).trim();
110
+ }
111
+ /** Focus a window by target (`session:name` or window ID). */
112
+ export function selectWindow(target) {
113
+ execFileSync("tmux", ["select-window", "-t", target], { stdio: "ignore" });
114
+ }
115
+ /** Kill a tmux window by target (window ID `@N`, or `session:name`). Idempotent: already-gone is a no-op. */
116
+ export function closeWindow(target) {
117
+ try {
118
+ execFileSync("tmux", ["kill-window", "-t", target], { stdio: "pipe" });
119
+ }
120
+ catch (err) {
121
+ if (isWindowGone(err))
122
+ return;
123
+ throw err;
124
+ }
125
+ }
126
+ /** Window names open in `session`, or `[]` if unreachable. */
127
+ export function listWindows(session) {
128
+ try {
129
+ return execFileSync("tmux", ["list-windows", "-t", session, "-F", "#W"], {
130
+ encoding: "utf8",
131
+ })
132
+ .split("\n")
133
+ .map((l) => l.trim())
134
+ .filter(Boolean);
135
+ }
136
+ catch {
137
+ return [];
138
+ }
139
+ }
140
+ /** Stable window IDs (`@N`) of every window in `session` whose name is exactly `label`. */
141
+ export function windowRefs(session, label) {
142
+ try {
143
+ return execFileSync("tmux", ["list-windows", "-t", session, "-F", "#{window_id} #{window_name}"], { encoding: "utf8" })
144
+ .split("\n")
145
+ .filter(Boolean)
146
+ .flatMap((line) => {
147
+ const sp = line.indexOf(" ");
148
+ const id = line.slice(0, sp);
149
+ const name = line.slice(sp + 1).trim();
150
+ return name === label ? [id] : [];
151
+ });
152
+ }
153
+ catch {
154
+ return [];
155
+ }
156
+ }
157
+ /** Render `env` as shell-safe `KEY='value'` pairs. tmux (like cmux) shell-renders env into the
158
+ * command line — pty passes it structurally — so reject any KEY that isn't a valid env identifier
159
+ * before rendering, rather than splice an attacker-influenced name into the command. Shipped
160
+ * connectors only generate safe names today; this is defense-in-depth. */
161
+ function envPairs(env) {
162
+ return Object.entries(env).map(([k, v]) => {
163
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(k))
164
+ throw new Error(`tmux: refusing to render unsafe env var name ${JSON.stringify(k)}`);
165
+ return `${k}=${shellQuote(v)}`;
166
+ });
167
+ }
168
+ /** Shell command string that runs `command args` with `env -i` isolation — only the given
169
+ * `env` entries reach the process (the tmux server's inherited env is stripped). */
170
+ export function isolatedCommand(env, command, args) {
171
+ return ["env", "-i", ...envPairs(env), shellQuote(command), ...args.map(shellQuote)].join(" ");
172
+ }
173
+ /** Shell command string that runs `command args` with extra `env` merged into the inherited env. */
174
+ export function mergedCommand(env, command, args) {
175
+ return ["env", ...envPairs(env), shellQuote(command), ...args.map(shellQuote)].join(" ");
176
+ }
177
+ /** Type literal text into a tmux target.
178
+ * `-l` bypasses tmux's key-name lookup; `--` guards against text starting with `-`. */
179
+ export function send(text, target) {
180
+ execFileSync("tmux", ["send-keys", "-l", "-t", target, "--", text], { stdio: "ignore" });
181
+ }
182
+ /** Send a named key sequence (e.g. `"Enter"`, `"C-c"`) to a tmux target.
183
+ * `--` guards against key names starting with `-`. */
184
+ export function sendKey(key, target) {
185
+ execFileSync("tmux", ["send-keys", "-t", target, "--", key], { stdio: "ignore" });
186
+ }
187
+ //# sourceMappingURL=driver.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"driver.js","sourceRoot":"","sources":["../src/driver.ts"],"names":[],"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registering `tmux` Runtime and TerminalLayout providers. Importing the package
3
+ * registers both with the core Registry (like a connector), so the manager can spawn
4
+ * into tmux windows and `cotal setup` can open/close them — neither depending on this
5
+ * package. The driver itself stays mesh-free; launch scripts import `./driver.js`
6
+ * directly to avoid the registration side effect. */
7
+ export * as tmux from "./driver.js";
8
+ export { TmuxRuntime, tmuxRuntimeProvider, tmuxTerminalProvider } from "./runtime.js";
9
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;sDAKsD;AACtD,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AAEpC,OAAO,EAAE,WAAW,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ /** @cotal-ai/tmux — the tmux integration: a thin driver over the tmux CLI plus
2
+ * self-registering `tmux` Runtime and TerminalLayout providers. Importing the package
3
+ * registers both with the core Registry (like a connector), so the manager can spawn
4
+ * into tmux windows and `cotal setup` can open/close them — neither depending on this
5
+ * package. The driver itself stays mesh-free; launch scripts import `./driver.js`
6
+ * directly to avoid the registration side effect. */
7
+ export * as tmux from "./driver.js";
8
+ // importing registers the tmux runtime + terminal-layout providers
9
+ export { TmuxRuntime, tmuxRuntimeProvider, tmuxTerminalProvider } from "./runtime.js";
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;sDAKsD;AACtD,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AACpC,mEAAmE;AACnE,OAAO,EAAE,WAAW,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC"}
@@ -0,0 +1,23 @@
1
+ import { type AgentHandle, type LaunchSpec, type Runtime, type RuntimeProvider, type TerminalLayout } from "@cotal-ai/core";
2
+ /**
3
+ * Spawns each agent into its own new tmux window in a shared per-space session, so
4
+ * spawned teammates get room rather than crowding the spawner. Opened unfocused so the
5
+ * human stays in their current window; switch to `session:name` to watch the worker.
6
+ * Like cmux, you watch natively, so `attach()` throws — but teardown is real: the window
7
+ * target is kept so it can be driven and closed.
8
+ */
9
+ export declare class TmuxRuntime implements Runtime {
10
+ private readonly session;
11
+ readonly kind: "tmux";
12
+ constructor(session: string);
13
+ spawn(name: string, spec: LaunchSpec, cwd: string): AgentHandle;
14
+ }
15
+ /** Self-registering runtime provider — `import "@cotal-ai/tmux"` makes the manager's
16
+ * `tmux` runtime available without the manager depending on this package. */
17
+ export declare const tmuxRuntimeProvider: RuntimeProvider;
18
+ /** Self-registering terminal-layout provider — lets a caller (e.g. `cotal setup`) open/close
19
+ * tmux windows by resolving `registry.resolve("terminal","tmux")`, so an implementation
20
+ * drives tmux without importing this package. The session is detected from the ambient `$TMUX`
21
+ * environment; throws if not inside tmux (per AGENTS.md: no silent fallback). */
22
+ export declare const tmuxTerminalProvider: TerminalLayout;
23
+ //# sourceMappingURL=runtime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,WAAW,EAChB,KAAK,UAAU,EACf,KAAK,OAAO,EACZ,KAAK,eAAe,EAEpB,KAAK,cAAc,EACpB,MAAM,gBAAgB,CAAC;AAoBxB;;;;;;GAMG;AACH,qBAAa,WAAY,YAAW,OAAO;IAG7B,OAAO,CAAC,QAAQ,CAAC,OAAO;IAFpC,QAAQ,CAAC,IAAI,EAAG,MAAM,CAAU;gBAEH,OAAO,EAAE,MAAM;IAE5C,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,GAAG,EAAE,MAAM,GAAG,WAAW;CAsDhE;AAED;8EAC8E;AAC9E,eAAO,MAAM,mBAAmB,EAAE,eAKjC,CAAC;AAkCF;;;kFAGkF;AAClF,eAAO,MAAM,oBAAoB,EAAE,cAclC,CAAC"}
@@ -0,0 +1,139 @@
1
+ import { registry, } from "@cotal-ai/core";
2
+ import * as tmux from "./driver.js";
3
+ /** Grace window for a clean exit before a graceful stop force-closes the window. */
4
+ const GRACE_MS = 1_500;
5
+ /** Schedule Enter keypresses to `target` every second for 5 seconds — auto-clears a
6
+ * one-time confirmation prompt (e.g. Claude's dev-channels prompt) without blocking. */
7
+ function scheduleConfirm(target) {
8
+ for (let i = 1; i <= 5; i++) {
9
+ setTimeout(() => {
10
+ try {
11
+ tmux.sendKey("Enter", target);
12
+ }
13
+ catch {
14
+ /* window may be gone — ignore */
15
+ }
16
+ }, i * 1_000);
17
+ }
18
+ }
19
+ /**
20
+ * Spawns each agent into its own new tmux window in a shared per-space session, so
21
+ * spawned teammates get room rather than crowding the spawner. Opened unfocused so the
22
+ * human stays in their current window; switch to `session:name` to watch the worker.
23
+ * Like cmux, you watch natively, so `attach()` throws — but teardown is real: the window
24
+ * target is kept so it can be driven and closed.
25
+ */
26
+ export class TmuxRuntime {
27
+ session;
28
+ kind = "tmux";
29
+ constructor(session) {
30
+ this.session = session;
31
+ }
32
+ spawn(name, spec, cwd) {
33
+ if (!/^[A-Za-z0-9_.-]+$/.test(name))
34
+ throw new Error(`tmux runtime: unsafe agent name ${JSON.stringify(name)} (allowed: letters, digits, _ . -)`);
35
+ if (!tmux.available())
36
+ throw new Error("tmux runtime: tmux is not available — is tmux installed and on PATH?");
37
+ tmux.ensureSession(this.session, cwd);
38
+ // P3: env -i strips the tmux server's inherited environment; only the connector-declared
39
+ // env reaches the spawned agent (identity, model key, OS allow-list).
40
+ const command = tmux.isolatedCommand(spec.env ?? {}, spec.command, spec.args);
41
+ // Key the whole lifecycle off the STABLE window ID (@N), not `session:name`. tmux can rename
42
+ // a window (automatic-rename / a title escape), which would desync a name-based status/stop.
43
+ const { windowId } = tmux.openWindow(this.session, name, command, cwd, { focus: false });
44
+ if (spec.confirm)
45
+ scheduleConfirm(windowId);
46
+ return {
47
+ name,
48
+ kind: "tmux",
49
+ status: () => (tmux.windowAliveRef(windowId) ? "running" : "exited"),
50
+ stop: (opts) => {
51
+ if (opts?.graceful === false)
52
+ return tmux.closeWindow(windowId);
53
+ // Graceful: type `/exit` so the Claude session shuts down cleanly (its SessionEnd
54
+ // hook leaves the mesh), then close the now-idle window regardless.
55
+ try {
56
+ tmux.send("/exit", windowId);
57
+ tmux.sendKey("Enter", windowId);
58
+ }
59
+ catch {
60
+ /* window already gone — still ensure it's closed below */
61
+ }
62
+ // Deferred, so a throw here is uncaught in a timer and would crash the manager.
63
+ // closeWindow already no-ops on an already-gone window; guard anyway and log a genuine
64
+ // tmux failure rather than let teardown cleanup take the process down.
65
+ setTimeout(() => {
66
+ try {
67
+ tmux.closeWindow(windowId);
68
+ }
69
+ catch (err) {
70
+ console.error(`tmux runtime: failed to close window for "${name}":`, err);
71
+ }
72
+ }, GRACE_MS);
73
+ },
74
+ interrupt: () => {
75
+ tmux.sendKey("C-c", windowId);
76
+ },
77
+ attach: () => {
78
+ throw new Error(`tmux runtime: attach natively — \`tmux attach-session -t ${this.session}\`, then ` +
79
+ `\`tmux select-window -t ${windowId}\` (window "${name}")`);
80
+ },
81
+ };
82
+ }
83
+ }
84
+ /** Self-registering runtime provider — `import "@cotal-ai/tmux"` makes the manager's
85
+ * `tmux` runtime available without the manager depending on this package. */
86
+ export const tmuxRuntimeProvider = {
87
+ kind: "runtime",
88
+ name: "tmux",
89
+ available: () => tmux.available(),
90
+ create: (opts) => new TmuxRuntime(opts.session),
91
+ };
92
+ registry.register(tmuxRuntimeProvider);
93
+ /** Translate a backend-agnostic {@link Tab} into a sequence of tmux commands on `session`.
94
+ * One pane → a bare window; several → a window + splits. These panes inherit the caller's
95
+ * env (setup panes run further `cotal` subcommands), so no `-i` isolation here. */
96
+ function tmuxLayout(session, label, tab) {
97
+ const [first, ...rest] = tab.panes;
98
+ if (!first)
99
+ throw new Error(`tmux layout "${label}": tab has no panes`);
100
+ const firstCmd = tmux.mergedCommand(first.env ?? {}, first.command, first.args ?? []);
101
+ // Drive splits/focus/confirm off the STABLE window/pane IDs returned here — never `session:label`
102
+ // (labels can collide or be renamed) or pane indexes `.0`/`.1` (shift under `pane-base-index`).
103
+ const { windowId, paneId: firstPane } = tmux.openWindow(session, label, firstCmd, first.cwd ?? ".", {
104
+ focus: false,
105
+ });
106
+ if (rest.length > 0 && !tab.split)
107
+ throw new Error(`tmux layout "${label}": ${tab.panes.length} panes need a split (direction + ratio)`);
108
+ if (first.confirm)
109
+ scheduleConfirm(firstPane);
110
+ rest.forEach((pane) => {
111
+ const cmd = tmux.mergedCommand(pane.env ?? {}, pane.command, pane.args ?? []);
112
+ const newPane = tmux.splitWindow(windowId, cmd, pane.cwd ?? ".", tab.split.direction, tab.split.ratio);
113
+ if (pane.confirm)
114
+ scheduleConfirm(newPane);
115
+ });
116
+ return windowId;
117
+ }
118
+ /** Self-registering terminal-layout provider — lets a caller (e.g. `cotal setup`) open/close
119
+ * tmux windows by resolving `registry.resolve("terminal","tmux")`, so an implementation
120
+ * drives tmux without importing this package. The session is detected from the ambient `$TMUX`
121
+ * environment; throws if not inside tmux (per AGENTS.md: no silent fallback). */
122
+ export const tmuxTerminalProvider = {
123
+ kind: "terminal",
124
+ name: "tmux",
125
+ available: () => tmux.available(),
126
+ open: (label, tab, opts) => {
127
+ const session = tmux.currentSession();
128
+ const windowId = tmuxLayout(session, label, tab);
129
+ if (opts?.focus)
130
+ tmux.selectWindow(windowId);
131
+ // Return the exact window ID we created (stable across renames) — not a label re-lookup, which
132
+ // could resolve a different same-label window.
133
+ return windowId;
134
+ },
135
+ close: (ref) => tmux.closeWindow(ref),
136
+ refs: (label) => tmux.windowRefs(tmux.currentSession(), label),
137
+ };
138
+ registry.register(tmuxTerminalProvider);
139
+ //# sourceMappingURL=runtime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.js","sourceRoot":"","sources":["../src/runt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AW,CAAC,GAAG,CAAC;IACrC,IAAI,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,cAAc,EAAE,EAAE,KAAK,CAAC;CAC/D,CAAC;AAEF,QAAQ,CAAC,QAAQ,CAAC,oBAAoB,CAAC,CAAC"}
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@cotal-ai/tmux",
3
+ "description": "Cotal tmux integration: a tmux Runtime and TerminalLayout provider for spawning agents into tmux windows.",
4
+ "version": "0.1.0",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/Cotal-AI/Cotal.git",
9
+ "directory": "extensions/tmux"
10
+ },
11
+ "type": "module",
12
+ "main": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.js"
18
+ }
19
+ },
20
+ "dependencies": {
21
+ "@cotal-ai/core": "0.7.0"
22
+ },
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "scripts": {
30
+ "typecheck": "tsc -p tsconfig.json --noEmit",
31
+ "build": "tsc -p tsconfig.json"
32
+ }
33
+ }