@netnodeag/kraftwerk 0.93.0 → 0.95.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.
package/dist/config.js CHANGED
@@ -3,6 +3,7 @@ import { readFile, stat, writeFile } from "node:fs/promises";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { parse } from "yaml";
6
+ import { readParsed } from "./core/file-cache.js";
6
7
  /**
7
8
  * Project resolution + optional project config.
8
9
  *
@@ -265,10 +266,26 @@ const KNOWN_KEYS = ["id", "name", "slug", "icon", "color", "port", "workflows",
265
266
  * never reach the rest of the code; doctor names them (`legacyKeys`).
266
267
  */
267
268
  const LEGACY_KEYS = ["public", "tunnel"];
269
+ /**
270
+ * kraftwerk.yml, parsed and checked — from the file cache while the file is
271
+ * unchanged (every request resolves the workspace, so this runs constantly).
272
+ * Each caller gets its own copy.
273
+ */
268
274
  async function loadConfig(configPath) {
275
+ try {
276
+ return await readParsed(configPath, (text) => checkConfig(configPath, text), (r) => ({ config: structuredClone(r.config), legacyKeys: [...r.legacyKeys] }));
277
+ }
278
+ catch (err) {
279
+ // The file could not be read at all (gone, no permission); a parse or validation error is already worded.
280
+ if (err.code)
281
+ throw new Error(`${path.basename(configPath)}: unreadable YAML: ${err.message}`);
282
+ throw err;
283
+ }
284
+ }
285
+ function checkConfig(configPath, text) {
269
286
  let raw;
270
287
  try {
271
- raw = parse(await readFile(configPath, "utf8"));
288
+ raw = parse(text);
272
289
  }
273
290
  catch (err) {
274
291
  throw new Error(`${path.basename(configPath)}: unreadable YAML: ${err.message}`);
@@ -1,6 +1,7 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { getOutputDir } from "../context.js";
4
+ import { readParsed } from "../file-cache.js";
4
5
  /**
5
6
  * Chats live on disk under <output>/chats/<chat-id>/ as meta.json plus an
6
7
  * append-only events.jsonl — inspectable with plain tools and durable
@@ -34,7 +35,8 @@ export async function readMeta(id) {
34
35
  }
35
36
  /** meta.json of a chat folder wherever it is (also one in the trash); throws when unreadable. */
36
37
  export async function readMetaAt(dir) {
37
- return upgradeMeta(JSON.parse(await fs.readFile(path.join(dir, "meta.json"), "utf8")));
38
+ // From the file cache while unchanged: the chat lists re-read every meta.json on each live update. Callers may change their copy.
39
+ return readParsed(path.join(dir, "meta.json"), (text) => upgradeMeta(JSON.parse(text)), (m) => structuredClone(m));
38
40
  }
39
41
  /**
40
42
  * Chats written before 0.36 scoped agent sessions as
@@ -0,0 +1,6 @@
1
+ /**
2
+ * `parse(text)` of `file`, from the cache while the file is unchanged.
3
+ * Rejects like `fs.readFile` when the file is missing, and with the parse
4
+ * error (again, without re-reading) while a broken file stays broken.
5
+ */
6
+ export declare function readParsed<T>(file: string, parse: (text: string) => T, clone?: (value: T) => T): Promise<T>;
@@ -0,0 +1,35 @@
1
+ import { promises as fs } from "node:fs";
2
+ /** Enough for every meta.json and trace.jsonl of a busy machine; the oldest go first. */
3
+ const MAX_ENTRIES = 20_000;
4
+ const entries = new Map();
5
+ function remember(file, entry) {
6
+ entries.delete(file);
7
+ entries.set(file, entry);
8
+ if (entries.size > MAX_ENTRIES)
9
+ entries.delete(entries.keys().next().value);
10
+ }
11
+ /**
12
+ * `parse(text)` of `file`, from the cache while the file is unchanged.
13
+ * Rejects like `fs.readFile` when the file is missing, and with the parse
14
+ * error (again, without re-reading) while a broken file stays broken.
15
+ */
16
+ export async function readParsed(file, parse, clone = (v) => v) {
17
+ const st = await fs.stat(file, { bigint: true });
18
+ const key = `${st.ino}:${st.size}:${st.mtimeNs}`;
19
+ const hit = entries.get(file);
20
+ if (hit?.key === key) {
21
+ if ("error" in hit)
22
+ throw hit.error;
23
+ return clone(hit.value);
24
+ }
25
+ const text = await fs.readFile(file, "utf8");
26
+ try {
27
+ const value = parse(text);
28
+ remember(file, { key, value });
29
+ return clone(value);
30
+ }
31
+ catch (error) {
32
+ remember(file, { key, error });
33
+ throw error;
34
+ }
35
+ }
package/dist/core/runs.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { getOutputDir } from "./context.js";
4
+ import { readParsed } from "./file-cache.js";
4
5
  import { moveToTrash } from "./trash.js";
5
6
  import { awaitingDecision, readDecision } from "./decisions.js";
6
7
  /**
@@ -10,14 +11,15 @@ import { awaitingDecision, readDecision } from "./decisions.js";
10
11
  */
11
12
  /** A run with no trace update for this long and no summary counts as aborted. */
12
13
  const STALE_MS = 15 * 60 * 1000;
14
+ /**
15
+ * A run's trace, from the file cache while unchanged (the run list reads
16
+ * every trace on each live update; finished runs never change again). The
17
+ * events are shared with the cache: read them, never change them.
18
+ */
13
19
  async function readTrace(runDir) {
14
- let raw;
15
- try {
16
- raw = await fs.readFile(path.join(runDir, "trace.jsonl"), "utf8");
17
- }
18
- catch {
19
- return [];
20
- }
20
+ return readParsed(path.join(runDir, "trace.jsonl"), parseTrace).catch(() => []);
21
+ }
22
+ function parseTrace(raw) {
21
23
  const events = [];
22
24
  for (const line of raw.split("\n")) {
23
25
  if (!line.trim())
@@ -6,8 +6,12 @@
6
6
  *
7
7
  * - right after any change made through the API (`touch()` from the router),
8
8
  * - when a chat's state changes (turn start/end, a question, an answer),
9
- * - and on the watch's interval, for changes nobody announces (an agent
10
- * writing files, a run progressing on disk).
9
+ * - when a file in the workspace changes (an agent writing files, a run
10
+ * progressing on disk) — where the platform watches a folder tree
11
+ * natively (macOS, Windows),
12
+ * - and on the watch's interval, for changes nobody announces. While the
13
+ * workspace's files are watched that is only a slow safety net
14
+ * (FALLBACK_MS), so an idle screen costs next to nothing.
11
15
  *
12
16
  * Evaluation runs in the watch's workspace — bound when the watch is made,
13
17
  * so a re-evaluation whatever triggers it (a timer, a change elsewhere)
@@ -23,6 +27,8 @@ interface Watch {
23
27
  ok: boolean;
24
28
  data: unknown;
25
29
  }>;
30
+ /** Whether its workspace's files are watched (then the interval is only a safety net). */
31
+ files(): boolean;
26
32
  watchers: Set<Watcher>;
27
33
  /** The last pushed JSON, to push changes only. */
28
34
  last?: string;
@@ -1,8 +1,83 @@
1
+ import { watch as watchFs } from "node:fs";
2
+ import path from "node:path";
1
3
  import { onChanged } from "../core/changes.js";
2
4
  import { currentWorkspace, perWorkspace } from "../core/workspace.js";
3
5
  const MIN_INTERVAL = 1000;
4
6
  const TOUCH_DEBOUNCE_MS = 60;
5
- const state = perWorkspace(() => ({ watches: new Map(), touchTimer: undefined }));
7
+ /** Re-evaluation after file changes: at most this often, however busy the disk (an agent writing code, a run streaming its trace). */
8
+ const FILES_THROTTLE_MS = 1000;
9
+ /** The interval while the workspace's files are watched: only what no file and no API call announces (a process ending, the clock). */
10
+ const FALLBACK_MS = 20_000;
11
+ /**
12
+ * Changes that never matter to a watch: version control and build trees,
13
+ * and a chat's transcript growing token by token (its state changes are
14
+ * announced by the chat itself).
15
+ */
16
+ const IGNORED = /(^|[/\\])(\.git|node_modules|\.next|\.vite|\.cache|\.turbo|dist|build|target|vendor)([/\\]|$)|(^|[/\\])chats[/\\]chat-[^/\\]+[/\\]events\.jsonl$/;
17
+ /** Native recursive folder watching: one cheap OS subscription for the whole tree. Elsewhere (Linux) the intervals do the work. */
18
+ const RECURSIVE = process.platform === "darwin" || process.platform === "win32";
19
+ const state = perWorkspace(() => ({
20
+ watches: new Map(),
21
+ touchTimer: undefined,
22
+ files: undefined,
23
+ }));
24
+ /** Re-evaluate every watch of the workspace now (each after whatever runs). */
25
+ function runAll(s) {
26
+ for (const w of s.watches.values())
27
+ void run(w, undefined).finally(() => schedule(w));
28
+ }
29
+ /**
30
+ * Watch the workspace's folder tree (and its output dir, when that lies
31
+ * elsewhere) while anyone watches a route there. A watcher that fails (too
32
+ * many open files, the folder gone) is dropped and the intervals take over.
33
+ */
34
+ function watchFiles(ws, s) {
35
+ if (!RECURSIVE || s.files)
36
+ return;
37
+ const files = { watchers: [] };
38
+ // `name` is relative to the watched folder, so a workspace that itself lives under a "build" folder is not ignored whole.
39
+ const onEvent = (_event, name) => {
40
+ if (name && IGNORED.test(String(name)))
41
+ return;
42
+ if (files.timer || s.files !== files)
43
+ return;
44
+ files.timer = setTimeout(() => {
45
+ files.timer = undefined;
46
+ if (s.files === files && !ws.closed)
47
+ runAll(s);
48
+ }, FILES_THROTTLE_MS);
49
+ files.timer.unref?.();
50
+ };
51
+ const dirs = [ws.root];
52
+ if (path.relative(ws.root, ws.outputDir).startsWith(".."))
53
+ dirs.push(ws.outputDir);
54
+ try {
55
+ for (const dir of dirs) {
56
+ const w = watchFs(dir, { recursive: true, persistent: false }, onEvent);
57
+ w.on("error", () => stopFiles(s, true));
58
+ files.watchers.push(w);
59
+ }
60
+ }
61
+ catch {
62
+ for (const w of files.watchers)
63
+ w.close();
64
+ return;
65
+ }
66
+ s.files = files;
67
+ }
68
+ /** Stop watching the folder tree; `failed` re-times every watch to its own interval at once. */
69
+ function stopFiles(s, failed = false) {
70
+ const files = s.files;
71
+ if (!files)
72
+ return;
73
+ s.files = undefined;
74
+ clearTimeout(files.timer);
75
+ for (const w of files.watchers)
76
+ w.close();
77
+ if (failed)
78
+ for (const w of s.watches.values())
79
+ schedule(w);
80
+ }
6
81
  /**
7
82
  * Evaluate after whatever evaluation is in flight (it may predate the
8
83
  * change that asked for this one). Requests that arrive while one waits
@@ -40,7 +115,8 @@ function schedule(w) {
40
115
  clearTimeout(w.timer);
41
116
  if (!w.watchers.size)
42
117
  return;
43
- const every = Math.max(MIN_INTERVAL, Math.min(...[...w.watchers].map((x) => x.interval)));
118
+ const asked = Math.min(...[...w.watchers].map((x) => x.interval));
119
+ const every = Math.max(MIN_INTERVAL, w.files() ? Math.max(asked, FALLBACK_MS) : asked);
44
120
  w.timer = setTimeout(() => void run(w, undefined).finally(() => schedule(w)), every);
45
121
  w.timer.unref?.();
46
122
  }
@@ -49,12 +125,14 @@ function schedule(w) {
49
125
  * every change, and at least every `interval` ms. Returns the unwatch.
50
126
  */
51
127
  export function watch(key, evaluate, interval, push) {
52
- const { watches } = state();
128
+ const s = state();
129
+ const { watches } = s;
53
130
  let w = watches.get(key);
54
131
  if (!w) {
55
132
  const ws = currentWorkspace();
56
- w = { evaluate: () => ws.run(evaluate), watchers: new Set() };
133
+ w = { evaluate: () => ws.run(evaluate), files: () => !!s.files, watchers: new Set() };
57
134
  watches.set(key, w);
135
+ watchFiles(ws, s);
58
136
  }
59
137
  const watcher = { interval, push };
60
138
  w.watchers.add(watcher);
@@ -67,6 +145,9 @@ export function watch(key, evaluate, interval, push) {
67
145
  clearTimeout(current.timer);
68
146
  if (watches.get(key) === current)
69
147
  watches.delete(key);
148
+ // Nobody watches anything here any more: the folder tree need not be watched either.
149
+ if (!watches.size)
150
+ stopFiles(s);
70
151
  }
71
152
  else
72
153
  schedule(current);
@@ -78,6 +159,7 @@ export function closeWatches() {
78
159
  for (const w of s.watches.values())
79
160
  clearTimeout(w.timer);
80
161
  s.watches.clear();
162
+ stopFiles(s);
81
163
  clearTimeout(s.touchTimer);
82
164
  s.touchTimer = undefined;
83
165
  }
@@ -95,8 +177,7 @@ export function touch() {
95
177
  return;
96
178
  s.touchTimer = setTimeout(() => {
97
179
  s.touchTimer = undefined;
98
- for (const w of s.watches.values())
99
- void run(w, undefined).finally(() => schedule(w));
180
+ runAll(s);
100
181
  }, TOUCH_DEBOUNCE_MS);
101
182
  s.touchTimer.unref?.();
102
183
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@netnodeag/kraftwerk",
3
- "version": "0.93.0",
3
+ "version": "0.95.0",
4
4
  "description": "Open-source agentic workspace for teams — where people and AI agents get work done together: agents (Claude Code, Codex, Pi), skills, shared knowledge, repeatable workflows, and deterministic verification",
5
5
  "keywords": [
6
6
  "agents",