forge-cw 0.1.22 → 0.1.24

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/index.js CHANGED
@@ -287,11 +287,12 @@ var init_db = __esm({
287
287
  // ../core/dist/modules.js
288
288
  import { readdirSync, readFileSync, existsSync } from "node:fs";
289
289
  import { join } from "node:path";
290
- var BUNDLED_MODULES, ModuleLoader;
290
+ var BUNDLED_MODULES, BUNDLED_V1_MODULES, ModuleLoader;
291
291
  var init_modules = __esm({
292
292
  "../core/dist/modules.js"() {
293
293
  "use strict";
294
294
  BUNDLED_MODULES = ["mod-qa"];
295
+ BUNDLED_V1_MODULES = ["mod-today"];
295
296
  ModuleLoader = class {
296
297
  modulesDir;
297
298
  bundledDir;
@@ -1931,16 +1932,309 @@ var init_output = __esm({
1931
1932
  }
1932
1933
  });
1933
1934
 
1935
+ // ../core/dist/cw-start.js
1936
+ import { existsSync as existsSync5, mkdirSync, readFileSync as readFileSync5, writeFileSync } from "node:fs";
1937
+ import { join as join7 } from "node:path";
1938
+ async function prepareStart(input, deps) {
1939
+ const { reader } = deps;
1940
+ const { type, project, task, description, workflow, account, directory, skipPermissions, model, loopPrompt, loopInterval, name, harness } = input;
1941
+ if (harness !== void 0 && !HARNESS_NAME_RE.test(harness)) {
1942
+ return { ok: false, status: 400, error: "Invalid harness" };
1943
+ }
1944
+ if (type === "login") {
1945
+ if (!account || !ACCOUNT_NAME_RE.test(account) || !reader.getAccounts().includes(account)) {
1946
+ return { ok: false, status: 400, error: "Unknown account" };
1947
+ }
1948
+ if (!harness)
1949
+ return { ok: false, status: 400, error: "Harness is required" };
1950
+ const sessionDirName2 = `login-${account}-${harness}`;
1951
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1952
+ const sessionData2 = {
1953
+ project: ACCOUNTS_PROJECT,
1954
+ type: "login",
1955
+ account,
1956
+ harness,
1957
+ workflow: "",
1958
+ worktree: "",
1959
+ notes: "",
1960
+ status: "active",
1961
+ created: now,
1962
+ last_opened: now,
1963
+ opens: 0,
1964
+ sessionDir: sessionDirName2
1965
+ };
1966
+ pendingSessions.set(`${ACCOUNTS_PROJECT}::${sessionDirName2}`, sessionData2);
1967
+ return { ok: true, session: sessionData2 };
1968
+ }
1969
+ if (type === "general") {
1970
+ const acct = account || "default";
1971
+ const sessionDirName2 = `general-${acct}-${Date.now()}`;
1972
+ const projectPath = project ? reader.getProjects()[project]?.path : void 0;
1973
+ const projectName = project && projectPath ? project : GENERAL_PROJECT;
1974
+ const sessionData2 = {
1975
+ project: projectName,
1976
+ task: task?.trim() || void 0,
1977
+ type: "general",
1978
+ account: acct,
1979
+ harness: harness || void 0,
1980
+ model: model || void 0,
1981
+ workflow: "",
1982
+ worktree: projectPath ?? directory ?? "",
1983
+ notes: "",
1984
+ status: "active",
1985
+ created: (/* @__PURE__ */ new Date()).toISOString(),
1986
+ last_opened: (/* @__PURE__ */ new Date()).toISOString(),
1987
+ opens: 0,
1988
+ sessionDir: sessionDirName2,
1989
+ skipPermissions: skipPermissions ?? false
1990
+ };
1991
+ pendingSessions.set(`${projectName}::${sessionDirName2}`, sessionData2);
1992
+ return { ok: true, session: sessionData2, command: `cw launch ${acct}` };
1993
+ }
1994
+ if (type === "create") {
1995
+ const name2 = project?.trim();
1996
+ if (!name2)
1997
+ return { ok: false, status: 400, error: "Project name is required" };
1998
+ const sessionDirName2 = `create-${name2}-${Date.now()}`;
1999
+ const sessionData2 = {
2000
+ project: CREATING_PROJECT,
2001
+ task: name2,
2002
+ type: "create",
2003
+ account: account ?? "",
2004
+ harness: harness || void 0,
2005
+ model: model || void 0,
2006
+ workflow: "",
2007
+ worktree: directory ?? "",
2008
+ notes: description ?? name2,
2009
+ status: "active",
2010
+ created: (/* @__PURE__ */ new Date()).toISOString(),
2011
+ last_opened: (/* @__PURE__ */ new Date()).toISOString(),
2012
+ opens: 0,
2013
+ sessionDir: sessionDirName2,
2014
+ skipPermissions: skipPermissions ?? false
2015
+ };
2016
+ pendingSessions.set(`${CREATING_PROJECT}::${sessionDirName2}`, sessionData2);
2017
+ return { ok: true, session: sessionData2 };
2018
+ }
2019
+ if (type === "loop") {
2020
+ if (!project)
2021
+ return { ok: false, status: 400, error: "Project is required" };
2022
+ if (harness && harness !== "claude") {
2023
+ return { ok: false, status: 400, error: "Loop runs on Claude Code only" };
2024
+ }
2025
+ const prompt = (loopPrompt ?? "").trim();
2026
+ if (!prompt)
2027
+ return { ok: false, status: 400, error: "Loop prompt is required" };
2028
+ const interval = (loopInterval ?? "").trim();
2029
+ if (interval && !/^\d+[smh]$/.test(interval)) {
2030
+ return { ok: false, status: 400, error: "Interval must be like 30s, 5m, 2h" };
2031
+ }
2032
+ const explicitName = name?.trim();
2033
+ if (explicitName && !/^[a-z0-9]([a-z0-9-]{0,28}[a-z0-9])?$/.test(explicitName)) {
2034
+ return { ok: false, status: 400, error: "Invalid name. Use lowercase letters, numbers, hyphens (max 30 chars)" };
2035
+ }
2036
+ const slug = (explicitName || prompt.toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 30)).replace(/^-+|-+$/g, "");
2037
+ if (!slug)
2038
+ return { ok: false, status: 400, error: "Could not derive a name from the prompt" };
2039
+ const sessionDirName2 = `loop-${slug}`;
2040
+ const loopSessionFile = join7(reader.cwHome, "sessions", project, sessionDirName2, "session.json");
2041
+ if (existsSync5(loopSessionFile)) {
2042
+ try {
2043
+ const meta = JSON.parse(readFileSync5(loopSessionFile, "utf-8"));
2044
+ if (meta.status === "active") {
2045
+ return { ok: false, status: 409, error: `Loop "${slug}" already exists for ${project}. Pick a different name or open the existing session.` };
2046
+ }
2047
+ } catch {
2048
+ }
2049
+ }
2050
+ const projectPath = reader.getProjects()[project]?.path ?? "";
2051
+ const sessionData2 = {
2052
+ project,
2053
+ task: slug,
2054
+ type: "loop",
2055
+ account: account ?? "",
2056
+ harness: harness || void 0,
2057
+ model: model || void 0,
2058
+ loop_prompt: prompt,
2059
+ loop_interval: interval,
2060
+ workflow: "",
2061
+ // This in-memory pending session may carry the project path (used as
2062
+ // the PTY's cwd), but it must never be persisted to CW's session.json —
2063
+ // `cw clean` treats a persisted worktree as a stale-space candidate to
2064
+ // rm -rf. CW itself writes 'worktree': '' when it creates the file.
2065
+ worktree: projectPath,
2066
+ notes: "",
2067
+ status: "active",
2068
+ created: (/* @__PURE__ */ new Date()).toISOString(),
2069
+ last_opened: (/* @__PURE__ */ new Date()).toISOString(),
2070
+ opens: 0,
2071
+ sessionDir: sessionDirName2,
2072
+ skipPermissions: skipPermissions ?? false
2073
+ };
2074
+ pendingSessions.set(`${project}::${sessionDirName2}`, sessionData2);
2075
+ return { ok: true, session: sessionData2 };
2076
+ }
2077
+ if (!project || !task) {
2078
+ return { ok: false, status: 400, error: "Project and task are required" };
2079
+ }
2080
+ const cwHome = reader.cwHome;
2081
+ let taskSlug = task.trim();
2082
+ let taskUrl;
2083
+ let taskSource;
2084
+ if (taskSlug.startsWith("http")) {
2085
+ taskUrl = taskSlug;
2086
+ if (taskSlug.includes("github.com")) {
2087
+ taskSource = "github";
2088
+ const m = taskSlug.match(/(\d+)\s*$/);
2089
+ if (m)
2090
+ taskSlug = m[1];
2091
+ } else if (taskSlug.includes("linear.app")) {
2092
+ taskSource = "linear";
2093
+ const m = taskSlug.match(/([A-Z]+-\d+)/);
2094
+ if (m)
2095
+ taskSlug = m[1];
2096
+ } else if (taskSlug.includes("notion.so") || taskSlug.includes("notion.site")) {
2097
+ taskSource = "notion";
2098
+ const parts = taskSlug.split("/");
2099
+ const last = parts[parts.length - 1] ?? "";
2100
+ taskSlug = last.replace(/-[a-f0-9]+$/, "").slice(0, 30);
2101
+ } else {
2102
+ taskSource = "url";
2103
+ taskSlug = taskSlug.replace(/^https?:\/\//, "").replace(/\//g, "-").slice(0, 30);
2104
+ }
2105
+ }
2106
+ const dirPrefix = type === "review" ? "review-pr-" : "task-";
2107
+ const sessionDir = sessionFolder(cwHome, project, `${dirPrefix}${taskSlug}`);
2108
+ if (!sessionDir)
2109
+ return { ok: false, status: 400, error: "Invalid project or task name" };
2110
+ const sessionFile = join7(sessionDir, "session.json");
2111
+ if (existsSync5(sessionFile)) {
2112
+ try {
2113
+ const meta = JSON.parse(readFileSync5(sessionFile, "utf-8"));
2114
+ if (meta.status === "active") {
2115
+ return { ok: false, status: 409, error: `Session "${taskSlug}" already exists for ${project}. Pick a different name or open the existing task.` };
2116
+ }
2117
+ } catch {
2118
+ }
2119
+ }
2120
+ const args = [];
2121
+ if (skipPermissions)
2122
+ args.push("--skip-permissions");
2123
+ if (type === "review") {
2124
+ args.push("review", project, task);
2125
+ if (account)
2126
+ args.push("--account", account);
2127
+ if (model)
2128
+ args.push("--model", model);
2129
+ } else {
2130
+ args.push("work", project, task);
2131
+ if (account)
2132
+ args.push("--account", account);
2133
+ if (workflow)
2134
+ args.push("--workflow", workflow);
2135
+ if (model)
2136
+ args.push("--model", model);
2137
+ }
2138
+ if (harness)
2139
+ args.push("--harness", harness);
2140
+ if (description) {
2141
+ const notesDir = sessionDir;
2142
+ mkdirSync(notesDir, { recursive: true });
2143
+ const notesFile = join7(notesDir, type === "review" ? "REVIEW_NOTES.md" : "TASK_NOTES.md");
2144
+ if (!existsSync5(notesFile)) {
2145
+ const header = type === "review" ? "Review" : "Task";
2146
+ const now = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
2147
+ writeFileSync(notesFile, [
2148
+ `# ${header}: ${taskSlug}`,
2149
+ `**Project:** ${project}`,
2150
+ `**Created:** ${now}`,
2151
+ "",
2152
+ "## Description",
2153
+ description,
2154
+ "",
2155
+ "## Context",
2156
+ "<!-- Additional context discovered during work -->",
2157
+ "",
2158
+ "## Decisions",
2159
+ "<!-- Important decisions made during this task -->",
2160
+ "",
2161
+ "## Status",
2162
+ "- [ ] Pending",
2163
+ "",
2164
+ "## Notes",
2165
+ "<!-- Findings, context, references -->",
2166
+ ""
2167
+ ].join("\n"));
2168
+ }
2169
+ }
2170
+ const sessionDirName = `${dirPrefix}${taskSlug}`;
2171
+ const sessionData = {
2172
+ project,
2173
+ task: type === "review" ? void 0 : taskSlug,
2174
+ pr: type === "review" ? taskSlug : void 0,
2175
+ type: type === "review" ? "review" : "task",
2176
+ account: account ?? "",
2177
+ harness: harness || void 0,
2178
+ workflow: workflow ?? "",
2179
+ model: model || void 0,
2180
+ source: taskSource,
2181
+ source_url: taskUrl,
2182
+ worktree: "",
2183
+ notes: "",
2184
+ status: "active",
2185
+ created: (/* @__PURE__ */ new Date()).toISOString(),
2186
+ last_opened: (/* @__PURE__ */ new Date()).toISOString(),
2187
+ opens: 0,
2188
+ sessionDir: sessionDirName,
2189
+ skipPermissions: skipPermissions ?? false
2190
+ };
2191
+ pendingSessions.set(`${project}::${sessionDirName}`, sessionData);
2192
+ return { ok: true, session: sessionData, command: `cw ${args.join(" ")}` };
2193
+ }
2194
+ function takeSession(reader, project, sessionDir, general) {
2195
+ const sessionId = `${project}::${sessionDir}`;
2196
+ const pending = pendingSessions.get(sessionId);
2197
+ if (pending) {
2198
+ pendingSessions.delete(sessionId);
2199
+ if (pending.type === "general")
2200
+ general?.remember(sessionId, pending);
2201
+ return { session: pending, isNew: true };
2202
+ }
2203
+ const session = reader.getSession(project, sessionDir);
2204
+ if (session)
2205
+ return { session, isNew: false };
2206
+ const known = general?.get(sessionId);
2207
+ return known ? { session: known, isNew: true } : null;
2208
+ }
2209
+ function launchHeadless(project, sessionDir, deps) {
2210
+ const taken = takeSession(deps.reader, project, sessionDir, deps.general);
2211
+ if (!taken)
2212
+ return null;
2213
+ return deps.manager.getOrCreate(project, sessionDir, taken.session, { isNew: taken.isNew, headless: true });
2214
+ }
2215
+ var GENERAL_PROJECT, CREATING_PROJECT, ACCOUNTS_PROJECT, pendingSessions;
2216
+ var init_cw_start = __esm({
2217
+ "../core/dist/cw-start.js"() {
2218
+ "use strict";
2219
+ init_cw_reader();
2220
+ init_cw_types();
2221
+ GENERAL_PROJECT = "__general";
2222
+ CREATING_PROJECT = "__creating";
2223
+ ACCOUNTS_PROJECT = "__accounts";
2224
+ pendingSessions = /* @__PURE__ */ new Map();
2225
+ }
2226
+ });
2227
+
1934
2228
  // ../core/dist/cw-routes.js
1935
2229
  import { Hono } from "hono";
1936
2230
  import { execFileSync, execFile as execFile4 } from "node:child_process";
1937
2231
  import { promisify as promisify2 } from "node:util";
1938
- import { readFileSync as readFileSync5, writeFileSync, existsSync as existsSync5, mkdirSync, rmSync, readdirSync as readdirSync3, statSync } from "node:fs";
1939
- import { join as join7, resolve as resolve2, dirname, basename, isAbsolute } from "node:path";
2232
+ import { writeFileSync as writeFileSync2, existsSync as existsSync6, rmSync, readdirSync as readdirSync3, statSync } from "node:fs";
2233
+ import { join as join8, resolve as resolve2, dirname, basename, isAbsolute } from "node:path";
1940
2234
  import { homedir as homedir2 } from "node:os";
1941
2235
  function resolveCwBin(cwHome) {
1942
- const candidate = join7(cwHome, "bin", "cw");
1943
- return existsSync5(candidate) ? candidate : "cw";
2236
+ const candidate = join8(cwHome, "bin", "cw");
2237
+ return existsSync6(candidate) ? candidate : "cw";
1944
2238
  }
1945
2239
  function cwDoneTimeoutMessage(ms) {
1946
2240
  return `cw --done timed out after ${ms % 1e3 === 0 ? `${ms / 1e3} s` : `${ms} ms`}`;
@@ -2009,7 +2303,8 @@ function cwRoutes(reader, options = {}) {
2009
2303
  });
2010
2304
  app.get("/spaces", (c) => {
2011
2305
  const project = c.req.query("project");
2012
- return c.json(reader.getSpaces(project));
2306
+ const spaces = [...reader.getSpaces(project), ...options.general?.list(project) ?? []];
2307
+ return c.json(spaces.sort((a, b) => new Date(b.last_opened).getTime() - new Date(a.last_opened).getTime()));
2013
2308
  });
2014
2309
  app.get("/session/:project/:sessionDir", (c) => {
2015
2310
  const { project, sessionDir } = c.req.param();
@@ -2074,13 +2369,13 @@ function cwRoutes(reader, options = {}) {
2074
2369
  if (!ACCOUNT_NAME_RE.test(name)) {
2075
2370
  return c.json({ ok: false, error: "Invalid account name" }, 400);
2076
2371
  }
2077
- const accountDir = join7(reader.cwHome, "accounts", name);
2078
- if (!existsSync5(accountDir)) {
2372
+ const accountDir = join8(reader.cwHome, "accounts", name);
2373
+ if (!existsSync6(accountDir)) {
2079
2374
  return c.json({ ok: false, error: `Account "${name}" not found` }, 404);
2080
2375
  }
2081
2376
  try {
2082
- const { rmSync: rmSync4 } = await import("node:fs");
2083
- rmSync4(accountDir, { recursive: true, force: true });
2377
+ const { rmSync: rmSync5 } = await import("node:fs");
2378
+ rmSync5(accountDir, { recursive: true, force: true });
2084
2379
  return c.json({ ok: true });
2085
2380
  } catch (err) {
2086
2381
  const message2 = err instanceof Error ? err.message : "Unknown error";
@@ -2195,7 +2490,7 @@ function cwRoutes(reader, options = {}) {
2195
2490
  return c.json(await cached.value);
2196
2491
  }
2197
2492
  const projectPath = reader.getProjects()[project]?.path ?? null;
2198
- const value = buildTaskReviewState(session, projectPath, { run: run2, limitGh, exists: existsSync5 });
2493
+ const value = buildTaskReviewState(session, projectPath, { run: run2, limitGh, exists: existsSync6 });
2199
2494
  reviewCache.set(key, { at: Date.now(), value });
2200
2495
  value.catch(() => reviewCache.delete(key));
2201
2496
  return c.json(await value);
@@ -2213,7 +2508,7 @@ function cwRoutes(reader, options = {}) {
2213
2508
  if (!target)
2214
2509
  return c.json({ ok: false, error: `Editor not available: ${editor}` }, 400);
2215
2510
  const session = reader.getSession(project, sessionDir);
2216
- if (!session?.worktree || !existsSync5(session.worktree)) {
2511
+ if (!session?.worktree || !existsSync6(session.worktree)) {
2217
2512
  return c.json({ ok: false, error: "This task has no workspace on disk yet" }, 404);
2218
2513
  }
2219
2514
  try {
@@ -2224,262 +2519,19 @@ function cwRoutes(reader, options = {}) {
2224
2519
  }
2225
2520
  });
2226
2521
  app.post("/start", async (c) => {
2227
- const { type, project, task, description, workflow, account, directory, skipPermissions, model, loopPrompt, loopInterval, name, harness } = await c.req.json();
2228
- if (harness !== void 0 && !HARNESS_NAME_RE.test(harness)) {
2229
- return c.json({ ok: false, error: "Invalid harness" }, 400);
2230
- }
2231
- if (type === "login") {
2232
- if (!account || !ACCOUNT_NAME_RE.test(account) || !reader.getAccounts().includes(account)) {
2233
- return c.json({ ok: false, error: "Unknown account" }, 400);
2234
- }
2235
- if (!harness)
2236
- return c.json({ ok: false, error: "Harness is required" }, 400);
2237
- const sessionDirName2 = `login-${account}-${harness}`;
2238
- const now = (/* @__PURE__ */ new Date()).toISOString();
2239
- const sessionData2 = {
2240
- project: ACCOUNTS_PROJECT,
2241
- type: "login",
2242
- account,
2243
- harness,
2244
- workflow: "",
2245
- worktree: "",
2246
- notes: "",
2247
- status: "active",
2248
- created: now,
2249
- last_opened: now,
2250
- opens: 0,
2251
- sessionDir: sessionDirName2
2252
- };
2253
- pendingSessions.set(`${ACCOUNTS_PROJECT}::${sessionDirName2}`, sessionData2);
2254
- return c.json({ ok: true, session: sessionData2 });
2255
- }
2256
- if (type === "general") {
2257
- const acct = account || "default";
2258
- const sessionDirName2 = `general-${acct}-${Date.now()}`;
2259
- const projectPath = project ? reader.getProjects()[project]?.path : void 0;
2260
- const projectName = project && projectPath ? project : GENERAL_PROJECT;
2261
- const sessionData2 = {
2262
- project: projectName,
2263
- task: task?.trim() || void 0,
2264
- type: "general",
2265
- account: acct,
2266
- harness: harness || void 0,
2267
- model: model || void 0,
2268
- workflow: "",
2269
- worktree: projectPath ?? directory ?? "",
2270
- notes: "",
2271
- status: "active",
2272
- created: (/* @__PURE__ */ new Date()).toISOString(),
2273
- last_opened: (/* @__PURE__ */ new Date()).toISOString(),
2274
- opens: 0,
2275
- sessionDir: sessionDirName2,
2276
- skipPermissions: skipPermissions ?? false
2277
- };
2278
- pendingSessions.set(`${projectName}::${sessionDirName2}`, sessionData2);
2279
- return c.json({ ok: true, session: sessionData2, command: `cw launch ${acct}` });
2280
- }
2281
- if (type === "create") {
2282
- const name2 = project?.trim();
2283
- if (!name2)
2284
- return c.json({ ok: false, error: "Project name is required" }, 400);
2285
- const sessionDirName2 = `create-${name2}-${Date.now()}`;
2286
- const sessionData2 = {
2287
- project: CREATING_PROJECT,
2288
- task: name2,
2289
- type: "create",
2290
- account: account ?? "",
2291
- harness: harness || void 0,
2292
- model: model || void 0,
2293
- workflow: "",
2294
- worktree: directory ?? "",
2295
- notes: description ?? name2,
2296
- status: "active",
2297
- created: (/* @__PURE__ */ new Date()).toISOString(),
2298
- last_opened: (/* @__PURE__ */ new Date()).toISOString(),
2299
- opens: 0,
2300
- sessionDir: sessionDirName2,
2301
- skipPermissions: skipPermissions ?? false
2302
- };
2303
- pendingSessions.set(`${CREATING_PROJECT}::${sessionDirName2}`, sessionData2);
2304
- return c.json({ ok: true, session: sessionData2 });
2305
- }
2306
- if (type === "loop") {
2307
- if (!project)
2308
- return c.json({ ok: false, error: "Project is required" }, 400);
2309
- if (harness && harness !== "claude") {
2310
- return c.json({ ok: false, error: "Loop runs on Claude Code only" }, 400);
2311
- }
2312
- const prompt = (loopPrompt ?? "").trim();
2313
- if (!prompt)
2314
- return c.json({ ok: false, error: "Loop prompt is required" }, 400);
2315
- const interval = (loopInterval ?? "").trim();
2316
- if (interval && !/^\d+[smh]$/.test(interval)) {
2317
- return c.json({ ok: false, error: "Interval must be like 30s, 5m, 2h" }, 400);
2318
- }
2319
- const explicitName = name?.trim();
2320
- if (explicitName && !/^[a-z0-9]([a-z0-9-]{0,28}[a-z0-9])?$/.test(explicitName)) {
2321
- return c.json({ ok: false, error: "Invalid name. Use lowercase letters, numbers, hyphens (max 30 chars)" }, 400);
2322
- }
2323
- const slug = (explicitName || prompt.toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 30)).replace(/^-+|-+$/g, "");
2324
- if (!slug)
2325
- return c.json({ ok: false, error: "Could not derive a name from the prompt" }, 400);
2326
- const sessionDirName2 = `loop-${slug}`;
2327
- const loopSessionFile = join7(reader.cwHome, "sessions", project, sessionDirName2, "session.json");
2328
- if (existsSync5(loopSessionFile)) {
2329
- try {
2330
- const meta = JSON.parse(readFileSync5(loopSessionFile, "utf-8"));
2331
- if (meta.status === "active") {
2332
- return c.json({ ok: false, error: `Loop "${slug}" already exists for ${project}. Pick a different name or open the existing session.` }, 409);
2333
- }
2334
- } catch {
2335
- }
2336
- }
2337
- const projectPath = reader.getProjects()[project]?.path ?? "";
2338
- const sessionData2 = {
2339
- project,
2340
- task: slug,
2341
- type: "loop",
2342
- account: account ?? "",
2343
- harness: harness || void 0,
2344
- model: model || void 0,
2345
- loop_prompt: prompt,
2346
- loop_interval: interval,
2347
- workflow: "",
2348
- // This in-memory pending session may carry the project path (used as
2349
- // the PTY's cwd), but it must never be persisted to CW's session.json —
2350
- // `cw clean` treats a persisted worktree as a stale-space candidate to
2351
- // rm -rf. CW itself writes 'worktree': '' when it creates the file.
2352
- worktree: projectPath,
2353
- notes: "",
2354
- status: "active",
2355
- created: (/* @__PURE__ */ new Date()).toISOString(),
2356
- last_opened: (/* @__PURE__ */ new Date()).toISOString(),
2357
- opens: 0,
2358
- sessionDir: sessionDirName2,
2359
- skipPermissions: skipPermissions ?? false
2360
- };
2361
- pendingSessions.set(`${project}::${sessionDirName2}`, sessionData2);
2362
- return c.json({ ok: true, session: sessionData2 });
2363
- }
2364
- if (!project || !task) {
2365
- return c.json({ ok: false, error: "Project and task are required" }, 400);
2366
- }
2367
- const cwHome = reader.cwHome;
2368
- let taskSlug = task.trim();
2369
- let taskUrl;
2370
- let taskSource;
2371
- if (taskSlug.startsWith("http")) {
2372
- taskUrl = taskSlug;
2373
- if (taskSlug.includes("github.com")) {
2374
- taskSource = "github";
2375
- const m = taskSlug.match(/(\d+)\s*$/);
2376
- if (m)
2377
- taskSlug = m[1];
2378
- } else if (taskSlug.includes("linear.app")) {
2379
- taskSource = "linear";
2380
- const m = taskSlug.match(/([A-Z]+-\d+)/);
2381
- if (m)
2382
- taskSlug = m[1];
2383
- } else if (taskSlug.includes("notion.so") || taskSlug.includes("notion.site")) {
2384
- taskSource = "notion";
2385
- const parts = taskSlug.split("/");
2386
- const last = parts[parts.length - 1] ?? "";
2387
- taskSlug = last.replace(/-[a-f0-9]+$/, "").slice(0, 30);
2388
- } else {
2389
- taskSource = "url";
2390
- taskSlug = taskSlug.replace(/^https?:\/\//, "").replace(/\//g, "-").slice(0, 30);
2391
- }
2392
- }
2393
- const dirPrefix = type === "review" ? "review-pr-" : "task-";
2394
- const sessionDir = sessionFolder(cwHome, project, `${dirPrefix}${taskSlug}`);
2395
- if (!sessionDir)
2396
- return c.json({ ok: false, error: "Invalid project or task name" }, 400);
2397
- const sessionFile = join7(sessionDir, "session.json");
2398
- if (existsSync5(sessionFile)) {
2399
- try {
2400
- const meta = JSON.parse(readFileSync5(sessionFile, "utf-8"));
2401
- if (meta.status === "active") {
2402
- return c.json({ ok: false, error: `Session "${taskSlug}" already exists for ${project}. Pick a different name or open the existing task.` }, 409);
2403
- }
2404
- } catch {
2405
- }
2406
- }
2407
- const args = [];
2408
- if (skipPermissions)
2409
- args.push("--skip-permissions");
2410
- if (type === "review") {
2411
- args.push("review", project, task);
2412
- if (account)
2413
- args.push("--account", account);
2414
- if (model)
2415
- args.push("--model", model);
2416
- } else {
2417
- args.push("work", project, task);
2418
- if (account)
2419
- args.push("--account", account);
2420
- if (workflow)
2421
- args.push("--workflow", workflow);
2422
- if (model)
2423
- args.push("--model", model);
2424
- }
2425
- if (harness)
2426
- args.push("--harness", harness);
2427
- if (description) {
2428
- const notesDir = sessionDir;
2429
- mkdirSync(notesDir, { recursive: true });
2430
- const notesFile = join7(notesDir, type === "review" ? "REVIEW_NOTES.md" : "TASK_NOTES.md");
2431
- if (!existsSync5(notesFile)) {
2432
- const header = type === "review" ? "Review" : "Task";
2433
- const now = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
2434
- writeFileSync(notesFile, [
2435
- `# ${header}: ${taskSlug}`,
2436
- `**Project:** ${project}`,
2437
- `**Created:** ${now}`,
2438
- "",
2439
- "## Description",
2440
- description,
2441
- "",
2442
- "## Context",
2443
- "<!-- Additional context discovered during work -->",
2444
- "",
2445
- "## Decisions",
2446
- "<!-- Important decisions made during this task -->",
2447
- "",
2448
- "## Status",
2449
- "- [ ] Pending",
2450
- "",
2451
- "## Notes",
2452
- "<!-- Findings, context, references -->",
2453
- ""
2454
- ].join("\n"));
2455
- }
2456
- }
2457
- const sessionDirName = `${dirPrefix}${taskSlug}`;
2458
- const sessionData = {
2459
- project,
2460
- task: type === "review" ? void 0 : taskSlug,
2461
- pr: type === "review" ? taskSlug : void 0,
2462
- type: type === "review" ? "review" : "task",
2463
- account: account ?? "",
2464
- harness: harness || void 0,
2465
- workflow: workflow ?? "",
2466
- model: model || void 0,
2467
- source: taskSource,
2468
- source_url: taskUrl,
2469
- worktree: "",
2470
- notes: "",
2471
- status: "active",
2472
- created: (/* @__PURE__ */ new Date()).toISOString(),
2473
- last_opened: (/* @__PURE__ */ new Date()).toISOString(),
2474
- opens: 0,
2475
- sessionDir: sessionDirName,
2476
- skipPermissions: skipPermissions ?? false
2477
- };
2478
- pendingSessions.set(`${project}::${sessionDirName}`, sessionData);
2479
- return c.json({ ok: true, session: sessionData, command: `cw ${args.join(" ")}` });
2522
+ const r = await prepareStart(await c.req.json(), { reader });
2523
+ if (!r.ok)
2524
+ return c.json({ ok: false, error: r.error }, r.status);
2525
+ return c.json({ ok: true, session: r.session, command: r.command });
2480
2526
  });
2481
2527
  app.post("/done", async (c) => {
2482
2528
  const { project, task, type, sessionDir } = await c.req.json();
2529
+ if (type === "general" && sessionDir) {
2530
+ const key = `${project}::${sessionDir}`;
2531
+ options.killSession?.(key);
2532
+ options.general?.forget(key);
2533
+ return c.json({ ok: true });
2534
+ }
2483
2535
  const sessionDirName = sessionDir ?? (type === "review" ? `review-pr-${task}` : type === "loop" ? `loop-${task}` : `task-${task}`);
2484
2536
  const args = type === "review" ? ["review", project, task, "--done"] : type === "loop" ? ["loop", project, task, "--done"] : ["work", project, task, "--done"];
2485
2537
  reviewCache.delete(`${project}::${sessionDirName}`);
@@ -2523,7 +2575,7 @@ ${result2.stderr}`);
2523
2575
  }
2524
2576
  projects[project] = { ...projects[project], account: toAccount };
2525
2577
  try {
2526
- writeFileSync(join7(reader.cwHome, "projects.json"), JSON.stringify(projects, null, 2));
2578
+ writeFileSync2(join8(reader.cwHome, "projects.json"), JSON.stringify(projects, null, 2));
2527
2579
  return c.json({ ok: true });
2528
2580
  } catch (err) {
2529
2581
  const message2 = err instanceof Error ? err.message : "Unknown error";
@@ -2541,7 +2593,7 @@ ${result2.stderr}`);
2541
2593
  execFileSync(cwBin, ["project", "remove", project, "--yes"], { encoding: "utf-8", timeout: 1e4, stdio: "pipe", env: envWithoutHarness() });
2542
2594
  } catch {
2543
2595
  }
2544
- if (existsSync5(sessionsDir)) {
2596
+ if (existsSync6(sessionsDir)) {
2545
2597
  try {
2546
2598
  rmSync(sessionsDir, { recursive: true, force: true });
2547
2599
  } catch {
@@ -2562,7 +2614,7 @@ ${result2.stderr}`);
2562
2614
  if (!p)
2563
2615
  p = home;
2564
2616
  if (p === "~" || p.startsWith("~/"))
2565
- p = join7(home, p.slice(1).replace(/^\//, ""));
2617
+ p = join8(home, p.slice(1).replace(/^\//, ""));
2566
2618
  if (!isAbsolute(p))
2567
2619
  return null;
2568
2620
  return resolve2(p);
@@ -2573,7 +2625,7 @@ ${result2.stderr}`);
2573
2625
  if (!target) {
2574
2626
  return c.json({ ok: false, error: "Path must be absolute or start with ~" }, 400);
2575
2627
  }
2576
- if (!existsSync5(target)) {
2628
+ if (!existsSync6(target)) {
2577
2629
  return c.json({ ok: false, error: `Path does not exist: ${target}` }, 404);
2578
2630
  }
2579
2631
  let stat;
@@ -2593,8 +2645,8 @@ ${result2.stderr}`);
2593
2645
  return c.json({ ok: false, error: `Cannot read directory: ${message2}` }, 500);
2594
2646
  }
2595
2647
  const dirs = entries.filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map(({ name }) => {
2596
- const full = join7(target, name);
2597
- return { name, path: full, isGitRepo: existsSync5(join7(full, ".git")) };
2648
+ const full = join8(target, name);
2649
+ return { name, path: full, isGitRepo: existsSync6(join8(full, ".git")) };
2598
2650
  }).sort((a, b) => a.name.localeCompare(b.name));
2599
2651
  const parent = dirname(target);
2600
2652
  return c.json({
@@ -2602,7 +2654,7 @@ ${result2.stderr}`);
2602
2654
  path: target,
2603
2655
  parent: parent === target ? null : parent,
2604
2656
  home: homedir2(),
2605
- isGitRepo: existsSync5(join7(target, ".git")),
2657
+ isGitRepo: existsSync6(join8(target, ".git")),
2606
2658
  entries: dirs
2607
2659
  });
2608
2660
  });
@@ -2618,10 +2670,10 @@ ${result2.stderr}`);
2618
2670
  if (!projectPath) {
2619
2671
  return c.json({ ok: false, error: "Path must be absolute or start with ~" }, 400);
2620
2672
  }
2621
- if (!existsSync5(projectPath)) {
2673
+ if (!existsSync6(projectPath)) {
2622
2674
  return c.json({ ok: false, error: `Path does not exist: ${projectPath}` }, 404);
2623
2675
  }
2624
- if (!existsSync5(join7(projectPath, ".git"))) {
2676
+ if (!existsSync6(join8(projectPath, ".git"))) {
2625
2677
  return c.json({ ok: false, error: "Selected directory is not a git repository" }, 400);
2626
2678
  }
2627
2679
  if (!reader.getAccounts().includes(account)) {
@@ -2647,7 +2699,7 @@ ${result2.stderr}`);
2647
2699
  });
2648
2700
  return app;
2649
2701
  }
2650
- var execFileAsync2, GENERAL_PROJECT, CREATING_PROJECT, ACCOUNTS_PROJECT, pendingSessions, CW_DONE_TIMEOUT_MS;
2702
+ var execFileAsync2, CW_DONE_TIMEOUT_MS;
2651
2703
  var init_cw_routes = __esm({
2652
2704
  "../core/dist/cw-routes.js"() {
2653
2705
  "use strict";
@@ -2661,18 +2713,15 @@ var init_cw_routes = __esm({
2661
2713
  init_task_review();
2662
2714
  init_editors();
2663
2715
  init_output();
2716
+ init_cw_start();
2664
2717
  execFileAsync2 = promisify2(execFile4);
2665
- GENERAL_PROJECT = "__general";
2666
- CREATING_PROJECT = "__creating";
2667
- ACCOUNTS_PROJECT = "__accounts";
2668
- pendingSessions = /* @__PURE__ */ new Map();
2669
2718
  CW_DONE_TIMEOUT_MS = 6e4;
2670
2719
  }
2671
2720
  });
2672
2721
 
2673
2722
  // ../core/dist/plugins.js
2674
- import { existsSync as existsSync6, readFileSync as readFileSync6, readdirSync as readdirSync4 } from "node:fs";
2675
- import { basename as basename2, join as join8, resolve as resolve3, sep as sep2 } from "node:path";
2723
+ import { existsSync as existsSync7, readFileSync as readFileSync6, readdirSync as readdirSync4 } from "node:fs";
2724
+ import { basename as basename2, join as join9, resolve as resolve3, sep as sep2 } from "node:path";
2676
2725
  function readJson(path) {
2677
2726
  try {
2678
2727
  const value = JSON.parse(readFileSync6(path, "utf-8"));
@@ -2699,9 +2748,9 @@ function createRemoteLookup(run2) {
2699
2748
  };
2700
2749
  }
2701
2750
  function scanDirs(root) {
2702
- if (!existsSync6(root))
2751
+ if (!existsSync7(root))
2703
2752
  return [];
2704
- return readdirSync4(root, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => join8(root, e.name));
2753
+ return readdirSync4(root, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => join9(root, e.name));
2705
2754
  }
2706
2755
  function skillDirs(installPath, manifest) {
2707
2756
  const listed = manifest["skills"];
@@ -2712,11 +2761,11 @@ function skillDirs(installPath, manifest) {
2712
2761
  const root = resolve3(installPath, listed);
2713
2762
  return inside(installPath, root) ? scanDirs(root) : [];
2714
2763
  }
2715
- return scanDirs(join8(installPath, "skills"));
2764
+ return scanDirs(join9(installPath, "skills"));
2716
2765
  }
2717
2766
  function readSkill(reader, dir, plugin) {
2718
2767
  try {
2719
- const { frontmatter } = reader.parseFrontmatter(readFileSync6(join8(dir, "SKILL.md"), "utf-8"));
2768
+ const { frontmatter } = reader.parseFrontmatter(readFileSync6(join9(dir, "SKILL.md"), "utf-8"));
2720
2769
  const name = String(frontmatter["name"] ?? basename2(dir));
2721
2770
  const hint = frontmatter["argument-hint"];
2722
2771
  const invocable = String(frontmatter["user-invocable"]) !== "false";
@@ -2732,12 +2781,12 @@ function readSkill(reader, dir, plugin) {
2732
2781
  }
2733
2782
  }
2734
2783
  function readCommands(reader, installPath) {
2735
- const dir = join8(installPath, "commands");
2736
- if (!existsSync6(dir))
2784
+ const dir = join9(installPath, "commands");
2785
+ if (!existsSync7(dir))
2737
2786
  return [];
2738
2787
  return readdirSync4(dir).filter((f) => f.endsWith(".md")).sort().flatMap((file) => {
2739
2788
  try {
2740
- const { frontmatter } = reader.parseFrontmatter(readFileSync6(join8(dir, file), "utf-8"));
2789
+ const { frontmatter } = reader.parseFrontmatter(readFileSync6(join9(dir, file), "utf-8"));
2741
2790
  const hint = frontmatter["argument-hint"];
2742
2791
  return [{ name: `/${basename2(file, ".md")}`, description: String(frontmatter["description"] ?? ""), ...typeof hint === "string" && hint ? { argumentHint: hint } : {} }];
2743
2792
  } catch {
@@ -2766,8 +2815,8 @@ function splitPluginId(id) {
2766
2815
  }
2767
2816
  function catalogVersion(configDir, marketplaces, marketplace, name) {
2768
2817
  const known = marketplaces[marketplace];
2769
- const location = isRecord(known) && typeof known["installLocation"] === "string" ? known["installLocation"] : join8(configDir, "plugins", "marketplaces", marketplace);
2770
- const entries = readJson(join8(location, ".claude-plugin", "marketplace.json"))["plugins"];
2818
+ const location = isRecord(known) && typeof known["installLocation"] === "string" ? known["installLocation"] : join9(configDir, "plugins", "marketplaces", marketplace);
2819
+ const entries = readJson(join9(location, ".claude-plugin", "marketplace.json"))["plugins"];
2771
2820
  if (!Array.isArray(entries))
2772
2821
  return void 0;
2773
2822
  const entry = entries.find((e) => isRecord(e) && e["name"] === name);
@@ -2781,7 +2830,7 @@ function catalogVersion(configDir, marketplaces, marketplace, name) {
2781
2830
  const dir = resolve3(location, source);
2782
2831
  if (!inside(location, dir))
2783
2832
  return void 0;
2784
- const version = readJson(join8(dir, ".claude-plugin", "plugin.json"))["version"];
2833
+ const version = readJson(join9(dir, ".claude-plugin", "plugin.json"))["version"];
2785
2834
  return typeof version === "string" ? version : void 0;
2786
2835
  }
2787
2836
  function hasUpdate({ latest, version }) {
@@ -2799,15 +2848,15 @@ function hasUpdate({ latest, version }) {
2799
2848
  return false;
2800
2849
  }
2801
2850
  function projectSkillNames(projectPath) {
2802
- const dir = join8(projectPath, ".claude", "skills");
2803
- if (!existsSync6(dir))
2851
+ const dir = join9(projectPath, ".claude", "skills");
2852
+ if (!existsSync7(dir))
2804
2853
  return [];
2805
- return readdirSync4(dir, { withFileTypes: true }).filter((e) => e.isDirectory() && existsSync6(join8(dir, e.name, "SKILL.md"))).map((e) => e.name).sort();
2854
+ return readdirSync4(dir, { withFileTypes: true }).filter((e) => e.isDirectory() && existsSync7(join9(dir, e.name, "SKILL.md"))).map((e) => e.name).sort();
2806
2855
  }
2807
2856
  function installsOf(reader, name) {
2808
2857
  return pluginScopes(reader).flatMap(({ scope, scopeRef }) => {
2809
2858
  const configDir = reader.getSkillConfigDir(scope, scopeRef);
2810
- const installed = readJson(join8(configDir, "plugins", "installed_plugins.json"))["plugins"];
2859
+ const installed = readJson(join9(configDir, "plugins", "installed_plugins.json"))["plugins"];
2811
2860
  if (!isRecord(installed))
2812
2861
  return [];
2813
2862
  return Object.entries(installed).flatMap(([id, entries]) => {
@@ -2822,11 +2871,11 @@ async function listPlugins(reader, remoteOf) {
2822
2871
  const found = /* @__PURE__ */ new Map();
2823
2872
  for (const { scope, scopeRef } of pluginScopes(reader)) {
2824
2873
  const configDir = reader.getSkillConfigDir(scope, scopeRef);
2825
- const installed = readJson(join8(configDir, "plugins", "installed_plugins.json"))["plugins"];
2874
+ const installed = readJson(join9(configDir, "plugins", "installed_plugins.json"))["plugins"];
2826
2875
  if (!isRecord(installed))
2827
2876
  continue;
2828
2877
  const marketplaces = knownMarketplaces(configDir);
2829
- const enabledPlugins = readJson(join8(configDir, "settings.json"))["enabledPlugins"];
2878
+ const enabledPlugins = readJson(join9(configDir, "settings.json"))["enabledPlugins"];
2830
2879
  for (const [id, entries] of Object.entries(installed)) {
2831
2880
  if (!Array.isArray(entries))
2832
2881
  continue;
@@ -2856,7 +2905,7 @@ async function listPlugins(reader, remoteOf) {
2856
2905
  const plugins = [];
2857
2906
  for (const [id, list] of found) {
2858
2907
  const newest = [...list].sort((a, b) => (b.install.lastUpdated ?? "").localeCompare(a.install.lastUpdated ?? ""))[0];
2859
- const manifest = readJson(join8(newest.install.installPath, ".claude-plugin", "plugin.json"));
2908
+ const manifest = readJson(join9(newest.install.installPath, ".claude-plugin", "plugin.json"));
2860
2909
  const repo = [manifestRepo(manifest), ...list.map((f) => f.repo)].map(normalizeRepo).find(Boolean);
2861
2910
  const match = repo ? remotes.find((r) => r.repo === repo) : void 0;
2862
2911
  plugins.push({
@@ -2868,7 +2917,7 @@ async function listPlugins(reader, remoteOf) {
2868
2917
  skills: skillDirs(newest.install.installPath, manifest).flatMap((dir) => readSkill(reader, dir, splitPluginId(id).name) ?? []),
2869
2918
  commands: readCommands(reader, newest.install.installPath),
2870
2919
  project: match?.name,
2871
- contributing: match ? existsSync6(join8(match.path, "CONTRIBUTING.md")) : false,
2920
+ contributing: match ? existsSync7(join9(match.path, "CONTRIBUTING.md")) : false,
2872
2921
  projectSkills: match ? projectSkillNames(match.path) : []
2873
2922
  });
2874
2923
  }
@@ -2879,13 +2928,13 @@ function readPluginSkill(plugin, name) {
2879
2928
  if (!skill)
2880
2929
  return null;
2881
2930
  try {
2882
- return { name: skill.name, description: skill.description, content: readFileSync6(join8(skill.path, "SKILL.md"), "utf-8") };
2931
+ return { name: skill.name, description: skill.description, content: readFileSync6(join9(skill.path, "SKILL.md"), "utf-8") };
2883
2932
  } catch {
2884
2933
  return null;
2885
2934
  }
2886
2935
  }
2887
2936
  function readCatalog(location, marketplace) {
2888
- const listed = readJson(join8(location, ".claude-plugin", "marketplace.json"))["plugins"];
2937
+ const listed = readJson(join9(location, ".claude-plugin", "marketplace.json"))["plugins"];
2889
2938
  return (Array.isArray(listed) ? listed : []).filter((p) => isRecord(p) && typeof p["name"] === "string").map((p) => ({
2890
2939
  id: `${String(p["name"])}@${marketplace}`,
2891
2940
  name: String(p["name"]),
@@ -2932,7 +2981,7 @@ var init_plugins = __esm({
2932
2981
  { scope: "global", scopeRef: "global" },
2933
2982
  ...reader.getAccounts().map((a) => ({ scope: "account", scopeRef: a }))
2934
2983
  ];
2935
- knownMarketplaces = (configDir) => readJson(join8(configDir, "plugins", "known_marketplaces.json"));
2984
+ knownMarketplaces = (configDir) => readJson(join9(configDir, "plugins", "known_marketplaces.json"));
2936
2985
  numeric = (v) => /^\d+(\.\d+)*$/.test(v) ? v.split(".").map(Number) : null;
2937
2986
  pluginUpdateArgs = (id) => [["plugin", "marketplace", "update", splitPluginId(id).marketplace], ["plugin", "update", id]];
2938
2987
  knowsMarketplace = (configDir, marketplace) => isRecord(knownMarketplaces(configDir)[marketplace]);
@@ -2941,17 +2990,17 @@ var init_plugins = __esm({
2941
2990
 
2942
2991
  // ../core/dist/skill-routes.js
2943
2992
  import { Hono as Hono2 } from "hono";
2944
- import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync2, rmSync as rmSync2, existsSync as existsSync7, unlinkSync, cpSync, readdirSync as readdirSync5 } from "node:fs";
2945
- import { dirname as dirname2, join as join9 } from "node:path";
2993
+ import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync3, rmSync as rmSync2, existsSync as existsSync8, unlinkSync, cpSync, readdirSync as readdirSync5 } from "node:fs";
2994
+ import { dirname as dirname2, join as join10 } from "node:path";
2946
2995
  function backUpSkill(backupDir, scope, ref, name, dir) {
2947
- const root = join9(backupDir, scope, ref, name);
2996
+ const root = join10(backupDir, scope, ref, name);
2948
2997
  const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
2949
- let dest = join9(root, stamp);
2950
- for (let n = 1; existsSync7(dest); n++)
2951
- dest = join9(root, `${stamp}-${String(n).padStart(3, "0")}`);
2998
+ let dest = join10(root, stamp);
2999
+ for (let n = 1; existsSync8(dest); n++)
3000
+ dest = join10(root, `${stamp}-${String(n).padStart(3, "0")}`);
2952
3001
  cpSync(dir, dest, { recursive: true, dereference: true });
2953
3002
  for (const old of readdirSync5(root).sort().slice(0, -BACKUPS_KEPT))
2954
- rmSync2(join9(root, old), { recursive: true, force: true });
3003
+ rmSync2(join10(root, old), { recursive: true, force: true });
2955
3004
  }
2956
3005
  function installFailure(result2) {
2957
3006
  try {
@@ -3019,9 +3068,9 @@ function skillRoutes(reader, options = {}) {
3019
3068
  return c.json({ error: `Unknown ${to.scope}: ${toRef}` }, 404);
3020
3069
  const source = reader.getSkillDir(from.scope, fromRef, from.name);
3021
3070
  const target = reader.getSkillDir(to.scope, toRef, from.name);
3022
- if (!existsSync7(join9(source, "SKILL.md")))
3071
+ if (!existsSync8(join10(source, "SKILL.md")))
3023
3072
  return c.json({ error: "Skill not found" }, 404);
3024
- if (existsSync7(target))
3073
+ if (existsSync8(target))
3025
3074
  return c.json({ error: `${from.name} already exists in ${toRef}` }, 409);
3026
3075
  try {
3027
3076
  cpSync(source, target, { recursive: true });
@@ -3056,12 +3105,12 @@ function skillRoutes(reader, options = {}) {
3056
3105
  const { scope, scopeRef, name, content } = await c.req.json();
3057
3106
  const ref = scopeRef ?? (scope === "global" ? "global" : "");
3058
3107
  const dir = reader.getSkillDir(scope, ref, name);
3059
- if (existsSync7(join9(dir, "SKILL.md"))) {
3108
+ if (existsSync8(join10(dir, "SKILL.md"))) {
3060
3109
  return c.json({ error: "Skill already exists" }, 409);
3061
3110
  }
3062
3111
  try {
3063
3112
  mkdirSync2(dir, { recursive: true });
3064
- writeFileSync2(join9(dir, "SKILL.md"), content, "utf-8");
3113
+ writeFileSync3(join10(dir, "SKILL.md"), content, "utf-8");
3065
3114
  return c.json({ ok: true, dir });
3066
3115
  } catch (err) {
3067
3116
  const message2 = err instanceof Error ? err.message : "Unknown error";
@@ -3079,8 +3128,8 @@ function skillRoutes(reader, options = {}) {
3079
3128
  const scopeRef = paramKey ? params[paramKey] ?? "" : "global";
3080
3129
  const name = params["name"] ?? "";
3081
3130
  const dir = reader.getSkillDir(scope, scopeRef, name);
3082
- const skillMd = join9(dir, "SKILL.md");
3083
- if (!existsSync7(skillMd)) {
3131
+ const skillMd = join10(dir, "SKILL.md");
3132
+ if (!existsSync8(skillMd)) {
3084
3133
  return c.json({ error: "Skill not found" }, 404);
3085
3134
  }
3086
3135
  const { content } = await c.req.json();
@@ -3088,7 +3137,7 @@ function skillRoutes(reader, options = {}) {
3088
3137
  if (failed)
3089
3138
  return c.json({ error: failed }, 500);
3090
3139
  try {
3091
- writeFileSync2(skillMd, content, "utf-8");
3140
+ writeFileSync3(skillMd, content, "utf-8");
3092
3141
  return c.json({ ok: true });
3093
3142
  } catch (err) {
3094
3143
  const message2 = err instanceof Error ? err.message : "Unknown error";
@@ -3101,8 +3150,8 @@ function skillRoutes(reader, options = {}) {
3101
3150
  const name = params["name"] ?? "";
3102
3151
  const filename = params["filename"] ?? "";
3103
3152
  const dir = reader.getSkillDir(scope, scopeRef, name);
3104
- const skillMd = join9(dir, "SKILL.md");
3105
- if (!existsSync7(skillMd)) {
3153
+ const skillMd = join10(dir, "SKILL.md");
3154
+ if (!existsSync8(skillMd)) {
3106
3155
  return c.json({ error: "Skill not found" }, 404);
3107
3156
  }
3108
3157
  const { content } = await c.req.json();
@@ -3110,9 +3159,9 @@ function skillRoutes(reader, options = {}) {
3110
3159
  if (failed)
3111
3160
  return c.json({ error: failed }, 500);
3112
3161
  try {
3113
- const refsDir = join9(dir, "references");
3162
+ const refsDir = join10(dir, "references");
3114
3163
  mkdirSync2(refsDir, { recursive: true });
3115
- writeFileSync2(join9(refsDir, filename), content, "utf-8");
3164
+ writeFileSync3(join10(refsDir, filename), content, "utf-8");
3116
3165
  return c.json({ ok: true });
3117
3166
  } catch (err) {
3118
3167
  const message2 = err instanceof Error ? err.message : "Unknown error";
@@ -3125,8 +3174,8 @@ function skillRoutes(reader, options = {}) {
3125
3174
  const name = params["name"] ?? "";
3126
3175
  const filename = params["filename"] ?? "";
3127
3176
  const dir = reader.getSkillDir(scope, scopeRef, name);
3128
- const refFile = join9(dir, "references", filename);
3129
- if (!existsSync7(refFile)) {
3177
+ const refFile = join10(dir, "references", filename);
3178
+ if (!existsSync8(refFile)) {
3130
3179
  return c.json({ error: "Reference not found" }, 404);
3131
3180
  }
3132
3181
  const failed = backup(scope, scopeRef, name, dir);
@@ -3145,7 +3194,7 @@ function skillRoutes(reader, options = {}) {
3145
3194
  const scopeRef = paramKey ? params[paramKey] ?? "" : "global";
3146
3195
  const name = params["name"] ?? "";
3147
3196
  const dir = reader.getSkillDir(scope, scopeRef, name);
3148
- if (!existsSync7(join9(dir, "SKILL.md"))) {
3197
+ if (!existsSync8(join10(dir, "SKILL.md"))) {
3149
3198
  return c.json({ error: "Skill not found" }, 404);
3150
3199
  }
3151
3200
  const failed = backup(scope, scopeRef, name, dir);
@@ -3291,15 +3340,15 @@ var init_skill_routes = __esm({
3291
3340
 
3292
3341
  // ../core/dist/pty-manager.js
3293
3342
  import * as pty2 from "node-pty";
3294
- import { existsSync as existsSync8, chmodSync, statSync as statSync2 } from "node:fs";
3295
- import { join as join10, dirname as dirname3 } from "node:path";
3343
+ import { existsSync as existsSync9, chmodSync, statSync as statSync2 } from "node:fs";
3344
+ import { join as join11, dirname as dirname3 } from "node:path";
3296
3345
  import { createRequire as createRequire2 } from "node:module";
3297
3346
  function ensureSpawnHelperPermissions() {
3298
3347
  try {
3299
3348
  const require2 = createRequire2(import.meta.url);
3300
3349
  const ptyPath = dirname3(require2.resolve("node-pty/package.json"));
3301
- const helper = join10(ptyPath, "prebuilds", `${process.platform}-${process.arch}`, "spawn-helper");
3302
- if (existsSync8(helper)) {
3350
+ const helper = join11(ptyPath, "prebuilds", `${process.platform}-${process.arch}`, "spawn-helper");
3351
+ if (existsSync9(helper)) {
3303
3352
  const mode = statSync2(helper).mode;
3304
3353
  if (!(mode & 73)) {
3305
3354
  chmodSync(helper, mode | 493);
@@ -3380,7 +3429,7 @@ function buildLaunch(session, isNew) {
3380
3429
  cmd += ` --model ${shellQuote(session.model)}`;
3381
3430
  return { command: cmd + harnessFlag, env };
3382
3431
  }
3383
- var SCROLLBACK_LIMIT, IDLE_TIMEOUT_MS, CLEANUP_INTERVAL_MS, shellQuote, SLASH_MAX, PTYManager;
3432
+ var SCROLLBACK_LIMIT, IDLE_TIMEOUT_MS, CLEANUP_INTERVAL_MS, shellQuote, SLASH_MAX, oneLine, PTYManager;
3384
3433
  var init_pty_manager = __esm({
3385
3434
  "../core/dist/pty-manager.js"() {
3386
3435
  "use strict";
@@ -3392,6 +3441,7 @@ var init_pty_manager = __esm({
3392
3441
  shellQuote = (value) => `'${value.replace(/'/g, "'\\''")}'`;
3393
3442
  ensureSpawnHelperPermissions();
3394
3443
  SLASH_MAX = 300;
3444
+ oneLine = (text2) => text2.replace(/[\x00-\x1f\x7f]+/g, " ").replace(/\s+/g, " ").trim();
3395
3445
  PTYManager = class {
3396
3446
  states;
3397
3447
  sessions = /* @__PURE__ */ new Map();
@@ -3412,7 +3462,7 @@ var init_pty_manager = __esm({
3412
3462
  return existing;
3413
3463
  const shell2 = process.env.SHELL || "/bin/zsh";
3414
3464
  const { command, env } = buildLaunch(session, options.isNew ?? false);
3415
- const cwd = session.worktree && existsSync8(session.worktree) ? session.worktree : session.type === "general" || session.type === "create" || session.type === "login" ? process.env.HOME ?? process.cwd() : process.cwd();
3465
+ const cwd = session.worktree && existsSync9(session.worktree) ? session.worktree : session.type === "general" || session.type === "create" || session.type === "login" ? process.env.HOME ?? process.cwd() : process.cwd();
3416
3466
  let ptyProcess;
3417
3467
  try {
3418
3468
  ptyProcess = pty2.spawn(shell2, ["-c", command], {
@@ -3433,6 +3483,7 @@ var init_pty_manager = __esm({
3433
3483
  cwd,
3434
3484
  command,
3435
3485
  createdAt: /* @__PURE__ */ new Date(),
3486
+ headless: options.headless ?? false,
3436
3487
  lastClientDisconnect: null,
3437
3488
  onDataDisposable: null,
3438
3489
  onExitDisposable: null
@@ -3534,7 +3585,7 @@ var init_pty_manager = __esm({
3534
3585
  if (session.clients.size === 0 && session.lastClientDisconnect && now - session.lastClientDisconnect.getTime() > IDLE_TIMEOUT_MS) {
3535
3586
  this.kill(key);
3536
3587
  }
3537
- if (session.clients.size === 0 && !session.lastClientDisconnect && now - session.createdAt.getTime() > IDLE_TIMEOUT_MS) {
3588
+ if (!session.headless && session.clients.size === 0 && !session.lastClientDisconnect && now - session.createdAt.getTime() > IDLE_TIMEOUT_MS) {
3538
3589
  this.kill(key);
3539
3590
  }
3540
3591
  }
@@ -3821,6 +3872,10 @@ var init_session_state = __esm({
3821
3872
  tracked?.screen.dispose();
3822
3873
  this.sessions.delete(key);
3823
3874
  }
3875
+ get(key) {
3876
+ const tracked = this.sessions.get(key);
3877
+ return tracked ? { ...tracked.entry } : void 0;
3878
+ }
3824
3879
  snapshot() {
3825
3880
  const now = Date.now();
3826
3881
  const out = {};
@@ -3942,21 +3997,6 @@ var init_state_log = __esm({
3942
3997
 
3943
3998
  // ../core/dist/pty-routes.js
3944
3999
  import { WebSocketServer, WebSocket } from "ws";
3945
- function takeSession(reader, project, sessionDir, general) {
3946
- const sessionId = `${project}::${sessionDir}`;
3947
- const pending = pendingSessions.get(sessionId);
3948
- if (pending) {
3949
- pendingSessions.delete(sessionId);
3950
- if (pending.type === "general")
3951
- general?.remember(sessionId, pending);
3952
- return { session: pending, isNew: true };
3953
- }
3954
- const session = reader.getSession(project, sessionDir);
3955
- if (session)
3956
- return { session, isNew: false };
3957
- const known = general?.get(sessionId);
3958
- return known ? { session: known, isNew: true } : null;
3959
- }
3960
4000
  function createTerminalWss(manager, reader, { localOnly = true, authToken, general } = {}) {
3961
4001
  const wss = new WebSocketServer({ noServer: true });
3962
4002
  function wireWs(ws, sessionId, project, sessionDir) {
@@ -4062,7 +4102,7 @@ var REFUSED_CLOSE_CODE;
4062
4102
  var init_pty_routes = __esm({
4063
4103
  "../core/dist/pty-routes.js"() {
4064
4104
  "use strict";
4065
- init_cw_routes();
4105
+ init_cw_start();
4066
4106
  init_origin_guard();
4067
4107
  init_auth();
4068
4108
  REFUSED_CLOSE_CODE = 4404;
@@ -4070,7 +4110,7 @@ var init_pty_routes = __esm({
4070
4110
  });
4071
4111
 
4072
4112
  // ../core/dist/general-sessions.js
4073
- import { existsSync as existsSync9, readFileSync as readFileSync7, writeFileSync as writeFileSync3, mkdirSync as mkdirSync4 } from "node:fs";
4113
+ import { existsSync as existsSync10, readFileSync as readFileSync7, writeFileSync as writeFileSync4, mkdirSync as mkdirSync4 } from "node:fs";
4074
4114
  import { dirname as dirname5 } from "node:path";
4075
4115
  var MAX_AGE_MS, GeneralSessions;
4076
4116
  var init_general_sessions = __esm({
@@ -4082,7 +4122,7 @@ var init_general_sessions = __esm({
4082
4122
  sessions = /* @__PURE__ */ new Map();
4083
4123
  constructor(file = null, now = Date.now()) {
4084
4124
  this.file = file;
4085
- if (!file || !existsSync9(file))
4125
+ if (!file || !existsSync10(file))
4086
4126
  return;
4087
4127
  try {
4088
4128
  const saved = JSON.parse(readFileSync7(file, "utf-8"));
@@ -4096,6 +4136,9 @@ var init_general_sessions = __esm({
4096
4136
  get(key) {
4097
4137
  return this.sessions.get(key);
4098
4138
  }
4139
+ list(project) {
4140
+ return [...this.sessions.values()].filter((s) => !project || s.project === project);
4141
+ }
4099
4142
  remember(key, session) {
4100
4143
  this.sessions.set(key, session);
4101
4144
  this.save();
@@ -4109,7 +4152,7 @@ var init_general_sessions = __esm({
4109
4152
  return;
4110
4153
  try {
4111
4154
  mkdirSync4(dirname5(this.file), { recursive: true });
4112
- writeFileSync3(this.file, JSON.stringify(Object.fromEntries(this.sessions), null, 2));
4155
+ writeFileSync4(this.file, JSON.stringify(Object.fromEntries(this.sessions), null, 2));
4113
4156
  } catch (err) {
4114
4157
  console.warn(`[pty] could not save general sessions: ${err.message}`);
4115
4158
  }
@@ -4119,10 +4162,10 @@ var init_general_sessions = __esm({
4119
4162
  });
4120
4163
 
4121
4164
  // ../core/dist/liveframe.js
4122
- import { existsSync as existsSync10, readFileSync as readFileSync8, readdirSync as readdirSync6 } from "node:fs";
4165
+ import { existsSync as existsSync11, readFileSync as readFileSync8, readdirSync as readdirSync6 } from "node:fs";
4123
4166
  import { mkdir, rm } from "node:fs/promises";
4124
4167
  import { homedir as homedir4 } from "node:os";
4125
- import { join as join11 } from "node:path";
4168
+ import { join as join12 } from "node:path";
4126
4169
  function slugify(name) {
4127
4170
  const slug = name.toLowerCase().normalize("NFKD").replace(/[\u0300-\u036f]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48);
4128
4171
  return slug || "untitled";
@@ -4171,13 +4214,13 @@ var init_liveframe = __esm({
4171
4214
  busy = /* @__PURE__ */ new Set();
4172
4215
  constructor(options = {}) {
4173
4216
  this.account = options.account ?? process.env.FORGE_LIVEFRAME_ACCOUNT ?? DEFAULT_ACCOUNT;
4174
- this.root = options.root ?? join11(homedir4(), "liveframe");
4175
- this.home = options.home ?? process.env.LIVEFRAME_HOME ?? join11(homedir4(), ".liveframe");
4217
+ this.root = options.root ?? join12(homedir4(), "liveframe");
4218
+ this.home = options.home ?? process.env.LIVEFRAME_HOME ?? join12(homedir4(), ".liveframe");
4176
4219
  this.run = options.run ?? createRunner(void 0, LF_TIMEOUT_MS);
4177
4220
  }
4178
4221
  // reads only the API base and whether a credential exists, never the credential itself
4179
4222
  config() {
4180
- const file = readJson2(join11(this.home, "config.json")) ?? {};
4223
+ const file = readJson2(join12(this.home, "config.json")) ?? {};
4181
4224
  const api = process.env.LIVEFRAME_API ?? (typeof file.api === "string" ? file.api : DEFAULT_API);
4182
4225
  return { api: api.replace(/\/+$/, ""), signedIn: Boolean(process.env.LIVEFRAME_TOKEN || file.oauth || file.token) };
4183
4226
  }
@@ -4187,11 +4230,11 @@ var init_liveframe = __esm({
4187
4230
  return { account: this.account, installed: version.code === 0, signedIn, api, root: this.root };
4188
4231
  }
4189
4232
  frameDir(project, frame) {
4190
- return join11(this.root, project, frame);
4233
+ return join12(this.root, project, frame);
4191
4234
  }
4192
4235
  readFrame(project, frame, api) {
4193
4236
  const dir = this.frameDir(project, frame);
4194
- const json = readJson2(join11(dir, "liveframe.json"));
4237
+ const json = readJson2(join12(dir, "liveframe.json"));
4195
4238
  if (!json || typeof json.key !== "string")
4196
4239
  return null;
4197
4240
  const branch = typeof json.branch === "string" ? json.branch : "main";
@@ -4211,14 +4254,14 @@ var init_liveframe = __esm({
4211
4254
  return this.readFrame(project, frame, this.config().api);
4212
4255
  }
4213
4256
  listFrames() {
4214
- if (!existsSync10(this.root))
4257
+ if (!existsSync11(this.root))
4215
4258
  return [];
4216
4259
  const { api } = this.config();
4217
4260
  const frames = [];
4218
4261
  for (const project of readdirSync6(this.root, { withFileTypes: true })) {
4219
4262
  if (!project.isDirectory() || !isFrameSegment(project.name))
4220
4263
  continue;
4221
- for (const frame of readdirSync6(join11(this.root, project.name), { withFileTypes: true })) {
4264
+ for (const frame of readdirSync6(join12(this.root, project.name), { withFileTypes: true })) {
4222
4265
  if (!frame.isDirectory() || !isFrameSegment(frame.name))
4223
4266
  continue;
4224
4267
  const found = this.readFrame(project.name, frame.name, api);
@@ -4249,9 +4292,9 @@ var init_liveframe = __esm({
4249
4292
  // runs lf into a fresh frame folder, removing whatever it left if it fails
4250
4293
  intoNewDir(project, frame, args) {
4251
4294
  return this.exclusive(project, frame, async () => {
4252
- const projectDir = join11(this.root, project);
4295
+ const projectDir = join12(this.root, project);
4253
4296
  const dir = this.frameDir(project, frame);
4254
- if (existsSync10(dir))
4297
+ if (existsSync11(dir))
4255
4298
  throw new LiveframeError(`${project}/${frame} already exists in ${this.root}`, 409);
4256
4299
  await mkdir(projectDir, { recursive: true });
4257
4300
  try {
@@ -4329,8 +4372,8 @@ var init_liveframe_routes = __esm({
4329
4372
  // ../core/dist/cw-install.js
4330
4373
  import { execFile as execFile5 } from "node:child_process";
4331
4374
  import { createHash as createHash3 } from "node:crypto";
4332
- import { accessSync as accessSync2, constants as constants2, existsSync as existsSync11, readFileSync as readFileSync9, statSync as statSync3, writeFileSync as writeFileSync4 } from "node:fs";
4333
- import { delimiter as delimiter2, join as join12 } from "node:path";
4375
+ import { accessSync as accessSync2, constants as constants2, existsSync as existsSync12, readFileSync as readFileSync9, statSync as statSync3, writeFileSync as writeFileSync5 } from "node:fs";
4376
+ import { delimiter as delimiter2, join as join13 } from "node:path";
4334
4377
  function readCwVersion(file) {
4335
4378
  try {
4336
4379
  const match = /^CW_VERSION="([^"]+)"/m.exec(readFileSync9(file, "utf-8"));
@@ -4351,9 +4394,9 @@ function compareVersions(a, b) {
4351
4394
  }
4352
4395
  function readCwBundle(dir) {
4353
4396
  try {
4354
- const { ref } = JSON.parse(readFileSync9(join12(dir, ".bundle.json"), "utf-8"));
4355
- const version = readCwVersion(join12(dir, "cw"));
4356
- if (!ref || !version || !existsSync11(join12(dir, "install.sh")))
4397
+ const { ref } = JSON.parse(readFileSync9(join13(dir, ".bundle.json"), "utf-8"));
4398
+ const version = readCwVersion(join13(dir, "cw"));
4399
+ if (!ref || !version || !existsSync12(join13(dir, "install.sh")))
4357
4400
  return null;
4358
4401
  return { dir, version, ref };
4359
4402
  } catch {
@@ -4383,7 +4426,7 @@ function findOnPath(name, pathVar, excludeDir) {
4383
4426
  for (const dir of (pathVar ?? "").split(delimiter2)) {
4384
4427
  if (!dir || dir === excludeDir)
4385
4428
  continue;
4386
- const candidate = join12(dir, name);
4429
+ const candidate = join13(dir, name);
4387
4430
  try {
4388
4431
  if (!statSync3(candidate).isFile())
4389
4432
  continue;
@@ -4395,13 +4438,13 @@ function findOnPath(name, pathVar, excludeDir) {
4395
4438
  return null;
4396
4439
  }
4397
4440
  function pathWithCw(cwHome, pathVar) {
4398
- const bin = join12(cwHome, "bin");
4441
+ const bin = join13(cwHome, "bin");
4399
4442
  const rest = (pathVar ?? "").split(delimiter2).filter((dir) => dir && dir !== bin);
4400
4443
  return [bin, ...rest].join(delimiter2);
4401
4444
  }
4402
4445
  function readMarker(cwHome) {
4403
4446
  try {
4404
- return JSON.parse(readFileSync9(join12(cwHome, MARKER_FILE), "utf-8"));
4447
+ return JSON.parse(readFileSync9(join13(cwHome, MARKER_FILE), "utf-8"));
4405
4448
  } catch {
4406
4449
  return null;
4407
4450
  }
@@ -4415,23 +4458,23 @@ async function ensureCw(options) {
4415
4458
  const { cwHome, bundleDir } = options;
4416
4459
  const env = options.env ?? process.env;
4417
4460
  const run2 = options.run ?? runInstall;
4418
- const bin = join12(cwHome, "bin", "cw");
4461
+ const bin = join13(cwHome, "bin", "cw");
4419
4462
  const bundle = readCwBundle(bundleDir);
4420
- const installed = existsSync11(bin) ? { version: readCwVersion(bin), sha256: sha256Of(bin) } : null;
4463
+ const installed = existsSync12(bin) ? { version: readCwVersion(bin), sha256: sha256Of(bin) } : null;
4421
4464
  const decision = decideCwInstall({
4422
4465
  bundle,
4423
4466
  installed,
4424
4467
  marker: readMarker(cwHome),
4425
- cwOnPath: findOnPath("cw", env.PATH, join12(cwHome, "bin")) !== null,
4468
+ cwOnPath: findOnPath("cw", env.PATH, join13(cwHome, "bin")) !== null,
4426
4469
  skip: env.FORGE_SKIP_CW_INSTALL === "1"
4427
4470
  });
4428
4471
  if (decision.action === "skip" || !bundle)
4429
4472
  return { action: "skipped", message: decision.reason };
4430
- const { code, output } = await run2(join12(bundle.dir, "install.sh"), ["--no-shell"], { ...env, CW_HOME: cwHome });
4431
- if (code !== 0 || !existsSync11(bin))
4473
+ const { code, output } = await run2(join13(bundle.dir, "install.sh"), ["--no-shell"], { ...env, CW_HOME: cwHome });
4474
+ if (code !== 0 || !existsSync12(bin))
4432
4475
  return { action: "failed", message: failureMessage2(output) };
4433
4476
  const marker = { version: bundle.version, ref: bundle.ref, sha256: sha256Of(bin) };
4434
- writeFileSync4(join12(cwHome, MARKER_FILE), JSON.stringify(marker, null, 2) + "\n");
4477
+ writeFileSync5(join13(cwHome, MARKER_FILE), JSON.stringify(marker, null, 2) + "\n");
4435
4478
  return {
4436
4479
  action: decision.action === "install" ? "installed" : "updated",
4437
4480
  version: bundle.version,
@@ -6549,9 +6592,9 @@ var init_kioku_versions = __esm({
6549
6592
 
6550
6593
  // ../core/dist/kioku.js
6551
6594
  import { spawn as spawn7 } from "node:child_process";
6552
- import { existsSync as existsSync12 } from "node:fs";
6595
+ import { existsSync as existsSync13 } from "node:fs";
6553
6596
  import { homedir as homedir5 } from "node:os";
6554
- import { join as join13 } from "node:path";
6597
+ import { join as join14 } from "node:path";
6555
6598
  import { createInterface } from "node:readline";
6556
6599
  import * as pty3 from "node-pty";
6557
6600
  function assertVersion(version) {
@@ -6563,8 +6606,8 @@ function assertRepo(repo, what) {
6563
6606
  throw new KiokuError(`${what} is named as owner/repo, not "${repo}"`, 400);
6564
6607
  }
6565
6608
  function resolveKiokuBin(pathVar = process.env.PATH, home = homedir5()) {
6566
- const fallback = join13(home, ".local", "bin", "kioku");
6567
- return findOnPath("kioku", pathVar) ?? (existsSync12(fallback) ? fallback : "kioku");
6609
+ const fallback = join14(home, ".local", "bin", "kioku");
6610
+ return findOnPath("kioku", pathVar) ?? (existsSync13(fallback) ? fallback : "kioku");
6568
6611
  }
6569
6612
  function rememberPrompt(text2) {
6570
6613
  return `Remember this with kioku: ${text2.replace(/\s+/g, " ").trim()}`;
@@ -6700,7 +6743,7 @@ var init_kioku = __esm({
6700
6743
  if (version.code !== 0)
6701
6744
  return MISSING;
6702
6745
  const listed = list?.brains ?? [];
6703
- const entries = Object.entries(this.projects()).filter(([, p]) => existsSync12(p.path));
6746
+ const entries = Object.entries(this.projects()).filter(([, p]) => existsSync13(p.path));
6704
6747
  const readBrain = async (b) => {
6705
6748
  if (!b.onDisk)
6706
6749
  return { kinds: {}, namespaces: [], writes: [] };
@@ -6842,7 +6885,7 @@ var init_kioku = __esm({
6842
6885
  if (!input.brain && !input.team)
6843
6886
  throw new KiokuError("name a project brain, a team brain, or both", 400);
6844
6887
  const path = this.projects()[input.project]?.path;
6845
- if (!path || !existsSync12(path))
6888
+ if (!path || !existsSync13(path))
6846
6889
  throw new KiokuError(`no CW project ${input.project} on this machine`, 404);
6847
6890
  if (input.brain)
6848
6891
  assertRepo(input.brain, "the project brain");
@@ -7077,16 +7120,24 @@ var SDK_VERSION, MODULE_ID_RE;
7077
7120
  var init_define = __esm({
7078
7121
  "../sdk/dist/define.js"() {
7079
7122
  "use strict";
7080
- SDK_VERSION = "1.0.0";
7123
+ SDK_VERSION = "1.1.0";
7081
7124
  MODULE_ID_RE = /^[a-z][a-z0-9-]{1,31}$/;
7082
7125
  }
7083
7126
  });
7084
7127
 
7085
7128
  // ../sdk/dist/errors.js
7086
- var PermissionError;
7129
+ var ModuleError, PermissionError;
7087
7130
  var init_errors = __esm({
7088
7131
  "../sdk/dist/errors.js"() {
7089
7132
  "use strict";
7133
+ ModuleError = class extends Error {
7134
+ code;
7135
+ constructor(code, message2) {
7136
+ super(message2);
7137
+ this.name = "ModuleError";
7138
+ this.code = code;
7139
+ }
7140
+ };
7090
7141
  PermissionError = class extends Error {
7091
7142
  permission;
7092
7143
  value;
@@ -7111,7 +7162,7 @@ var init_dist = __esm({
7111
7162
 
7112
7163
  // ../core/dist/module-permissions.js
7113
7164
  import { realpathSync } from "node:fs";
7114
- import { basename as basename3, dirname as dirname6, join as join14, resolve as resolve5, sep as sep3 } from "node:path";
7165
+ import { basename as basename3, dirname as dirname6, join as join15, resolve as resolve5, sep as sep3 } from "node:path";
7115
7166
  function expandGrants(permissions, settings) {
7116
7167
  const p = permissions ?? {};
7117
7168
  return {
@@ -7119,7 +7170,9 @@ function expandGrants(permissions, settings) {
7119
7170
  fsRead: expandAll(p["fs:read"], settings, "path").map(expandHome),
7120
7171
  fsWrite: expandAll(p["fs:write"], settings, "path").map(expandHome),
7121
7172
  shell: expandAll(p.shell, settings, "path").map(expandHome),
7122
- pty: p.pty === true
7173
+ pty: p.pty === true,
7174
+ cw: new Set(p.cw ?? []),
7175
+ agent: p.agent === true
7123
7176
  };
7124
7177
  }
7125
7178
  function expandAll(templates, settings, kind) {
@@ -7191,7 +7244,7 @@ function realOrParent(path) {
7191
7244
  return realpathSync(path);
7192
7245
  } catch {
7193
7246
  const parent = dirname6(path);
7194
- return parent === path ? path : join14(realOrParent(parent), basename3(path));
7247
+ return parent === path ? path : join15(realOrParent(parent), basename3(path));
7195
7248
  }
7196
7249
  }
7197
7250
  var TEMPLATE_RE;
@@ -7205,7 +7258,7 @@ var init_module_permissions = __esm({
7205
7258
 
7206
7259
  // ../core/dist/module-manifest.js
7207
7260
  import { readFileSync as readFileSync10 } from "node:fs";
7208
- import { join as join15, resolve as resolve6, sep as sep4 } from "node:path";
7261
+ import { join as join16, resolve as resolve6, sep as sep4 } from "node:path";
7209
7262
  function checkSdk(range, version = SDK_VERSION) {
7210
7263
  if (!import_semver2.default.validRange(range))
7211
7264
  return `sdk range "${range}" is not valid semver`;
@@ -7239,6 +7292,8 @@ function checkManifest(raw, moduleDir) {
7239
7292
  err("/view/entry", "required string");
7240
7293
  else if (raw.view.title !== void 0 && typeof raw.view.title !== "string")
7241
7294
  err("/view/title", "must be a string");
7295
+ if (isObject(raw.view) && raw.view.banner !== void 0 && (typeof raw.view.banner !== "string" || raw.view.banner === ""))
7296
+ err("/view/banner", "must be a non-empty string");
7242
7297
  }
7243
7298
  if (raw.permissions !== void 0) {
7244
7299
  if (!isObject(raw.permissions))
@@ -7247,9 +7302,14 @@ function checkManifest(raw, moduleDir) {
7247
7302
  for (const [key, value] of Object.entries(raw.permissions)) {
7248
7303
  if (!PERMISSIONS.has(key))
7249
7304
  err(`/permissions/${key}`, "unknown permission");
7250
- else if (key === "pty" ? typeof value !== "boolean" : !isStringArray(value)) {
7251
- err(`/permissions/${key}`, key === "pty" ? "must be a boolean" : "must be a list of strings");
7252
- }
7305
+ else if (BOOLEAN_PERMISSIONS.has(key)) {
7306
+ if (typeof value !== "boolean")
7307
+ err(`/permissions/${key}`, "must be a boolean");
7308
+ } else if (key === "cw") {
7309
+ if (!Array.isArray(value) || !value.every((v) => v === "start" || v === "send"))
7310
+ err("/permissions/cw", 'must be a list of "start" or "send"');
7311
+ } else if (!isStringArray(value))
7312
+ err(`/permissions/${key}`, "must be a list of strings");
7253
7313
  }
7254
7314
  }
7255
7315
  }
@@ -7270,7 +7330,7 @@ function checkManifest(raw, moduleDir) {
7270
7330
  return { kind: "invalid", reason: sdkReason };
7271
7331
  }
7272
7332
  if (errors.length === 0) {
7273
- const entries = [["/server", raw.server], ["/view/entry", isObject(raw.view) ? raw.view.entry : void 0]];
7333
+ const entries = [["/server", raw.server], ["/view/entry", isObject(raw.view) ? raw.view.entry : void 0], ["/view/banner", isObject(raw.view) ? raw.view.banner : void 0]];
7274
7334
  for (const [path, value] of entries) {
7275
7335
  if (typeof value === "string" && !insideFolder(moduleDir, value))
7276
7336
  err(path, "points outside the module folder");
@@ -7313,11 +7373,11 @@ function insideFolder(dir, relative) {
7313
7373
  }
7314
7374
  function manifestFileFor(dir) {
7315
7375
  try {
7316
- const pkg = JSON.parse(readFileSync10(join15(dir, "package.json"), "utf-8"));
7376
+ const pkg = JSON.parse(readFileSync10(join16(dir, "package.json"), "utf-8"));
7317
7377
  const manifest = typeof pkg.forge?.manifest === "string" ? pkg.forge.manifest : "forge-module.json";
7318
- return { file: join15(dir, manifest), hasForgeField: pkg.forge !== void 0 };
7378
+ return { file: join16(dir, manifest), hasForgeField: pkg.forge !== void 0 };
7319
7379
  } catch {
7320
- return { file: join15(dir, "forge-module.json"), hasForgeField: false };
7380
+ return { file: join16(dir, "forge-module.json"), hasForgeField: false };
7321
7381
  }
7322
7382
  }
7323
7383
  function validateSettings(schema, values) {
@@ -7383,7 +7443,7 @@ function scalar(def, raw, path, errors) {
7383
7443
  return typeof v === "string" && def.values.includes(v) ? v : fail(`must be one of ${def.values.join(", ")}`);
7384
7444
  }
7385
7445
  }
7386
- var import_semver2, V1_FIELDS, TOP_LEVEL, PERMISSIONS, SCALAR_TYPES, FORMATS, isObject, isStringArray;
7446
+ var import_semver2, V1_FIELDS, TOP_LEVEL, PERMISSIONS, BOOLEAN_PERMISSIONS, SCALAR_TYPES, FORMATS, isObject, isStringArray;
7387
7447
  var init_module_manifest = __esm({
7388
7448
  "../core/dist/module-manifest.js"() {
7389
7449
  "use strict";
@@ -7392,7 +7452,8 @@ var init_module_manifest = __esm({
7392
7452
  init_module_permissions();
7393
7453
  V1_FIELDS = ["server", "view", "permissions", "id"];
7394
7454
  TOP_LEVEL = /* @__PURE__ */ new Set(["$schema", "id", "name", "version", "sdk", "displayName", "description", "icon", "color", "server", "view", "permissions", "settings", "actions", "detectors", "panels", "claude"]);
7395
- PERMISSIONS = /* @__PURE__ */ new Set(["network", "fs:read", "fs:write", "shell", "pty"]);
7455
+ PERMISSIONS = /* @__PURE__ */ new Set(["network", "fs:read", "fs:write", "shell", "pty", "cw", "agent"]);
7456
+ BOOLEAN_PERMISSIONS = /* @__PURE__ */ new Set(["pty", "agent"]);
7396
7457
  SCALAR_TYPES = /* @__PURE__ */ new Set(["string", "number", "boolean", "enum"]);
7397
7458
  FORMATS = /* @__PURE__ */ new Set(["path", "cw-project", "url"]);
7398
7459
  isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
@@ -7422,7 +7483,32 @@ function createForgeContext(deps, mod, getSettings, getGrants, onDenial) {
7422
7483
  return getSettings();
7423
7484
  },
7424
7485
  sessions: {
7425
- list: async () => deps.reader.getSpaces().map(toSessionInfo)
7486
+ list: async () => deps.reader.getSpaces().map(toSessionInfo),
7487
+ send: async (project, sessionDir, text2) => {
7488
+ if (!getGrants().cw.has("send"))
7489
+ deny("cw", "send");
7490
+ if (!deps.cw)
7491
+ throw new Error("sessions.send is not available in this Forge");
7492
+ return deps.cw.send(project, sessionDir, text2);
7493
+ }
7494
+ },
7495
+ cw: {
7496
+ start: async (input) => {
7497
+ if (!getGrants().cw.has("start"))
7498
+ deny("cw", "start");
7499
+ if (!deps.cw)
7500
+ throw new Error("cw.start is not available in this Forge");
7501
+ return deps.cw.start(input);
7502
+ }
7503
+ },
7504
+ agent: {
7505
+ run: async (input) => {
7506
+ if (!getGrants().agent)
7507
+ deny("agent", input.account);
7508
+ if (!deps.agent)
7509
+ throw new Error("agent.run is not available in this Forge");
7510
+ return deps.agent.run(input);
7511
+ }
7426
7512
  },
7427
7513
  projects: {
7428
7514
  list: async () => Object.entries(deps.reader.getProjects()).map(([name, p]) => ({ name, path: p.path, account: p.account })),
@@ -7512,7 +7598,8 @@ function toSessionInfo(s) {
7512
7598
  harness: s.harness,
7513
7599
  provider: s.provider,
7514
7600
  model: s.model,
7515
- worktreePath: s.worktree
7601
+ worktreePath: s.worktree,
7602
+ taskUrl: s.source_url || void 0
7516
7603
  };
7517
7604
  }
7518
7605
  function parseGitStatus(output) {
@@ -7544,15 +7631,15 @@ var init_module_context = __esm({
7544
7631
  });
7545
7632
 
7546
7633
  // ../core/dist/module-host.js
7547
- import { existsSync as existsSync13, readdirSync as readdirSync7, readFileSync as readFileSync11, statSync as statSync4, writeFileSync as writeFileSync5 } from "node:fs";
7548
- import { basename as basename4, dirname as dirname7, join as join16, resolve as resolve7, sep as sep5 } from "node:path";
7634
+ import { existsSync as existsSync14, mkdirSync as mkdirSync5, readdirSync as readdirSync7, readFileSync as readFileSync11, statSync as statSync4, writeFileSync as writeFileSync6 } from "node:fs";
7635
+ import { basename as basename4, dirname as dirname7, join as join17, resolve as resolve7, sep as sep5 } from "node:path";
7549
7636
  import { pathToFileURL } from "node:url";
7550
7637
  function disabled(id, c, reason, m) {
7551
7638
  const text2 = (v, fallback) => typeof v === "string" && v ? v : fallback;
7552
7639
  return { id, name: text2(m?.name, id), version: text2(m?.version, ""), displayName: text2(m?.displayName, id), source: c.source, state: "disabled", reason };
7553
7640
  }
7554
7641
  function packages(root, source, packaged) {
7555
- if (!existsSync13(root))
7642
+ if (!existsSync14(root))
7556
7643
  return [];
7557
7644
  const out = [];
7558
7645
  const consider = (dir, name) => {
@@ -7565,20 +7652,20 @@ function packages(root, source, packaged) {
7565
7652
  if (!isDir(root, entry) || entry.name.startsWith("."))
7566
7653
  continue;
7567
7654
  if (entry.name.startsWith("@")) {
7568
- for (const sub of readdirSync7(join16(root, entry.name), { withFileTypes: true })) {
7569
- if (isDir(join16(root, entry.name), sub))
7570
- consider(join16(root, entry.name, sub.name), `${entry.name}/${sub.name}`);
7655
+ for (const sub of readdirSync7(join17(root, entry.name), { withFileTypes: true })) {
7656
+ if (isDir(join17(root, entry.name), sub))
7657
+ consider(join17(root, entry.name, sub.name), `${entry.name}/${sub.name}`);
7571
7658
  }
7572
7659
  } else {
7573
- consider(join16(root, entry.name), entry.name);
7660
+ consider(join17(root, entry.name), entry.name);
7574
7661
  }
7575
7662
  }
7576
7663
  return out;
7577
7664
  }
7578
7665
  function nearestPackage(dir) {
7579
7666
  for (let d = dir; ; d = dirname7(d)) {
7580
- const path = join16(d, "package.json");
7581
- if (existsSync13(path)) {
7667
+ const path = join17(d, "package.json");
7668
+ if (existsSync14(path)) {
7582
7669
  try {
7583
7670
  return { path, type: JSON.parse(readFileSync11(path, "utf-8")).type };
7584
7671
  } catch {
@@ -7595,7 +7682,7 @@ function isDir(parent, entry) {
7595
7682
  if (!entry.isSymbolicLink())
7596
7683
  return false;
7597
7684
  try {
7598
- return statSync4(join16(parent, entry.name)).isDirectory();
7685
+ return statSync4(join17(parent, entry.name)).isDirectory();
7599
7686
  } catch {
7600
7687
  return false;
7601
7688
  }
@@ -7635,14 +7722,16 @@ var init_module_host = __esm({
7635
7722
  init_module_permissions();
7636
7723
  init_module_context();
7637
7724
  init_modules();
7638
- RESERVED_SEGMENTS = /* @__PURE__ */ new Set(["settings", "actions", "view.js", "status", "notifications", "reload"]);
7725
+ RESERVED_SEGMENTS = /* @__PURE__ */ new Set(["settings", "actions", "view.js", "banner.js", "banner", "status", "notifications", "reload"]);
7639
7726
  ModuleHost = class {
7640
7727
  opts;
7641
7728
  statuses = [];
7642
7729
  loaded = /* @__PURE__ */ new Map();
7643
7730
  origins = /* @__PURE__ */ new Map();
7731
+ bannersFile;
7644
7732
  constructor(opts) {
7645
7733
  this.opts = opts;
7734
+ this.bannersFile = join17(dirname7(opts.devFile), "module-banners.json");
7646
7735
  }
7647
7736
  list() {
7648
7737
  return this.statuses;
@@ -7658,7 +7747,7 @@ var init_module_host = __esm({
7658
7747
  // only what was installed into the modules folder; bundled, dev and Forge's own packages stay
7659
7748
  removable(c) {
7660
7749
  const { modulesDir } = this.opts;
7661
- return c.source === "installed" && dirname7(c.dir) === modulesDir || c.dir.startsWith(join16(modulesDir, "node_modules") + sep5);
7750
+ return c.source === "installed" && dirname7(c.dir) === modulesDir || c.dir.startsWith(join17(modulesDir, "node_modules") + sep5);
7662
7751
  }
7663
7752
  // scans, reloads and dev changes run one at a time: each one awaits imports midway
7664
7753
  queue = Promise.resolve();
@@ -7711,14 +7800,14 @@ var init_module_host = __esm({
7711
7800
  const dirs = this.devDirs();
7712
7801
  const dir = resolve7(path);
7713
7802
  if (!dirs.includes(dir))
7714
- writeFileSync5(this.opts.devFile, JSON.stringify([...dirs, dir], null, 2));
7803
+ writeFileSync6(this.opts.devFile, JSON.stringify([...dirs, dir], null, 2));
7715
7804
  await this.scanNow();
7716
7805
  return this.statuses.find((s) => this.loaded.get(s.id)?.dir === dir) ?? this.statuses.find((s) => s.state !== "enabled" && s.id === basename4(dir));
7717
7806
  }
7718
7807
  removeDev(path) {
7719
7808
  return this.serial(async () => {
7720
7809
  const dir = resolve7(path);
7721
- writeFileSync5(this.opts.devFile, JSON.stringify(this.devDirs().filter((d) => d !== dir), null, 2));
7810
+ writeFileSync6(this.opts.devFile, JSON.stringify(this.devDirs().filter((d) => d !== dir), null, 2));
7722
7811
  await this.scanNow();
7723
7812
  });
7724
7813
  }
@@ -7755,6 +7844,24 @@ var init_module_host = __esm({
7755
7844
  mod.abort.abort();
7756
7845
  this.loaded.delete(id);
7757
7846
  }
7847
+ readBanners() {
7848
+ try {
7849
+ const raw = JSON.parse(readFileSync11(this.bannersFile, "utf-8"));
7850
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
7851
+ return {};
7852
+ return Object.fromEntries(Object.entries(raw).filter((e) => typeof e[1] === "boolean"));
7853
+ } catch {
7854
+ return {};
7855
+ }
7856
+ }
7857
+ setBanner(id, enabled) {
7858
+ const banner = this.loaded.get(id)?.status.banner;
7859
+ if (!banner)
7860
+ return;
7861
+ mkdirSync5(dirname7(this.bannersFile), { recursive: true });
7862
+ writeFileSync6(this.bannersFile, JSON.stringify({ ...this.readBanners(), [id]: enabled }, null, 2));
7863
+ banner.enabled = enabled;
7864
+ }
7758
7865
  devDirs() {
7759
7866
  try {
7760
7867
  const raw = JSON.parse(readFileSync11(this.opts.devFile, "utf-8"));
@@ -7765,18 +7872,18 @@ var init_module_host = __esm({
7765
7872
  }
7766
7873
  candidates() {
7767
7874
  const out = [];
7768
- const folder = (dir, source) => out.push({ dir, source, manifestFile: join16(dir, "forge-module.json"), packaged: false });
7875
+ const folder = (dir, source) => out.push({ dir, source, manifestFile: join17(dir, "forge-module.json"), packaged: false });
7769
7876
  if (this.opts.bundledDir)
7770
- for (const name of BUNDLED_MODULES)
7771
- folder(join16(this.opts.bundledDir, name), "bundled");
7877
+ for (const name of [...BUNDLED_MODULES, ...BUNDLED_V1_MODULES])
7878
+ folder(join17(this.opts.bundledDir, name), "bundled");
7772
7879
  for (const dir of this.devDirs())
7773
7880
  folder(dir, "dev");
7774
- if (existsSync13(this.opts.modulesDir)) {
7881
+ if (existsSync14(this.opts.modulesDir)) {
7775
7882
  for (const entry of readdirSync7(this.opts.modulesDir, { withFileTypes: true })) {
7776
7883
  if (entry.isDirectory() && entry.name !== "node_modules" && !entry.name.startsWith("."))
7777
- folder(join16(this.opts.modulesDir, entry.name), "installed");
7884
+ folder(join17(this.opts.modulesDir, entry.name), "installed");
7778
7885
  }
7779
- out.push(...packages(join16(this.opts.modulesDir, "node_modules"), "node_modules", true));
7886
+ out.push(...packages(join17(this.opts.modulesDir, "node_modules"), "node_modules", true));
7780
7887
  }
7781
7888
  if (this.opts.forgeNodeModules)
7782
7889
  out.push(...packages(this.opts.forgeNodeModules, "node_modules", false));
@@ -7790,7 +7897,7 @@ var init_module_host = __esm({
7790
7897
  }
7791
7898
  async loadCandidate(c, seen) {
7792
7899
  const fallbackId = basename4(c.dir);
7793
- if (!existsSync13(c.manifestFile)) {
7900
+ if (!existsSync14(c.manifestFile)) {
7794
7901
  return c.packaged ? disabled(fallbackId, c, `no manifest at ${c.manifestFile}`) : void 0;
7795
7902
  }
7796
7903
  let raw;
@@ -7845,9 +7952,14 @@ var init_module_host = __esm({
7845
7952
  };
7846
7953
  if (m.view) {
7847
7954
  const entry = resolve7(c.dir, m.view.entry);
7848
- const mtime = existsSync13(entry) ? Math.floor(statSync4(entry).mtimeMs) : 0;
7955
+ const mtime = existsSync14(entry) ? Math.floor(statSync4(entry).mtimeMs) : 0;
7849
7956
  status.view = { url: `/api/modules/${m.id}/view.js`, title: m.view.title ?? m.displayName, version: `${m.version}-${mtime}` };
7850
7957
  }
7958
+ if (m.view?.banner) {
7959
+ const file = resolve7(c.dir, m.view.banner);
7960
+ const mtime = existsSync14(file) ? Math.floor(statSync4(file).mtimeMs) : 0;
7961
+ status.banner = { url: `/api/modules/${m.id}/banner.js`, version: mtime, enabled: this.readBanners()[m.id] ?? c.source === "bundled" };
7962
+ }
7851
7963
  const settings = this.readSettings(m);
7852
7964
  const abort = new AbortController();
7853
7965
  const mod = { status, dir: c.dir, manifest: m, server, abort, settings, candidate: c, grants: expandGrants(m.permissions, settings), ctx: void 0 };
@@ -7930,13 +8042,13 @@ var init_module_confirmations = __esm({
7930
8042
 
7931
8043
  // ../core/dist/module-install.js
7932
8044
  import { randomBytes as randomBytes2 } from "node:crypto";
7933
- import { existsSync as existsSync14, mkdirSync as mkdirSync5, mkdtempSync, readFileSync as readFileSync12, rmSync as rmSync3 } from "node:fs";
8045
+ import { existsSync as existsSync15, mkdirSync as mkdirSync6, mkdtempSync, readFileSync as readFileSync12, rmSync as rmSync3 } from "node:fs";
7934
8046
  import { homedir as homedir7, tmpdir } from "node:os";
7935
- import { isAbsolute as isAbsolute2, join as join17, resolve as resolve8, sep as sep6 } from "node:path";
8047
+ import { isAbsolute as isAbsolute2, join as join18, resolve as resolve8, sep as sep6 } from "node:path";
7936
8048
  async function previewManifest(spec, opts) {
7937
8049
  if (isPathSpec(spec, opts.cwd))
7938
8050
  return readFolder(expand(spec, opts.cwd));
7939
- const tmp = mkdtempSync(join17(tmpdir(), "forge-module-pack-"));
8051
+ const tmp = mkdtempSync(join18(tmpdir(), "forge-module-pack-"));
7940
8052
  try {
7941
8053
  const packed = await opts.run("npm", ["pack", spec, "--pack-destination", tmp, "--ignore-scripts", "--json"], opts.cwd);
7942
8054
  if (packed.code !== 0)
@@ -7945,10 +8057,10 @@ async function previewManifest(spec, opts) {
7945
8057
  const filename = info?.filename;
7946
8058
  if (!filename)
7947
8059
  throw new Error(`npm pack ${spec} produced no tarball`);
7948
- const untar = await opts.run("tar", ["-xzf", join17(tmp, filename), "-C", tmp], opts.cwd);
8060
+ const untar = await opts.run("tar", ["-xzf", join18(tmp, filename), "-C", tmp], opts.cwd);
7949
8061
  if (untar.code !== 0)
7950
8062
  throw new Error(`could not unpack ${filename}: ${untar.stderr.trim()}`);
7951
- const preview = readFolder(join17(tmp, "package"));
8063
+ const preview = readFolder(join18(tmp, "package"));
7952
8064
  return info.name && info.version ? { ...preview, packed: { name: info.name, version: info.version } } : preview;
7953
8065
  } finally {
7954
8066
  rmSync3(tmp, { recursive: true, force: true });
@@ -7962,7 +8074,7 @@ function npmPackError(spec, output) {
7962
8074
  }
7963
8075
  function readFolder(dir) {
7964
8076
  const manifestFile = manifestFileFor(dir).file;
7965
- if (!existsSync14(manifestFile))
8077
+ if (!existsSync15(manifestFile))
7966
8078
  throw new Error(`${dir} has no forge-module.json`);
7967
8079
  const raw = JSON.parse(readFileSync12(manifestFile, "utf-8"));
7968
8080
  const check = checkManifest(raw, dir);
@@ -7979,6 +8091,10 @@ function permissionLines(manifest) {
7979
8091
  }
7980
8092
  if (p.pty)
7981
8093
  lines2.push({ kind: "pty", value: "yes" });
8094
+ if (p.cw?.length)
8095
+ lines2.push({ kind: "cw", value: p.cw.join(", ") });
8096
+ if (p.agent)
8097
+ lines2.push({ kind: "agent", value: "runs Claude with MCP tools" });
7982
8098
  const legacy = "actions" in manifest && (manifest.actions ?? []).some((a) => "command" in a);
7983
8099
  if (legacy)
7984
8100
  lines2.push({ kind: "shell", value: "runs the shell commands in its manifest" });
@@ -7993,7 +8109,7 @@ function installArgs(spec, prefix) {
7993
8109
  }
7994
8110
  function packageName(dir) {
7995
8111
  try {
7996
- const name = JSON.parse(readFileSync12(join17(dir, "package.json"), "utf-8")).name;
8112
+ const name = JSON.parse(readFileSync12(join18(dir, "package.json"), "utf-8")).name;
7997
8113
  return typeof name === "string" ? name : void 0;
7998
8114
  } catch {
7999
8115
  return void 0;
@@ -8007,7 +8123,7 @@ var init_module_install = __esm({
8007
8123
  init_output();
8008
8124
  init_state_log();
8009
8125
  TRUST_NOTE = "Modules run inside Forge with your access. Forge checks every call against these permissions, but it is not a sandbox: install only modules you trust.";
8010
- isPathSpec = (spec, cwd) => spec.startsWith(".") || spec.startsWith("~") || isAbsolute2(spec) || existsSync14(resolve8(cwd, spec)) && !spec.startsWith("@");
8126
+ isPathSpec = (spec, cwd) => spec.startsWith(".") || spec.startsWith("~") || isAbsolute2(spec) || existsSync15(resolve8(cwd, spec)) && !spec.startsWith("@");
8011
8127
  expand = (spec, cwd) => resolve8(cwd, expandHome(spec));
8012
8128
  InstallError = class extends Error {
8013
8129
  code;
@@ -8054,6 +8170,7 @@ var init_module_install = __esm({
8054
8170
  displayName: m.displayName,
8055
8171
  description: "description" in m && typeof m.description === "string" ? m.description : void 0,
8056
8172
  spec: pinned,
8173
+ banner: "view" in m && m.view?.banner ? true : void 0,
8057
8174
  permissions: permissionLines(m),
8058
8175
  trustNote: TRUST_NOTE
8059
8176
  };
@@ -8064,7 +8181,7 @@ var init_module_install = __esm({
8064
8181
  if (!p || p.expires < this.now)
8065
8182
  throw new InstallError("confirmation_required", "Preview the module again before installing it");
8066
8183
  return this.exclusive(async () => {
8067
- mkdirSync5(this.opts.modulesDir, { recursive: true });
8184
+ mkdirSync6(this.opts.modulesDir, { recursive: true });
8068
8185
  const res = await this.opts.run("npm", installArgs(p.spec, this.opts.modulesDir), this.opts.modulesDir);
8069
8186
  if (res.code !== 0)
8070
8187
  throw new InstallError("install_failed", `npm install failed: ${tailOutput(res.stderr || res.stdout, 6)}`);
@@ -8079,7 +8196,7 @@ var init_module_install = __esm({
8079
8196
  throw new InstallError("not_found", `No module ${id}`);
8080
8197
  if (!found.removable)
8081
8198
  throw new InstallError("bad_request", `${id} was not installed into Forge's modules folder; a dev folder unloads when forge module dev stops`);
8082
- const packages2 = join17(this.opts.modulesDir, "node_modules") + sep6;
8199
+ const packages2 = join18(this.opts.modulesDir, "node_modules") + sep6;
8083
8200
  if (found.dir.startsWith(packages2)) {
8084
8201
  const name = packageName(found.dir) ?? found.dir.slice(packages2.length);
8085
8202
  const res = await this.opts.run("npm", ["uninstall", "--prefix", this.opts.modulesDir, name], this.opts.modulesDir);
@@ -8206,6 +8323,31 @@ function moduleRoutes(host, opts) {
8206
8323
  return c.json({ code: "not_found", message: `view bundle missing: ${err.message}` }, 404);
8207
8324
  }
8208
8325
  });
8326
+ app.get("/:id/banner.js", async (c) => {
8327
+ const mod = host.get(c.req.param("id"));
8328
+ if (!mod?.manifest.view?.banner)
8329
+ return c.json(removed(c.req.param("id")), 404);
8330
+ try {
8331
+ const code = await readFile2(resolve9(mod.dir, mod.manifest.view.banner), "utf-8");
8332
+ return c.body(code, 200, { "Content-Type": "text/javascript; charset=utf-8", "Cache-Control": "no-cache" });
8333
+ } catch (err) {
8334
+ return c.json({ code: "not_found", message: `banner bundle missing: ${err.message}` }, 404);
8335
+ }
8336
+ });
8337
+ app.put("/:id/banner", async (c) => {
8338
+ const id = c.req.param("id");
8339
+ if (!host.get(id)?.status.banner)
8340
+ return c.json(removed(id), 404);
8341
+ const body2 = await c.req.json().catch(() => ({}));
8342
+ if (typeof body2.enabled !== "boolean")
8343
+ return c.json({ code: "bad_request", message: "enabled must be a boolean" }, 400);
8344
+ try {
8345
+ host.setBanner(id, body2.enabled);
8346
+ } catch (err) {
8347
+ return c.json({ code: "internal", message: `could not save the banner switch: ${err.message}` }, 500);
8348
+ }
8349
+ return c.json(host.get(id).status);
8350
+ });
8209
8351
  app.post("/:id/actions/:action/prepare", async (c) => {
8210
8352
  const found = await findAction(c);
8211
8353
  if (found instanceof Response)
@@ -8415,6 +8557,158 @@ var init_module_routes = __esm({
8415
8557
  }
8416
8558
  });
8417
8559
 
8560
+ // ../core/dist/module-cw.js
8561
+ function createCwDeps(o) {
8562
+ const { reader, manager, states, general } = o;
8563
+ const waitMs = o.waitMs ?? DEFAULT_WAIT_MS;
8564
+ const waitFor = async (key, ready) => {
8565
+ const deadline = Date.now() + waitMs;
8566
+ while (!ready(states?.get(key)?.state)) {
8567
+ if (Date.now() >= deadline)
8568
+ throw new ModuleError("unreachable", `${key} did not reach its prompt in ${Math.round(waitMs / 1e3)} s`);
8569
+ await sleep(POLL_MS);
8570
+ }
8571
+ };
8572
+ const start = async (input) => {
8573
+ const account = input.account ?? (input.type === "general" ? (input.project ? reader.getProjects()[input.project]?.account : void 0) ?? reader.getAccounts()[0] : void 0);
8574
+ const prepared = await prepareStart({
8575
+ type: input.type,
8576
+ project: input.project,
8577
+ task: input.task,
8578
+ description: input.description,
8579
+ directory: input.directory,
8580
+ account,
8581
+ harness: input.harness
8582
+ }, { reader });
8583
+ if (!prepared.ok)
8584
+ throw new ModuleError("bad_request", prepared.error);
8585
+ const { project, sessionDir } = prepared.session;
8586
+ if (!sessionDir)
8587
+ throw new ModuleError("upstream", "the session has no folder name");
8588
+ const pty4 = launchHeadless(project, sessionDir, { reader, manager, general });
8589
+ if (!pty4)
8590
+ throw new ModuleError("upstream", `could not start ${project}/${sessionDir}`);
8591
+ const prompt = input.type === "general" && input.prompt ? oneLine(input.prompt) : "";
8592
+ if (prompt) {
8593
+ await waitFor(`${project}::${sessionDir}`, (state) => state === "waiting");
8594
+ if (!manager.typeLine(project, sessionDir, prompt))
8595
+ throw new ModuleError("unreachable", `${project}::${sessionDir} closed before it could be typed into`);
8596
+ }
8597
+ return { project, sessionDir };
8598
+ };
8599
+ const send = async (project, sessionDir, text2) => {
8600
+ const key = `${project}::${sessionDir}`;
8601
+ const stored = reader.getSession(project, sessionDir);
8602
+ const session = stored ?? general.get(key);
8603
+ if (!session)
8604
+ return "unavailable";
8605
+ if ((session.harness ?? "claude") !== "claude")
8606
+ return "unsupported";
8607
+ const wasLive = manager.has(key);
8608
+ if (!wasLive) {
8609
+ if (!stored)
8610
+ return "unavailable";
8611
+ const pty4 = manager.getOrCreate(project, sessionDir, stored, { isNew: false, headless: true });
8612
+ if (!pty4)
8613
+ throw new ModuleError("unreachable", `could not resume ${key}`);
8614
+ }
8615
+ await waitFor(key, (state) => state === "waiting" || state === "idle");
8616
+ if (!manager.typeLine(project, sessionDir, oneLine(text2)))
8617
+ throw new ModuleError("unreachable", `${key} closed before it could be typed into`);
8618
+ return wasLive ? "typed" : "resumed";
8619
+ };
8620
+ return { start, send };
8621
+ }
8622
+ var POLL_MS, DEFAULT_WAIT_MS, sleep;
8623
+ var init_module_cw = __esm({
8624
+ "../core/dist/module-cw.js"() {
8625
+ "use strict";
8626
+ init_dist();
8627
+ init_pty_manager();
8628
+ init_cw_start();
8629
+ POLL_MS = 500;
8630
+ DEFAULT_WAIT_MS = 9e4;
8631
+ sleep = (ms) => new Promise((resolve11) => setTimeout(resolve11, ms));
8632
+ }
8633
+ });
8634
+
8635
+ // ../core/dist/agent-runner.js
8636
+ import { spawn as nodeSpawn } from "node:child_process";
8637
+ import { existsSync as existsSync16, mkdtempSync as mkdtempSync2, rmSync as rmSync4 } from "node:fs";
8638
+ import { tmpdir as tmpdir2 } from "node:os";
8639
+ import { join as join19 } from "node:path";
8640
+ function runAgent(input, o) {
8641
+ if (!ACCOUNT_NAME_RE.test(input.account))
8642
+ return Promise.reject(new ModuleError("bad_request", "Invalid account"));
8643
+ const configDir = join19(o.cwHome, "accounts", input.account);
8644
+ if (!existsSync16(configDir))
8645
+ return Promise.reject(new ModuleError("not_found", `Unknown account ${input.account}`));
8646
+ const bad = input.allowedTools.find((tool) => !tool.startsWith("mcp__"));
8647
+ if (bad !== void 0)
8648
+ return Promise.reject(new ModuleError("bad_request", `allowedTools only takes MCP tools, not ${bad}`));
8649
+ const args = ["-p"];
8650
+ if (input.model)
8651
+ args.push("--model", input.model);
8652
+ args.push("--tools", "");
8653
+ args.push("--allowedTools", input.allowedTools.join(","), "--output-format", "json");
8654
+ const spawn9 = o.spawn ?? nodeSpawn;
8655
+ const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
8656
+ const cwd = mkdtempSync2(join19(tmpdir2(), "forge-agent-"));
8657
+ const cleanup = () => rmSync4(cwd, { recursive: true, force: true });
8658
+ return new Promise((resolve11, reject) => {
8659
+ const child = spawn9("claude", args, { cwd, env: { ...envWithoutHarness(), CLAUDE_CONFIG_DIR: configDir }, stdio: ["pipe", "pipe", "pipe"] });
8660
+ child.stdin?.on("error", () => {
8661
+ });
8662
+ child.stdin?.end(input.prompt);
8663
+ let stdout = "";
8664
+ let stderr = "";
8665
+ let settled = false;
8666
+ const settle = (fn) => {
8667
+ if (settled)
8668
+ return;
8669
+ settled = true;
8670
+ clearTimeout(timer);
8671
+ fn();
8672
+ };
8673
+ const timer = setTimeout(() => {
8674
+ child.kill("SIGKILL");
8675
+ settle(() => reject(new ModuleError("unreachable", `the agent did not finish in ${Math.round(timeoutMs / 1e3)} s`)));
8676
+ }, timeoutMs);
8677
+ child.stdout?.on("data", (d) => {
8678
+ stdout += d.toString();
8679
+ });
8680
+ child.stderr?.on("data", (d) => {
8681
+ stderr += d.toString();
8682
+ });
8683
+ child.on("error", (err) => settle(() => reject(new ModuleError("unreachable", `could not run claude: ${err.message}`))));
8684
+ child.on("close", (code) => settle(() => {
8685
+ let parsed;
8686
+ try {
8687
+ parsed = JSON.parse(stdout);
8688
+ } catch {
8689
+ return reject(new ModuleError("upstream", `claude did not print JSON (exit ${code}): ${stderr.trim().slice(0, 200)}`));
8690
+ }
8691
+ if (typeof parsed.result !== "string")
8692
+ return reject(new ModuleError("upstream", `claude answered without a result (exit ${code})`));
8693
+ resolve11({
8694
+ text: parsed.result,
8695
+ costUsd: typeof parsed.total_cost_usd === "number" ? parsed.total_cost_usd : void 0,
8696
+ turns: typeof parsed.num_turns === "number" ? parsed.num_turns : void 0
8697
+ });
8698
+ }));
8699
+ }).finally(cleanup);
8700
+ }
8701
+ var DEFAULT_TIMEOUT_MS;
8702
+ var init_agent_runner = __esm({
8703
+ "../core/dist/agent-runner.js"() {
8704
+ "use strict";
8705
+ init_dist();
8706
+ init_cw_types();
8707
+ init_cw_doctor();
8708
+ DEFAULT_TIMEOUT_MS = 18e4;
8709
+ }
8710
+ });
8711
+
8418
8712
  // ../core/dist/module-jobs.js
8419
8713
  function parseEvery(text2) {
8420
8714
  const m = /^(\d+)(s|m|h)$/.exec(text2.trim());
@@ -8548,15 +8842,15 @@ var init_module_events = __esm({
8548
8842
  // ../core/dist/server.js
8549
8843
  import { Hono as Hono6 } from "hono";
8550
8844
  import { cors } from "hono/cors";
8551
- import { join as join18, basename as basename5, resolve as resolve10 } from "node:path";
8552
- import { readdirSync as readdirSync8, existsSync as existsSync15 } from "node:fs";
8845
+ import { join as join20, basename as basename5, resolve as resolve10 } from "node:path";
8846
+ import { readdirSync as readdirSync8, existsSync as existsSync17 } from "node:fs";
8553
8847
  function createForgeServer(options) {
8554
8848
  const { dataDir, db: externalDb, authToken, localOnly = true } = options;
8555
8849
  const authProblem = remoteAuthProblem(localOnly, authToken);
8556
8850
  if (authProblem)
8557
8851
  throw new Error(authProblem);
8558
- const dbPath = join18(dataDir, "forge.db");
8559
- const modulesDir = join18(dataDir, "modules");
8852
+ const dbPath = join20(dataDir, "forge.db");
8853
+ const modulesDir = join20(dataDir, "modules");
8560
8854
  const db = externalDb ?? new ForgeDB(dbPath);
8561
8855
  const loader = new ModuleLoader(modulesDir, options.bundledModulesDir);
8562
8856
  const runner = new ActionRunner();
@@ -8573,9 +8867,10 @@ function createForgeServer(options) {
8573
8867
  mountAuthRoute(app, authToken);
8574
8868
  }
8575
8869
  const cwReader = new CWReader(options.cwDir);
8870
+ const generalSessions = new GeneralSessions(join20(dataDir, "general-sessions.json"));
8576
8871
  const loginManager = new LoginManager(resolveCwBin(cwReader.cwHome));
8577
- app.route("/api/cw", cwRoutes(cwReader, { loginManager, localOnly, events: { emit: (name, payload) => moduleEvents.emit(name, payload) } }));
8578
- app.route("/api/skills", skillRoutes(cwReader, { backupDir: join18(dataDir, "skill-backups") }));
8872
+ app.route("/api/cw", cwRoutes(cwReader, { loginManager, localOnly, general: generalSessions, killSession: (key) => ptyManager.kill(key), events: { emit: (name, payload) => moduleEvents.emit(name, payload) } }));
8873
+ app.route("/api/skills", skillRoutes(cwReader, { backupDir: join20(dataDir, "skill-backups") }));
8579
8874
  const { remote, shadow, warning } = remoteClassifierFromEnv();
8580
8875
  if (warning)
8581
8876
  console.warn(`[state] ${warning}`);
@@ -8595,7 +8890,6 @@ function createForgeServer(options) {
8595
8890
  }
8596
8891
  });
8597
8892
  const ptyManager = new PTYManager(states);
8598
- const generalSessions = new GeneralSessions(join18(dataDir, "general-sessions.json"));
8599
8893
  const terminalWss = createTerminalWss(ptyManager, cwReader, { localOnly, authToken, general: generalSessions });
8600
8894
  app.route("/api/liveframe", liveframeRoutes());
8601
8895
  const kioku = new Kioku({ projects: () => cwReader.getProjects(), pluginInstalls: () => installsOf(cwReader, "kioku") });
@@ -8629,9 +8923,15 @@ function createForgeServer(options) {
8629
8923
  modulesDir,
8630
8924
  bundledDir: options.bundledModulesDir,
8631
8925
  forgeNodeModules: options.forgeNodeModules,
8632
- devFile: join18(dataDir, "dev-modules.json"),
8926
+ devFile: join20(dataDir, "dev-modules.json"),
8633
8927
  localOnly,
8634
- deps: { db, reader: cwReader, runner },
8928
+ deps: {
8929
+ db,
8930
+ reader: cwReader,
8931
+ runner,
8932
+ cw: createCwDeps({ reader: cwReader, manager: ptyManager, states, general: generalSessions }),
8933
+ agent: { run: (i) => runAgent(i, { cwHome: cwReader.cwHome }) }
8934
+ },
8635
8935
  hooks: {
8636
8936
  loaded: (mod) => {
8637
8937
  for (const sub of mod.server?.events ?? [])
@@ -8808,21 +9108,21 @@ data: ${JSON.stringify(data)}
8808
9108
  if (!dir.startsWith(home)) {
8809
9109
  return c.json({ error: "Access denied: path must be within home directory" }, 403);
8810
9110
  }
8811
- if (!existsSync15(dir)) {
9111
+ if (!existsSync17(dir)) {
8812
9112
  return c.json({ error: "Directory not found" }, 404);
8813
9113
  }
8814
9114
  try {
8815
9115
  const entries = readdirSync8(dir, { withFileTypes: true });
8816
9116
  const dirs = entries.filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => ({
8817
9117
  name: e.name,
8818
- path: join18(dir, e.name),
8819
- hasPackageJson: existsSync15(join18(dir, e.name, "package.json")),
8820
- hasGit: existsSync15(join18(dir, e.name, ".git"))
9118
+ path: join20(dir, e.name),
9119
+ hasPackageJson: existsSync17(join20(dir, e.name, "package.json")),
9120
+ hasGit: existsSync17(join20(dir, e.name, ".git"))
8821
9121
  })).sort((a, b) => a.name.localeCompare(b.name));
8822
9122
  return c.json({
8823
9123
  current: dir,
8824
9124
  name: basename5(dir),
8825
- parent: join18(dir, ".."),
9125
+ parent: join20(dir, ".."),
8826
9126
  directories: dirs
8827
9127
  });
8828
9128
  } catch {
@@ -8870,6 +9170,8 @@ var init_server = __esm({
8870
9170
  init_module_host();
8871
9171
  init_module_routes();
8872
9172
  init_module_install();
9173
+ init_module_cw();
9174
+ init_agent_runner();
8873
9175
  init_task_review();
8874
9176
  init_module_jobs();
8875
9177
  init_module_events();
@@ -9027,8 +9329,8 @@ async function createDatabase(opts) {
9027
9329
  await db.migrate();
9028
9330
  return db;
9029
9331
  }
9030
- const { join: join22 } = await import("node:path");
9031
- return new ForgeDB(join22(opts.dataDir, "forge.db"));
9332
+ const { join: join24 } = await import("node:path");
9333
+ return new ForgeDB(join24(opts.dataDir, "forge.db"));
9032
9334
  }
9033
9335
  var init_db_factory = __esm({
9034
9336
  "../core/dist/db-factory.js"() {
@@ -9038,22 +9340,22 @@ var init_db_factory = __esm({
9038
9340
  });
9039
9341
 
9040
9342
  // ../core/dist/init.js
9041
- import { existsSync as existsSync16, mkdirSync as mkdirSync6, writeFileSync as writeFileSync6 } from "node:fs";
9042
- import { join as join19 } from "node:path";
9343
+ import { existsSync as existsSync18, mkdirSync as mkdirSync7, writeFileSync as writeFileSync7 } from "node:fs";
9344
+ import { join as join21 } from "node:path";
9043
9345
  import { homedir as homedir8 } from "node:os";
9044
9346
  function getForgeDir() {
9045
- return join19(homedir8(), ".forge");
9347
+ return join21(homedir8(), ".forge");
9046
9348
  }
9047
9349
  function ensureForgeDir() {
9048
9350
  const forgeDir = getForgeDir();
9049
- if (existsSync16(forgeDir)) {
9351
+ if (existsSync18(forgeDir)) {
9050
9352
  return { forgeDir, created: false };
9051
9353
  }
9052
- mkdirSync6(forgeDir, { recursive: true });
9354
+ mkdirSync7(forgeDir, { recursive: true });
9053
9355
  for (const d of FORGE_SUBDIRS) {
9054
- mkdirSync6(join19(forgeDir, d), { recursive: true });
9356
+ mkdirSync7(join21(forgeDir, d), { recursive: true });
9055
9357
  }
9056
- writeFileSync6(join19(forgeDir, "config.json"), JSON.stringify({
9358
+ writeFileSync7(join21(forgeDir, "config.json"), JSON.stringify({
9057
9359
  port: 3e3,
9058
9360
  theme: "dark",
9059
9361
  openBrowser: true,
@@ -9116,8 +9418,8 @@ var init_port_in_use = __esm({
9116
9418
  });
9117
9419
 
9118
9420
  // ../core/dist/start.js
9119
- import { existsSync as existsSync17, readFileSync as readFileSync13 } from "node:fs";
9120
- import { join as join20 } from "node:path";
9421
+ import { existsSync as existsSync19, readFileSync as readFileSync13 } from "node:fs";
9422
+ import { join as join22 } from "node:path";
9121
9423
  async function startForge(options) {
9122
9424
  const { port, version, consoleDist: consoleDist2, bundledModulesDir: bundledModulesDir2, databaseUrl, authToken, fallbackToFreePort = false } = options;
9123
9425
  const { forgeDir } = ensureForgeDir();
@@ -9137,10 +9439,10 @@ async function startForge(options) {
9137
9439
  bundledModulesDir: bundledModulesDir2,
9138
9440
  version
9139
9441
  });
9140
- if (consoleDist2 && existsSync17(join20(consoleDist2, "index.html"))) {
9442
+ if (consoleDist2 && existsSync19(join22(consoleDist2, "index.html"))) {
9141
9443
  const { serveStatic } = await import("@hono/node-server/serve-static");
9142
9444
  server.app.use("/*", serveStatic({ root: consoleDist2 }));
9143
- const indexHtml = readFileSync13(join20(consoleDist2, "index.html"), "utf-8");
9445
+ const indexHtml = readFileSync13(join22(consoleDist2, "index.html"), "utf-8");
9144
9446
  server.app.get("*", (c) => c.html(indexHtml));
9145
9447
  }
9146
9448
  const { serve } = await import("@hono/node-server");
@@ -9271,9 +9573,9 @@ var init_dist2 = __esm({
9271
9573
  });
9272
9574
 
9273
9575
  // src/index.ts
9274
- import { existsSync as existsSync18, readFileSync as readFileSync14 } from "node:fs";
9576
+ import { existsSync as existsSync20, readFileSync as readFileSync14 } from "node:fs";
9275
9577
  import { homedir as homedir9 } from "node:os";
9276
- import { join as join21 } from "node:path";
9578
+ import { join as join23 } from "node:path";
9277
9579
  function parseArgs(argv) {
9278
9580
  const out = { open: true };
9279
9581
  for (let i = 0; i < argv.length; i++) {
@@ -9284,11 +9586,11 @@ function parseArgs(argv) {
9284
9586
  }
9285
9587
  return out;
9286
9588
  }
9287
- var packageRoot = join21(import.meta.dirname, "..");
9288
- var isCheckout = existsSync18(join21(packageRoot, "src"));
9289
- var consoleDist = isCheckout ? join21(packageRoot, "../console/dist") : join21(packageRoot, "console");
9290
- var forgeVersion = JSON.parse(readFileSync14(join21(packageRoot, "package.json"), "utf-8")).version;
9291
- var bundledModulesDir = isCheckout ? join21(packageRoot, "../../modules") : join21(packageRoot, "modules");
9589
+ var packageRoot = join23(import.meta.dirname, "..");
9590
+ var isCheckout = existsSync20(join23(packageRoot, "src"));
9591
+ var consoleDist = isCheckout ? join23(packageRoot, "../console/dist") : join23(packageRoot, "console");
9592
+ var forgeVersion = JSON.parse(readFileSync14(join23(packageRoot, "package.json"), "utf-8")).version;
9593
+ var bundledModulesDir = isCheckout ? join23(packageRoot, "../../modules") : join23(packageRoot, "modules");
9292
9594
  async function main() {
9293
9595
  const { ensureForgeDir: ensureForgeDir2, startForge: startForge2, ensureCw: ensureCw2, pathWithCw: pathWithCw2, quietSqliteWarning: quietSqliteWarning2, portInUseMessage: portInUseMessage2 } = await Promise.resolve().then(() => (init_dist2(), dist_exports));
9294
9596
  quietSqliteWarning2();
@@ -9297,8 +9599,8 @@ async function main() {
9297
9599
  if (created) {
9298
9600
  console.log("First run \u2014 initialized Forge.");
9299
9601
  }
9300
- const cwHome = join21(process.env.HOME ?? homedir9(), ".cw");
9301
- const cw = isCheckout ? { action: "skipped", message: "a checkout does not install CW" } : await ensureCw2({ cwHome, bundleDir: join21(packageRoot, "cw") });
9602
+ const cwHome = join23(process.env.HOME ?? homedir9(), ".cw");
9603
+ const cw = isCheckout ? { action: "skipped", message: "a checkout does not install CW" } : await ensureCw2({ cwHome, bundleDir: join23(packageRoot, "cw") });
9302
9604
  if (cw.action === "installed") console.log(` Installed CW ${cw.version} in ${cwHome}`);
9303
9605
  else if (cw.action === "updated") console.log(` Updated ${cw.message}`);
9304
9606
  else if (cw.action === "failed") console.log(` Could not install CW: ${cw.message}`);