@netnodeag/kraftwerk 0.65.0 → 0.67.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +112 -27
  2. package/dist/acp.js +3 -1
  3. package/dist/cli/daemon.d.ts +14 -0
  4. package/dist/cli/daemon.js +60 -0
  5. package/dist/cli/doctor.js +9 -1
  6. package/dist/cli/init.js +1 -0
  7. package/dist/cli/kraftwerk.js +4 -0
  8. package/dist/cli/ui.d.ts +8 -0
  9. package/dist/cli/ui.js +35 -8
  10. package/dist/cli/workspaces.js +5 -3
  11. package/dist/client/index.d.ts +8 -0
  12. package/dist/client/index.js +2 -1
  13. package/dist/client/live.d.ts +1 -2
  14. package/dist/client/live.js +2 -1
  15. package/dist/client/routes.d.ts +3 -0
  16. package/dist/client/routes.js +3 -0
  17. package/dist/config.d.ts +16 -0
  18. package/dist/config.js +23 -1
  19. package/dist/core/chat/pi.js +2 -1
  20. package/dist/core/chat/sessions.d.ts +1 -1
  21. package/dist/core/chat/sessions.js +1 -1
  22. package/dist/core/chat/state.d.ts +2 -0
  23. package/dist/core/chat/state.js +5 -0
  24. package/dist/core/daemon.d.ts +27 -0
  25. package/dist/core/daemon.js +61 -0
  26. package/dist/core/env.d.ts +16 -0
  27. package/dist/core/env.js +45 -0
  28. package/dist/core/git.d.ts +2 -0
  29. package/dist/core/git.js +20 -4
  30. package/dist/core/instances.d.ts +34 -12
  31. package/dist/core/instances.js +142 -66
  32. package/dist/core/routines.d.ts +6 -0
  33. package/dist/core/routines.js +11 -0
  34. package/dist/core/runner.js +7 -3
  35. package/dist/core/search.d.ts +2 -0
  36. package/dist/core/search.js +1 -0
  37. package/dist/core/vibeables.d.ts +2 -0
  38. package/dist/core/vibeables.js +17 -5
  39. package/dist/core/workspace.d.ts +13 -0
  40. package/dist/core/workspace.js +25 -0
  41. package/dist/server/api/hub.d.ts +25 -0
  42. package/dist/server/api/hub.js +32 -0
  43. package/dist/server/api/index.d.ts +35 -3
  44. package/dist/server/api/index.js +2 -0
  45. package/dist/server/api/socket.d.ts +9 -1
  46. package/dist/server/api/socket.js +27 -7
  47. package/dist/server/api/workspace.d.ts +16 -2
  48. package/dist/server/api/workspace.js +44 -4
  49. package/dist/server/cloud.d.ts +5 -1
  50. package/dist/server/cloud.js +86 -54
  51. package/dist/server/hub-context.d.ts +7 -0
  52. package/dist/server/hub-context.js +18 -0
  53. package/dist/server/live.d.ts +2 -0
  54. package/dist/server/live.js +9 -0
  55. package/dist/server/preview.js +2 -1
  56. package/dist/server/server.d.ts +52 -1
  57. package/dist/server/server.js +283 -52
  58. package/dist/server/target.d.ts +20 -0
  59. package/dist/server/target.js +18 -0
  60. package/package.json +1 -1
  61. package/schema/kraftwerk.schema.json +5 -0
  62. package/web/dist/assets/{dist-10uPVFvu.js → dist-BMZBs9W4.js} +1 -1
  63. package/web/dist/assets/{dist-v6-49xpW.js → dist-BkZKygT6.js} +1 -1
  64. package/web/dist/assets/{dist-Bnxg6V5L.js → dist-CZjwFXw-.js} +1 -1
  65. package/web/dist/assets/{dist-DS1R2xKJ.js → dist-D7BYSDIr.js} +1 -1
  66. package/web/dist/assets/dist-DZLlNafq.js +1 -0
  67. package/web/dist/assets/{dist-BCfXUgtf.js → dist-D_nqqdyh.js} +1 -1
  68. package/web/dist/assets/{dist-nA7q2-h7.js → dist-IO8GeoYh.js} +1 -1
  69. package/web/dist/assets/{dist-hevbMnoj.js → dist-LUKHNpC7.js} +1 -1
  70. package/web/dist/assets/{dist-DnMgiPT1.js → dist-Y0KLvK_g.js} +1 -1
  71. package/web/dist/assets/{dist-C-CclD1E.js → dist-aMqhK50K.js} +1 -1
  72. package/web/dist/assets/{dist-CAWmDGJC.js → dist-jyZ9dxfk.js} +1 -1
  73. package/web/dist/assets/{editor-C8yy8YS9.js → editor-DQouCIUq.js} +3 -3
  74. package/web/dist/assets/index-D57IrV_V.js +229 -0
  75. package/web/dist/index.html +1 -1
  76. package/web/dist/assets/dist-yoh47aAL.js +0 -1
  77. package/web/dist/assets/index-DWS1u71Y.js +0 -229
@@ -3,8 +3,10 @@ import { createHash } from "node:crypto";
3
3
  import fsSync, { promises as fs } from "node:fs";
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
- import { absolutePath, isDir, resolveWorkspace } from "../config.js";
6
+ import { absolutePath, isDir, resolveWorkspace, slugFromFolder, workspaceSlug } from "../config.js";
7
7
  import { selfCommand } from "./self-command.js";
8
+ import { DAEMON_PORT, daemonCall, findDaemon } from "./daemon.js";
9
+ import { currentWorkspace } from "./workspace.js";
8
10
  /**
9
11
  * Two registries under ~/.kraftwerk, two lifecycles:
10
12
  *
@@ -31,9 +33,16 @@ const workspacesDir = () => path.join(kwHome(), "workspaces");
31
33
  /** Where the records lived before 0.49 (`kraftwerk projects`); moved over once, see migrateRegistry. */
32
34
  export const legacyWorkspacesDir = () => path.join(kwHome(), "projects");
33
35
  const logsDir = () => path.join(kwHome(), "logs");
34
- const selfFile = () => path.join(instancesDir(), `${process.pid}.json`);
35
- let selfPort = null;
36
- let selfRoot = null;
36
+ const own = new Map();
37
+ /** The workspace the caller runs in (a request, a timer), or null outside any. */
38
+ function currentRoot() {
39
+ try {
40
+ return currentWorkspace().root;
41
+ }
42
+ catch {
43
+ return null;
44
+ }
45
+ }
37
46
  /** File name of a root's record: a hash of the absolute root, the same under the old and the new directory. */
38
47
  export const workspaceRecordName = (root) => `${createHash("sha1").update(absolutePath(root)).digest("hex").slice(0, 16)}.json`;
39
48
  const recordFile = (root) => path.join(workspacesDir(), workspaceRecordName(root));
@@ -43,42 +52,61 @@ export const tildify = (p) => {
43
52
  return p === home || p.startsWith(home + path.sep) ? "~" + p.slice(home.length) : p;
44
53
  };
45
54
  /* ---------- instances (ephemeral) ---------- */
46
- /** Write this instance's registry file (call once the server listens). */
47
- export async function registerInstance(port, root) {
48
- selfPort = port;
49
- selfRoot = absolutePath(root);
55
+ /**
56
+ * Write a served workspace's registry file (call once the server listens).
57
+ * A daemon's workspaces carry their slug and address and get a file each;
58
+ * a standalone server keeps the one `<pid>.json` it always had.
59
+ */
60
+ export async function registerInstance(port, root, opts = {}) {
61
+ const abs = absolutePath(root);
62
+ const file = path.join(instancesDir(), opts.hub ? `${process.pid}-${workspaceRecordName(abs)}` : `${process.pid}.json`);
63
+ const url = opts.url ?? `http://localhost:${port}`;
64
+ const mine = { port, url, file };
65
+ own.set(abs, mine);
50
66
  try {
51
67
  await fs.mkdir(instancesDir(), { recursive: true });
52
- const rec = { pid: process.pid, port, startedAt: new Date().toISOString(), root: selfRoot };
53
- await fs.writeFile(selfFile(), JSON.stringify(rec));
68
+ const rec = { pid: process.pid, port, startedAt: new Date().toISOString(), root: abs, ...(opts.hub ? { url, slug: opts.slug, hub: true } : {}) };
69
+ await fs.writeFile(file, JSON.stringify(rec));
70
+ // Closed while this wrote (an open and a close in quick succession): the file must not outlive it.
71
+ if (own.get(abs) !== mine)
72
+ await fs.unlink(file).catch(() => { });
54
73
  }
55
74
  catch { } // best-effort — without it discovery just won't see us
75
+ cache = null;
76
+ wsCache.clear();
56
77
  }
57
- /** Where this instance answers, as the switcher links it (null before listen). */
58
- export const currentInstanceUrl = () => (selfPort ? `http://localhost:${selfPort}` : null);
59
- /** Remove this instance's registry file. Sync so exit handlers can call it. */
60
- export function unregisterInstance() {
61
- try {
62
- fsSync.unlinkSync(selfFile());
78
+ /** Where the current workspace answers, as the switcher links it (null before listen). */
79
+ export const currentInstanceUrl = () => own.get(currentRoot() ?? "")?.url ?? null;
80
+ /** Remove a served workspace's registry file — every one this process wrote when no root is given. Sync so exit handlers can call it. */
81
+ export function unregisterInstance(root) {
82
+ const roots = root ? [absolutePath(root)] : [...own.keys()];
83
+ for (const r of roots) {
84
+ try {
85
+ fsSync.unlinkSync(own.get(r)?.file ?? "");
86
+ }
87
+ catch { }
88
+ own.delete(r);
63
89
  }
64
- catch { }
90
+ cache = null;
91
+ wsCache.clear();
65
92
  }
66
93
  /**
67
94
  * Probe one registered port: is a kraftwerk inspector answering? `probe=1`
68
95
  * tells the other side to skip its own discovery — two instances probing
69
96
  * each other's /api/meta must not recurse.
70
97
  */
71
- async function probe(port) {
98
+ async function probe(port, slug) {
72
99
  // `listen(port, "localhost")` binds one address family, whichever the
73
100
  // resolver returns first (::1 on this platform), so an instance started
74
101
  // with KRAFTWERK_UI_HOST=localhost or ::1 is not on 127.0.0.1. A refused
75
102
  // connection returns at once, so the second try costs nothing when the
76
103
  // first one answers.
77
- return (await probeAt("127.0.0.1", port)) ?? (await probeAt("[::1]", port));
104
+ return (await probeAt("127.0.0.1", port, slug)) ?? (await probeAt("[::1]", port, slug));
78
105
  }
79
- async function probeAt(host, port) {
106
+ async function probeAt(host, port, slug) {
80
107
  try {
81
- const r = await fetch(`http://${host}:${port}/api/meta?probe=1`, {
108
+ // A daemon's workspace answers under its slug; the path form needs no name resolution.
109
+ const r = await fetch(`http://${host}:${port}${slug ? `/w/${slug}` : ""}/api/meta?probe=1`, {
82
110
  signal: AbortSignal.timeout(400),
83
111
  });
84
112
  if (!r.ok)
@@ -110,7 +138,7 @@ let cache = null;
110
138
  */
111
139
  export async function discoverInstances(opts = {}) {
112
140
  if (!opts.fresh && cache && Date.now() - cache.at < 5_000)
113
- return cache.entries;
141
+ return notSelf(cache.entries);
114
142
  let files;
115
143
  try {
116
144
  files = await fs.readdir(instancesDir());
@@ -128,21 +156,25 @@ export async function discoverInstances(opts = {}) {
128
156
  catch {
129
157
  return null;
130
158
  }
131
- if (rec.pid === process.pid || rec.port === selfPort)
132
- return null;
133
- const found = await probe(rec.port);
159
+ const found = await probe(rec.port, rec.hub ? rec.slug : undefined);
134
160
  if (!found) {
135
161
  if (!opts.readOnly)
136
162
  await fs.unlink(path.join(instancesDir(), f)).catch(() => { }); // stale — prune
137
163
  return null;
138
164
  }
139
- return { ...found, root: rec.root, pid: rec.pid };
165
+ return { ...found, root: rec.root, pid: rec.pid, ...(rec.hub ? { url: rec.url ?? found.url, slug: rec.slug, hub: true } : {}) };
140
166
  }));
141
167
  const entries = probed
142
168
  .filter((e) => e != null)
143
169
  .sort((a, b) => a.name.localeCompare(b.name));
144
170
  cache = { at: Date.now(), entries };
145
- return entries;
171
+ return notSelf(entries);
172
+ }
173
+ /** Leave out the asking workspace itself (an older instance file without a root: by this process and port). */
174
+ function notSelf(entries) {
175
+ const me = currentRoot();
176
+ const port = me ? own.get(me)?.port : undefined;
177
+ return entries.filter((e) => (e.root ? e.root !== me : !(e.pid === process.pid && e.url === `http://localhost:${port}`)));
146
178
  }
147
179
  /* ---------- workspaces (durable) ---------- */
148
180
  let migrated = null;
@@ -182,6 +214,7 @@ async function readRecord(file) {
182
214
  return null;
183
215
  return {
184
216
  root: rec.root,
217
+ ...(typeof rec.slug === "string" ? { slug: rec.slug } : {}),
185
218
  firstSeen: rec.firstSeen ?? rec.lastStarted ?? "",
186
219
  lastStarted: rec.lastStarted ?? rec.firstSeen ?? "",
187
220
  lastStopped: rec.lastStopped,
@@ -197,14 +230,19 @@ async function readRecord(file) {
197
230
  }
198
231
  /** Upsert the project record for a root (call on every inspector start). */
199
232
  export async function registerWorkspace(root) {
200
- await migrateRegistry();
201
233
  const abs = absolutePath(root);
234
+ // Where it goes is decided now: the registry of the home this was called in, whatever HOME is by the time it writes.
235
+ const dir = workspacesDir();
236
+ const file = path.join(dir, workspaceRecordName(abs));
237
+ await migrateRegistry();
202
238
  const now = new Date().toISOString();
203
239
  try {
204
- await fs.mkdir(workspacesDir(), { recursive: true });
205
- const prev = await readRecord(recordFile(abs));
240
+ await fs.mkdir(dir, { recursive: true });
241
+ const prev = await readRecord(file);
242
+ const slug = await resolveWorkspace(abs).then(workspaceSlug, () => slugFromFolder(path.basename(abs)));
206
243
  const rec = {
207
244
  root: abs,
245
+ slug,
208
246
  firstSeen: prev?.firstSeen || now,
209
247
  lastStarted: now,
210
248
  startCount: (prev?.startCount ?? 0) + 1,
@@ -212,7 +250,7 @@ export async function registerWorkspace(root) {
212
250
  ...(prev?.channels ? { channels: prev.channels } : {}),
213
251
  ...(prev?.projects ? { projects: prev.projects } : {}),
214
252
  };
215
- await fs.writeFile(recordFile(abs), JSON.stringify(rec, null, 2));
253
+ await fs.writeFile(file, JSON.stringify(rec, null, 2));
216
254
  }
217
255
  catch { } // best-effort, like the instance file
218
256
  }
@@ -241,17 +279,17 @@ async function syncWorkspaceList(root, key, list) {
241
279
  export const syncWorkspaceAgents = (root, agents) => syncWorkspaceList(root, "agents", agents);
242
280
  export const syncWorkspaceChannels = (root, channels) => syncWorkspaceList(root, "channels", channels);
243
281
  export const syncWorkspaceProjects = (root, projects) => syncWorkspaceList(root, "projects", projects);
244
- /** Stamp lastStopped on clean shutdown. Sync so exit handlers can call it. */
245
- export function markWorkspaceStopped() {
246
- if (!selfRoot)
247
- return;
248
- try {
249
- const file = recordFile(selfRoot);
250
- const rec = JSON.parse(fsSync.readFileSync(file, "utf8"));
251
- rec.lastStopped = new Date().toISOString();
252
- fsSync.writeFileSync(file, JSON.stringify(rec, null, 2));
282
+ /** Stamp lastStopped on a clean stop — every workspace this process serves when no root is given. Sync so exit handlers can call it. */
283
+ export function markWorkspaceStopped(root) {
284
+ for (const r of root ? [absolutePath(root)] : [...own.keys()]) {
285
+ try {
286
+ const file = recordFile(r);
287
+ const rec = JSON.parse(fsSync.readFileSync(file, "utf8"));
288
+ rec.lastStopped = new Date().toISOString();
289
+ fsSync.writeFileSync(file, JSON.stringify(rec, null, 2));
290
+ }
291
+ catch { }
253
292
  }
254
- catch { }
255
293
  }
256
294
  /** All known workspaces, most recently started first. */
257
295
  export async function listWorkspaceRecords() {
@@ -268,6 +306,13 @@ export async function listWorkspaceRecords() {
268
306
  .filter((r) => r != null)
269
307
  .sort((a, b) => b.lastStarted.localeCompare(a.lastStarted));
270
308
  }
309
+ /** A record's slug: as registered, or (records from before 0.66) its folder name made into one. */
310
+ export const recordSlug = (r) => r.slug ?? slugFromFolder(path.basename(r.root));
311
+ /** Other registered workspaces with this slug — two workspaces cannot share an address. */
312
+ export async function slugClashes(slug, root) {
313
+ const abs = absolutePath(root);
314
+ return (await listWorkspaceRecords()).filter((r) => r.root !== abs && recordSlug(r) === slug);
315
+ }
271
316
  /** Drop a workspace record (the root itself is untouched) — from the legacy directory too, see migrateRegistry. */
272
317
  export async function forgetWorkspace(root) {
273
318
  await migrateRegistry();
@@ -290,7 +335,7 @@ export async function forgetWorkspace(root) {
290
335
  * so without this check a stale record would wear its parent's identity.
291
336
  */
292
337
  async function describeRoot(root) {
293
- const fallback = { name: path.basename(root), named: false, port: 1981, exists: false };
338
+ const fallback = { name: path.basename(root), named: false, slug: slugFromFolder(path.basename(root)), port: 1981, exists: false };
294
339
  if (!(await isDir(root)))
295
340
  return fallback;
296
341
  try {
@@ -300,6 +345,7 @@ async function describeRoot(root) {
300
345
  return {
301
346
  name: project.config.name ?? path.basename(project.root),
302
347
  named: !!project.config.name,
348
+ slug: workspaceSlug(project),
303
349
  icon: project.config.icon || undefined,
304
350
  color: project.config.color || undefined,
305
351
  port: project.config.port ?? 1981,
@@ -310,7 +356,8 @@ async function describeRoot(root) {
310
356
  return fallback;
311
357
  }
312
358
  }
313
- let wsCache = null;
359
+ /** Per asking workspace: each leaves itself out of its list. */
360
+ const wsCache = new Map();
314
361
  /**
315
362
  * The switcher's view: every known project joined with the live instances,
316
363
  * plus running instances with no project record yet. The calling instance
@@ -318,13 +365,15 @@ let wsCache = null;
318
365
  * discoverInstances — /api/meta is polled and this stats every root.
319
366
  */
320
367
  export async function discoverWorkspaces() {
321
- if (wsCache && Date.now() - wsCache.at < 5_000)
322
- return wsCache.entries;
368
+ const me = currentRoot() ?? "";
369
+ const hit = wsCache.get(me);
370
+ if (hit && Date.now() - hit.at < 5_000)
371
+ return hit.entries;
323
372
  const [projects, live] = await Promise.all([listWorkspaceRecords(), discoverInstances()]);
324
373
  const liveByRoot = new Map(live.filter((i) => i.root).map((i) => [i.root, i]));
325
374
  const consumed = new Set();
326
375
  const entries = (await Promise.all(projects
327
- .filter((p) => p.root !== selfRoot)
376
+ .filter((p) => p.root !== me)
328
377
  .map(async (p) => {
329
378
  const base = { root: p.root, rootLabel: tildify(p.root), lastStarted: p.lastStarted, lastStopped: p.lastStopped };
330
379
  let running = liveByRoot.get(p.root);
@@ -348,11 +397,12 @@ export async function discoverWorkspaces() {
348
397
  icon: running.icon,
349
398
  color: running.color ?? d?.color,
350
399
  named: running.named ?? d?.named,
400
+ slug: running.slug ?? recordSlug(p),
351
401
  live: true,
352
402
  exists: true,
353
403
  };
354
404
  }
355
- return { ...base, name: d.name, url: `http://localhost:${d.port}`, icon: d.icon, color: d.color, named: d.named, live: false, exists: d.exists };
405
+ return { ...base, name: d.name, url: `http://localhost:${d.port}`, icon: d.icon, color: d.color, named: d.named, slug: d.slug, live: false, exists: d.exists };
356
406
  }))).concat(await Promise.all(live
357
407
  .filter((i) => !consumed.has(i))
358
408
  .map(async (i) => ({
@@ -361,6 +411,7 @@ export async function discoverWorkspaces() {
361
411
  icon: i.icon,
362
412
  color: i.color,
363
413
  named: i.named,
414
+ slug: i.slug,
364
415
  live: true,
365
416
  root: i.root,
366
417
  rootLabel: i.root ? tildify(i.root) : undefined,
@@ -371,7 +422,7 @@ export async function discoverWorkspaces() {
371
422
  return a.live ? -1 : 1;
372
423
  return (b.lastStarted ?? "").localeCompare(a.lastStarted ?? "") || a.name.localeCompare(b.name);
373
424
  });
374
- wsCache = { at: Date.now(), entries };
425
+ wsCache.set(me, { at: Date.now(), entries });
375
426
  return entries;
376
427
  }
377
428
  const countDirs = async (dir, marker) => {
@@ -403,25 +454,28 @@ const countEntries = async (dir) => {
403
454
  export async function listWorkspacesDetailed() {
404
455
  const others = await discoverWorkspaces();
405
456
  const all = [...others];
406
- if (selfRoot && selfPort) {
407
- const d = await describeRoot(selfRoot);
408
- const rec = await readRecord(recordFile(selfRoot));
457
+ const me = currentRoot();
458
+ const mine = me ? own.get(me) : undefined;
459
+ if (me && mine) {
460
+ const d = await describeRoot(me);
461
+ const rec = await readRecord(recordFile(me));
409
462
  all.unshift({
410
463
  name: d.name,
411
464
  icon: d.icon,
412
465
  color: d.color,
413
466
  named: d.named,
414
- url: `http://localhost:${selfPort}`,
467
+ slug: d.slug,
468
+ url: mine.url,
415
469
  live: true,
416
- root: selfRoot,
417
- rootLabel: tildify(selfRoot),
470
+ root: me,
471
+ rootLabel: tildify(me),
418
472
  exists: true,
419
473
  lastStarted: rec?.lastStarted,
420
474
  lastStopped: rec?.lastStopped,
421
475
  });
422
476
  }
423
477
  return Promise.all(all.map(async (e) => {
424
- const current = !!selfRoot && e.root === selfRoot;
478
+ const current = !!me && e.root === me;
425
479
  const base = { ...e, current, state: e.live ? "running" : "stopped" };
426
480
  if (!e.root)
427
481
  return base;
@@ -476,15 +530,25 @@ export async function startWorkspace(root) {
476
530
  if (!exists)
477
531
  return { ok: false, error: `not a project directory (missing or moved): ${abs}` };
478
532
  const url = `http://localhost:${port}`;
479
- if (abs === selfRoot)
533
+ if (abs === currentRoot())
480
534
  return { ok: false, url, live: true, error: "that is this workspace" };
481
535
  // Already running, or the port is taken by another kraftwerk?
482
- cache = wsCache = null;
536
+ cache = null;
537
+ wsCache.clear();
483
538
  const live = await discoverInstances();
484
539
  const byRoot = live.find((i) => i.root === abs);
485
540
  if (byRoot)
486
541
  return { ok: true, url: byRoot.url, live: true };
487
- if (port === selfPort)
542
+ // The machine runs a daemon: it serves this workspace next to the others.
543
+ const daemon = await findDaemon();
544
+ if (daemon) {
545
+ const r = await daemonCall(daemon.port, "open", abs).catch((err) => ({ ok: false, status: 0, data: { error: err.message } }));
546
+ cache = null;
547
+ wsCache.clear();
548
+ return r.ok ? { ok: true, url: r.data.url, live: true, pid: daemon.pid } : { ok: false, error: r.data.error ?? `the daemon refused (${r.status})` };
549
+ }
550
+ const mine = own.get(currentRoot() ?? "");
551
+ if (mine && port === mine.port)
488
552
  return { ok: false, url, error: `port ${port} is used by this workspace` };
489
553
  const byPort = live.find((i) => i.url === url);
490
554
  if (byPort)
@@ -526,7 +590,8 @@ export async function startWorkspace(root) {
526
590
  if (exited)
527
591
  return { ok: false, url, pid: child.pid, log, error: `kraftwerk ui ${exited}` };
528
592
  if (await probe(port)) {
529
- cache = wsCache = null;
593
+ cache = null;
594
+ wsCache.clear();
530
595
  return { ok: true, url, live: true, pid: child.pid, log };
531
596
  }
532
597
  }
@@ -534,20 +599,30 @@ export async function startWorkspace(root) {
534
599
  }
535
600
  /* ---------- stop a project ---------- */
536
601
  /**
537
- * Stop a running workspace: SIGTERM to its server process, which
538
- * unregisters, stamps lastStopped and exits; the `kraftwerk ui` supervisor
539
- * follows. Matched by root, or by url for instances from older versions
540
- * that registered no root. Waits up to ~5s for the port to go quiet.
602
+ * Stop a running workspace. A daemon's workspace is closed there — the
603
+ * daemon and every other workspace in it keep running. A standalone one
604
+ * gets SIGTERM to its server process, which unregisters, stamps
605
+ * lastStopped and exits; the `kraftwerk ui` supervisor follows. Matched by
606
+ * root, or by url for instances from older versions that registered no
607
+ * root. Waits up to ~5s for it to go quiet.
541
608
  */
542
609
  export async function stopWorkspace(target) {
543
- if (target.root && absolutePath(target.root) === selfRoot) {
610
+ if (target.root && absolutePath(target.root) === currentRoot()) {
544
611
  return { ok: false, error: "that is this workspace — stop it from its own terminal or pid" };
545
612
  }
546
- cache = wsCache = null;
613
+ cache = null;
614
+ wsCache.clear();
547
615
  const live = await discoverInstances();
548
616
  const inst = live.find((i) => (target.root && i.root === absolutePath(target.root)) || (target.url && i.url === target.url));
549
617
  if (!inst)
550
618
  return { ok: false, error: "not running" };
619
+ if (inst.hub && inst.root) {
620
+ const port = Number(new URL(inst.url).port) || DAEMON_PORT;
621
+ const r = await daemonCall(port, "close", inst.root).catch((err) => ({ ok: false, status: 0, data: { error: err.message } }));
622
+ cache = null;
623
+ wsCache.clear();
624
+ return r.ok ? { ok: true } : { ok: false, error: r.data.error ?? `the daemon refused (${r.status})` };
625
+ }
551
626
  try {
552
627
  process.kill(inst.pid, "SIGTERM");
553
628
  }
@@ -559,7 +634,8 @@ export async function stopWorkspace(target) {
559
634
  while (Date.now() < deadline) {
560
635
  await new Promise((r) => setTimeout(r, 250));
561
636
  if (!(await probe(port))) {
562
- cache = wsCache = null;
637
+ cache = null;
638
+ wsCache.clear();
563
639
  return { ok: true };
564
640
  }
565
641
  }
@@ -76,4 +76,10 @@ export declare function runRoutineNow(slug: string, id: string): Promise<{
76
76
  }>;
77
77
  /** Start the current workspace's scheduler; safe to call more than once. Ticks run in that workspace. */
78
78
  export declare function startRoutineScheduler(): void;
79
+ /** Stop the current workspace's scheduler (the workspace closes): no routine of it fires any more. */
80
+ export declare function stopRoutineScheduler(): void;
81
+ /** Whether the current workspace's scheduler runs (tests, the hub's view). */
82
+ export declare const routineSchedulerRunning: () => boolean;
83
+ /** The current workspace's scheduler timer, or null — for tests that check it really stops (a cleared slot would read null either way). */
84
+ export declare const routineSchedulerTimer: () => ReturnType<typeof setInterval> | null;
79
85
  export {};
@@ -305,3 +305,14 @@ export function startRoutineScheduler() {
305
305
  s.timer = setInterval(() => void tick().catch(() => { }), 20_000);
306
306
  s.timer.unref?.();
307
307
  }
308
+ /** Stop the current workspace's scheduler (the workspace closes): no routine of it fires any more. */
309
+ export function stopRoutineScheduler() {
310
+ const s = scheduler();
311
+ if (s.timer)
312
+ clearInterval(s.timer);
313
+ s.timer = null;
314
+ }
315
+ /** Whether the current workspace's scheduler runs (tests, the hub's view). */
316
+ export const routineSchedulerRunning = () => scheduler().timer !== null;
317
+ /** The current workspace's scheduler timer, or null — for tests that check it really stops (a cleared slot would read null either way). */
318
+ export const routineSchedulerTimer = () => scheduler().timer;
@@ -2,10 +2,11 @@ import { spawn, spawnSync } from "node:child_process";
2
2
  import { mkdirSync, openSync, closeSync, writeFileSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { workspaceRoot } from "./context.js";
5
- import { perWorkspace } from "./workspace.js";
5
+ import { perWorkspace, workspaceOpen } from "./workspace.js";
6
6
  import { RUN_ID_RE, getRun, safeRunDir } from "./runs.js";
7
7
  import { pushNotification } from "./notifications.js";
8
8
  import { newRunId } from "../workflow.js";
9
+ import { workspaceEnv } from "./env.js";
9
10
  /**
10
11
  * Workflow trigger for the web UI. The inspector stays decoupled from the
11
12
  * framework runtime: it shells out to `npx kraftwerk run` in the consumer
@@ -54,7 +55,7 @@ export function triggerRun(opts) {
54
55
  cwd: workspaceRoot(),
55
56
  detached: true,
56
57
  stdio: ["ignore", log, log],
57
- env: { ...process.env, FORCE_COLOR: "0" },
58
+ env: { ...workspaceEnv(), FORCE_COLOR: "0" },
58
59
  });
59
60
  child.unref();
60
61
  closeSync(log);
@@ -66,13 +67,16 @@ export function triggerRun(opts) {
66
67
  // framework wrote a trace (missing env var, npx failure) shows as failed
67
68
  // instead of running until the stale timeout.
68
69
  child.on("exit", (code, signal) => {
69
- launchers().delete(runId);
70
70
  try {
71
71
  writeFileSync(path.join(runDir, "trigger.json"), JSON.stringify({ exitCode: code ?? 1, signal, finishedAt: new Date().toISOString() }, null, 2) + "\n");
72
72
  }
73
73
  catch {
74
74
  /* run dir removed meanwhile */
75
75
  }
76
+ // A run outlives its workspace closing (it is detached): the file above is all it leaves then.
77
+ if (!workspaceOpen())
78
+ return;
79
+ launchers().delete(runId);
76
80
  void getRun(runId)
77
81
  .then((run) => {
78
82
  const ok = run?.status === "ok";
@@ -14,6 +14,8 @@ export interface WorkspaceAgents {
14
14
  icon?: string;
15
15
  /** Where the workspace's UI lives — hits link to `${url}/#/agents/<slug>`. */
16
16
  url: string;
17
+ /** Its slug: how a daemon addresses it. */
18
+ slug?: string;
17
19
  /** Project root (what /api/projects/start takes for a stopped workspace). */
18
20
  root?: string;
19
21
  /** The instance answering this request: hits navigate in place. */
@@ -26,6 +26,7 @@ export async function searchAgents() {
26
26
  name: w.name,
27
27
  icon: w.icon,
28
28
  url: w.url,
29
+ slug: w.slug,
29
30
  root: w.root,
30
31
  current: false,
31
32
  live: w.live,
@@ -140,3 +140,5 @@ export declare function startDev(slug: string): Promise<VibeableStatus>;
140
140
  export declare function stopDev(slug: string): Promise<VibeableStatus>;
141
141
  /** Server shutdown: no dev server may outlive the inspector. */
142
142
  export declare function disposeAllDevs(): void;
143
+ /** The current workspace's dev servers and file watchers end (the workspace closes). */
144
+ export declare function disposeWorkspaceDevs(): void;
@@ -6,9 +6,10 @@ import path from "node:path";
6
6
  import { parse } from "yaml";
7
7
  import { resolveWorkspace, vibeablesRootFor } from "../config.js";
8
8
  import { workspaceRoot } from "./context.js";
9
- import { perWorkspace } from "./workspace.js";
9
+ import { perWorkspace, workspaceOpen } from "./workspace.js";
10
10
  import { moveToTrash } from "./trash.js";
11
11
  import { newestMtime } from "./mtime.js";
12
+ import { workspaceEnv } from "./env.js";
12
13
  export const VIBEABLE_CONFIG_FILE = "vibeable.yml";
13
14
  const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
14
15
  export function safeVibeableSlug(slug) {
@@ -353,7 +354,7 @@ async function startDevNow(slug) {
353
354
  detached: process.platform !== "win32",
354
355
  stdio: ["ignore", "pipe", "pipe"],
355
356
  env: {
356
- ...process.env,
357
+ ...workspaceEnv(),
357
358
  PORT: String(port),
358
359
  BASE_PATH: basePath,
359
360
  PUBLIC_URL: basePath,
@@ -371,19 +372,22 @@ async function startDevNow(slug) {
371
372
  pushLog(d, Buffer.from(`spawn failed: ${err.message}\n`));
372
373
  d.exitCode = null;
373
374
  d.ready = false;
374
- broadcast(slug, { type: "dev", dev: devView(slug) });
375
+ if (workspaceOpen())
376
+ broadcast(slug, { type: "dev", dev: devView(slug) });
375
377
  });
376
378
  child.on("exit", (code) => {
377
379
  d.exitCode = code;
378
380
  d.ready = false;
379
381
  pushLog(d, Buffer.from(`[exited with ${code ?? "signal"}]\n`));
380
- broadcast(slug, { type: "dev", dev: devView(slug) });
382
+ // Closing the workspace ends its dev servers: their exit then has nobody to tell.
383
+ if (workspaceOpen())
384
+ broadcast(slug, { type: "dev", dev: devView(slug) });
381
385
  });
382
386
  broadcast(slug, { type: "dev", dev: devView(slug) });
383
387
  // Readiness runs in the background; the pane follows the dev events.
384
388
  void (async () => {
385
389
  const until = Date.now() + READY_TIMEOUT;
386
- while (Date.now() < until && d.exitCode === undefined && devs().get(slug) === d) {
390
+ while (Date.now() < until && d.exitCode === undefined && workspaceOpen() && devs().get(slug) === d) {
387
391
  if (await probe(port)) {
388
392
  d.ready = true;
389
393
  broadcast(slug, { type: "dev", dev: devView(slug) });
@@ -432,3 +436,11 @@ export function disposeAllDevs() {
432
436
  if (d.exitCode === undefined)
433
437
  killGroup(d, "SIGTERM");
434
438
  }
439
+ /** The current workspace's dev servers and file watchers end (the workspace closes). */
440
+ export function disposeWorkspaceDevs() {
441
+ for (const d of devs().values())
442
+ if (d.exitCode === undefined)
443
+ killGroup(d, "SIGTERM");
444
+ for (const slug of [...channels().keys()])
445
+ dropChannel(slug);
446
+ }
@@ -18,19 +18,32 @@
18
18
  export declare class Workspace {
19
19
  readonly root: string;
20
20
  readonly outputDir: string;
21
+ /** Its address on this machine (kraftwerk.yml `slug`, else the folder name), when known. */
22
+ readonly slug?: string;
23
+ /** Its `.env` (parsed, not applied — see env.ts); {} when none was given. */
24
+ readonly env: Record<string, string>;
21
25
  private readonly slots;
22
26
  /** `root` defaults to the parent of the output dir (wrong for nested output dirs — pass it when known). */
23
27
  constructor(opts: {
24
28
  outputDir: string;
25
29
  root?: string;
30
+ slug?: string;
31
+ env?: Record<string, string>;
26
32
  });
27
33
  /** Run `fn` (and everything it starts) in this workspace. */
28
34
  run<T>(fn: () => T): T;
35
+ /** Closed (no longer served): its state is gone and may not come back — see close(). */
36
+ get closed(): boolean;
37
+ private isClosed;
29
38
  slot<T>(key: object, init: () => T): T;
39
+ /** No longer served: sweeps over all workspaces (shutdown, the idle reaper) skip it. Its slots are dropped. */
40
+ close(): void;
30
41
  peek<T>(key: object): T | undefined;
31
42
  }
32
43
  /** The workspace a single-workspace process serves; used outside any `ws.run`. */
33
44
  export declare function setDefaultWorkspace(ws: Workspace): Workspace;
45
+ /** Whether the caller's workspace is still served (a background loop checks before its next round); true outside any. */
46
+ export declare function workspaceOpen(): boolean;
34
47
  export declare function currentWorkspace(): Workspace;
35
48
  export interface PerWorkspace<T> {
36
49
  /** The current workspace's value, created on first use. */