@k-electron/k-bench 0.3.0 → 0.4.1

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.
@@ -1,17 +1,44 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { statSync } from "node:fs";
3
- import { basename, resolve } from "node:path";
4
- import { DEFAULT_LAUNCH_OPTIONS } from "../shared/launch-options.js";
2
+ import { mkdirSync, statSync } from "node:fs";
3
+ import { basename, dirname, resolve } from "node:path";
4
+ import { DEFAULT_LAUNCH_OPTIONS, ROLE_LAUNCH_OPTIONS, } from "../shared/launch-options.js";
5
+ import { sessionsByRole } from "../shared/session-roles.js";
5
6
  import { availableName } from "./naming.js";
6
7
  import { Reconciler } from "./reconciler.js";
7
- /** A failure the HTTP layer maps to a status code. */
8
+ import { nowInSeconds } from "./tmux.js";
9
+ /**
10
+ * A failure the HTTP layer maps to a status code. `details` go into the response body
11
+ * next to the message, for a client that acts on the refusal.
12
+ */
8
13
  export class ServiceError extends Error {
9
14
  kind;
10
- constructor(kind, message) {
15
+ details;
16
+ constructor(kind, message, details = {}) {
11
17
  super(message);
12
18
  this.kind = kind;
19
+ this.details = details;
13
20
  }
14
21
  }
22
+ /** A Workspace's Prime and Worker, in the order they are listed. */
23
+ const ROLES = ["prime", "worker"];
24
+ /** The fixed names of the Prime and Worker, which no Other Session may take. */
25
+ const ROLE_NAMES = { prime: "Prime", worker: "Worker" };
26
+ function isRoleName(name) {
27
+ return ROLES.some((role) => ROLE_NAMES[role] === name);
28
+ }
29
+ /** The Prime and Worker last as long as their Workspace, under their fixed names. */
30
+ function assertNoRole(session, change) {
31
+ if (session.role) {
32
+ throw new ServiceError("conflict", `The ${ROLE_NAMES[session.role]} can't be ${change}`);
33
+ }
34
+ }
35
+ /**
36
+ * A Session's state: none for a shell or a Stopped Session. A running Claude Session is in the
37
+ * state its hooks last wrote, and Idle until one has run (see `LiveSession.activity`).
38
+ */
39
+ function activityOf(session, live) {
40
+ return session.kind === "claude" && live ? live.activity : null;
41
+ }
15
42
  function isDirectory(path) {
16
43
  try {
17
44
  return statSync(path).isDirectory();
@@ -20,6 +47,40 @@ function isDirectory(path) {
20
47
  return false;
21
48
  }
22
49
  }
50
+ function assertDirectory(folder) {
51
+ if (!isDirectory(folder)) {
52
+ throw new ServiceError("invalid", `Folder does not exist: ${folder}`);
53
+ }
54
+ }
55
+ /** Why a folder couldn't be made, in the owner's words. */
56
+ function mkdirFailure(error) {
57
+ const code = error.code;
58
+ if (code === "EEXIST" || code === "ENOTDIR")
59
+ return "a file is in the way";
60
+ if (code === "EACCES" || code === "EPERM")
61
+ return "permission denied";
62
+ if (code === "ENAMETOOLONG")
63
+ return "the name is too long";
64
+ return code ?? String(error);
65
+ }
66
+ /**
67
+ * Makes `folder` and any missing folders above it, from the top down. A failure names the
68
+ * folder that couldn't be made; the folders made before it stay.
69
+ */
70
+ function makeFolders(folder) {
71
+ const missing = [];
72
+ for (let path = folder; !isDirectory(path) && path !== dirname(path); path = dirname(path)) {
73
+ missing.unshift(path);
74
+ }
75
+ for (const path of missing) {
76
+ try {
77
+ mkdirSync(path);
78
+ }
79
+ catch (error) {
80
+ throw new ServiceError("invalid", `Couldn't make the folder ${path}: ${mkdirFailure(error)}`);
81
+ }
82
+ }
83
+ }
23
84
  /** The domain operations. The store holds what the owner chose; tmux says what is alive. */
24
85
  export class Service {
25
86
  store;
@@ -27,29 +88,70 @@ export class Service {
27
88
  sessionCreations = Promise.resolve();
28
89
  reconciler;
29
90
  restarts = new Map();
30
- constructor(store, tmux) {
91
+ /** How long a Working Session prints nothing before it decays to Idle. */
92
+ workingQuietMs;
93
+ constructor(store, tmux, options) {
31
94
  this.store = store;
32
95
  this.tmux = tmux;
33
96
  this.reconciler = new Reconciler(store, tmux);
97
+ this.workingQuietMs = options.workingQuietMs;
34
98
  }
35
- /** Kills tmux sessions that have no store record. Runs at startup and on every state read. */
99
+ /**
100
+ * Kills tmux sessions that have no store record and stores the conversation each Claude
101
+ * Session is on. Runs at startup, on every state read and whenever Claude Code reports a
102
+ * conversation.
103
+ */
36
104
  async reconcile() {
37
105
  await this.reconciler.reconcile();
38
106
  }
107
+ /**
108
+ * With `createMissingFolders`, a folder that doesn't exist yet is made (with any missing
109
+ * folders above it) once every other check has passed; without it, it is refused.
110
+ */
39
111
  createWorkspace(input) {
40
112
  const folder = resolve(input.folder);
41
- if (!isDirectory(folder)) {
42
- throw new ServiceError("invalid", `Folder does not exist: ${folder}`);
43
- }
113
+ if (!input.createMissingFolders)
114
+ assertDirectory(folder);
115
+ this.assertFolderFree(folder);
44
116
  const explicit = input.name?.trim();
45
117
  if (explicit)
46
118
  this.assertWorkspaceNameFree(explicit);
119
+ if (input.createMissingFolders)
120
+ makeFolders(folder);
47
121
  const name = explicit || availableName(basename(folder), this.workspaceNames());
48
- const { id } = this.store.addWorkspace({ name, folder });
122
+ // The Prime and Worker are recorded with the Workspace and started only when asked to.
123
+ const { id } = this.store.transaction(() => {
124
+ const workspace = this.store.addWorkspace({ name, folder });
125
+ for (const role of ROLES) {
126
+ this.store.addSession({
127
+ id: randomUUID(),
128
+ workspaceId: workspace.id,
129
+ name: ROLE_NAMES[role],
130
+ role,
131
+ conversationId: randomUUID(),
132
+ launchOptions: ROLE_LAUNCH_OPTIONS[role],
133
+ });
134
+ }
135
+ return workspace;
136
+ });
49
137
  return { id, name, folder };
50
138
  }
51
- /** Renames and/or re-folders a Workspace; both changes are checked before either is made. */
52
- updateWorkspace(id, changes) {
139
+ /**
140
+ * Where the folder picker opens: the parent of the most recently created Workspace's
141
+ * folder, or `root` (Home) when there is none or that parent is gone.
142
+ */
143
+ pickerStart(root) {
144
+ const newest = this.store.newestWorkspace();
145
+ const parent = newest && dirname(newest.folder);
146
+ return parent && isDirectory(parent) ? parent : root;
147
+ }
148
+ /**
149
+ * Renames and/or re-folders a Workspace; both changes are checked before either is made.
150
+ * `createMissingFolders` works as in `createWorkspace`. Moving the Open Workspace onto a
151
+ * folder starts its Stopped Prime and Worker there, so fixing a Missing one needs no
152
+ * second open.
153
+ */
154
+ async updateWorkspace(id, changes) {
53
155
  const workspace = this.store.getWorkspace(id);
54
156
  if (!workspace)
55
157
  throw new ServiceError("not_found", "Unknown Workspace");
@@ -63,14 +165,85 @@ export class Service {
63
165
  }
64
166
  if (changes.folder !== undefined) {
65
167
  const folder = resolve(changes.folder);
66
- if (!isDirectory(folder)) {
67
- throw new ServiceError("invalid", `Folder does not exist: ${folder}`);
68
- }
168
+ if (!changes.createMissingFolders)
169
+ assertDirectory(folder);
170
+ this.assertFolderFree(folder, id);
69
171
  update.folder = folder;
70
172
  }
173
+ if (update.folder !== undefined && changes.createMissingFolders) {
174
+ makeFolders(update.folder);
175
+ }
71
176
  this.store.updateWorkspace(id, update);
177
+ if (update.folder !== undefined && this.openWorkspaceId() === id) {
178
+ await this.startRoles(id);
179
+ }
72
180
  return { ...workspace, ...update };
73
181
  }
182
+ /**
183
+ * Makes the Workspace the Open Workspace and, unless it is Missing, starts its Stopped
184
+ * Prime and Worker, resuming their conversations. Opening it again changes nothing that
185
+ * is running. With `showWorker` (the owner chose it by name), its right Pane shows the
186
+ * Worker again, keeping its tabs.
187
+ */
188
+ async openWorkspace(id, options = {}) {
189
+ const workspace = this.store.getWorkspace(id);
190
+ if (!workspace)
191
+ throw new ServiceError("not_found", "Unknown Workspace");
192
+ this.store.transaction(() => {
193
+ this.store.setOpenWorkspaceId(id);
194
+ if (options.showWorker) {
195
+ this.store.setRightPane(id, { ...this.rightPane(id), shown: null });
196
+ }
197
+ });
198
+ if (isDirectory(workspace.folder))
199
+ await this.startRoles(id);
200
+ return { id };
201
+ }
202
+ /**
203
+ * The Open Workspace: the one last opened or, when none is set, the first by position.
204
+ * Null when there are no Workspaces.
205
+ */
206
+ openWorkspaceId() {
207
+ return this.store.getOpenWorkspaceId() ?? this.store.listWorkspaces()[0]?.id ?? null;
208
+ }
209
+ /** Starts the Workspace's Prime and Worker, those that are Stopped, together. */
210
+ async startRoles(workspaceId) {
211
+ const { primeAndWorker } = sessionsByRole(this.store.listSessions(workspaceId));
212
+ await Promise.all(primeAndWorker.map((session) => this.restartSession(session.id)));
213
+ }
214
+ /**
215
+ * Sets what the Workspace's right Pane holds. Every tab must be one of its Other Sessions,
216
+ * once, and what's shown must be one of the tabs, or null for the Worker.
217
+ */
218
+ setRightPane(workspaceId, rightPane) {
219
+ if (!this.store.getWorkspace(workspaceId)) {
220
+ throw new ServiceError("not_found", "Unknown Workspace");
221
+ }
222
+ const others = this.otherSessionIds(workspaceId);
223
+ const { shown, tabs } = rightPane;
224
+ if (!tabs.every((id) => others.has(id)) || new Set(tabs).size !== tabs.length) {
225
+ throw new ServiceError("invalid", "tabs must list Other Sessions of the Workspace, each at most once");
226
+ }
227
+ if (shown !== null && !tabs.includes(shown)) {
228
+ throw new ServiceError("invalid", "shown must be null or one of the tabs");
229
+ }
230
+ this.store.setRightPane(workspaceId, { shown, tabs });
231
+ }
232
+ otherSessionIds(workspaceId) {
233
+ const { others } = sessionsByRole(this.store.listSessions(workspaceId));
234
+ return new Set(others.map((session) => session.id));
235
+ }
236
+ /**
237
+ * What the Workspace's right Pane holds, leaving out any Session that is no longer one of
238
+ * its Other Sessions.
239
+ */
240
+ rightPane(workspaceId) {
241
+ const others = this.otherSessionIds(workspaceId);
242
+ const stored = this.store.getRightPane(workspaceId);
243
+ const tabs = stored.tabs.filter((id) => others.has(id));
244
+ const shown = stored.shown !== null && tabs.includes(stored.shown) ? stored.shown : null;
245
+ return { shown, tabs };
246
+ }
74
247
  /** `ids` must be every Workspace exactly once, in the order the owner wants. */
75
248
  reorderWorkspaces(ids) {
76
249
  const known = this.store.listWorkspaces().map((w) => w.id);
@@ -79,7 +252,24 @@ export class Service {
79
252
  }
80
253
  this.store.setWorkspaceOrder(ids);
81
254
  }
82
- /** Ends the Workspace's shells first, then forgets it. The folder on disk is never touched. */
255
+ /**
256
+ * `ids` must be every Other Session of the Workspace exactly once, in the order the owner
257
+ * wants. The Prime and Worker always come first, so they are never in it.
258
+ */
259
+ reorderSessions(workspaceId, ids) {
260
+ if (!this.store.getWorkspace(workspaceId)) {
261
+ throw new ServiceError("not_found", "Unknown Workspace");
262
+ }
263
+ const known = [...this.otherSessionIds(workspaceId)];
264
+ if (ids.length !== known.length || !known.every((id) => ids.includes(id))) {
265
+ throw new ServiceError("invalid", "ids must list every Other Session of the Workspace exactly once");
266
+ }
267
+ this.store.setSessionOrder(workspaceId, ids);
268
+ }
269
+ /**
270
+ * Ends the Workspace's shells first, then forgets it. The folder on disk is never touched.
271
+ * Deleting the Open Workspace opens the first Workspace by position, or none.
272
+ */
83
273
  async deleteWorkspace(id) {
84
274
  if (!this.store.getWorkspace(id))
85
275
  throw new ServiceError("not_found", "Unknown Workspace");
@@ -90,7 +280,14 @@ export class Service {
90
280
  const failed = kills.find((kill) => kill.status === "rejected");
91
281
  if (failed)
92
282
  throw failed.reason;
93
- this.store.deleteWorkspace(id);
283
+ const wasOpen = this.openWorkspaceId() === id;
284
+ this.store.transaction(() => {
285
+ this.store.deleteWorkspace(id);
286
+ // The first Workspace by position becomes open, and stays so through a reorder. It is
287
+ // not started: only opening it does that.
288
+ if (wasOpen)
289
+ this.store.setOpenWorkspaceId(this.store.listWorkspaces()[0]?.id ?? null);
290
+ });
94
291
  }
95
292
  workspaceNames(exceptId) {
96
293
  return new Set(this.store
@@ -104,6 +301,19 @@ export class Service {
104
301
  throw new ServiceError("conflict", `A Workspace named "${name}" already exists`);
105
302
  }
106
303
  }
304
+ /**
305
+ * A folder has at most one Workspace, so a project never gets two sets of Claudes. The
306
+ * refusal names the Workspace that has it, so a client can take the owner there.
307
+ * `folder` is already resolved. Changing a folder passes the Workspace being moved.
308
+ */
309
+ assertFolderFree(folder, exceptId) {
310
+ const owner = this.store
311
+ .listWorkspaces()
312
+ .find((w) => w.id !== exceptId && resolve(w.folder) === folder);
313
+ if (owner) {
314
+ throw new ServiceError("conflict", `A Workspace for this folder already exists: "${owner.name}"`, { workspace: { id: owner.id, name: owner.name } });
315
+ }
316
+ }
107
317
  /**
108
318
  * One at a time: choosing the name and storing the Session are separated by starting
109
319
  * the shell, so overlapping creations would otherwise pick the same default name.
@@ -130,7 +340,7 @@ export class Service {
130
340
  n++;
131
341
  name = `session ${n}`;
132
342
  }
133
- else if (taken.has(name)) {
343
+ else if (taken.has(name) || isRoleName(name)) {
134
344
  throw new ServiceError("conflict", `A Session named "${name}" already exists`);
135
345
  }
136
346
  const id = randomUUID();
@@ -169,29 +379,44 @@ export class Service {
169
379
  const session = this.store.getSession(sessionId);
170
380
  if (!session)
171
381
  throw new ServiceError("not_found", "Unknown Session");
382
+ assertNoRole(session, "renamed");
172
383
  const name = requestedName.trim();
173
384
  if (!name)
174
385
  throw new ServiceError("invalid", "name is required");
175
386
  const clash = this.store
176
387
  .listSessions(session.workspaceId)
177
388
  .some((other) => other.id !== sessionId && other.name === name);
178
- if (clash) {
389
+ if (clash || isRoleName(name)) {
179
390
  throw new ServiceError("conflict", `A Session named "${name}" already exists`);
180
391
  }
181
392
  this.store.renameSession(sessionId, name);
182
393
  return { id: sessionId, name };
183
394
  }
184
- /** Ends the Session's shell and everything in it, then forgets the Session. */
395
+ /**
396
+ * Ends the Session's shell and everything in it, then forgets the Session, and its tab in
397
+ * the right Pane, which shows the Worker if that tab was shown.
398
+ */
185
399
  async deleteSession(sessionId) {
186
- if (!this.store.getSession(sessionId)) {
400
+ const session = this.store.getSession(sessionId);
401
+ if (!session)
187
402
  throw new ServiceError("not_found", "Unknown Session");
188
- }
403
+ assertNoRole(session, "deleted");
189
404
  await this.tmux.killSession(sessionId);
190
- this.store.deleteSession(sessionId);
405
+ this.store.transaction(() => {
406
+ this.store.deleteSession(sessionId);
407
+ this.store.setRightPane(session.workspaceId, this.rightPane(session.workspaceId));
408
+ });
191
409
  }
410
+ /**
411
+ * The state, read fresh. Reading it is not free of effects: like `reconcile`, it changes
412
+ * tmux, writing Idle back to each quiet Working Session (`decayQuietWork`), so the decay
413
+ * latches.
414
+ */
192
415
  async getState() {
193
416
  const live = await this.reconciler.reconcile();
417
+ await this.decayQuietWork(live);
194
418
  return {
419
+ openWorkspaceId: this.openWorkspaceId(),
195
420
  workspaces: this.store.listWorkspaces().map((workspace) => ({
196
421
  ...workspace,
197
422
  missing: !isDirectory(workspace.folder),
@@ -199,12 +424,32 @@ export class Service {
199
424
  id: session.id,
200
425
  name: session.name,
201
426
  kind: session.kind,
427
+ role: session.role,
202
428
  status: live.has(session.id) ? "running" : "stopped",
203
429
  bell: live.get(session.id)?.bell ?? false,
430
+ activity: activityOf(session, live.get(session.id)),
204
431
  })),
432
+ rightPane: this.rightPane(workspace.id),
205
433
  })),
206
434
  };
207
435
  }
436
+ /**
437
+ * Makes Idle each Working Session that has printed nothing for the quiet time: Claude Code
438
+ * fires no hook when a turn is interrupted, and a wrong Idle is better than a wrong Working.
439
+ * The Idle is written back to tmux, so it latches: the redraws an idle Claude Code makes
440
+ * now and then don't bring Working back, and only a hook or the owner's key moves it on.
441
+ * Waiting never decays, since a permission prompt doesn't redraw.
442
+ */
443
+ async decayQuietWork(live) {
444
+ const quietSince = nowInSeconds() - Math.ceil(this.workingQuietMs / 1000);
445
+ await Promise.all([...live.values()]
446
+ .filter((session) => session.activity === "working" && session.lastChange <= quietSince)
447
+ .map(async (session) => {
448
+ const activity = await this.tmux.decayWorking(session.id, quietSince);
449
+ if (activity !== undefined)
450
+ session.activity = activity;
451
+ }));
452
+ }
208
453
  /**
209
454
  * Gives a Stopped Session a fresh program in its Workspace folder, keeping its id and name:
210
455
  * a shell, or Claude Code for a Claude Session.
@@ -234,8 +479,11 @@ export class Service {
234
479
  : {
235
480
  conversationId: session.conversationId,
236
481
  mode: "resume",
237
- // Every Launch option is passed again each time (ADR-0005).
238
- options: session.launchOptions ?? DEFAULT_LAUNCH_OPTIONS,
482
+ // Every Launch option is passed again each time (ADR-0005). A Prime's or
483
+ // Worker's are k-bench's fixed ones, whatever was stored with it.
484
+ options: session.role
485
+ ? ROLE_LAUNCH_OPTIONS[session.role]
486
+ : (session.launchOptions ?? DEFAULT_LAUNCH_OPTIONS),
239
487
  }));
240
488
  }
241
489
  /** Whether the terminal WebSocket has a shell to attach to: a known Session that is running. */