@vibecontrols/vibe-plugin-session-terminal 2026.608.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/LICENSE +25 -0
- package/README.md +42 -0
- package/dist/index.d.ts +122 -0
- package/dist/index.js +3 -0
- package/package.json +96 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Burdenoff Consultancy Services Private Limited,
|
|
4
|
+
Algoshred Technologies Private Limited,
|
|
5
|
+
and all its sister companies.
|
|
6
|
+
|
|
7
|
+
Maintainer: Vignesh T.V <https://github.com/tvvignesh>
|
|
8
|
+
|
|
9
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
10
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
11
|
+
in the Software without restriction, including without limitation the rights
|
|
12
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
13
|
+
copies of the Software, and to permit persons to whom the Software is furnished
|
|
14
|
+
to do so, subject to the following conditions:
|
|
15
|
+
|
|
16
|
+
The above copyright notice and this permission notice shall be included in all
|
|
17
|
+
copies or substantial portions of the Software.
|
|
18
|
+
|
|
19
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
20
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
21
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
22
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
23
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
24
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
25
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# @vibecontrols/vibe-plugin-session-terminal
|
|
2
|
+
|
|
3
|
+
Direct **ttyd** session provider for the VibeControls Agent — a plain terminal
|
|
4
|
+
with **no multiplexer** (no tmux / wezterm / zellij) and **no persisted
|
|
5
|
+
session**.
|
|
6
|
+
|
|
7
|
+
`startTerminal` spawns `ttyd` wrapping the login shell directly, so:
|
|
8
|
+
|
|
9
|
+
- **Native selection / copy-paste** — there is no tmux mouse mode to intercept
|
|
10
|
+
a drag, so click-drag selects text and copies exactly like a local terminal
|
|
11
|
+
(iTerm2-style).
|
|
12
|
+
- **Ephemeral** — there is no daemon to reattach to; closing the terminal ends
|
|
13
|
+
the shell. This is the "just open a terminal" mode.
|
|
14
|
+
|
|
15
|
+
The provider registers itself as `session-terminal`. The workspace backend
|
|
16
|
+
maps `SessionType.TERMINAL` to this provider, so creating a session of type
|
|
17
|
+
**Terminal** in the web UI routes here. Agents that don't have this plugin
|
|
18
|
+
installed simply fall back to their default multiplexer.
|
|
19
|
+
|
|
20
|
+
## Capabilities
|
|
21
|
+
|
|
22
|
+
| feature | supported |
|
|
23
|
+
| ---------------------------------------------------- | ---------------------------- |
|
|
24
|
+
| web terminal (ttyd) | ✅ |
|
|
25
|
+
| native scrollback / clipboard | ✅ |
|
|
26
|
+
| resize (xterm over ws) | ✅ |
|
|
27
|
+
| programmatic input / capture (`sendKeys`, `capture`) | ❌ (use tmux/wezterm/zellij) |
|
|
28
|
+
| split panes / tabs / mouse mode | ❌ |
|
|
29
|
+
|
|
30
|
+
## Prerequisites
|
|
31
|
+
|
|
32
|
+
- `ttyd` (auto-installed from the official static releases on Linux/Windows;
|
|
33
|
+
`brew install ttyd` on macOS).
|
|
34
|
+
|
|
35
|
+
## Development
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
bun install
|
|
39
|
+
bun run sanity # format:check, lint, type:check, build
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
License: MIT
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import type { VibePluginFactory } from "@vibecontrols/plugin-sdk/contract";
|
|
2
|
+
type SessionStatus = "active" | "inactive" | "terminated" | "error";
|
|
3
|
+
interface SessionConfig {
|
|
4
|
+
id?: string;
|
|
5
|
+
name: string;
|
|
6
|
+
command?: string;
|
|
7
|
+
workingDirectory?: string;
|
|
8
|
+
environment?: Record<string, string>;
|
|
9
|
+
shell?: string;
|
|
10
|
+
size?: {
|
|
11
|
+
cols: number;
|
|
12
|
+
rows: number;
|
|
13
|
+
};
|
|
14
|
+
projectId?: string;
|
|
15
|
+
/** Ignored by this provider — there is no provider-native session to attach to. */
|
|
16
|
+
externalName?: string;
|
|
17
|
+
}
|
|
18
|
+
interface TerminalInfo {
|
|
19
|
+
url: string;
|
|
20
|
+
port: number;
|
|
21
|
+
pid: number;
|
|
22
|
+
host?: string;
|
|
23
|
+
wsPath?: string;
|
|
24
|
+
subprotocols?: string[];
|
|
25
|
+
}
|
|
26
|
+
interface SessionInfo {
|
|
27
|
+
id: string;
|
|
28
|
+
name: string;
|
|
29
|
+
status: SessionStatus;
|
|
30
|
+
provider: string;
|
|
31
|
+
command?: string;
|
|
32
|
+
workingDirectory?: string;
|
|
33
|
+
pid?: number;
|
|
34
|
+
projectId?: string;
|
|
35
|
+
createdAt: string;
|
|
36
|
+
updatedAt?: string;
|
|
37
|
+
terminal?: TerminalInfo;
|
|
38
|
+
metadata?: Record<string, unknown>;
|
|
39
|
+
}
|
|
40
|
+
interface HealthCheckResult {
|
|
41
|
+
ok: boolean;
|
|
42
|
+
sessions: number;
|
|
43
|
+
terminals: number;
|
|
44
|
+
message?: string;
|
|
45
|
+
}
|
|
46
|
+
interface SystemSessionInfo {
|
|
47
|
+
id: string;
|
|
48
|
+
name: string;
|
|
49
|
+
windows: number;
|
|
50
|
+
attached: boolean;
|
|
51
|
+
createdAt?: string;
|
|
52
|
+
}
|
|
53
|
+
interface SystemTerminalInfo {
|
|
54
|
+
pid: number;
|
|
55
|
+
port: number;
|
|
56
|
+
sessionId?: string;
|
|
57
|
+
}
|
|
58
|
+
interface SessionProviderCapabilities {
|
|
59
|
+
provider: string;
|
|
60
|
+
features: {
|
|
61
|
+
mouse: boolean;
|
|
62
|
+
resize: boolean;
|
|
63
|
+
capture: boolean;
|
|
64
|
+
webTerminal: boolean;
|
|
65
|
+
splitPanes: boolean;
|
|
66
|
+
tabs: boolean;
|
|
67
|
+
scrollback: boolean;
|
|
68
|
+
clipboard: boolean;
|
|
69
|
+
search: boolean;
|
|
70
|
+
};
|
|
71
|
+
platform: string[];
|
|
72
|
+
}
|
|
73
|
+
interface SessionProvider {
|
|
74
|
+
readonly name: string;
|
|
75
|
+
create(config: SessionConfig): Promise<SessionInfo>;
|
|
76
|
+
terminate(sessionId: string): Promise<void>;
|
|
77
|
+
getInfo(sessionId: string): Promise<SessionInfo | null>;
|
|
78
|
+
list(): Promise<SessionInfo[]>;
|
|
79
|
+
sendCommand(sessionId: string, command: string): Promise<void>;
|
|
80
|
+
sendKeys(sessionId: string, keys: string): Promise<void>;
|
|
81
|
+
sendInterrupt(sessionId: string): Promise<void>;
|
|
82
|
+
captureOutput(sessionId: string): Promise<string>;
|
|
83
|
+
rename(sessionId: string, newName: string): Promise<void>;
|
|
84
|
+
toggleMouse(sessionId: string): Promise<boolean>;
|
|
85
|
+
getTerminationStatus(sessionId: string): Promise<{
|
|
86
|
+
terminated: boolean;
|
|
87
|
+
exists: boolean;
|
|
88
|
+
}>;
|
|
89
|
+
getTerminalInfo(sessionId: string): Promise<TerminalInfo | null>;
|
|
90
|
+
startTerminal(sessionId: string, port?: number): Promise<TerminalInfo>;
|
|
91
|
+
stopTerminal(sessionId: string): Promise<void>;
|
|
92
|
+
listSystemSessions(): Promise<SystemSessionInfo[]>;
|
|
93
|
+
listSystemTerminals(): Promise<SystemTerminalInfo[]>;
|
|
94
|
+
bulkKillSystemSessions(sessionIds: string[]): Promise<{
|
|
95
|
+
killed: number;
|
|
96
|
+
failed: number;
|
|
97
|
+
}>;
|
|
98
|
+
bulkKillSystemTerminals(pids: number[]): Promise<{
|
|
99
|
+
killed: number;
|
|
100
|
+
failed: number;
|
|
101
|
+
}>;
|
|
102
|
+
healthCheck(): Promise<HealthCheckResult>;
|
|
103
|
+
getSessionsByProject(projectId: string): Promise<SessionInfo[]>;
|
|
104
|
+
cleanup(): Promise<{
|
|
105
|
+
cleaned: number;
|
|
106
|
+
}>;
|
|
107
|
+
get(sessionId: string): Promise<SessionInfo | null>;
|
|
108
|
+
kill(sessionId: string): Promise<void>;
|
|
109
|
+
interrupt(sessionId: string): Promise<void>;
|
|
110
|
+
capture(sessionId: string, options?: {
|
|
111
|
+
lines?: number;
|
|
112
|
+
pane?: string;
|
|
113
|
+
}): Promise<string>;
|
|
114
|
+
resize(sessionId: string, cols: number, rows: number): Promise<void>;
|
|
115
|
+
listSystem(): Promise<SystemSessionInfo[]>;
|
|
116
|
+
killSystem(sessionId: string): Promise<void>;
|
|
117
|
+
killSystemTerminal(pid: number): Promise<void>;
|
|
118
|
+
getCapabilities?(): SessionProviderCapabilities;
|
|
119
|
+
}
|
|
120
|
+
declare const factory: VibePluginFactory;
|
|
121
|
+
export default factory;
|
|
122
|
+
export type { SessionProvider, SessionProviderCapabilities, SessionConfig, SessionInfo, SessionStatus, TerminalInfo, HealthCheckResult, SystemSessionInfo, SystemTerminalInfo, };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Elysia}from"elysia";function createLifecycleHooks(spec){let{name,onInit,onShutdown,onNuke,telemetryEventName,skipPlatforms}=spec;return{onServerStart:async(_app,hostServices)=>{if(skipPlatforms&&skipPlatforms.includes(process.platform)){process.stderr.write(`[${name}] skipping init on unsupported platform '${process.platform}'
|
|
3
|
+
`);return}if(onInit)await onInit(hostServices);if(telemetryEventName)hostServices.telemetry?.emit(telemetryEventName,{plugin:name})},onServerStop:async(hostServices)=>{if(onShutdown)await onShutdown(hostServices)},onNuke:async(hostServices,ctx)=>{if(onNuke)return onNuke(hostServices,ctx)}}}var TypedStore=class{constructor(storage,namespace,key,logger,pluginName="plugin"){this.storage=storage,this.namespace=namespace,this.key=key,this.logger=logger,this.pluginName=pluginName}storage;namespace;key;logger;pluginName;async get(){let raw=await this.storage.get(this.namespace,this.key);if(raw===null||raw===void 0)return null;if(typeof raw!=="string")return raw;try{return JSON.parse(raw)}catch(err){return this.logger?.error?.(this.pluginName,"TypedStore: corrupt JSON",{namespace:this.namespace,key:this.key,message:err instanceof Error?err.message:String(err)}),null}}async set(value){await this.storage.set(this.namespace,this.key,JSON.stringify(value))}async delete(){return this.storage.delete(this.namespace,this.key)}};import{createServer}from"net";function sleep(ms){return new Promise((resolve)=>setTimeout(resolve,ms))}function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch{return!1}}async function gracefulKill(pid,timeoutMs=3000,logger){if(!isProcessAlive(pid))return;try{process.kill(pid,"SIGTERM")}catch(err){logger?.warn?.("subprocess","SIGTERM failed",{pid,message:err instanceof Error?err.message:String(err)});return}let pollMs=50,elapsed=0;while(elapsed<timeoutMs)if(await sleep(pollMs),elapsed+=pollMs,!isProcessAlive(pid))return;try{process.kill(pid,"SIGKILL")}catch(err){logger?.warn?.("subprocess","SIGKILL failed",{pid,message:err instanceof Error?err.message:String(err)})}}async function findAvailablePort(start,range=200){for(let i=0;i<range;i++){let port=start+i;if(await isPortFree(port))return port}throw Error(`findAvailablePort: no port free in [${start}, ${start+range-1}]`)}function isPortFree(port){return new Promise((resolve)=>{let server=createServer();server.once("error",()=>{resolve(!1)}),server.once("listening",()=>{server.close(()=>resolve(!0))});try{server.listen({port,host:"0.0.0.0"})}catch{resolve(!1)}})}var BoundLogger=class{constructor(logger,source){this.logger=logger,this.source=source}logger;source;info(message,meta){this.logger?.info?.(this.source,message,meta)}warn(message,meta){this.logger?.warn?.(this.source,message,meta)}error(message,meta){this.logger?.error?.(this.source,message,meta)}debug(message,meta){this.logger?.debug?.(this.source,message,meta)}};var TelemetryEmitter=class{constructor(pluginName,pluginVersion,hostServices){this.pluginName=pluginName,this.pluginVersion=pluginVersion,this.hostServices=hostServices}pluginName;pluginVersion;hostServices;emit(eventName,payload){let target=this.hostServices?.telemetry;if(!target)return;target.emit(eventName,{plugin:this.pluginName,version:this.pluginVersion,timestamp:new Date().toISOString(),...payload??{}})}emitReady(context){this.emit(`${this.pluginName}.ready`,context)}emitError(error,context){this.emit(`${this.pluginName}.error`,{message:error.message,...context??{}})}emitEvent(type,payload){this.emit(type,payload)}};var CONTEXT_PROVIDER_TYPE="context",REGISTRY_KEY=Symbol.for("@vibecontrols/plugin-sdk:contextProviders@1");function getRegistry(){let slots=globalThis,existing=slots[REGISTRY_KEY];if(existing)return existing;let created=new Map;return slots[REGISTRY_KEY]=created,created}function registerContextProvider(provider,hostServices){if(!provider||typeof provider.name!=="string"||provider.name.length===0)throw Error("ContextProvider.name is required");if(typeof provider.getContext!=="function")throw Error("ContextProvider.getContext must be a function");getRegistry().set(provider.name,provider),hostServices?.serviceRegistry?.registerProvider?.(CONTEXT_PROVIDER_TYPE,provider,provider.name)}function listContextProviders(){return Array.from(getRegistry().values())}function getContextProvider(name){return getRegistry().get(name)}var ProviderRegistry=class{constructor(hostServices){this.hostServices=hostServices}hostServices;registerContextProvider(provider){registerContextProvider(provider,this.hostServices)}listContextProviders(){return listContextProviders()}getContextProvider(name){return getContextProvider(name)}getServiceRegistry(){return this.hostServices?.serviceRegistry}registerProvider(type,name,provider){this.hostServices?.serviceRegistry?.registerProvider?.(type,provider,name)}getProvider(type,name){let reg=this.hostServices?.serviceRegistry;if(!reg)return;if(name===void 0)return reg.getProvider?.(type);if(reg.getProviderByName)return reg.getProviderByName(type,name);if(!reg.listProvidersForType)return;if(!(reg.listProvidersForType(type)??[]).some((entry)=>typeof entry==="string"?entry===name:entry.pluginName===name))return;return reg.getProvider?.(type)}listProviders(type){return(this.hostServices?.serviceRegistry?.listProvidersForType?.(type)??[]).map((entry)=>typeof entry==="string"?entry:entry.pluginName)}withCliContribution(contribution){let contributors=this.hostServices?.cliContributors;if(!contributors)return;for(let section of contribution.statusSections??[])contributors.addStatusSection?.(section);for(let check of contribution.doctorChecks??[])contributors.addDoctorCheck?.(check)}};import{spawn}from"child_process";import{createHash}from"crypto";import{existsSync,promises,createWriteStream}from"fs";import{homedir,tmpdir}from"os";import*as path from"path";import{Readable}from"stream";import{pipeline}from"stream/promises";function currentPlatform(){let arch=process.arch==="x64"?"x64":"arm64";return`${process.platform==="win32"?"win32":process.platform==="darwin"?"darwin":"linux"}-${arch}`}function toolsCacheRoot(){return path.join(homedir(),".boff","vibecontrols","tools")}function binFileName(name,binaryName){let base=binaryName??name;if(process.platform==="win32"&&!base.toLowerCase().endsWith(".exe"))return`${base}.exe`;return base}function cachedBinaryPath(name,binaryName,cacheRoot){return path.join(cacheRoot??toolsCacheRoot(),name,binFileName(name,binaryName))}function resolveBinary(name,binaryName,cacheRoot){let cached=cachedBinaryPath(name,binaryName,cacheRoot);if(existsSync(cached))return cached;try{let onPath=typeof Bun<"u"&&typeof Bun.which==="function"?Bun.which(binaryName??name,{PATH:process.env.PATH}):null;if(onPath)return onPath}catch{}return null}async function versionOk(binaryPath,spec){if(!spec.versionMatcher)return!0;return new Promise((resolve)=>{let child=spawn(binaryPath,spec.versionArgs??["--version"],{stdio:["ignore","pipe","pipe"]}),out="";child.stdout.on("data",(b)=>out+=b.toString()),child.stderr.on("data",(b)=>out+=b.toString()),child.on("close",()=>{try{resolve(new RegExp(spec.versionMatcher).test(out))}catch{resolve(!1)}}),child.on("error",()=>resolve(!1))})}async function installBinary(spec){let platform=spec.platform??currentPlatform(),binaryName=binFileName(spec.name,spec.binaryName),cached=cachedBinaryPath(spec.name,spec.binaryName,spec.cacheRoot);if(existsSync(cached)&&await versionOk(cached,spec))return cached;try{let onPath=typeof Bun<"u"&&typeof Bun.which==="function"?Bun.which(spec.binaryName??spec.name,{PATH:process.env.PATH}):null;if(onPath&&await versionOk(onPath,spec))return spec.log?.info?.(`[install] using PATH binary ${spec.name} (${onPath})`),onPath}catch{}let download=spec.downloads[platform];if(!download)throw Error(`[install] no download manifest entry for ${spec.name} on ${platform}`);return spec.log?.info?.(`[install] downloading ${spec.name} for ${platform}`),await promises.mkdir(path.dirname(cached),{recursive:!0}),await downloadAndInstall(download,cached,binaryName,spec.name),spec.log?.info?.(`[install] installed ${spec.name} \u2192 ${cached}`),cached}async function downloadAndInstall(d,destBinary,binaryName,toolName){let destDir=path.dirname(destBinary),tmp=path.join(tmpdir(),`vibe-install-${toolName}-${process.pid}`);await promises.mkdir(tmp,{recursive:!0});let archivePath=path.join(tmp,"artifact");try{let res=await fetch(d.url,{redirect:"follow"});if(!res.ok)throw Error(`download failed (${res.status}) for ${d.url}`);if(!res.body)throw Error(`empty response body for ${d.url}`);if(await pipeline(Readable.fromWeb(res.body),createWriteStream(archivePath)),d.sha256){let actual=createHash("sha256").update(await promises.readFile(archivePath)).digest("hex");if(actual!==d.sha256)throw Error(`sha256 mismatch for ${toolName}: expected ${d.sha256}, got ${actual}`)}let archiveType=d.archive??(d.url.endsWith(".tar.gz")||d.url.endsWith(".tgz")?"tar.gz":d.url.endsWith(".zip")?"zip":"raw");if(archiveType==="raw")await promises.copyFile(archivePath,destBinary);else{if(archiveType==="tar.gz")await runProcess("tar",["-xzf",archivePath,"-C",tmp]);else await extractZip(archivePath,tmp);let inner=d.binaryWithinArchive??binaryName;await promises.copyFile(path.join(tmp,inner),destBinary)}if(process.platform!=="win32")await promises.chmod(destBinary,493)}finally{await promises.rm(tmp,{recursive:!0,force:!0})}}async function extractZip(archive,dest){try{await runProcess("unzip",["-q","-o",archive,"-d",dest]);return}catch(err){if(process.platform!=="win32")throw err;await runProcess("tar",["-xf",archive,"-C",dest])}}async function runProcess(cmd,args){return new Promise((resolve,reject)=>{let child=spawn(cmd,args,{stdio:["ignore","ignore","pipe"]}),err="";child.stderr.on("data",(b)=>err+=b.toString()),child.on("close",(code)=>code===0?resolve():reject(Error(`${cmd} exit ${code}: ${err}`))),child.on("error",reject)})}var CLOUDFLARED_BASE="https://github.com/cloudflare/cloudflared/releases/latest/download",CLOUDFLARED_DOWNLOADS={"linux-x64":{url:`${CLOUDFLARED_BASE}/cloudflared-linux-amd64`,archive:"raw"},"linux-arm64":{url:`${CLOUDFLARED_BASE}/cloudflared-linux-arm64`,archive:"raw"},"darwin-x64":{url:`${CLOUDFLARED_BASE}/cloudflared-darwin-amd64.tgz`,archive:"tar.gz",binaryWithinArchive:"cloudflared"},"darwin-arm64":{url:`${CLOUDFLARED_BASE}/cloudflared-darwin-arm64.tgz`,archive:"tar.gz",binaryWithinArchive:"cloudflared"},"win32-x64":{url:`${CLOUDFLARED_BASE}/cloudflared-windows-amd64.exe`,archive:"raw"},"win32-arm64":{url:`${CLOUDFLARED_BASE}/cloudflared-windows-arm64.exe`,archive:"raw"}};var TTYD_DOWNLOADS={"linux-x64":{url:"https://github.com/tsl0922/ttyd/releases/latest/download/ttyd.x86_64",archive:"raw"},"linux-arm64":{url:"https://github.com/tsl0922/ttyd/releases/latest/download/ttyd.aarch64",archive:"raw"},"win32-x64":{url:"https://github.com/tsl0922/ttyd/releases/latest/download/ttyd.win32.exe",archive:"raw"}};function ttydManualInstall(){if(process.platform==="darwin")return"Install ttyd with: brew install ttyd";if(process.platform==="win32")return"Install ttyd from https://github.com/tsl0922/ttyd/releases";return"Install ttyd with your package manager (e.g. apt install ttyd) or from https://github.com/tsl0922/ttyd/releases"}async function ensureTtydBinary(log){let existing=resolveBinary("ttyd");if(existing)return existing;log?.info("ttyd not found \u2014 attempting auto-install");try{let installed=await installBinary({name:"ttyd",downloads:TTYD_DOWNLOADS,versionMatcher:"ttyd version",log:{info:(msg)=>log?.info(msg),warn:(msg)=>log?.warn(msg),error:(msg)=>log?.error(msg)}});return log?.info("ttyd auto-installed",{path:installed}),installed}catch(err){let cause=err instanceof Error?err.message:String(err);throw Error(`ttyd is not available and auto-install failed. ${ttydManualInstall()}. Cause: ${cause}`,{cause:err})}}var TTYD_HOST="127.0.0.1",TTYD_WS_PATH="/ws",TTYD_SUBPROTOCOLS=["tty"],PLUGIN_NAME="session-terminal",PLUGIN_VERSION="2026.608.1",PROVIDER_NAME="session-terminal",STORAGE_NAMESPACE="session-terminal",STORAGE_KEY_SESSIONS="sessions",STORAGE_KEY_TERMINALS="terminals",TTYD_BASE_PORT=7881,TTYD_PORT_RANGE=200;function generateId(){let bytes=new Uint8Array(4);return crypto.getRandomValues(bytes),[...bytes].map((b)=>b.toString(16).padStart(2,"0")).join("")}function nowISO(){return new Date().toISOString()}function resolveShell(configured){if(configured&&configured.trim())return configured.trim();if(process.platform==="win32")return process.env.COMSPEC||"powershell.exe";return process.env.SHELL||"/bin/bash"}function buildShellInvocation(shell,command){if(!command||!command.trim())return process.platform==="win32"?[shell]:[shell,"-l"];if(process.platform==="win32")return[shell,"-NoExit","-Command",command];return[shell,"-lc",`${command}; exec ${shell} -l`]}class TerminalSessionProvider{name=PROVIDER_NAME;log=new BoundLogger(void 0,PLUGIN_NAME);sessionsStore=null;terminalsStore=null;ttydPids=new Map;ttydPorts=new Map;async init(services){if(this.log=new BoundLogger(services.logger,PLUGIN_NAME),services.storage)this.sessionsStore=new TypedStore(services.storage,STORAGE_NAMESPACE,STORAGE_KEY_SESSIONS,services.logger,PLUGIN_NAME),this.terminalsStore=new TypedStore(services.storage,STORAGE_NAMESPACE,STORAGE_KEY_TERMINALS,services.logger,PLUGIN_NAME);this.log.info("TerminalSessionProvider initialising",{provider:this.name});try{let path2=resolveBinary("ttyd");if(path2)this.log.info("ttyd detected",{path:path2});else this.log.warn("ttyd not found \u2014 will auto-install on first terminal")}catch{}await this.reconcile(),this.log.info("TerminalSessionProvider ready")}async shutdown(context){if(context?.reason==="reload"){this.log.info("Hot-reload: preserving ttyd processes"),await this.persistTerminals(),this.ttydPids.clear(),this.ttydPorts.clear();return}this.log.info("TerminalSessionProvider shutting down \u2014 stopping terminals");let stops=[];for(let[sessionId]of this.ttydPids)stops.push(this.stopTerminal(sessionId));await Promise.allSettled(stops);try{await this.terminalsStore?.delete()}catch{}this.log.info("TerminalSessionProvider shutdown complete")}async nuke(){this.log.info("TerminalSessionProvider nuke \u2014 reaping spawned terminals");let tracked=[...this.ttydPids.keys()],terminalsReaped=0;await Promise.allSettled(tracked.map(async(sessionId)=>{let pid=this.ttydPids.get(sessionId);if(await this.stopTerminal(sessionId),pid!==void 0)terminalsReaped++}));try{await this.sessionsStore?.delete(),await this.terminalsStore?.delete()}catch{}return{terminalsReaped}}async loadSessions(){if(!this.sessionsStore)return[];return await this.sessionsStore.get()??[]}async saveSessions(sessions){await this.sessionsStore?.set(sessions)}async saveSession(session){let sessions=await this.loadSessions(),idx=sessions.findIndex((s)=>s.id===session.id);if(idx>=0)sessions[idx]=session;else sessions.push(session);await this.saveSessions(sessions)}async persistTerminals(){if(!this.terminalsStore)return;let record={};for(let[sessionId,pid]of this.ttydPids){let port=this.ttydPorts.get(sessionId);if(port!==void 0)record[sessionId]={pid,port}}await this.terminalsStore.set(record)}async reconcile(){let persisted=await this.terminalsStore?.get()??{};for(let[sessionId,t]of Object.entries(persisted))if(t&&typeof t.pid==="number"&&isProcessAlive(t.pid))this.ttydPids.set(sessionId,t.pid),this.ttydPorts.set(sessionId,t.port);await this.persistTerminals()}async requireSession(sessionId){let session=await this.getInfo(sessionId);if(!session)throw Error(`Session not found: ${sessionId}`);return session}getRunningTerminalInfo(sessionId){let pid=this.ttydPids.get(sessionId),port=this.ttydPorts.get(sessionId);if(pid===void 0||port===void 0)return null;if(!isProcessAlive(pid))return this.ttydPids.delete(sessionId),this.ttydPorts.delete(sessionId),null;return{url:`http://localhost:${port}`,port,pid,host:TTYD_HOST,wsPath:TTYD_WS_PATH,subprotocols:[...TTYD_SUBPROTOCOLS]}}async create(config){let id=config.id?.trim()||generateId(),existing=await this.getInfo(id);if(existing)return this.log.debug("create: session already exists, returning",{id}),existing;let session={id,name:config.name,status:"inactive",provider:this.name,command:config.command,workingDirectory:config.workingDirectory,projectId:config.projectId,createdAt:nowISO(),metadata:{shell:resolveShell(config.shell),environment:config.environment??{}}};return await this.saveSession(session),this.log.info("Terminal session created",{id,name:session.name}),session}async terminate(sessionId){await this.stopTerminal(sessionId);let sessions=await this.loadSessions();await this.saveSessions(sessions.filter((s)=>s.id!==sessionId)),this.log.info("Terminal session terminated",{sessionId})}async getInfo(sessionId){return(await this.loadSessions()).find((s)=>s.id===sessionId)??null}async list(){return this.loadSessions()}async getSessionsByProject(projectId){return(await this.loadSessions()).filter((s)=>s.projectId===projectId)}async startTerminal(sessionId,port){let session=await this.requireSession(sessionId),existing=this.getRunningTerminalInfo(sessionId);if(existing)return this.log.debug("Terminal already running",{sessionId,...existing}),existing;let inUsePorts=[...this.ttydPorts.values()],scanStart=inUsePorts.length?Math.max(TTYD_BASE_PORT,Math.max(...inUsePorts)+1):TTYD_BASE_PORT,assignedPort=port??await findAvailablePort(scanStart,TTYD_PORT_RANGE),shell=resolveShell(session.metadata?.shell??void 0),invocation=buildShellInvocation(shell,session.command),ttydEnv={...process.env};ttydEnv.VIBECONTROLS_PROVIDER="terminal";for(let v of["TMUX","TMUX_PANE","WEZTERM_PANE","WEZTERM_UNIX_SOCKET","STY","WINDOW","ZELLIJ","ZELLIJ_SESSION_NAME","ZELLIJ_PANE_ID"])if(v in ttydEnv)delete ttydEnv[v];let sessionEnv=session.metadata?.environment??{};for(let[k,val]of Object.entries(sessionEnv))ttydEnv[k]=val;let ttydCmd=await ensureTtydBinary(this.log);this.log.info("Starting ttyd terminal (direct shell)",{sessionId,port:assignedPort,shell});let child=Bun.spawn([ttydCmd,"-i",TTYD_HOST,"-t","fontSize=14","-t",'theme={"background":"#1e1e1e","foreground":"#cccccc"}',"--writable","--port",String(assignedPort),...invocation],{stdout:"ignore",stderr:"pipe",stdin:"ignore",env:ttydEnv,cwd:session.workingDirectory||void 0});if(!child.pid)throw Error("Failed to start ttyd \u2014 no PID returned");let ttydStderr="",stderrStream=child.stderr;if(stderrStream&&typeof stderrStream.getReader==="function")(async()=>{try{let reader=stderrStream.getReader(),dec=new TextDecoder;for(;;){let{done,value}=await reader.read();if(done)break;if(ttydStderr.length<4096)ttydStderr+=dec.decode(value,{stream:!0})}}catch{}})();if(await sleep(500),child.exitCode!==null||!isProcessAlive(child.pid)){let detail=ttydStderr.trim().slice(0,300)||"no stderr captured";throw this.log.error("ttyd exited immediately after launch",{sessionId,port:assignedPort,exitCode:child.exitCode,stderr:detail}),Error(`ttyd exited immediately (code ${child.exitCode??"unknown"}) on port ${assignedPort} running "${shell}": ${detail}`)}this.ttydPids.set(sessionId,child.pid),this.ttydPorts.set(sessionId,assignedPort),await this.persistTerminals();let terminalInfo={url:`http://localhost:${assignedPort}`,port:assignedPort,pid:child.pid,host:TTYD_HOST,wsPath:TTYD_WS_PATH,subprotocols:[...TTYD_SUBPROTOCOLS]};return session.terminal=terminalInfo,session.status="active",session.pid=child.pid,session.updatedAt=nowISO(),await this.saveSession(session),this.log.info("ttyd terminal started",{sessionId,port:assignedPort,pid:child.pid}),terminalInfo}async stopTerminal(sessionId){let pid=this.ttydPids.get(sessionId);if(pid===void 0){this.log.debug("No ttyd process for session",{sessionId});return}this.log.info("Stopping ttyd terminal",{sessionId,pid}),await gracefulKill(pid),this.ttydPids.delete(sessionId),this.ttydPorts.delete(sessionId),await this.persistTerminals();let session=await this.getInfo(sessionId);if(session)session.terminal=void 0,session.status="inactive",session.pid=void 0,session.updatedAt=nowISO(),await this.saveSession(session);this.log.info("ttyd terminal stopped",{sessionId})}async getTerminalInfo(sessionId){return this.getRunningTerminalInfo(sessionId)}async getTerminationStatus(sessionId){if(!await this.getInfo(sessionId))return{terminated:!0,exists:!1};return{terminated:!(this.getRunningTerminalInfo(sessionId)!==null),exists:!0}}async rename(sessionId,newName){let session=await this.requireSession(sessionId);session.name=newName,session.updatedAt=nowISO(),await this.saveSession(session)}async resize(_sessionId,_cols,_rows){}async toggleMouse(_sessionId){return!1}async sendCommand(_sessionId,_command){throw Error("sendCommand is not supported by the direct-terminal provider (no multiplexer). Use a tmux/wezterm/zellij session for programmatic input.")}async sendKeys(_sessionId,_keys){throw Error("sendKeys is not supported by the direct-terminal provider (no multiplexer).")}async sendInterrupt(_sessionId){throw Error("sendInterrupt is not supported by the direct-terminal provider (no multiplexer).")}async captureOutput(_sessionId){return""}async listSystemSessions(){return[]}async listSystemTerminals(){let out=[];for(let[sessionId,pid]of this.ttydPids){let port=this.ttydPorts.get(sessionId);if(port!==void 0&&isProcessAlive(pid))out.push({pid,port,sessionId})}return out}async bulkKillSystemSessions(sessionIds){let killed=0,failed=0;for(let id of sessionIds)try{await this.terminate(id),killed++}catch{failed++}return{killed,failed}}async bulkKillSystemTerminals(pids){let killed=0,failed=0;for(let pid of pids)try{await gracefulKill(pid),killed++}catch{failed++}return{killed,failed}}async healthCheck(){let sessions=(await this.loadSessions()).length,ok=!0,message;try{if(!resolveBinary("ttyd"))ok=!1,message="ttyd not installed (will auto-install on first terminal)"}catch{}return{ok,sessions,terminals:this.ttydPids.size,message}}async cleanup(){let cleaned=0;for(let[sessionId,pid]of[...this.ttydPids])if(!isProcessAlive(pid)){this.ttydPids.delete(sessionId),this.ttydPorts.delete(sessionId);let session=await this.getInfo(sessionId);if(session)session.terminal=void 0,session.status="inactive",session.pid=void 0,await this.saveSession(session);cleaned++}if(cleaned)await this.persistTerminals();return{cleaned}}async get(sessionId){return this.getInfo(sessionId)}async kill(sessionId){return this.terminate(sessionId)}async interrupt(sessionId){return this.sendInterrupt(sessionId)}async capture(sessionId,_options){return this.captureOutput(sessionId)}async listSystem(){return this.listSystemSessions()}async killSystem(sessionId){return this.terminate(sessionId)}async killSystemTerminal(pid){await gracefulKill(pid);for(let[sessionId,p]of this.ttydPids)if(p===pid)this.ttydPids.delete(sessionId),this.ttydPorts.delete(sessionId);await this.persistTerminals()}getCapabilities(){return{provider:"terminal",features:{mouse:!1,resize:!0,capture:!1,webTerminal:!0,splitPanes:!1,tabs:!1,scrollback:!0,clipboard:!0,search:!1},platform:["linux","darwin","win32"]}}}function createPrereqsRoutes(){return new Elysia().get("/prereqs",()=>({plugin:PLUGIN_NAME,prerequisites:[{name:"ttyd",kind:"binary",present:(()=>{try{return!!resolveBinary("ttyd")}catch{return!1}})(),autoInstall:!0,manual:ttydManualInstall()}]}))}var provider=new TerminalSessionProvider,factory=(_ctx)=>{let lifecycle=createLifecycleHooks({name:PLUGIN_NAME,telemetryEventName:`${PLUGIN_NAME}.ready`,onInit:async(services)=>{new ProviderRegistry(services).registerProvider("session",PROVIDER_NAME,provider),new TelemetryEmitter(PLUGIN_NAME,PLUGIN_VERSION,services).emit("session.provider.ready",{provider:"terminal"}),await provider.init(services)},onShutdown:async()=>{await provider.shutdown({reason:"shutdown"})},onNuke:async(_hostServices,ctx)=>{if(ctx.dryRun)return{reaped:["ttyd terminal servers + session-terminal storage"]};let{terminalsReaped}=await provider.nuke();return{reaped:[`${terminalsReaped} ttyd terminal server${terminalsReaped===1?"":"s"} + session-terminal storage`]}}});return{capabilities:{storage:"rw",subprocess:!0,telemetry:!0},name:PLUGIN_NAME,version:PLUGIN_VERSION,description:"Direct ttyd session provider \u2014 a plain shell over ttyd with no multiplexer and no persisted session",tags:["backend","provider"],apiPrefix:"/api/session-terminal",prerequisites:[{name:"ttyd",kind:"binary",requiresSudo:!1}],createRoutes:()=>createPrereqsRoutes(),onServerStart:lifecycle.onServerStart,onServerStop:lifecycle.onServerStop,onNuke:lifecycle.onNuke}},src_default=factory;export{src_default as default};
|
package/package.json
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@vibecontrols/vibe-plugin-session-terminal",
|
|
3
|
+
"version": "2026.608.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"main": "./dist/index.js",
|
|
6
|
+
"description": "Direct ttyd session provider plugin for VibeControls Agent — a plain shell over ttyd with no multiplexer and no persisted session",
|
|
7
|
+
"engines": {
|
|
8
|
+
"bun": ">=1.3.14"
|
|
9
|
+
},
|
|
10
|
+
"author": {
|
|
11
|
+
"name": "Vignesh T.V",
|
|
12
|
+
"url": "https://github.com/tvvignesh"
|
|
13
|
+
},
|
|
14
|
+
"license": "MIT",
|
|
15
|
+
"scripts": {
|
|
16
|
+
"build": "bun build ./src/index.ts --outdir ./dist --target bun --minify-syntax --minify-whitespace --external elysia && tsc --emitDeclarationOnly --declaration --outDir ./dist",
|
|
17
|
+
"dev": "tsc --watch",
|
|
18
|
+
"lint": "eslint ./src",
|
|
19
|
+
"lint:sanity": "if [ \"${CI:-}\" = \"true\" ]; then bun run lint; else bun run lint -- --cache --cache-location .eslintcache; fi",
|
|
20
|
+
"format": "bunx prettier . --write",
|
|
21
|
+
"format:check": "bunx prettier . --check",
|
|
22
|
+
"type:check": "tsc --noEmit",
|
|
23
|
+
"clean": "rimraf dist",
|
|
24
|
+
"prebuild": "bun run clean",
|
|
25
|
+
"prepublishOnly": "bun run build",
|
|
26
|
+
"sanity": "bun run format:check && bun run lint:sanity && bun run type:check && bun run build"
|
|
27
|
+
},
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"@vibecontrols/plugin-sdk": "2026.601.1",
|
|
30
|
+
"elysia": "^1.4.28"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@eslint/js": "^10.0.1",
|
|
34
|
+
"@types/bun": "^1.3.9",
|
|
35
|
+
"@types/node": "^22.0.0",
|
|
36
|
+
"eslint": "^9.30.1",
|
|
37
|
+
"globals": "^17.3.0",
|
|
38
|
+
"prettier": "^3.6.2",
|
|
39
|
+
"rimraf": "^6.0.1",
|
|
40
|
+
"typescript": "^5.9.3",
|
|
41
|
+
"typescript-eslint": "^8.56.0"
|
|
42
|
+
},
|
|
43
|
+
"peerDependencies": {
|
|
44
|
+
"@vibecontrols/agent": "2026.428.5",
|
|
45
|
+
"@vibecontrols/vibe-plugin-session-manager": "2026.509.1"
|
|
46
|
+
},
|
|
47
|
+
"peerDependenciesMeta": {
|
|
48
|
+
"@vibecontrols/agent": {
|
|
49
|
+
"optional": true
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
"keywords": [
|
|
53
|
+
"vibecontrols",
|
|
54
|
+
"vibe",
|
|
55
|
+
"vibe-plugin",
|
|
56
|
+
"ttyd",
|
|
57
|
+
"terminal",
|
|
58
|
+
"session",
|
|
59
|
+
"bun"
|
|
60
|
+
],
|
|
61
|
+
"repository": {
|
|
62
|
+
"type": "git",
|
|
63
|
+
"url": "git+https://github.com/algoshred/vibe-plugin-session-terminal.git"
|
|
64
|
+
},
|
|
65
|
+
"bugs": {
|
|
66
|
+
"url": "https://github.com/algoshred/vibe-plugin-session-terminal/issues"
|
|
67
|
+
},
|
|
68
|
+
"homepage": "https://vibecontrols.com",
|
|
69
|
+
"publishConfig": {
|
|
70
|
+
"access": "public",
|
|
71
|
+
"registry": "https://registry.npmjs.org/"
|
|
72
|
+
},
|
|
73
|
+
"files": [
|
|
74
|
+
"dist/**/*",
|
|
75
|
+
"!dist/**/*.map",
|
|
76
|
+
"README.md",
|
|
77
|
+
"LICENSE"
|
|
78
|
+
],
|
|
79
|
+
"overrides": {
|
|
80
|
+
"lodash": ">=4.17.21",
|
|
81
|
+
"lodash-es": ">=4.17.21",
|
|
82
|
+
"dompurify": ">=3.3.4",
|
|
83
|
+
"fast-xml-parser": ">=4.5.5",
|
|
84
|
+
"@xmldom/xmldom": ">=0.8.12",
|
|
85
|
+
"swiper": ">=12.1.2",
|
|
86
|
+
"brace-expansion": ">=1.1.13",
|
|
87
|
+
"follow-redirects": ">=1.15.12",
|
|
88
|
+
"smol-toml": ">=1.6.1",
|
|
89
|
+
"axios": ">=1.15.0",
|
|
90
|
+
"flatted": ">=3.4.1",
|
|
91
|
+
"yaml": ">=2.8.3",
|
|
92
|
+
"picomatch": ">=2.3.2",
|
|
93
|
+
"immutable": ">=3.8.3",
|
|
94
|
+
"minimatch": ">=3.1.3"
|
|
95
|
+
}
|
|
96
|
+
}
|