kimaki 0.4.77 → 0.4.78

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/dist/cli.js CHANGED
@@ -735,6 +735,16 @@ async function registerCommands({ token, appId, guildIds, userCommands = [], age
735
735
  .setDescription('List and manage MCP servers for this project')
736
736
  .setDMPermission(false)
737
737
  .toJSON(),
738
+ new SlashCommandBuilder()
739
+ .setName('screenshare')
740
+ .setDescription('Start screen sharing via VNC tunnel (auto-stops after 1 hour)')
741
+ .setDMPermission(false)
742
+ .toJSON(),
743
+ new SlashCommandBuilder()
744
+ .setName('screenshare-stop')
745
+ .setDescription('Stop screen sharing')
746
+ .setDMPermission(false)
747
+ .toJSON(),
738
748
  ];
739
749
  // Add user-defined commands with source-based suffixes (-cmd / -skill)
740
750
  // Also populate registeredUserCommands in the store for /queue-command autocomplete
@@ -2937,6 +2947,23 @@ cli
2937
2947
  command: command.length > 0 ? command : undefined,
2938
2948
  });
2939
2949
  });
2950
+ cli
2951
+ .command('screenshare', 'Share your screen via VNC tunnel. Auto-stops after 1 hour. Runs until Ctrl+C. Use tmux to run in background.')
2952
+ .action(async () => {
2953
+ const { startScreenshare } = await import('./commands/screenshare.js');
2954
+ try {
2955
+ const session = await startScreenshare({
2956
+ sessionKey: 'cli',
2957
+ startedBy: 'cli',
2958
+ });
2959
+ cliLogger.log(`Screen sharing started: ${session.noVncUrl}`);
2960
+ cliLogger.log('Press Ctrl+C to stop');
2961
+ }
2962
+ catch (err) {
2963
+ cliLogger.error('Failed to start screen share:', err instanceof Error ? err.message : String(err));
2964
+ process.exit(EXIT_NO_RESTART);
2965
+ }
2966
+ });
2940
2967
  cli
2941
2968
  .command('sqlitedb', 'Show the location of the SQLite database file')
2942
2969
  .action(() => {
@@ -3,7 +3,7 @@ import { ChannelType, EmbedBuilder, MessageFlags, } from 'discord.js';
3
3
  import path from 'node:path';
4
4
  import { resolveWorkingDirectory, SILENT_MESSAGE_FLAGS, } from '../discord-utils.js';
5
5
  import { createLogger, LogPrefix } from '../logger.js';
6
- import { execAsync } from '../worktrees.js';
6
+ import { uploadGitDiffViaCritique } from '../critique-utils.js';
7
7
  const logger = createLogger(LogPrefix.DIFF);
8
8
  export async function handleDiffCommand({ command, }) {
9
9
  const channel = command.channel;
@@ -39,90 +39,25 @@ export async function handleDiffCommand({ command, }) {
39
39
  }
40
40
  const { workingDirectory } = resolved;
41
41
  await command.deferReply({ flags: SILENT_MESSAGE_FLAGS });
42
- try {
43
- const projectName = path.basename(workingDirectory);
44
- const title = `${projectName}: Discord /diff`;
45
- const { stdout, stderr } = await execAsync(`bunx critique --web "${title}" --json`, {
46
- cwd: workingDirectory,
47
- timeout: 30000,
48
- });
49
- // critique --json outputs JSON on the last line: {"url":"...","id":"..."} or {"error":"..."}
50
- const output = stdout || stderr;
51
- const lines = output.trim().split('\n');
52
- const jsonLine = lines[lines.length - 1];
53
- if (!jsonLine) {
54
- await command.editReply({
55
- content: 'No changes to show',
56
- });
57
- return;
58
- }
59
- let result;
60
- try {
61
- result = JSON.parse(jsonLine);
62
- }
63
- catch {
64
- // Fallback: try to find URL in output
65
- const urlMatch = output.match(/https?:\/\/critique\.work\/[^\s]+/);
66
- if (urlMatch) {
67
- await command.editReply({
68
- content: `[diff](${urlMatch[0]})`,
69
- });
70
- logger.log(`Diff shared: ${urlMatch[0]}`);
71
- return;
72
- }
73
- await command.editReply({
74
- content: 'No changes to show',
75
- });
76
- return;
77
- }
78
- if (result.error || !result.url || !result.id) {
79
- await command.editReply({
80
- content: result.error || 'No changes to show',
81
- });
82
- return;
83
- }
84
- const imageUrl = `https://critique.work/og/${result.id}.png`;
85
- const embed = new EmbedBuilder()
86
- .setTitle(title)
87
- .setURL(result.url)
88
- .setImage(imageUrl);
89
- await command.editReply({
90
- embeds: [embed],
91
- });
92
- logger.log(`Diff shared: ${result.url}`);
42
+ const projectName = path.basename(workingDirectory);
43
+ const title = `${projectName}: Discord /diff`;
44
+ const result = await uploadGitDiffViaCritique({
45
+ title,
46
+ cwd: workingDirectory,
47
+ });
48
+ if (!result) {
49
+ await command.editReply({ content: 'No changes to show' });
50
+ return;
93
51
  }
94
- catch (error) {
95
- logger.error('[DIFF] Error:', error);
96
- // exec error includes stdout/stderr - try to parse JSON from it
97
- const execError = error;
98
- const output = execError.stdout || execError.stderr || '';
99
- // Check if critique output JSON even on error
100
- const lines = output.trim().split('\n');
101
- const jsonLine = lines[lines.length - 1];
102
- if (jsonLine) {
103
- try {
104
- const result = JSON.parse(jsonLine);
105
- if (result.error) {
106
- await command.editReply({
107
- content: result.error,
108
- });
109
- return;
110
- }
111
- }
112
- catch {
113
- // not JSON, continue to generic error
114
- }
115
- }
116
- // Check for common errors
117
- const message = execError.message || 'Unknown error';
118
- if (message.includes('command not found') || message.includes('ENOENT')) {
119
- await command.editReply({
120
- content: 'bunx/critique not available',
121
- });
122
- return;
123
- }
124
- await command.editReply({
125
- content: `Failed to generate diff: ${message.slice(0, 200)}`,
126
- });
52
+ if (result.error || !result.url) {
53
+ await command.editReply({ content: result.error || 'No changes to show' });
54
+ return;
127
55
  }
56
+ const imageUrl = `https://critique.work/og/${result.id}.png`;
57
+ const embed = new EmbedBuilder()
58
+ .setTitle(title)
59
+ .setURL(result.url)
60
+ .setImage(imageUrl);
61
+ await command.editReply({ embeds: [embed] });
62
+ logger.log(`Diff shared: ${result.url}`);
128
63
  }
@@ -0,0 +1,295 @@
1
+ // /screenshare command - Start screen sharing via VNC + WebSocket bridge + kimaki tunnel.
2
+ // On macOS: uses built-in Screen Sharing (port 5900).
3
+ // On Linux: spawns x11vnc against the current $DISPLAY.
4
+ // Exposes the VNC stream via an in-process websockify bridge and a traforo tunnel,
5
+ // then sends the user a noVNC URL they can open in a browser.
6
+ //
7
+ // /screenshare-stop command - Stops the active screen share for this guild.
8
+ import { MessageFlags } from 'discord.js';
9
+ import crypto from 'node:crypto';
10
+ import { spawn } from 'node:child_process';
11
+ import net from 'node:net';
12
+ import { TunnelClient } from 'traforo/client';
13
+ import { SILENT_MESSAGE_FLAGS } from '../discord-utils.js';
14
+ import { startWebsockify } from '../websockify.js';
15
+ import { createLogger } from '../logger.js';
16
+ import { execAsync } from '../worktrees.js';
17
+ const logger = createLogger('SCREEN');
18
+ /** One active screenshare per guild (Discord) or per machine (CLI) */
19
+ const activeSessions = new Map();
20
+ const VNC_PORT = 5900;
21
+ const MAX_SESSION_MS = 60 * 60 * 1000; // 1 hour
22
+ const TUNNEL_BASE_DOMAIN = 'kimaki.xyz';
23
+ // Public noVNC client — we point it at our tunnel URL
24
+ export function buildNoVncUrl({ tunnelHost }) {
25
+ const params = new URLSearchParams({
26
+ autoconnect: 'true',
27
+ host: tunnelHost,
28
+ port: '443',
29
+ encrypt: '1',
30
+ resize: 'scale',
31
+ view_only: 'false',
32
+ });
33
+ return `https://novnc.com/noVNC/vnc.html?${params.toString()}`;
34
+ }
35
+ // macOS has two separate services:
36
+ // - "Screen Sharing" = view-only VNC (com.apple.screensharing)
37
+ // - "Remote Management" = full control VNC with mouse/keyboard (ARDAgent)
38
+ // We need Remote Management for interactive control, not just Screen Sharing.
39
+ export async function ensureMacRemoteManagement() {
40
+ // Check if port 5900 is listening via netstat (no sudo needed).
41
+ // lsof and launchctl list both require sudo for system daemons.
42
+ try {
43
+ const { stdout } = await execAsync('netstat -an | grep "\\.5900 " | grep LISTEN', { timeout: 5000 });
44
+ if (stdout.trim()) {
45
+ return;
46
+ }
47
+ }
48
+ catch {
49
+ // not listening
50
+ }
51
+ throw new Error('macOS Remote Management is not enabled.\n' +
52
+ 'Enable it: **System Settings > General > Sharing > Remote Management**\n' +
53
+ 'Make sure "VNC viewers may control screen with password" is enabled.\n' +
54
+ 'Or via terminal:\n' +
55
+ '```\nsudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart \\\n' +
56
+ ' -activate -configure -allowAccessFor -allUsers -privs -all \\\n' +
57
+ ' -clientopts -setvnclegacy -vnclegacy yes \\\n' +
58
+ ' -restart -agent -console\n```');
59
+ }
60
+ export function spawnX11Vnc() {
61
+ const display = process.env['DISPLAY'] || ':0';
62
+ const child = spawn('x11vnc', [
63
+ '-display', display,
64
+ '-nopw',
65
+ '-localhost',
66
+ '-rfbport', String(VNC_PORT),
67
+ '-shared',
68
+ '-forever',
69
+ ], {
70
+ stdio: ['ignore', 'pipe', 'pipe'],
71
+ });
72
+ child.stdout?.on('data', (data) => {
73
+ logger.log(`x11vnc: ${data.toString().trim()}`);
74
+ });
75
+ child.stderr?.on('data', (data) => {
76
+ logger.error(`x11vnc: ${data.toString().trim()}`);
77
+ });
78
+ return child;
79
+ }
80
+ function waitForPort({ port, process: proc, timeoutMs, }) {
81
+ return new Promise((resolve, reject) => {
82
+ const maxAttempts = Math.ceil(timeoutMs / 100);
83
+ let attempts = 0;
84
+ const check = () => {
85
+ if (proc.exitCode !== null) {
86
+ reject(new Error(`x11vnc exited with code ${proc.exitCode} before becoming ready`));
87
+ return;
88
+ }
89
+ const sock = net.createConnection(port, 'localhost');
90
+ sock.on('connect', () => {
91
+ sock.destroy();
92
+ resolve();
93
+ });
94
+ sock.on('error', () => {
95
+ sock.destroy();
96
+ if (++attempts >= maxAttempts) {
97
+ reject(new Error(`Port ${port} not reachable after ${timeoutMs}ms`));
98
+ }
99
+ else {
100
+ setTimeout(check, 100);
101
+ }
102
+ });
103
+ };
104
+ check();
105
+ });
106
+ }
107
+ export function cleanupSession(session) {
108
+ clearTimeout(session.timeoutTimer);
109
+ try {
110
+ session.tunnelClient.close();
111
+ }
112
+ catch { }
113
+ try {
114
+ session.wss.close();
115
+ }
116
+ catch { }
117
+ if (session.vncProcess) {
118
+ try {
119
+ session.vncProcess.kill();
120
+ }
121
+ catch { }
122
+ }
123
+ }
124
+ /**
125
+ * Core screenshare start logic, reused by both Discord command and CLI.
126
+ * Returns the session or throws on failure.
127
+ */
128
+ export async function startScreenshare({ sessionKey, startedBy, }) {
129
+ const existing = activeSessions.get(sessionKey);
130
+ if (existing) {
131
+ throw new Error(`Screen sharing is already active: ${existing.noVncUrl}`);
132
+ }
133
+ const platform = process.platform;
134
+ let vncProcess;
135
+ // Step 1: ensure VNC server is running
136
+ if (platform === 'darwin') {
137
+ await ensureMacRemoteManagement();
138
+ }
139
+ else if (platform === 'linux') {
140
+ if (!process.env['DISPLAY']) {
141
+ throw new Error('No $DISPLAY found. Screen sharing requires a running X11 display.');
142
+ }
143
+ try {
144
+ await execAsync('which x11vnc', { timeout: 3000 });
145
+ }
146
+ catch {
147
+ throw new Error('x11vnc is not installed. Install it with: sudo apt install x11vnc');
148
+ }
149
+ vncProcess = spawnX11Vnc();
150
+ // Wait for x11vnc to actually be ready (port 5900 accepting connections)
151
+ // instead of a blind 1s sleep. Polls every 100ms, fails if process exits first.
152
+ await waitForPort({ port: VNC_PORT, process: vncProcess, timeoutMs: 3000 });
153
+ }
154
+ else {
155
+ throw new Error(`Screen sharing is not supported on ${platform}. Only macOS and Linux are supported.`);
156
+ }
157
+ // Step 2: start in-process websockify bridge
158
+ let wsInstance;
159
+ try {
160
+ wsInstance = await startWebsockify({
161
+ wsPort: 0,
162
+ tcpHost: 'localhost',
163
+ tcpPort: VNC_PORT,
164
+ });
165
+ }
166
+ catch (err) {
167
+ if (vncProcess) {
168
+ vncProcess.kill();
169
+ }
170
+ throw err;
171
+ }
172
+ // Step 3: create tunnel
173
+ const tunnelId = crypto.randomBytes(8).toString('hex');
174
+ const tunnelClient = new TunnelClient({
175
+ localPort: wsInstance.port,
176
+ tunnelId,
177
+ baseDomain: TUNNEL_BASE_DOMAIN,
178
+ });
179
+ try {
180
+ await Promise.race([
181
+ tunnelClient.connect(),
182
+ new Promise((_, reject) => {
183
+ setTimeout(() => {
184
+ reject(new Error('Tunnel connection timed out after 15s'));
185
+ }, 15000);
186
+ }),
187
+ ]);
188
+ }
189
+ catch (err) {
190
+ tunnelClient.close();
191
+ wsInstance.close();
192
+ if (vncProcess) {
193
+ vncProcess.kill();
194
+ }
195
+ throw err;
196
+ }
197
+ const tunnelHost = `${tunnelId}-tunnel.${TUNNEL_BASE_DOMAIN}`;
198
+ const tunnelUrl = `https://${tunnelHost}`;
199
+ const noVncUrl = buildNoVncUrl({ tunnelHost });
200
+ // Auto-kill after 1 hour
201
+ const timeoutTimer = setTimeout(() => {
202
+ logger.log(`Screen share auto-stopped after 1 hour (key: ${sessionKey})`);
203
+ stopScreenshare({ sessionKey });
204
+ }, MAX_SESSION_MS);
205
+ // Don't keep the process alive just for this timer
206
+ timeoutTimer.unref();
207
+ const session = {
208
+ tunnelClient,
209
+ wss: wsInstance.wss,
210
+ vncProcess,
211
+ url: tunnelUrl,
212
+ noVncUrl,
213
+ startedBy,
214
+ startedAt: Date.now(),
215
+ timeoutTimer,
216
+ };
217
+ activeSessions.set(sessionKey, session);
218
+ logger.log(`Screen share started by ${startedBy}: ${tunnelUrl}`);
219
+ return session;
220
+ }
221
+ /**
222
+ * Core screenshare stop logic, reused by both Discord command and CLI.
223
+ */
224
+ export function stopScreenshare({ sessionKey }) {
225
+ const session = activeSessions.get(sessionKey);
226
+ if (!session) {
227
+ return false;
228
+ }
229
+ cleanupSession(session);
230
+ activeSessions.delete(sessionKey);
231
+ logger.log(`Screen share stopped (key: ${sessionKey})`);
232
+ return true;
233
+ }
234
+ export async function handleScreenshareCommand({ command, }) {
235
+ const guildId = command.guildId;
236
+ if (!guildId) {
237
+ await command.reply({
238
+ content: 'This command can only be used in a server',
239
+ flags: MessageFlags.Ephemeral | SILENT_MESSAGE_FLAGS,
240
+ });
241
+ return;
242
+ }
243
+ await command.deferReply({ flags: SILENT_MESSAGE_FLAGS });
244
+ try {
245
+ const session = await startScreenshare({
246
+ sessionKey: guildId,
247
+ startedBy: command.user.tag,
248
+ });
249
+ await command.editReply({
250
+ content: `Screen sharing started\n${session.noVncUrl}`,
251
+ });
252
+ }
253
+ catch (err) {
254
+ logger.error('Failed to start screen share:', err);
255
+ await command.editReply({
256
+ content: `Failed to start screen share: ${err instanceof Error ? err.message : String(err)}`,
257
+ });
258
+ }
259
+ }
260
+ export async function handleScreenshareStopCommand({ command, }) {
261
+ const guildId = command.guildId;
262
+ if (!guildId) {
263
+ await command.reply({
264
+ content: 'This command can only be used in a server',
265
+ flags: MessageFlags.Ephemeral | SILENT_MESSAGE_FLAGS,
266
+ });
267
+ return;
268
+ }
269
+ const stopped = stopScreenshare({ sessionKey: guildId });
270
+ if (!stopped) {
271
+ await command.reply({
272
+ content: 'No active screen share to stop',
273
+ flags: MessageFlags.Ephemeral | SILENT_MESSAGE_FLAGS,
274
+ });
275
+ return;
276
+ }
277
+ await command.reply({
278
+ content: 'Screen sharing stopped',
279
+ flags: SILENT_MESSAGE_FLAGS,
280
+ });
281
+ }
282
+ /** Cleanup all sessions on bot shutdown */
283
+ export function cleanupAllScreenshares() {
284
+ for (const [guildId, session] of activeSessions) {
285
+ cleanupSession(session);
286
+ activeSessions.delete(guildId);
287
+ }
288
+ }
289
+ // Kill all screenshares when the process exits (Ctrl+C, SIGTERM, etc.)
290
+ function onProcessExit() {
291
+ cleanupAllScreenshares();
292
+ }
293
+ process.on('SIGINT', onProcessExit);
294
+ process.on('SIGTERM', onProcessExit);
295
+ process.on('exit', onProcessExit);
@@ -0,0 +1,95 @@
1
+ // Shared utilities for invoking the critique CLI and parsing its JSON output.
2
+ // Used by /diff command and footer diff link uploads.
3
+ import { execAsync } from './worktrees.js';
4
+ import { createLogger, LogPrefix } from './logger.js';
5
+ const logger = createLogger(LogPrefix.DIFF);
6
+ const CRITIQUE_TIMEOUT_MS = 30_000;
7
+ /**
8
+ * Shell-quote a string by wrapping in single quotes and escaping embedded
9
+ * single quotes. Prevents injection when interpolating into shell commands.
10
+ */
11
+ function shellQuote(s) {
12
+ return `'${s.replace(/'/g, "'\\''")}'`;
13
+ }
14
+ /**
15
+ * Parse critique --json output. Critique prints progress to stderr and JSON
16
+ * to stdout. The JSON line contains { url, id } on success or { error } on
17
+ * failure. We scan all lines for the first valid JSON object with a url or
18
+ * error field, falling back to searching for a critique.work URL in the raw
19
+ * output.
20
+ */
21
+ export function parseCritiqueOutput(output) {
22
+ const lines = output.trim().split('\n');
23
+ for (const line of lines) {
24
+ if (!line.startsWith('{')) {
25
+ continue;
26
+ }
27
+ try {
28
+ const parsed = JSON.parse(line);
29
+ if (parsed.error) {
30
+ return { error: parsed.error };
31
+ }
32
+ if (parsed.url && parsed.id) {
33
+ return { url: parsed.url, id: parsed.id };
34
+ }
35
+ }
36
+ catch {
37
+ // not valid JSON, try next line
38
+ }
39
+ }
40
+ // Fallback: try to find a URL in the raw output
41
+ const urlMatch = output.match(/https?:\/\/critique\.work\/[^\s]+/);
42
+ if (urlMatch) {
43
+ const url = urlMatch[0];
44
+ // Extract ID from URL path: /v/{id}
45
+ const idMatch = url.match(/\/v\/([a-f0-9]+)/);
46
+ const id = idMatch?.[1];
47
+ if (id) {
48
+ return { url, id };
49
+ }
50
+ // URL without parseable id — return as error so callers don't build
51
+ // broken OG image URLs from an empty id
52
+ return { error: url };
53
+ }
54
+ return undefined;
55
+ }
56
+ /**
57
+ * Run critique on the current git working tree diff and return the result.
58
+ * Used by the /diff slash command.
59
+ */
60
+ export async function uploadGitDiffViaCritique({ title, cwd, }) {
61
+ try {
62
+ const { stdout, stderr } = await execAsync(`critique --web ${shellQuote(title)} --json`, { cwd, timeout: CRITIQUE_TIMEOUT_MS });
63
+ return parseCritiqueOutput(stdout || stderr);
64
+ }
65
+ catch (error) {
66
+ // exec error includes stdout/stderr — try to parse JSON from it
67
+ const execError = error;
68
+ const output = execError.stdout || execError.stderr || '';
69
+ const parsed = parseCritiqueOutput(output);
70
+ if (parsed) {
71
+ return parsed;
72
+ }
73
+ const message = execError.message || 'Unknown error';
74
+ if (message.includes('command not found') || message.includes('ENOENT')) {
75
+ return { error: 'critique not available' };
76
+ }
77
+ return { error: `Failed to generate diff: ${message.slice(0, 200)}` };
78
+ }
79
+ }
80
+ /**
81
+ * Upload a .patch file to critique.work via critique --stdin.
82
+ * Returns the critique URL on success, undefined on failure.
83
+ * Default timeout is 10s since this runs in the background (footer edit).
84
+ */
85
+ export async function uploadPatchViaCritique({ patchPath, title, cwd, timeoutMs = 10_000, }) {
86
+ try {
87
+ const { stdout } = await execAsync(`critique --stdin --web ${shellQuote(title)} --json < ${shellQuote(patchPath)}`, { cwd, timeout: timeoutMs });
88
+ const result = parseCritiqueOutput(stdout);
89
+ return result?.url;
90
+ }
91
+ catch (error) {
92
+ logger.error('critique upload failed:', error);
93
+ return undefined;
94
+ }
95
+ }