-
Notifications
You must be signed in to change notification settings - Fork 304
Expand file tree
/
Copy pathindex.ts
More file actions
471 lines (409 loc) · 16.5 KB
/
index.ts
File metadata and controls
471 lines (409 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
/**
* Plannotator Shared Server
*
* Provides a consistent server implementation for both Claude Code and OpenCode plugins.
*
* Environment variables:
* PLANNOTATOR_REMOTE - Set to "1" or "true" for remote/devcontainer mode
* PLANNOTATOR_PORT - Fixed port to use (default: random locally, 19432 for remote)
* PLANNOTATOR_ORIGIN - Origin identifier ("claude-code" or "opencode")
*/
import { resolve } from "path";
import { isRemoteSession, getServerPort, getServerHostname } from "./remote";
import { openEditorDiff } from "./ide";
import {
saveToObsidian,
saveToBear,
type ObsidianConfig,
type BearConfig,
type IntegrationResult,
} from "./integrations";
import {
generateSlug,
savePlan,
saveAnnotations,
saveFinalSnapshot,
saveToHistory,
getPlanVersion,
getPlanVersionPath,
getVersionCount,
listVersions,
listProjectPlans,
} from "./storage";
import { getRepoInfo } from "./repo";
import { detectProjectName } from "./project";
import { handleImage, handleUpload, handleAgents, handleServerReady, handleDraftSave, handleDraftLoad, handleDraftDelete, type OpencodeClient } from "./shared-handlers";
import { contentHash, deleteDraft } from "./draft";
import { handleDoc, handleObsidianVaults, handleObsidianFiles, handleObsidianDoc } from "./reference-handlers";
import { createEditorAnnotationHandler } from "./editor-annotations";
// Re-export utilities
export { isRemoteSession, getServerPort, getServerHostname } from "./remote";
export { openBrowser } from "./browser";
export * from "./integrations";
export * from "./storage";
export { handleServerReady } from "./shared-handlers";
export { type VaultNode, buildFileTree } from "./reference-handlers";
// --- Types ---
export interface ServerOptions {
/** The plan markdown content */
plan: string;
/** Origin identifier (e.g., "claude-code", "opencode") */
origin: string;
/** HTML content to serve for the UI */
htmlContent: string;
/** Current permission mode to preserve (Claude Code only) */
permissionMode?: string;
/** Whether URL sharing is enabled (default: true) */
sharingEnabled?: boolean;
/** Custom base URL for share links (default: https://share.plannotator.ai) */
shareBaseUrl?: string;
/** Base URL of the paste service API for short URL sharing */
pasteApiUrl?: string;
/** Called when server starts with the URL, remote status, and port */
onReady?: (url: string, isRemote: boolean, port: number) => void;
/** OpenCode client for querying available agents (OpenCode only) */
opencodeClient?: OpencodeClient;
}
export interface ServerResult {
/** The port the server is running on */
port: number;
/** The full URL to access the server */
url: string;
/** Whether running in remote mode */
isRemote: boolean;
/** Wait for user decision (approve/deny) */
waitForDecision: () => Promise<{
approved: boolean;
feedback?: string;
savedPath?: string;
agentSwitch?: string;
permissionMode?: string;
}>;
/** Stop the server */
stop: () => void;
}
// --- Server Implementation ---
const MAX_RETRIES = 5;
const RETRY_DELAY_MS = 500;
/**
* Start the Plannotator server
*
* Handles:
* - Remote detection and port configuration
* - All API routes (/api/plan, /api/approve, /api/deny, etc.)
* - Obsidian/Bear integrations
* - Port conflict retries
*/
export async function startPlannotatorServer(
options: ServerOptions
): Promise<ServerResult> {
const { plan, origin, htmlContent, permissionMode, sharingEnabled = true, shareBaseUrl, pasteApiUrl, onReady } = options;
const isRemote = isRemoteSession();
const configuredPort = getServerPort();
const hostname = await getServerHostname();
const draftKey = contentHash(plan);
const editorAnnotations = createEditorAnnotationHandler();
// Generate slug for potential saving (actual save happens on decision)
const slug = generateSlug(plan);
// Detect repo info (cached for this session)
const repoInfo = await getRepoInfo();
// Version history: save plan and detect previous version
const project = (await detectProjectName()) ?? "_unknown";
const historyResult = saveToHistory(project, slug, plan);
const currentPlanPath = historyResult.path;
const previousPlan =
historyResult.version > 1
? getPlanVersion(project, slug, historyResult.version - 1)
: null;
const versionInfo = {
version: historyResult.version,
totalVersions: getVersionCount(project, slug),
project,
};
// Decision promise
let resolveDecision: (result: {
approved: boolean;
feedback?: string;
savedPath?: string;
agentSwitch?: string;
permissionMode?: string;
}) => void;
const decisionPromise = new Promise<{
approved: boolean;
feedback?: string;
savedPath?: string;
agentSwitch?: string;
permissionMode?: string;
}>((resolve) => {
resolveDecision = resolve;
});
// Start server with retry logic
let server: ReturnType<typeof Bun.serve> | null = null;
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
try {
server = Bun.serve({
port: configuredPort,
hostname: hostname !== "localhost" ? "0.0.0.0" : undefined,
async fetch(req) {
const url = new URL(req.url);
// API: Get a specific plan version from history
if (url.pathname === "/api/plan/version") {
const vParam = url.searchParams.get("v");
if (!vParam) {
return new Response("Missing v parameter", { status: 400 });
}
const v = parseInt(vParam, 10);
if (isNaN(v) || v < 1) {
return new Response("Invalid version number", { status: 400 });
}
const content = getPlanVersion(project, slug, v);
if (content === null) {
return Response.json({ error: "Version not found" }, { status: 404 });
}
return Response.json({ plan: content, version: v });
}
// API: List all versions for the current plan
if (url.pathname === "/api/plan/versions") {
return Response.json({
project,
slug,
versions: listVersions(project, slug),
});
}
// API: List all plans in the current project
if (url.pathname === "/api/plan/history") {
return Response.json({
project,
plans: listProjectPlans(project),
});
}
// API: Get plan content
if (url.pathname === "/api/plan") {
return Response.json({ plan, origin, permissionMode, sharingEnabled, shareBaseUrl, pasteApiUrl, repoInfo, previousPlan, versionInfo });
}
// API: Serve a linked markdown document
if (url.pathname === "/api/doc" && req.method === "GET") {
return handleDoc(req);
}
// API: Serve images (local paths or temp uploads)
if (url.pathname === "/api/image") {
return handleImage(req);
}
// API: Upload image -> save to temp -> return path
if (url.pathname === "/api/upload" && req.method === "POST") {
return handleUpload(req);
}
// API: Open plan diff in VS Code
if (url.pathname === "/api/plan/vscode-diff" && req.method === "POST") {
try {
const body = (await req.json()) as { baseVersion: number };
if (!body.baseVersion) {
return Response.json({ error: "Missing baseVersion" }, { status: 400 });
}
const basePath = getPlanVersionPath(project, slug, body.baseVersion);
if (!basePath) {
return Response.json({ error: `Version ${body.baseVersion} not found` }, { status: 404 });
}
const result = await openEditorDiff(basePath, currentPlanPath);
if ("error" in result) {
return Response.json({ error: result.error }, { status: 500 });
}
return Response.json({ ok: true });
} catch (err) {
const message = err instanceof Error ? err.message : "Failed to open VS Code diff";
return Response.json({ error: message }, { status: 500 });
}
}
// API: Detect Obsidian vaults
if (url.pathname === "/api/obsidian/vaults") {
return handleObsidianVaults();
}
// API: List Obsidian vault files as a tree
if (url.pathname === "/api/reference/obsidian/files" && req.method === "GET") {
return handleObsidianFiles(req);
}
// API: Read an Obsidian vault document
if (url.pathname === "/api/reference/obsidian/doc" && req.method === "GET") {
return handleObsidianDoc(req);
}
// API: Get available agents (OpenCode only)
if (url.pathname === "/api/agents") {
return handleAgents(options.opencodeClient);
}
// API: Annotation draft persistence
if (url.pathname === "/api/draft") {
if (req.method === "POST") return handleDraftSave(req, draftKey);
if (req.method === "DELETE") return handleDraftDelete(draftKey);
return handleDraftLoad(draftKey);
}
// API: Editor annotations (VS Code extension)
const editorResponse = await editorAnnotations.handle(req, url);
if (editorResponse) return editorResponse;
// API: Save to notes (decoupled from approve/deny)
if (url.pathname === "/api/save-notes" && req.method === "POST") {
const results: { obsidian?: IntegrationResult; bear?: IntegrationResult } = {};
try {
const body = (await req.json()) as {
obsidian?: ObsidianConfig;
bear?: BearConfig;
};
if (body.obsidian?.vaultPath && body.obsidian?.plan) {
results.obsidian = await saveToObsidian(body.obsidian);
if (results.obsidian.success) {
console.error(`[Obsidian] Saved plan to: ${results.obsidian.path}`);
} else {
console.error(`[Obsidian] Save failed: ${results.obsidian.error}`);
}
}
if (body.bear?.plan) {
results.bear = await saveToBear(body.bear);
if (results.bear.success) {
console.error(`[Bear] Saved plan to Bear`);
} else {
console.error(`[Bear] Save failed: ${results.bear.error}`);
}
}
} catch (err) {
console.error(`[Save Notes] Error:`, err);
return Response.json({ error: "Save failed" }, { status: 500 });
}
return Response.json({ ok: true, results });
}
// API: Approve plan
if (url.pathname === "/api/approve" && req.method === "POST") {
// Check for note integrations and optional feedback
let feedback: string | undefined;
let agentSwitch: string | undefined;
let requestedPermissionMode: string | undefined;
let planSaveEnabled = true; // default to enabled for backwards compat
let planSaveCustomPath: string | undefined;
try {
const body = (await req.json().catch(() => ({}))) as {
obsidian?: ObsidianConfig;
bear?: BearConfig;
feedback?: string;
agentSwitch?: string;
planSave?: { enabled: boolean; customPath?: string };
permissionMode?: string;
};
// Capture feedback if provided (for "approve with notes")
if (body.feedback) {
feedback = body.feedback;
}
// Capture agent switch setting for OpenCode
if (body.agentSwitch) {
agentSwitch = body.agentSwitch;
}
// Capture permission mode from client request (Claude Code)
if (body.permissionMode) {
requestedPermissionMode = body.permissionMode;
}
// Capture plan save settings
if (body.planSave !== undefined) {
planSaveEnabled = body.planSave.enabled;
planSaveCustomPath = body.planSave.customPath;
}
// Obsidian integration
if (body.obsidian?.vaultPath && body.obsidian?.plan) {
const result = await saveToObsidian(body.obsidian);
if (result.success) {
console.error(`[Obsidian] Saved plan to: ${result.path}`);
} else {
console.error(`[Obsidian] Save failed: ${result.error}`);
}
}
// Bear integration
if (body.bear?.plan) {
const result = await saveToBear(body.bear);
if (result.success) {
console.error(`[Bear] Saved plan to Bear`);
} else {
console.error(`[Bear] Save failed: ${result.error}`);
}
}
} catch (err) {
// Don't block approval on integration errors
console.error(`[Integration] Error:`, err);
}
// Save annotations and final snapshot (if enabled)
let savedPath: string | undefined;
if (planSaveEnabled) {
const annotations = feedback || "";
if (annotations) {
saveAnnotations(slug, annotations, planSaveCustomPath);
}
savedPath = saveFinalSnapshot(slug, "approved", plan, annotations, planSaveCustomPath);
}
// Clean up draft on successful submit
deleteDraft(draftKey);
// Use permission mode from client request if provided, otherwise fall back to hook input
const effectivePermissionMode = requestedPermissionMode || permissionMode;
resolveDecision({ approved: true, feedback, savedPath, agentSwitch, permissionMode: effectivePermissionMode });
return Response.json({ ok: true, savedPath });
}
// API: Deny with feedback
if (url.pathname === "/api/deny" && req.method === "POST") {
let feedback = "Plan rejected by user";
let planSaveEnabled = true; // default to enabled for backwards compat
let planSaveCustomPath: string | undefined;
try {
const body = (await req.json()) as {
feedback?: string;
planSave?: { enabled: boolean; customPath?: string };
};
feedback = body.feedback || feedback;
// Capture plan save settings
if (body.planSave !== undefined) {
planSaveEnabled = body.planSave.enabled;
planSaveCustomPath = body.planSave.customPath;
}
} catch {
// Use default feedback
}
// Save annotations and final snapshot (if enabled)
let savedPath: string | undefined;
if (planSaveEnabled) {
saveAnnotations(slug, feedback, planSaveCustomPath);
savedPath = saveFinalSnapshot(slug, "denied", plan, feedback, planSaveCustomPath);
}
deleteDraft(draftKey);
resolveDecision({ approved: false, feedback, savedPath });
return Response.json({ ok: true, savedPath });
}
// Serve embedded HTML for all other routes (SPA)
return new Response(htmlContent, {
headers: { "Content-Type": "text/html" },
});
},
});
break; // Success, exit retry loop
} catch (err: unknown) {
const isAddressInUse =
err instanceof Error && err.message.includes("EADDRINUSE");
if (isAddressInUse && attempt < MAX_RETRIES) {
await Bun.sleep(RETRY_DELAY_MS);
continue;
}
if (isAddressInUse) {
const hint = isRemote ? " (set PLANNOTATOR_PORT to use different port)" : "";
throw new Error(`Port ${configuredPort} in use after ${MAX_RETRIES} retries${hint}`);
}
throw err;
}
}
if (!server) {
throw new Error("Failed to start server");
}
const serverUrl = `http://${hostname}:${server.port}`;
// Notify caller that server is ready
if (onReady) {
onReady(serverUrl, isRemote, server.port);
}
return {
port: server.port,
url: serverUrl,
isRemote,
waitForDecision: () => decisionPromise,
stop: () => server.stop(),
};
}