@a-t-h-i/bot-lobby 0.7.1 → 0.7.3

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 (50) hide show
  1. package/THIRD_PARTY_NOTICES.md +17 -0
  2. package/package.json +1 -1
  3. package/prompts/global.md +13 -0
  4. package/prompts/lobby-chat.md +2 -2
  5. package/prompts/master.md +8 -8
  6. package/prompts/planner.md +14 -0
  7. package/src/classifier/knowledge.ts +22 -3
  8. package/src/classifier/lobby.ts +4 -3
  9. package/src/execution/lint-setup.ts +409 -0
  10. package/src/execution/lint.ts +25 -13
  11. package/src/execution/verification.ts +65 -13
  12. package/src/index.ts +3 -0
  13. package/src/lobby/host.ts +5 -0
  14. package/src/lobby/keys.ts +1 -0
  15. package/src/lobby/planner.ts +2 -2
  16. package/src/lobby/runtime.ts +12 -0
  17. package/src/lobby/service.ts +23 -0
  18. package/src/master/master.ts +30 -13
  19. package/src/pi/commands.ts +23 -2
  20. package/src/pi/events.ts +3 -1
  21. package/src/pi/start-task-tool.ts +80 -0
  22. package/src/pi/tools.ts +1 -1
  23. package/src/schemas/configuration.ts +14 -1
  24. package/src/schemas/lint.ts +50 -0
  25. package/src/text.ts +22 -0
  26. package/src/webui/api/index.ts +14 -2
  27. package/src/webui/api/sessions.ts +6 -0
  28. package/src/webui/api/settings.ts +39 -0
  29. package/src/webui/dev/fake-service.ts +1 -0
  30. package/src/webui/protocol.ts +6 -0
  31. package/src/workflow/workflow.ts +22 -7
  32. package/webui/dist/apple-touch-icon.png +0 -0
  33. package/webui/dist/assets/{CodeSurface-Bdkhh84z.js → CodeSurface-CL7RbdNJ.js} +1 -1
  34. package/webui/dist/assets/{TerminalView-CsDNheS9.js → TerminalView-BrZ9qW_T.js} +1 -1
  35. package/webui/dist/assets/index-5eWi36H6.js +117 -0
  36. package/webui/dist/assets/index-Crl5pWLp.css +2 -0
  37. package/webui/dist/build.json +51 -31
  38. package/webui/dist/icon-192.png +0 -0
  39. package/webui/dist/icon-512.png +0 -0
  40. package/webui/dist/icon-maskable-192.png +0 -0
  41. package/webui/dist/icon-maskable-512.png +0 -0
  42. package/webui/dist/index.html +2 -2
  43. package/webui/dist/licenses/sounds.txt +33 -0
  44. package/webui/dist/sounds/attention.mp3 +0 -0
  45. package/webui/dist/sounds/done.mp3 +0 -0
  46. package/webui/dist/sounds/error.mp3 +0 -0
  47. package/webui/dist/sounds/question.mp3 +0 -0
  48. package/webui/dist/sounds/sent.mp3 +0 -0
  49. package/webui/dist/assets/index-Bt0RLI3l.css +0 -2
  50. package/webui/dist/assets/index-C3Bn07Vr.js +0 -115
@@ -65,6 +65,8 @@ interface Linter {
65
65
  /** The installed binary as `[command, ...leading args]`, looked for from `folder` up to the repository's top. */
66
66
  binary(folder: string, top: string): string[] | undefined;
67
67
  args(files: readonly string[]): string[];
68
+ /** Flags from Settings that go before the files (ESLint's `--rule`s). */
69
+ extra?(config: Pick<LintConfig, "eslintRules">): string[];
68
70
  read(result: LintExecResult, folder: string, top: string): Parsed | undefined;
69
71
  }
70
72
 
@@ -220,6 +222,7 @@ export const LINTERS: readonly Linter[] = [
220
222
  extensions: JS,
221
223
  binary: nodeBin("eslint", "eslint"),
222
224
  args: (files) => ["--format", "json", ...files],
225
+ extra: (config) => Object.entries(config.eslintRules ?? {}).flatMap(([rule, level]) => ["--rule", `${rule}: ${level}`]),
223
226
  read: eslintRead,
224
227
  },
225
228
  {
@@ -352,7 +355,7 @@ export function planLint(top: string, files: readonly string[], config: Pick<Lin
352
355
  }
353
356
 
354
357
  /** Run one planned linter over its files. */
355
- export async function runPlan(plan: LintPlan, top: string, config: Pick<LintConfig, "command" | "timeoutMs">, exec: LintExec = execLint, signal?: AbortSignal): Promise<LintRun> {
358
+ export async function runPlan(plan: LintPlan, top: string, config: Pick<LintConfig, "command" | "timeoutMs"> & Partial<Pick<LintConfig, "eslintRules">>, exec: LintExec = execLint, signal?: AbortSignal): Promise<LintRun> {
356
359
  const started = Date.now();
357
360
  const folder = repoPath(top, plan.folder);
358
361
  const files = plan.files;
@@ -373,7 +376,7 @@ export async function runPlan(plan: LintPlan, top: string, config: Pick<LintConf
373
376
  }
374
377
  const binary = plan.linter.binary(plan.folder, top);
375
378
  if (!binary) return unavailable(plan.tool, folder, files, `${plan.tool} is configured${folder ? ` in ${folder}/` : ""} but not installed: install the project's dependencies there.`);
376
- const result = await exec(binary[0]!, [...binary.slice(1), ...plan.linter.args(files.map((file) => argument(plan.folder, top, file)))], { cwd: plan.folder, timeoutMs: config.timeoutMs, ...(signal ? { signal } : {}) });
379
+ const result = await exec(binary[0]!, [...binary.slice(1), ...(plan.linter.extra?.({ eslintRules: config.eslintRules ?? {} }) ?? []), ...plan.linter.args(files.map((file) => argument(plan.folder, top, file)))], { cwd: plan.folder, timeoutMs: config.timeoutMs, ...(signal ? { signal } : {}) });
377
380
  const ms = Date.now() - started;
378
381
  if (result.code === null) return unavailable(plan.tool, folder, files, why(result, plan.tool, config.timeoutMs), ms);
379
382
  const parsed = plan.linter.read(result, plan.folder, top);
@@ -382,22 +385,31 @@ export async function runPlan(plan: LintPlan, top: string, config: Pick<LintConf
382
385
  }
383
386
 
384
387
  /** A key for the touched files as they stand and the settings that lint them: equal keys, equal results. */
385
- export function lintFingerprint(top: string, files: readonly string[], config: Pick<LintConfig, "command" | "extensions">): string {
388
+ export function lintFingerprint(top: string, files: readonly string[], config: Pick<LintConfig, "command" | "extensions"> & Partial<Pick<LintConfig, "eslintRules">>): string {
386
389
  const hash = createHash("sha256");
387
- hash.update(JSON.stringify([config.command, config.extensions]));
388
- for (const file of [...files].sort()) {
389
- let stamp = "gone";
390
- try {
391
- const stat = statSync(join(top, file));
392
- stamp = `${stat.size}:${stat.mtimeMs}`;
393
- } catch {
394
- // A deleted file keys as gone.
395
- }
396
- hash.update(`\0${file}\0${stamp}`);
390
+ hash.update(JSON.stringify([config.command, config.extensions, config.eslintRules ?? {}]));
391
+ for (const file of [...files].sort()) hash.update(`\0${file}\0${stamp(join(top, file))}`);
392
+ // The linters' own configs above the files too: a rule switched in Settings (or by hand) lints again.
393
+ const folders = new Set<string>();
394
+ for (const file of files) for (const folder of upward(dirname(join(top, file)), top)) folders.add(folder);
395
+ const names = [...new Set([...LINTERS.flatMap((linter) => linter.configs), "package.json", "pyproject.toml"])];
396
+ for (const folder of [...folders].sort()) for (const name of names) {
397
+ const path = join(folder, name);
398
+ if (existsSync(path)) hash.update(`\0${relative(top, path)}\0${stamp(path)}`);
397
399
  }
398
400
  return hash.digest("hex").slice(0, 24);
399
401
  }
400
402
 
403
+ function stamp(path: string): string {
404
+ try {
405
+ const stat = statSync(path);
406
+ return `${stat.size}:${stat.mtimeMs}`;
407
+ } catch {
408
+ // A deleted file keys as gone.
409
+ return "gone";
410
+ }
411
+ }
412
+
401
413
  /** A linter the project configures, where, and whether its binary is there to run. */
402
414
  export interface FoundLinter {
403
415
  tool: string;
@@ -114,7 +114,7 @@ export interface FinalCheckSpec {
114
114
 
115
115
  /** The checks a project's own scripts define, in run order; absent scripts are not applicable. */
116
116
  export const FINAL_CHECK_SPECS: readonly FinalCheckSpec[] = [
117
- { script: "typecheck", check: { id: "typecheck", timeoutMs: 10 * 60_000, inputs: ["package.json", "package-lock.json", "tsconfig.json", "src", "webui/tsconfig.json", "webui/src"] } },
117
+ { script: "typecheck", check: { id: "typecheck", timeoutMs: 10 * 60_000, inputs: ["package.json", "package-lock.json", "tsconfig.json", "src", "test", "webui/tsconfig.json", "webui/src"] } },
118
118
  { script: "test", check: { id: "test", timeoutMs: 60 * 60_000, inputs: ["package.json", "package-lock.json", "tsconfig.json", "src", "test"] } },
119
119
  { script: "web:build", check: { id: "web:build", timeoutMs: 10 * 60_000, inputs: ["package.json", "package-lock.json", "webui", "src/lobby/prompts.ts", "src/webui/protocol.ts"] } },
120
120
  { script: "web:check", check: { id: "web:check", timeoutMs: 60 * 60_000, inputs: ["package.json", "package-lock.json", "playwright.config.ts", "test/web", "webui/dist/build.json", "src"], dependsOn: ["web:build"] } },
@@ -134,32 +134,72 @@ export function finalChecks(top: string): VerifyCheck[] {
134
134
  });
135
135
  }
136
136
 
137
- const inFlight = new Map<string, Promise<VerifyResult>>();
137
+ /**
138
+ * One shared execution per fingerprint. It runs under its own controller, so
139
+ * one caller's cancellation never cancels another caller's wait: the shared
140
+ * run is aborted only once every caller waiting on it has aborted.
141
+ */
142
+ interface SharedRun {
143
+ result: Promise<VerifyResult>;
144
+ controller: AbortController;
145
+ waiters: number;
146
+ }
147
+
148
+ const inFlight = new Map<string, SharedRun>();
138
149
 
139
150
  function resultOf(id: string, state: VerifyState, summary: string, fingerprint: string, ms = 0, output?: string, reused = false): VerifyResult {
140
151
  return { id, state, at: new Date().toISOString(), ms, fingerprint, summary, ...(output ? { output } : {}), ...(reused ? { reused: true } : {}) };
141
152
  }
142
153
 
143
- /** Run one check: single-flight per fingerprint, so concurrent callers share the work. */
144
- function runCheck(top: string, check: VerifyCheck, exec: VerifyExec, signal: AbortSignal | undefined): Promise<VerifyResult> {
145
- const fingerprint = checkFingerprint(top, check);
146
- const key = `${top}:${check.id}:${fingerprint}`;
147
- const existing = inFlight.get(key);
148
- if (existing) return existing;
154
+ function cancelledResult(check: VerifyCheck, fingerprint: string, ms = 0): VerifyResult {
155
+ return resultOf(check.id, "cancelled", `${check.id} was cancelled; a cancelled check is not a pass — complete again to re-run it`, fingerprint, ms);
156
+ }
157
+
158
+ function startShared(top: string, check: VerifyCheck, exec: VerifyExec, fingerprint: string, key: string): SharedRun {
159
+ const controller = new AbortController();
149
160
  const started = Date.now();
150
- const run = exec(check.command, check.args, { cwd: top, timeoutMs: check.timeoutMs, ...(signal ? { signal } : {}) })
161
+ const result = exec(check.command, check.args, { cwd: top, timeoutMs: check.timeoutMs, signal: controller.signal })
151
162
  .then((outcome): VerifyResult => {
152
163
  const ms = Date.now() - started;
153
- if (signal?.aborted) return resultOf(check.id, "cancelled", `${check.id} was cancelled; a cancelled check is not a pass — complete again to re-run it`, fingerprint, ms);
164
+ if (controller.signal.aborted) return cancelledResult(check, fingerprint, ms);
154
165
  if (outcome.timedOut) return resultOf(check.id, "fail", `${check.id} timed out after ${Math.round(check.timeoutMs / 60_000)} min`, fingerprint, ms, outcome.output.slice(-4_000));
155
166
  if (outcome.code === 0) return resultOf(check.id, "pass", `${check.id} passed`, fingerprint, ms);
156
167
  if (outcome.code === null) return resultOf(check.id, "unavailable", `${check.id} could not run (command not found or terminated); an unavailable check is not a pass`, fingerprint, ms, outcome.output.slice(-4_000));
157
168
  return resultOf(check.id, "fail", `${check.id} failed with exit ${outcome.code}`, fingerprint, ms, outcome.output.slice(-4_000));
158
169
  })
159
170
  .catch((error: unknown) => resultOf(check.id, "unavailable", `${check.id} could not run: ${error instanceof Error ? error.message : String(error)}`, fingerprint, Date.now() - started))
160
- .finally(() => { if (inFlight.get(key) === run) inFlight.delete(key); });
161
- inFlight.set(key, run);
162
- return run;
171
+ .finally(() => { if (inFlight.get(key) === shared) inFlight.delete(key); });
172
+ const shared: SharedRun = { controller, waiters: 0, result };
173
+ inFlight.set(key, shared);
174
+ return shared;
175
+ }
176
+
177
+ /** Run one check: single-flight per fingerprint, so concurrent callers share the work, each under its own cancellation. */
178
+ function runCheck(top: string, check: VerifyCheck, exec: VerifyExec, signal: AbortSignal | undefined): Promise<VerifyResult> {
179
+ const fingerprint = checkFingerprint(top, check);
180
+ if (signal?.aborted) return Promise.resolve(cancelledResult(check, fingerprint));
181
+ const key = `${top}:${check.id}:${fingerprint}`;
182
+ const shared = inFlight.get(key) ?? startShared(top, check, exec, fingerprint, key);
183
+ shared.waiters += 1;
184
+ if (!signal) return shared.result;
185
+ return new Promise<VerifyResult>((resolve) => {
186
+ const started = Date.now();
187
+ const onAbort = () => {
188
+ shared.waiters -= 1;
189
+ // The last waiter leaving stops the shared run (and its process tree); earlier ones just stop waiting.
190
+ if (shared.waiters <= 0) {
191
+ // A stopped run is never joined again: the next caller starts a fresh one.
192
+ if (inFlight.get(key) === shared) inFlight.delete(key);
193
+ shared.controller.abort();
194
+ }
195
+ resolve(cancelledResult(check, fingerprint, Date.now() - started));
196
+ };
197
+ signal.addEventListener("abort", onAbort, { once: true });
198
+ shared.result.then((result) => {
199
+ signal.removeEventListener("abort", onAbort);
200
+ resolve(signal.aborted ? cancelledResult(check, fingerprint, result.ms) : result);
201
+ });
202
+ });
163
203
  }
164
204
 
165
205
  export interface VerificationInput {
@@ -198,6 +238,18 @@ export async function runVerification(input: VerificationInput): Promise<Verific
198
238
  return { at: (input.now ?? (() => new Date()))().toISOString(), state, fingerprint, results, ...(results.length === 0 ? { note: "no applicable checks: the project defines none of typecheck, test, web:build, web:check" } : {}) };
199
239
  }
200
240
 
241
+ /**
242
+ * The passing checks whose inputs no longer match the report: what changed
243
+ * since verification finished. Completion calls this again right before it
244
+ * commits, so an edit made after the run never inherits its success.
245
+ */
246
+ export function staleVerification(top: string, checks: readonly VerifyCheck[], report: VerificationReport): string[] {
247
+ return report.results.flatMap((result) => {
248
+ const check = checks.find((entry) => entry.id === result.id);
249
+ return check && result.state === "pass" && result.fingerprint !== checkFingerprint(top, check) ? [result.id] : [];
250
+ });
251
+ }
252
+
201
253
  /** Checks cannot pass on inputs that changed while this run was in flight. */
202
254
  function invalidateChangedInputs(top: string, checks: readonly VerifyCheck[], results: VerifyResult[]): void {
203
255
  for (const result of results) {
package/src/index.ts CHANGED
@@ -4,6 +4,7 @@ import { CONFIG_DIR_NAME, type ExtensionAPI } from "@earendil-works/pi-coding-ag
4
4
  import { registerCommands } from "./pi/commands.ts";
5
5
  import { registerLifecycle } from "./pi/events.ts";
6
6
  import { registerOrchestrateTool } from "./pi/tools.ts";
7
+ import { registerStartTaskTool } from "./pi/start-task-tool.ts";
7
8
  import { onTransition } from "./state/task-state.ts";
8
9
  import { releaseAttachments } from "./state/attachments.ts";
9
10
  import { detectProjectRoot } from "./state/project.ts";
@@ -47,6 +48,8 @@ export default function (pi: ExtensionAPI): void {
47
48
  });
48
49
  registerCommands(pi, CONFIG_DIR_NAME);
49
50
  registerOrchestrateTool(pi, CONFIG_DIR_NAME);
51
+ // The Master starts a task itself from the lobby chat when a request is too big to do in one reply.
52
+ registerStartTaskTool(pi, CONFIG_DIR_NAME);
50
53
  // The questionnaire the oracle (and pi without a task) asks the user with; no other extension is needed for it.
51
54
  registerAskTool(pi, undefined, CONFIG_DIR_NAME);
52
55
  // The web tools, for the researcher and for pi without a task (the oracle leaves them to the researcher).
package/src/lobby/host.ts CHANGED
@@ -195,6 +195,11 @@ export interface LobbyService {
195
195
  liveSessions(): readonly LiveSession[];
196
196
  /** Run another session in this window (stopping its background process first); resolves to a notice. */
197
197
  switchTo(target: SwitchTarget): Promise<string>;
198
+ /**
199
+ * Open a fresh, empty session in this window (this one carries on in the background if it is at work). Whether
200
+ * it opens one, and a notice only when there is something to say (why not, or what carries on in the background).
201
+ */
202
+ newSession?(): { opened: boolean; notice?: string };
198
203
  /** Archived tasks, most recently archived first. */
199
204
  archivedTasks(): Task[];
200
205
  /** Archive, restore or delete a task; each returns a notice. */
package/src/lobby/keys.ts CHANGED
@@ -9,6 +9,7 @@ export const LOBBY_ACTIONS = {
9
9
  help: { key: "alt+h", help: "show or hide this list" },
10
10
  settings: { key: "alt+s", help: "settings: each agent's model and effort" },
11
11
  savePlan: { key: "ctrl+s", help: "save the plan from the Plan tab" },
12
+ newSession: { key: "alt+n", help: "open a new session in this window" },
12
13
  sidebar: { key: "alt+b", help: "fold or open the sidebar (on a phone, open it)" },
13
14
  activity: { key: "alt+a", help: "open or fold every step in the Lobby conversation" },
14
15
  thinking: { key: "alt+t", help: "show or hide Thinking on the Lobby" },
@@ -1108,7 +1108,7 @@ export class PlanningSession {
1108
1108
  const seated = eligible.filter((member) => this.pins.has(member) || decision.seat.has(member));
1109
1109
  for (const member of open) if (!decision.seat.has(member)) this.satOut.set(member, decision.probabilities.get(member) ?? 0);
1110
1110
  const out = [...this.satOut].map(([member, probability]) => `${MEMBER_LABELS[member]} sat out (${probability.toFixed(2)})`);
1111
- this.deps.feed?.log("CLASSIFIER", [`seated ${seated.length > 0 ? seated.map((member) => MEMBER_LABELS[member]).join(", ") : "nobody (the oracle plans alone)"}`, ...out, `${decision.ms} ms`].join(" · "), "info");
1111
+ this.deps.feed?.log("CLASSIFIER", [`seated ${seated.length > 0 ? seated.map((member) => MEMBER_LABELS[member]).join(", ") : "nobody (the orchestrator plans alone)"}`, ...out, `${decision.ms} ms`].join(" · "), "info");
1112
1112
  return seated;
1113
1113
  }
1114
1114
 
@@ -1183,7 +1183,7 @@ export class PlanningSession {
1183
1183
  }
1184
1184
  this.reply = { ...reply, status: ready ? "ready" : "grilling", ...(mode !== "normal" ? { questions: [] } : {}), ...(plan ? { plan } : {}) };
1185
1185
  } else {
1186
- this.error = `the oracle's part of the round failed — ${lead.error ?? lead.status}`;
1186
+ this.error = `the orchestrator's part of the round failed — ${lead.error ?? lead.status}`;
1187
1187
  }
1188
1188
  if (!reply && seatQuestions.length === 0) return;
1189
1189
  this.questions = ready ? [] : questions;
@@ -24,6 +24,7 @@ import { KnowledgeBook } from "./knowledge.ts";
24
24
  import type { LobbyService } from "./host.ts";
25
25
  import { backgroundSessions, carryHandOff, chatProfile, chatReplied, chatHistoryLines, createLobbyService, lobbyNotify, lobbyProfile, plannerDeps, resumeSession, seatProfile, setServiceState, savePlan as serviceSavePlan, answerPanel as serviceAnswerPanel } from "./service.ts";
26
26
  import { lobbyTopics } from "./topics.ts";
27
+ import { sessionTitle } from "../text.ts";
27
28
  export { backgroundSessions, setSessionLauncher } from "./service.ts";
28
29
  import { deliverComments, onOwnerEvent } from "../pi/owner.ts";
29
30
  import { pushNotice } from "../webui/notices.ts";
@@ -280,6 +281,17 @@ export function registerLobbyEvents(pi: ExtensionAPI, configDir: string): void {
280
281
  pi.on("ui_prompt_end", () => {
281
282
  lobbyTopics.bump("status");
282
283
  });
284
+ // A session starts unnamed (New session asks nothing): the first prompt names it, as a chat app titles a chat.
285
+ pi.on("before_agent_start", (event) => {
286
+ if (isMinimized() || event.messageType !== "user" || pi.getSessionName()) return;
287
+ const prompt = event.prompt.trim();
288
+ if (!prompt || prompt.startsWith("/") || prompt.startsWith("bot-lobby:")) return;
289
+ const name = sessionTitle(prompt);
290
+ if (!name) return;
291
+ pi.setSessionName(name);
292
+ lobbyTopics.bump("status");
293
+ lobbyTopics.bump("sessions");
294
+ });
283
295
  pi.on("agent_start", (_event, ctx) => {
284
296
  track(ctx);
285
297
  runtime?.keeper?.window.schedule();
@@ -822,6 +822,28 @@ async function switchTo(state: Runtime, target: SwitchTarget): Promise<string> {
822
822
  return leaving ? `${leaving.name} carries on in the background; switching this window to ${target.name}…` : `switching this window to ${target.name}…`;
823
823
  }
824
824
 
825
+ /**
826
+ * Open a fresh, empty session in this window through `/bot-lobby new` (only a
827
+ * command context may replace the session). New session asks nothing: the
828
+ * first prompt names the session (see registerLobbyEvents). As with a switch,
829
+ * a turn at work or a task this session drives carries on in the background.
830
+ */
831
+ function newSession(state: Runtime): { opened: boolean; notice?: string } {
832
+ if (switching) return { opened: false, notice: "a switch is already under way — wait a moment" };
833
+ // An empty session is already new: nothing to open, and nothing worth a notice.
834
+ if (!state.ctx.sessionManager.getBranch().some((entry) => entry.type === "message")) return { opened: false };
835
+ const leaving = handOffFor(state);
836
+ if (typeof leaving === "string") return { opened: false, notice: leaving };
837
+ const resumeOwner = pauseOwner();
838
+ if (!state.ctx.isIdle()) state.ctx.abort();
839
+ switchPending(() => {
840
+ handOff = undefined;
841
+ resumeOwner();
842
+ });
843
+ state.pi.sendUserMessage("/bot-lobby new", { expandPromptTemplates: true });
844
+ return leaving ? { opened: true, notice: `${leaving.name} carries on in the background` } : { opened: true };
845
+ }
846
+
825
847
  /** A switch is under way (between the reply and pi opening the next session). */
826
848
  let switching = false;
827
849
 
@@ -1267,6 +1289,7 @@ export function createLobbyService(state: Runtime): LobbyService {
1267
1289
  sendToSession: (sessionId, text) => sendToSession(state, sessionId, text),
1268
1290
  liveSessions: () => liveSessions(state),
1269
1291
  switchTo: (target) => switchTo(state, target),
1292
+ newSession: () => newSession(state),
1270
1293
  archivedTasks: () => listArchivedTasks(state.root, state.configDir),
1271
1294
  archiveTask: (taskId) => archiveTask(state, taskId),
1272
1295
  restoreTask: (taskId) => restoreTask(state, taskId),
@@ -577,20 +577,29 @@ export function packFingerprint(content: string): string {
577
577
  return createHash("sha1").update(content).digest("hex").slice(0, 16);
578
578
  }
579
579
 
580
- /** A stale entry's refreshed form: new fingerprint, re-read snippet for its range, ranges clamped into the file as it is. */
580
+ /** A stale entry's refreshed form: new fingerprint, ranges clamped into the file as it is, and a snippet re-read across every range. */
581
581
  function refreshedEntry(file: ContextPackFile, content: string): ContextPackFile {
582
582
  const lines = content.replace(/\r?\n$/, "").split("\n");
583
583
  const clamp = (value: number): number => Math.min(Math.max(1, value), Math.max(1, lines.length));
584
584
  const ranges = file.ranges?.map(([start, end]): [number, number] => { const from = clamp(start); const to = clamp(end); return from <= to ? [from, to] : [to, from]; });
585
- const [start, end] = ranges?.[0] ?? [1, Math.min(lines.length, 60)];
586
- const snippet = file.snippet === undefined && !ranges?.length ? undefined : lines.slice(Math.max(0, start - 1), Math.max(0, end)).join("\n").slice(0, CONTEXT_SNIPPET_MAX_CHARS);
585
+ const read = (ranges?.length ? ranges : [[1, Math.min(lines.length, 60)] as [number, number]]).map(([start, end]) => lines.slice(Math.max(0, start - 1), Math.max(0, end)).join("\n"));
586
+ const snippet = file.snippet === undefined && !ranges?.length ? undefined : read.join("\n…\n").slice(0, CONTEXT_SNIPPET_MAX_CHARS);
587
587
  return { ...file, ...(ranges ? { ranges } : {}), fingerprint: packFingerprint(content), ...(snippet !== undefined ? { snippet } : {}) };
588
588
  }
589
589
 
590
+ /** The 1-based line a snippet starts on in the file as it is, when the snippet is still there verbatim. */
591
+ function snippetLine(content: string, snippet: string): number | undefined {
592
+ const at = snippet.trim() ? content.indexOf(snippet) : -1;
593
+ return at < 0 ? undefined : content.slice(0, at).split("\n").length;
594
+ }
595
+
590
596
  /**
591
- * Stale-context refresh at dispatch. A fingerprint that no longer matches
592
- * the file refreshes that entry (new fingerprint plus a re-read snippet and
593
- * clamped range); a path that no longer exists drops its entry. The pack is
597
+ * Stale-context refresh at dispatch. The engine fingerprints every entry
598
+ * itself, so an orchestrator never has to compute a hash: a missing or
599
+ * mismatched fingerprint is checked against the file. A snippet still in the
600
+ * file verbatim is kept (its ranges follow it if lines moved); otherwise the
601
+ * entry is refreshed (new fingerprint, ranges clamped, snippet re-read across
602
+ * every range). A path that no longer exists drops its entry. The pack is
594
603
  * never delivered silently stale, and the returned notes say exactly what
595
604
  * changed so the worker knows which entries are newer than the rest.
596
605
  */
@@ -598,20 +607,28 @@ export async function refreshContextPack(pack: ContextPack, root: string): Promi
598
607
  const notes: string[] = [];
599
608
  const files: ContextPackFile[] = [];
600
609
  for (const file of pack.files) {
601
- if (!file.fingerprint) {
602
- files.push(file);
603
- continue;
604
- }
605
610
  const content = await readFile(join(root, file.path), "utf8").catch(() => undefined);
606
611
  if (content === undefined) {
607
612
  notes.push(`dropped ${file.path} (the file no longer exists)`);
608
613
  continue;
609
614
  }
610
615
  const fingerprint = packFingerprint(content);
611
- if (fingerprint === file.fingerprint) files.push(file);
612
- else {
616
+ if (fingerprint === file.fingerprint) {
617
+ files.push(file);
618
+ continue;
619
+ }
620
+ const line = file.snippet === undefined ? undefined : snippetLine(content, file.snippet);
621
+ if (file.snippet === undefined && !file.ranges?.length) {
622
+ // Path only: nothing to go stale, the engine's fingerprint is all it needs.
623
+ files.push({ ...file, fingerprint });
624
+ } else if (line !== undefined) {
625
+ const shift = file.ranges?.[0] ? line - file.ranges[0][0] : 0;
626
+ const ranges = file.ranges?.map(([start, end]): [number, number] => [Math.max(1, start + shift), Math.max(1, end + shift)]);
627
+ files.push({ ...file, ...(ranges ? { ranges } : {}), fingerprint });
628
+ if (shift !== 0) notes.push(`moved ${file.path} ranges by ${shift > 0 ? "+" : ""}${shift} lines (the snippet is unchanged)`);
629
+ } else {
613
630
  files.push(refreshedEntry(file, content));
614
- notes.push(`refreshed ${file.path} (content had changed; new fingerprint ${fingerprint})`);
631
+ notes.push(`refreshed ${file.path} (${file.fingerprint ? "content had changed" : "the snippet no longer matches the file"}; new fingerprint ${fingerprint})`);
615
632
  }
616
633
  }
617
634
  pack.files = files;
@@ -57,16 +57,17 @@ const HELP = [
57
57
  "/bot-lobby carry-on <taskId> Take over a task no running session drives, unpause it and have the orchestrator carry it on (the Tasks screen's Resume)",
58
58
  "/bot-lobby auto [on|off] Auto mode: the orchestrator drives this session's task without asking (alt+g)",
59
59
  "/bot-lobby start-plan PLAN-… [auto] Start a planned task here; its agreed plan needs no approval",
60
+ "/bot-lobby new Open a fresh session in this window (named after its first prompt)",
60
61
  "/bot-lobby switch <session.jsonl> Run a saved session in this window (the web lobby's session browser uses it)",
61
62
  "/bot-lobby web [stop|link|reset] Open the browser UI (it starts with pi, on this machine only), or stop it, print its link, reset its link",
62
63
  "/bot-lobby help This help",
63
64
  ].join("\n");
64
65
 
65
66
  /** Subcommands only win when no free-form text follows (so tasks still start). */
66
- const SUBCOMMANDS = new Set(["lobby", "help", "status", "runs", "tasks", "pause", "resume", "cancel", "approve", "amend", "decline", "accept", "knowledge", "config", "settings", "on", "off", "minimize", "restore", "claim", "carry-on", "auto", "start-plan", "switch", "web"]);
67
+ const SUBCOMMANDS = new Set(["lobby", "help", "status", "runs", "tasks", "pause", "resume", "cancel", "approve", "amend", "decline", "accept", "knowledge", "config", "settings", "on", "off", "minimize", "restore", "claim", "carry-on", "auto", "start-plan", "switch", "new", "web"]);
67
68
 
68
69
  /** Subcommands that act on a task or open the lobby turn bot-lobby on first; the rest work while it is off. */
69
- const TURNS_ON = new Set(["lobby", "settings", "resume", "approve", "amend", "decline", "accept", "claim", "carry-on", "auto", "start-plan", "switch", "web"]);
70
+ const TURNS_ON = new Set(["lobby", "settings", "resume", "approve", "amend", "decline", "accept", "claim", "carry-on", "auto", "start-plan", "switch", "new", "web"]);
70
71
 
71
72
  /** `Task-Change-Table-Font-27-09-2026`, or an older `TASK-add-login` id. */
72
73
  function isTaskId(value: string | undefined): boolean {
@@ -330,6 +331,24 @@ async function switchCommand(ctx: ExtensionCommandContext, path: string): Promis
330
331
  }
331
332
  }
332
333
 
334
+ /**
335
+ * `/bot-lobby new`: open a fresh session in this window, as the lobby's New
336
+ * session asks. Like a switch, the context is stale once it lands.
337
+ */
338
+ async function newCommand(ctx: ExtensionCommandContext): Promise<void> {
339
+ let result: { cancelled: boolean };
340
+ try {
341
+ result = await ctx.newSession();
342
+ } catch (error) {
343
+ switchFailed();
344
+ throw error;
345
+ }
346
+ if (result.cancelled) {
347
+ switchFailed();
348
+ ctx.ui.notify("bot-lobby: the new session was cancelled", "warning");
349
+ }
350
+ }
351
+
333
352
  /** `/bot-lobby auto [on|off]`: switch (or set) auto mode for this session's task. */
334
353
  function autoCommand(ctx: ExtensionCommandContext, configDir: string, value: string | undefined): void {
335
354
  if (!value) return ctx.ui.notify(`bot-lobby: ${toggleOwnAuto()}`, "info");
@@ -407,6 +426,8 @@ export function registerCommands(pi: ExtensionAPI, configDir: string): void {
407
426
  return autoCommand(ctx, configDir, rest[0]);
408
427
  case "switch":
409
428
  return switchCommand(ctx, restText);
429
+ case "new":
430
+ return newCommand(ctx);
410
431
  case "web":
411
432
  return webCommand(ctx, rest[0]);
412
433
  case "start-plan": {
package/src/pi/events.ts CHANGED
@@ -64,7 +64,9 @@ export const LOBBY_CHAT_NOTE = [
64
64
  "## Bot Lobby chat",
65
65
  "You are the Master in Bot Lobby's chat: the user talks to the team here, and everyday work (questions, code changes, updates, minor fixes) happens in the chat itself, so do it directly.",
66
66
  "DESIGN, DEV, QA, RESEARCH and the scout answer in this chat too when the user names one with @ or the classifier gives a message to one; those lines reach you as \"The user asked …\" and \"… answered\" messages, for context: you need not answer them.",
67
- "Bot Lobby's workflow (scouts, a plan, the QA gate) runs only when the user types /plan (plan it with the panel) or /task (start it as a task). When a request is large, risky or spans several areas, suggest one of them in a line; never start one yourself.",
67
+ "You are the orchestrator, so judge each request before you act. Questions, explanations and small, clear changes (a few files in one area) you do yourself, right here.",
68
+ "Work that is large, risky or spans several areas (a new feature, frontend and backend together, an architecture change, anything that needs tests and review) goes to the team: call start_task with the request written in full, say in one line that you started a task, and end your turn. Effort decides its track, and the task's kickoff follows. Do not ask first.",
69
+ "If the request is unclear, ask one short question before starting a task. The user can also type /plan (plan it with the panel) or /task (start a task) themselves.",
68
70
  ].join("\n");
69
71
 
70
72
  /**
@@ -0,0 +1,80 @@
1
+ /**
2
+ * `start_task`: the Master's own way to turn a lobby request into a task.
3
+ * In the lobby chat it judges each message: a question or a small change it
4
+ * does itself; work that is large, risky or spans several areas it hands to
5
+ * the team by starting a task here, the same as the user typing `/task`.
6
+ * The task's track (fast or full) still comes from the effort and triage
7
+ * reads, and the kickoff follows the current turn, in a fresh context.
8
+ */
9
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
10
+ import { Container, Text } from "@earendil-works/pi-tui";
11
+ import { Type } from "typebox";
12
+ import { isSubagentProcess } from "./quiet.ts";
13
+ import { isMinimized } from "./ui.ts";
14
+ import { startTask } from "./start-task.ts";
15
+ import { activeTask } from "../state/persistence.ts";
16
+ import { detectProjectRoot } from "../state/project.ts";
17
+ import { lobbyFeed } from "../lobby/feed.ts";
18
+ import { lobbyTopics } from "../lobby/topics.ts";
19
+ import type { TrackPath } from "../schemas/task.ts";
20
+
21
+ export const START_TASK_TOOL = "start_task";
22
+
23
+ const Params = Type.Object({
24
+ request: Type.String({ minLength: 1, maxLength: 8000, description: "The work, written in full for the team: what the user wants, the files or areas you already know it touches, and any constraint they gave. The task starts in a fresh context, so this must stand on its own." }),
25
+ title: Type.Optional(Type.String({ maxLength: 80, description: "A short title (3-8 words); derived from the request when absent." })),
26
+ track: Type.Optional(Type.Union([Type.Literal("fast"), Type.Literal("full")], { description: "Only when you are sure: fast (small and clear, straight to the agents) or full (scouts, proposal, QA). Left out, the effort read picks." })),
27
+ auto: Type.Optional(Type.Boolean({ description: "true only when the user asked for it to run without them (no proposal approval or questions)." })),
28
+ });
29
+
30
+ type StartTaskParams = { request: string; title?: string; track?: TrackPath; auto?: boolean };
31
+
32
+ const DESCRIPTION = [
33
+ "Start a bot-lobby task from the lobby chat and hand the work to the team (scouts, DESIGN/DEV workers, QA), the same as the user typing /task.",
34
+ "Use it when the request is too big to do well yourself in one reply: several files or areas, a new feature, a risky or architectural change, or work that needs tests and review.",
35
+ "Do questions, explanations and small, clear edits yourself instead.",
36
+ "After calling it, tell the user in one short line that you started a task and why, then end your turn: the task's kickoff follows.",
37
+ ].join(" ");
38
+
39
+ export function registerStartTaskTool(pi: ExtensionAPI, configDir: string): void {
40
+ if (isSubagentProcess()) return;
41
+ pi.registerTool({
42
+ name: START_TASK_TOOL,
43
+ label: "Start task",
44
+ description: DESCRIPTION,
45
+ promptSnippet: "Turn a large lobby request into a bot-lobby task the team works on",
46
+ promptGuidelines: [
47
+ "In the lobby chat, judge each request: do small things yourself; call start_task for work that spans several areas, needs a plan, or needs tests and review.",
48
+ ],
49
+ parameters: Params,
50
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
51
+ const call = params as StartTaskParams;
52
+ if (isMinimized()) throw new Error("bot-lobby is off in this session; do the work yourself or ask the user to turn it on.");
53
+ const root = detectProjectRoot(ctx.cwd, configDir);
54
+ const current = activeTask(root, configDir, ctx.sessionManager.getSessionId());
55
+ if (current) throw new Error(`this session already drives ${current.id}; use the orchestrate tool for it.`);
56
+ lobbyFeed.log("LOBBY", "the orchestrator is starting a task for this request", "info");
57
+ const task = await startTask(pi, ctx, configDir, call.request.trim(), {
58
+ ...(call.title?.trim() ? { title: call.title.trim() } : {}),
59
+ ...(call.track ? { track: call.track } : {}),
60
+ ...(call.auto ? { auto: true } : {}),
61
+ });
62
+ if (!task) throw new Error("the task did not start: this session already drives one.");
63
+ lobbyTopics.bump("tasks");
64
+ const path = task.track?.path === "fast" ? "fast track: straight to the agents" : "full track: scouts, then a proposal for the user";
65
+ return {
66
+ content: [{ type: "text", text: `Started ${task.id} (${task.title}), ${path}. Tell the user in one line and end your turn; the kickoff follows.` }],
67
+ details: { taskId: task.id, title: task.title, track: task.track?.path },
68
+ };
69
+ },
70
+ renderCall(args, theme) {
71
+ const call = args as Partial<StartTaskParams>;
72
+ return new Text(`${theme.fg("toolTitle", theme.bold("start task"))}${call.title ? ` ${theme.fg("accent", call.title)}` : ""}`, 0, 0);
73
+ },
74
+ renderResult(result, _options, theme) {
75
+ const details = result.details as { taskId?: string; track?: string } | undefined;
76
+ if (!details?.taskId) return new Container();
77
+ return new Text(`${theme.fg("success", "✓")} ${theme.fg("accent", details.taskId)}${details.track ? ` ${theme.fg("muted", details.track)}` : ""}`, 0, 0);
78
+ },
79
+ });
80
+ }
package/src/pi/tools.ts CHANGED
@@ -31,7 +31,7 @@ export const ContextPackSchema = Type.Object({
31
31
  files: Type.Array(Type.Object({
32
32
  path: Type.String({ minLength: 1 }),
33
33
  ranges: Type.Optional(Type.Array(Type.Tuple([Type.Integer({ minimum: 1 }), Type.Integer({ minimum: 1 })]), { description: "[start, end] line ranges with 1 <= start <= end" })),
34
- fingerprint: Type.Optional(Type.String({ minLength: 1, description: "content hash at pack-build time; dispatch refreshes stale entries" })),
34
+ fingerprint: Type.Optional(Type.String({ minLength: 1, description: "optional; leave it out — the engine fingerprints each file at dispatch and refreshes stale snippets" })),
35
35
  snippet: Type.Optional(Type.String({ maxLength: 2000, description: "bounded excerpt, current at pack-build time" })),
36
36
  }, { additionalProperties: false })),
37
37
  invariants: Type.Optional(Type.Array(Type.String({ minLength: 1 }))),
@@ -124,6 +124,9 @@ export function isLintMode(value: unknown): value is LintMode {
124
124
  return typeof value === "string" && (LINT_MODES as readonly string[]).includes(value);
125
125
  }
126
126
 
127
+ export const LINT_RULE_LEVELS = ["off", "warn", "error"] as const;
128
+ export type LintRuleLevel = (typeof LINT_RULE_LEVELS)[number];
129
+
127
130
  export interface LintConfig {
128
131
  mode: LintMode;
129
132
  /** A command of your own, run without a shell from the repository's top; `{files}` stands for the touched files (they are appended when it is absent). Empty: the project's own linters are found (ESLint, Biome, Oxlint, Ruff). */
@@ -132,6 +135,8 @@ export interface LintConfig {
132
135
  extensions: string[];
133
136
  /** Time limit for one linter run. */
134
137
  timeoutMs: number;
138
+ /** ESLint rules the gate adds on top of the project's config (`--rule name: level`), set in Settings' linting wizard. ESLint's config is code, so it is never rewritten. */
139
+ eslintRules: Record<string, LintRuleLevel>;
135
140
  }
136
141
 
137
142
  export interface KnowledgeConfig {
@@ -289,7 +294,7 @@ export const DEFAULT_CONFIG: BotLobbyConfig = {
289
294
  cleanReview: true,
290
295
  knowledgeStartupBudget: 8000,
291
296
  },
292
- lint: { mode: "advise", command: "", extensions: [], timeoutMs: 2 * 60 * 1000 },
297
+ lint: { mode: "advise", command: "", extensions: [], timeoutMs: 2 * 60 * 1000, eslintRules: {} },
293
298
  knowledge: {
294
299
  compactionThreshold: 20000,
295
300
  backupCount: 1,
@@ -474,9 +479,17 @@ function normalizeLint(value: unknown): LintConfig {
474
479
  command: text(source.command, defaults.command),
475
480
  extensions: [...new Set(extensions)],
476
481
  timeoutMs: timeout ? Math.min(30 * 60 * 1000, Math.round(timeout)) : defaults.timeoutMs,
482
+ eslintRules: eslintRules(source.eslintRules),
477
483
  };
478
484
  }
479
485
 
486
+ /** Rule names as ESLint writes them (`no-console`, `@typescript-eslint/no-explicit-any`), each with a level; at most 200. */
487
+ function eslintRules(value: unknown): Record<string, LintRuleLevel> {
488
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
489
+ const entries = Object.entries(value as Record<string, unknown>).filter((entry): entry is [string, LintRuleLevel] => /^[@\w][\w@/.-]{0,120}$/.test(entry[0]) && (LINT_RULE_LEVELS as readonly unknown[]).includes(entry[1]));
490
+ return Object.fromEntries(entries.slice(0, 200));
491
+ }
492
+
480
493
  function normalizeClassifier(value: unknown): ClassifierConfig {
481
494
  const source = (value && typeof value === "object" ? value : {}) as Record<string, unknown>;
482
495
  const defaults = DEFAULT_CONFIG.classifier;