kimaki 0.4.76 → 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.
Files changed (162) hide show
  1. package/dist/adapter-rest-boundary.test.js +34 -0
  2. package/dist/agent-model.e2e.test.js +2 -20
  3. package/dist/cli.js +50 -13
  4. package/dist/commands/channel-ref.js +16 -0
  5. package/dist/commands/diff.js +20 -85
  6. package/dist/commands/merge-worktree.js +5 -17
  7. package/dist/commands/new-worktree.js +5 -9
  8. package/dist/commands/permissions.js +77 -11
  9. package/dist/commands/resume.js +5 -9
  10. package/dist/commands/screenshare.js +295 -0
  11. package/dist/commands/session.js +6 -17
  12. package/dist/critique-utils.js +95 -0
  13. package/dist/diff-patch-plugin.js +314 -0
  14. package/dist/discord-bot.js +19 -14
  15. package/dist/discord-js-import-boundary.test.js +62 -0
  16. package/dist/discord-utils.js +44 -0
  17. package/dist/event-stream-real-capture.e2e.test.js +2 -20
  18. package/dist/gateway-proxy.e2e.test.js +2 -5
  19. package/dist/generated/cloudflare/browser.js +17 -0
  20. package/dist/generated/cloudflare/client.js +34 -0
  21. package/dist/generated/cloudflare/commonInputTypes.js +10 -0
  22. package/dist/generated/cloudflare/enums.js +48 -0
  23. package/dist/generated/cloudflare/internal/class.js +47 -0
  24. package/dist/generated/cloudflare/internal/prismaNamespace.js +252 -0
  25. package/dist/generated/cloudflare/internal/prismaNamespaceBrowser.js +222 -0
  26. package/dist/generated/cloudflare/internal/query_compiler_fast_bg.js +135 -0
  27. package/dist/generated/cloudflare/models/bot_api_keys.js +1 -0
  28. package/dist/generated/cloudflare/models/bot_tokens.js +1 -0
  29. package/dist/generated/cloudflare/models/channel_agents.js +1 -0
  30. package/dist/generated/cloudflare/models/channel_directories.js +1 -0
  31. package/dist/generated/cloudflare/models/channel_mention_mode.js +1 -0
  32. package/dist/generated/cloudflare/models/channel_models.js +1 -0
  33. package/dist/generated/cloudflare/models/channel_verbosity.js +1 -0
  34. package/dist/generated/cloudflare/models/channel_worktrees.js +1 -0
  35. package/dist/generated/cloudflare/models/forum_sync_configs.js +1 -0
  36. package/dist/generated/cloudflare/models/global_models.js +1 -0
  37. package/dist/generated/cloudflare/models/ipc_requests.js +1 -0
  38. package/dist/generated/cloudflare/models/part_messages.js +1 -0
  39. package/dist/generated/cloudflare/models/scheduled_tasks.js +1 -0
  40. package/dist/generated/cloudflare/models/session_agents.js +1 -0
  41. package/dist/generated/cloudflare/models/session_events.js +1 -0
  42. package/dist/generated/cloudflare/models/session_models.js +1 -0
  43. package/dist/generated/cloudflare/models/session_start_sources.js +1 -0
  44. package/dist/generated/cloudflare/models/thread_sessions.js +1 -0
  45. package/dist/generated/cloudflare/models/thread_worktrees.js +1 -0
  46. package/dist/generated/cloudflare/models.js +1 -0
  47. package/dist/generated/node/browser.js +17 -0
  48. package/dist/generated/node/client.js +37 -0
  49. package/dist/generated/node/commonInputTypes.js +10 -0
  50. package/dist/generated/node/enums.js +48 -0
  51. package/dist/generated/node/internal/class.js +49 -0
  52. package/dist/generated/node/internal/prismaNamespace.js +252 -0
  53. package/dist/generated/node/internal/prismaNamespaceBrowser.js +222 -0
  54. package/dist/generated/node/models/bot_api_keys.js +1 -0
  55. package/dist/generated/node/models/bot_tokens.js +1 -0
  56. package/dist/generated/node/models/channel_agents.js +1 -0
  57. package/dist/generated/node/models/channel_directories.js +1 -0
  58. package/dist/generated/node/models/channel_mention_mode.js +1 -0
  59. package/dist/generated/node/models/channel_models.js +1 -0
  60. package/dist/generated/node/models/channel_verbosity.js +1 -0
  61. package/dist/generated/node/models/channel_worktrees.js +1 -0
  62. package/dist/generated/node/models/forum_sync_configs.js +1 -0
  63. package/dist/generated/node/models/global_models.js +1 -0
  64. package/dist/generated/node/models/ipc_requests.js +1 -0
  65. package/dist/generated/node/models/part_messages.js +1 -0
  66. package/dist/generated/node/models/scheduled_tasks.js +1 -0
  67. package/dist/generated/node/models/session_agents.js +1 -0
  68. package/dist/generated/node/models/session_events.js +1 -0
  69. package/dist/generated/node/models/session_models.js +1 -0
  70. package/dist/generated/node/models/session_start_sources.js +1 -0
  71. package/dist/generated/node/models/thread_sessions.js +1 -0
  72. package/dist/generated/node/models/thread_worktrees.js +1 -0
  73. package/dist/generated/node/models.js +1 -0
  74. package/dist/interaction-handler.js +10 -0
  75. package/dist/kimaki-digital-twin.e2e.test.js +2 -20
  76. package/dist/message-flags-boundary.test.js +54 -0
  77. package/dist/message-formatting.js +3 -62
  78. package/dist/onboarding-tutorial-plugin.js +1 -1
  79. package/dist/opencode-command.js +129 -0
  80. package/dist/opencode-command.test.js +48 -0
  81. package/dist/opencode-interrupt-plugin.js +19 -1
  82. package/dist/opencode-interrupt-plugin.test.js +0 -5
  83. package/dist/opencode-plugin-loading.e2e.test.js +9 -20
  84. package/dist/opencode-plugin.js +4 -4
  85. package/dist/opencode.js +150 -27
  86. package/dist/patch-text-parser.js +97 -0
  87. package/dist/platform/components-v2.js +20 -0
  88. package/dist/platform/discord-adapter.js +1440 -0
  89. package/dist/platform/discord-routes.js +31 -0
  90. package/dist/platform/message-flags.js +8 -0
  91. package/dist/platform/platform-value.js +41 -0
  92. package/dist/platform/slack-adapter.js +872 -0
  93. package/dist/platform/slack-markdown.js +169 -0
  94. package/dist/platform/types.js +4 -0
  95. package/dist/queue-advanced-e2e-setup.js +265 -0
  96. package/dist/queue-advanced-footer.e2e.test.js +173 -0
  97. package/dist/queue-advanced-model-switch.e2e.test.js +299 -0
  98. package/dist/queue-advanced-permissions-typing.e2e.test.js +73 -1
  99. package/dist/runtime-lifecycle.e2e.test.js +2 -20
  100. package/dist/session-handler/event-stream-state.js +5 -0
  101. package/dist/session-handler/event-stream-state.test.js +6 -2
  102. package/dist/session-handler/thread-session-runtime.js +32 -2
  103. package/dist/system-message.js +26 -23
  104. package/dist/test-utils.js +16 -0
  105. package/dist/thread-message-queue.e2e.test.js +2 -20
  106. package/dist/utils.js +3 -1
  107. package/dist/voice-message.e2e.test.js +2 -20
  108. package/dist/voice.js +122 -9
  109. package/dist/voice.test.js +17 -2
  110. package/dist/websockify.js +69 -0
  111. package/dist/worktree-lifecycle.e2e.test.js +308 -0
  112. package/package.json +4 -2
  113. package/skills/critique/SKILL.md +17 -0
  114. package/skills/egaki/SKILL.md +35 -0
  115. package/skills/event-sourcing-state/SKILL.md +252 -0
  116. package/skills/goke/SKILL.md +1 -0
  117. package/skills/npm-package/SKILL.md +21 -2
  118. package/skills/playwriter/SKILL.md +1 -1
  119. package/skills/x-articles/SKILL.md +554 -0
  120. package/src/agent-model.e2e.test.ts +4 -19
  121. package/src/cli.ts +60 -13
  122. package/src/commands/diff.ts +25 -99
  123. package/src/commands/merge-worktree.ts +5 -21
  124. package/src/commands/new-worktree.ts +5 -11
  125. package/src/commands/permissions.ts +100 -15
  126. package/src/commands/resume.ts +5 -12
  127. package/src/commands/screenshare.ts +354 -0
  128. package/src/commands/session.ts +6 -23
  129. package/src/critique-utils.ts +139 -0
  130. package/src/discord-bot.ts +20 -15
  131. package/src/discord-utils.ts +53 -0
  132. package/src/event-stream-real-capture.e2e.test.ts +4 -20
  133. package/src/gateway-proxy.e2e.test.ts +2 -5
  134. package/src/interaction-handler.ts +15 -0
  135. package/src/kimaki-digital-twin.e2e.test.ts +2 -21
  136. package/src/message-formatting.ts +3 -68
  137. package/src/onboarding-tutorial-plugin.ts +1 -1
  138. package/src/opencode-command.test.ts +70 -0
  139. package/src/opencode-command.ts +188 -0
  140. package/src/opencode-interrupt-plugin.test.ts +0 -5
  141. package/src/opencode-interrupt-plugin.ts +34 -1
  142. package/src/opencode-plugin-loading.e2e.test.ts +25 -35
  143. package/src/opencode-plugin.ts +5 -4
  144. package/src/opencode.ts +199 -32
  145. package/src/patch-text-parser.ts +107 -0
  146. package/src/queue-advanced-e2e-setup.ts +273 -0
  147. package/src/queue-advanced-footer.e2e.test.ts +211 -0
  148. package/src/queue-advanced-model-switch.e2e.test.ts +383 -0
  149. package/src/queue-advanced-permissions-typing.e2e.test.ts +92 -0
  150. package/src/runtime-lifecycle.e2e.test.ts +4 -19
  151. package/src/session-handler/event-stream-state.test.ts +6 -2
  152. package/src/session-handler/event-stream-state.ts +5 -0
  153. package/src/session-handler/thread-session-runtime.ts +45 -2
  154. package/src/system-message.ts +26 -23
  155. package/src/test-utils.ts +17 -0
  156. package/src/thread-message-queue.e2e.test.ts +2 -20
  157. package/src/utils.ts +3 -1
  158. package/src/voice-message.e2e.test.ts +3 -20
  159. package/src/voice.test.ts +26 -2
  160. package/src/voice.ts +147 -9
  161. package/src/websockify.ts +101 -0
  162. package/src/worktree-lifecycle.e2e.test.ts +391 -0
@@ -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);
@@ -4,7 +4,7 @@ import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { getChannelDirectory } from '../database.js';
6
6
  import { initializeOpencodeForDirectory } from '../opencode.js';
7
- import { SILENT_MESSAGE_FLAGS } from '../discord-utils.js';
7
+ import { SILENT_MESSAGE_FLAGS, resolveProjectDirectoryFromAutocomplete } from '../discord-utils.js';
8
8
  import { getOrCreateRuntime } from '../session-handler/thread-session-runtime.js';
9
9
  import { createLogger, LogPrefix } from '../logger.js';
10
10
  import * as errore from 'errore';
@@ -80,14 +80,10 @@ export async function handleSessionCommand({ command, appId, }) {
80
80
  }
81
81
  async function handleAgentAutocomplete({ interaction, }) {
82
82
  const focusedValue = interaction.options.getFocused();
83
- let projectDirectory;
84
- if (interaction.channel &&
85
- interaction.channel.type === ChannelType.GuildText) {
86
- const channelConfig = await getChannelDirectory(interaction.channel.id);
87
- if (channelConfig) {
88
- projectDirectory = channelConfig.directory;
89
- }
90
- }
83
+ // interaction.channel can be null when the channel isn't cached
84
+ // (common with gateway-proxy). Use channelId which is always available
85
+ // from the raw interaction payload.
86
+ const projectDirectory = await resolveProjectDirectoryFromAutocomplete(interaction);
91
87
  if (!projectDirectory) {
92
88
  await interaction.respond([]);
93
89
  return;
@@ -139,14 +135,7 @@ export async function handleSessionAutocomplete({ interaction, }) {
139
135
  .map((f) => f.trim())
140
136
  .filter((f) => f);
141
137
  const currentQuery = (parts[parts.length - 1] || '').trim();
142
- let projectDirectory;
143
- if (interaction.channel &&
144
- interaction.channel.type === ChannelType.GuildText) {
145
- const channelConfig = await getChannelDirectory(interaction.channel.id);
146
- if (channelConfig) {
147
- projectDirectory = channelConfig.directory;
148
- }
149
- }
138
+ const projectDirectory = await resolveProjectDirectoryFromAutocomplete(interaction);
150
139
  if (!projectDirectory) {
151
140
  await interaction.respond([]);
152
141
  return;
@@ -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
+ }