@turri-dev/cli 0.3.0 → 0.3.1-next.f3b1920

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.
@@ -32,6 +32,50 @@ export function codeTreeOf(moduleDir, commit) {
32
32
  export function holdsCommit(moduleDir, ancestor, commit) {
33
33
  return git(moduleDir, ["merge-base", "--is-ancestor", ancestor, commit]).status === 0;
34
34
  }
35
+ /**
36
+ * Where a codebase's history started: the module below it whose code it started from, and that module's commit - what
37
+ * its first commit says (`start from <module> at <commit>`, copyRequiredCode). None for a codebase that started from
38
+ * nothing.
39
+ */
40
+ export function startedFrom(moduleDir) {
41
+ const roots = git(moduleDir, ["log", "--max-parents=0", "--format=%s", "HEAD"]);
42
+ if (roots.status !== 0)
43
+ return undefined;
44
+ for (const subject of roots.stdout.trim().split("\n")) {
45
+ const match = /^start from (\S+) at (\w+)$/.exec(subject.trim());
46
+ if (match !== null)
47
+ return { module: match[1], commit: match[2] };
48
+ }
49
+ return undefined;
50
+ }
51
+ /**
52
+ * Whether a codebase's code holds a commit of another module - one below it in its requires chain, whose code it started
53
+ * from: the commit is that module's, or held by the one it started from - down the chain, as far as it goes.
54
+ */
55
+ export function heldUpChain(moduleDir, module, commit) {
56
+ let dir = moduleDir;
57
+ const seen = new Set();
58
+ while (!seen.has(dir)) {
59
+ seen.add(dir);
60
+ const from = startedFrom(dir);
61
+ if (from === undefined)
62
+ return false;
63
+ const fromDir = join(dirname(dir), from.module);
64
+ if (from.module === module)
65
+ return holdsCommit(fromDir, commit, from.commit);
66
+ dir = fromDir;
67
+ }
68
+ return false;
69
+ }
70
+ /**
71
+ * Whether `to` - a codebase at a commit - holds `from`'s commit: the same codebase, the commit or one built on it; a
72
+ * codebase above `from`'s in its requires chain, built from code that held it.
73
+ */
74
+ export function holdsAcross(from, to) {
75
+ if (from.codebase === to.codebase)
76
+ return holdsCommit(to.moduleDir, from.commit, to.commit);
77
+ return heldUpChain(to.moduleDir, from.codebase, from.commit);
78
+ }
35
79
  /**
36
80
  * Which codebase to launch for a spec, and at which commit: the tip of its codebase - code accumulates up a requires
37
81
  * chain, so the top module holds everything below it - at `commit`, or its last. Before the tip has anything committed,
@@ -39,17 +83,22 @@ export function holdsCommit(moduleDir, ancestor, commit) {
39
83
  */
40
84
  export function launchTarget(plainFile, options = {}) {
41
85
  const { tip, chain } = findCodebaseTip(plainFile, { allowNoFunctionalities: true, ...(options.inModule !== undefined ? { inModule: options.inModule } : {}) });
86
+ // The modules below the one launched, in its requires chain: their code is in it.
87
+ const belowOf = (entry) => {
88
+ const at = chain.findIndex((each) => each.moduleName === entry.moduleName);
89
+ return (at === -1 ? chain : chain.slice(0, at)).map((each) => each.moduleName).filter((name) => name !== entry.moduleName);
90
+ };
42
91
  if (options.commit !== undefined) {
43
92
  const commit = committedCode(dirname(tip.buildDir), options.commit);
44
93
  if (commit === undefined)
45
94
  throw new Error(`${tip.moduleName} has no commit ${options.commit} with code in it: nothing to launch.`);
46
- return { entry: tip, commit };
95
+ return { entry: tip, commit, below: belowOf(tip) };
47
96
  }
48
97
  const candidates = [tip, ...[...chain].reverse().filter((entry) => entry.moduleName !== tip.moduleName)];
49
98
  for (const entry of candidates) {
50
99
  const commit = committedCode(dirname(entry.buildDir));
51
100
  if (commit !== undefined)
52
- return { entry, commit, ...(entry.moduleName !== tip.moduleName ? { instead: tip.moduleName } : {}) };
101
+ return { entry, commit, below: belowOf(entry), ...(entry.moduleName !== tip.moduleName ? { instead: tip.moduleName } : {}) };
53
102
  }
54
103
  throw new Error(`Nothing is built yet for ${tip.moduleName}${candidates.length > 1 ? " or the modules it requires" : ""}: there is no code to launch. Regenerate it first.`);
55
104
  }
@@ -109,7 +158,9 @@ export function describeExport(code) {
109
158
  : []),
110
159
  ].join("\n");
111
160
  }
161
+ /** What this turri's launches started, by module and name: two modules' servers may have the same name. */
112
162
  const processes = new Map();
163
+ const keyOf = (moduleName, name) => `${moduleName}\u0000${name}`;
113
164
  const RUNNING_DIR = "running";
114
165
  function writeRecord(logDir, record) {
115
166
  try {
@@ -187,6 +238,7 @@ const groupAlive = (pgid) => {
187
238
  * not start is never stopped. Records of what has ended are taken out. Returns what was stopped.
188
239
  */
189
240
  export async function stopLeftBehind(projectDir, codebase) {
241
+ const codebases = codebase === undefined ? undefined : typeof codebase === "string" ? [codebase] : codebase;
190
242
  const dir = join(projectDir, ".turri", "launch", RUNNING_DIR);
191
243
  let names;
192
244
  try {
@@ -205,7 +257,7 @@ export async function stopLeftBehind(projectDir, codebase) {
205
257
  catch {
206
258
  continue;
207
259
  }
208
- if (codebase !== undefined && record.moduleName !== codebase)
260
+ if (codebases !== undefined && !codebases.includes(record.moduleName))
209
261
  continue;
210
262
  // This turri's own are stopLaunched's; another turri still running keeps its own.
211
263
  if (record.turri === process.pid || alive(record.turri))
@@ -268,9 +320,13 @@ function signalGroup(pid, signal) {
268
320
  }
269
321
  }
270
322
  const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
271
- /** Stop one launched process, or every one of a module, or every one: politely, then not. Returns the names stopped. */
272
- export async function stopLaunched(which = {}) {
273
- const targets = [...processes.values()].filter(({ info }) => info.exited === undefined && (which.name === undefined || info.name === which.name) && (which.moduleName === undefined || info.moduleName === which.moduleName));
323
+ /** Stop launched processes - those the filter names, or every one: politely, then not. Returns what was stopped. */
324
+ export async function stopLaunchedProcesses(which = {}) {
325
+ const targets = [...processes.values()].filter(({ info }) => info.exited === undefined &&
326
+ (which.name === undefined || info.name === which.name) &&
327
+ (which.moduleName === undefined || info.moduleName === which.moduleName) &&
328
+ (which.modules === undefined || which.modules.includes(info.moduleName)) &&
329
+ (which.pid === undefined || info.pid === which.pid));
274
330
  for (const { info } of targets)
275
331
  signalGroup(info.pid, "SIGTERM");
276
332
  const deadline = Date.now() + 5000;
@@ -279,7 +335,143 @@ export async function stopLaunched(which = {}) {
279
335
  for (const { info } of targets)
280
336
  if (info.exited === undefined)
281
337
  signalGroup(info.pid, "SIGKILL");
282
- return targets.map(({ info }) => info.name);
338
+ return targets.map(({ info }) => info);
339
+ }
340
+ /** Stop one launched process, or every one of a module, or every one: politely, then not. Returns the names stopped. */
341
+ export async function stopLaunched(which = {}) {
342
+ return (await stopLaunchedProcesses(which)).map((info) => info.name);
343
+ }
344
+ function psField(pid, field) {
345
+ const found = spawnSync("ps", ["-o", `${field}=`, "-p", String(pid)], { encoding: "utf8", env: { ...process.env, LC_ALL: "C" } });
346
+ if (found.status !== 0)
347
+ return undefined;
348
+ const value = found.stdout.trim();
349
+ return value === "" ? undefined : value;
350
+ }
351
+ function readRecords(logDir) {
352
+ const dir = join(logDir, RUNNING_DIR);
353
+ let names;
354
+ try {
355
+ names = readdirSync(dir).filter((name) => name.endsWith(".json"));
356
+ }
357
+ catch {
358
+ return [];
359
+ }
360
+ const records = [];
361
+ for (const name of names) {
362
+ const file = join(dir, name);
363
+ try {
364
+ records.push({ record: JSON.parse(readFileSync(file, "utf8")), file });
365
+ }
366
+ catch {
367
+ /* half-written, or not one */
368
+ }
369
+ }
370
+ return records;
371
+ }
372
+ /**
373
+ * Whose a process is - any process of the group a launch started: what this turri started, what turri's records of the
374
+ * project (`logDir`, its `.turri/launch`) name, or neither. Only a record whose group is still the one it names counts:
375
+ * a pid given to another process since is not turri's.
376
+ */
377
+ export function whoHolds(pid, logDir) {
378
+ const group = Number(psField(pid, "pgid") ?? Number.NaN);
379
+ if (Number.isFinite(group)) {
380
+ const own = [...processes.values()].find(({ info }) => info.exited === undefined && info.pid === group);
381
+ if (own !== undefined)
382
+ return { kind: "this", pid, process: own.info };
383
+ for (const { record, file } of readRecords(logDir)) {
384
+ if (record.pgid !== group || !groupOf(record).includes(pid))
385
+ continue;
386
+ if (record.turri !== process.pid && alive(record.turri))
387
+ return { kind: "turri", pid, record };
388
+ return { kind: "left", pid, record, file };
389
+ }
390
+ }
391
+ return { kind: "unknown", pid, command: psField(pid, "command") ?? "a process ps cannot name" };
392
+ }
393
+ /** The processes listening on a TCP port, as lsof says them - undefined when it cannot say (no lsof). */
394
+ export function listenersOf(port) {
395
+ const found = spawnSync("lsof", ["-t", "-nP", `-iTCP:${port}`, "-sTCP:LISTEN"], { encoding: "utf8" });
396
+ if (found.error !== undefined)
397
+ return undefined;
398
+ return [...new Set(found.stdout.split("\n").map((line) => Number(line.trim())).filter((pid) => Number.isInteger(pid) && pid > 0))];
399
+ }
400
+ /** A holder in a line: what it is, and whose - the launch and module a turri started it for. */
401
+ export function describeHolder(holder) {
402
+ const at = (commit) => (commit !== undefined ? ` at ${commit}` : "");
403
+ switch (holder.kind) {
404
+ case "this": {
405
+ const item = holder.process;
406
+ return `${item.name} (pid ${item.pid}${item.url !== undefined ? `, ${item.url}` : ""}), which this turri started for ${item.moduleName}'s launch${item.launch !== undefined ? ` ${item.launch}` : ""}${at(item.commit)}, from ${shortPath(item.dir)}`;
407
+ }
408
+ case "left": {
409
+ const record = holder.record;
410
+ return `${record.name} (pid ${record.pid}${record.url !== undefined ? `, ${record.url}` : ""}), which an earlier turri session (pid ${record.turri}, ended) started for a launch of ${record.moduleName}${at(record.commit)}, from ${shortPath(record.dir)}`;
411
+ }
412
+ case "turri": {
413
+ const record = holder.record;
414
+ return `${record.name} (pid ${record.pid}${record.url !== undefined ? `, ${record.url}` : ""}), which another turri still running (pid ${record.turri}) started for its launch of ${record.moduleName}${at(record.commit)}, from ${shortPath(record.dir)}`;
415
+ }
416
+ case "unknown":
417
+ return `pid ${holder.pid} (${holder.command}), which turri did not start - none of its records of this project names it`;
418
+ }
419
+ }
420
+ /** How the person frees what a holder holds, from the chat - or that turri frees it itself. */
421
+ export function howToFree(holder) {
422
+ switch (holder.kind) {
423
+ case "this":
424
+ return `It is this turri's: \`/halt launched ${holder.process.moduleName}\` in the chat stops it, then ask for the launch again.`;
425
+ case "left":
426
+ return `Its turri has ended: turri stops it before the next launch of ${holder.record.moduleName}, or ask the chat to launch again.`;
427
+ case "turri":
428
+ return `It is that turri's, and this one never stops it: \`/halt launched ${holder.record.moduleName}\` in that turri's chat stops it, or quit that turri - then ask the chat here to launch again.`;
429
+ case "unknown":
430
+ return `turri never stops a process it did not start: if it is the person's to stop, they can stop it or ask the chat to (\`kill ${holder.pid}\`) - then ask the chat to launch again.`;
431
+ }
432
+ }
433
+ /** Whether turri frees what a holder holds for a launch itself: what its own launches started, this session's or a dead turri's. */
434
+ export const turriFrees = (holder) => holder.kind === "this" || holder.kind === "left";
435
+ /**
436
+ * Stop what turri's own launches started - this session's, or an ended turri's - for a launch that needs what it holds
437
+ * (`held`, "port 5173"). Returns what was stopped; the rest is never touched.
438
+ */
439
+ export async function freeHeld(holders, held) {
440
+ const freed = [];
441
+ const seen = new Set();
442
+ for (const holder of holders) {
443
+ if (holder.kind === "this") {
444
+ if (seen.has(holder.process.pid))
445
+ continue;
446
+ seen.add(holder.process.pid);
447
+ const stopped = await stopLaunchedProcesses({ moduleName: holder.process.moduleName, name: holder.process.name, pid: holder.process.pid });
448
+ for (const item of stopped) {
449
+ freed.push({ name: item.name, moduleName: item.moduleName, pid: item.pid, held, ...(item.url !== undefined ? { url: item.url } : {}), ...(item.launch !== undefined ? { launch: item.launch } : {}), ...(item.commit !== undefined ? { commit: item.commit } : {}) });
450
+ }
451
+ }
452
+ else if (holder.kind === "left") {
453
+ const record = holder.record;
454
+ if (seen.has(record.pgid))
455
+ continue;
456
+ seen.add(record.pgid);
457
+ // Taken by whoever takes the record out first, as stopLeftBehind does.
458
+ if (!dropRecord(holder.file))
459
+ continue;
460
+ signalGroup(record.pgid, "SIGTERM");
461
+ const deadline = Date.now() + 5000;
462
+ while (Date.now() < deadline && groupAlive(record.pgid))
463
+ await sleep(100);
464
+ if (groupAlive(record.pgid))
465
+ signalGroup(record.pgid, "SIGKILL");
466
+ freed.push({ name: record.name, moduleName: record.moduleName, pid: record.pid, held, earlier: true, ...(record.url !== undefined ? { url: record.url } : {}), ...(record.commit !== undefined ? { commit: record.commit } : {}) });
467
+ }
468
+ }
469
+ return freed;
470
+ }
471
+ /** What was freed for a launch, in a line - for its summary. */
472
+ export function describeFreed(freed, forName) {
473
+ const whose = freed.earlier === true ? `an earlier turri session's launch of ${freed.moduleName}` : `${freed.moduleName}'s launch${freed.launch !== undefined ? ` ${freed.launch}` : ""}`;
474
+ return `Stopped ${freed.name} (pid ${freed.pid}${freed.url !== undefined ? `, ${freed.url}` : ""}), from ${whose}${freed.commit !== undefined ? ` at ${freed.commit}` : ""}: it held ${freed.held}, which ${forName} needs.`;
283
475
  }
284
476
  /** Stop everything at once, without waiting: for when turri itself is going. */
285
477
  export function stopAllLaunchedNow() {
@@ -312,11 +504,6 @@ function portTaken(host, port) {
312
504
  socket.once("error", () => finish(false));
313
505
  });
314
506
  }
315
- /** What holds a port, as lsof says it - or nothing when it cannot say. */
316
- export function holderOf(port) {
317
- const found = spawnSync("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN"], { encoding: "utf8" });
318
- return found.status === 0 ? found.stdout.trim().split("\n").slice(0, 4).join("\n") : "";
319
- }
320
507
  async function answers(url) {
321
508
  try {
322
509
  await fetch(url, { redirect: "manual", signal: AbortSignal.timeout(2000) });
@@ -338,6 +525,39 @@ const ALIVE_AFTER_MS = 4000;
338
525
  * nothing is started: an app moved to a port of the harness's choosing would not be the one the
339
526
  * person was told about. With no URL, it only has to still be running a few seconds on.
340
527
  */
528
+ /**
529
+ * A port the server needs is held: by what turri's own launches started - this session's for another module, a dead
530
+ * turri's - it is stopped, said, and the port taken; by anything else - another turri still running, a program turri did
531
+ * not start - nothing is stopped and nothing started, and what holds it is said, whose it is, and how the person frees it.
532
+ */
533
+ async function takePort(port, host, input) {
534
+ const notStarted = `so ${input.name} was not started. Do not move the app to another port: tell the person what holds it, whose it is and how to free it, as said here.`;
535
+ const pids = listenersOf(port);
536
+ if (pids === undefined || pids.length === 0) {
537
+ return { ok: false, text: `Port ${port} is in use already, and turri cannot tell what holds it here${pids === undefined ? " (there is no lsof)" : ""} - ${notStarted}` };
538
+ }
539
+ const holders = pids.map((pid) => whoHolds(pid, input.logDir));
540
+ // This launch's own: two of its servers on one port is the agent's to sort out, not turri's to stop.
541
+ const own = holders.filter((holder) => holder.kind === "this" && holder.process.launch !== undefined && holder.process.launch === input.launch?.id);
542
+ const others = holders.filter((holder) => !own.includes(holder) && !turriFrees(holder));
543
+ if (own.length > 0 || others.length > 0) {
544
+ const lines = [...own, ...others].map((holder) => `- ${describeHolder(holder)}.${own.includes(holder) ? " This launch started it itself: activate it again under the same name to restart it." : ` ${howToFree(holder)}`}`);
545
+ return { ok: false, text: [`Port ${port} is held by:`, ...lines, notStarted].join("\n") };
546
+ }
547
+ const freed = await freeHeld(holders, `port ${port}`);
548
+ input.freed?.(freed);
549
+ const deadline = Date.now() + 5000;
550
+ while (Date.now() < deadline && (await portTaken(host, port)))
551
+ await sleep(200);
552
+ if (await portTaken(host, port)) {
553
+ const still = (listenersOf(port) ?? []).map((pid) => whoHolds(pid, input.logDir));
554
+ return {
555
+ ok: false,
556
+ text: [`Port ${port} is still held, after turri stopped what its own launches had there:`, ...still.map((holder) => `- ${describeHolder(holder)}. ${howToFree(holder)}`), notStarted].join("\n"),
557
+ };
558
+ }
559
+ return { ok: true, text: freed.map((each) => describeFreed(each, input.name)).join("\n") };
560
+ }
341
561
  /** A folder's entries as a listing says them - folders with a slash - or that it is empty. */
342
562
  function listing(dir) {
343
563
  try {
@@ -371,8 +591,10 @@ export async function startLaunched(input) {
371
591
  : `${input.name} was not started: ${shortPath(input.dir)} ${why}.`,
372
592
  };
373
593
  }
374
- await stopLaunched({ name: input.name });
594
+ // One already running under the name - of this module - is restarted.
595
+ await stopLaunched({ name: input.name, moduleName: input.moduleName });
375
596
  let url;
597
+ let before = "";
376
598
  if (input.url !== undefined) {
377
599
  try {
378
600
  url = new URL(input.url);
@@ -382,11 +604,10 @@ export async function startLaunched(input) {
382
604
  }
383
605
  const port = portOf(url);
384
606
  if (await portTaken(url.hostname, port)) {
385
- const holder = holderOf(port);
386
- return {
387
- ok: false,
388
- text: `Port ${port} is in use already - by something turri did not start - so ${input.name} was not started.${holder !== "" ? `\n${holder}` : ""}\nTell the person which port and what holds it; do not move the app to another port.`,
389
- };
607
+ const taken = await takePort(port, url.hostname, input);
608
+ if (!taken.ok)
609
+ return { ok: false, text: taken.text };
610
+ before = taken.text;
390
611
  }
391
612
  }
392
613
  mkdirSync(input.logDir, { recursive: true });
@@ -410,7 +631,17 @@ export async function startLaunched(input) {
410
631
  await spawned;
411
632
  return { ok: false, text: `${input.name} could not be started in ${shortPath(input.dir)}: ${spawnError?.message ?? "no process was made"}.` };
412
633
  }
413
- const started = { name: input.name, moduleName: input.moduleName, command: input.command, dir: input.dir, log, pid: child.pid, startedAt: Date.now(), ...(input.url !== undefined ? { url: input.url } : {}) };
634
+ const started = {
635
+ name: input.name,
636
+ moduleName: input.moduleName,
637
+ command: input.command,
638
+ dir: input.dir,
639
+ log,
640
+ pid: child.pid,
641
+ startedAt: Date.now(),
642
+ ...(input.url !== undefined ? { url: input.url } : {}),
643
+ ...(input.launch !== undefined ? { launch: input.launch.id, commit: input.launch.commit } : {}),
644
+ };
414
645
  info = started;
415
646
  const record = writeRecord(input.logDir, {
416
647
  pid: child.pid,
@@ -421,31 +652,35 @@ export async function startLaunched(input) {
421
652
  dir: input.dir,
422
653
  ...(input.url !== undefined ? { url: input.url } : {}),
423
654
  startedAt: started.startedAt,
655
+ ...(input.launch !== undefined ? { launch: input.launch.id, commit: input.launch.commit } : {}),
424
656
  turri: process.pid,
425
657
  });
426
658
  child.on("exit", (code, signal) => {
427
659
  started.exited = { code, signal };
428
660
  dropRecord(record);
429
661
  });
430
- processes.set(input.name, { info: started, child, ...(record !== undefined ? { record } : {}) });
662
+ processes.set(keyOf(input.moduleName, input.name), { info: started, child, ...(record !== undefined ? { record } : {}) });
431
663
  stopOnExit();
664
+ // The log's path is said whole: the agent works from dist/<module> or the host codebase, and a path relative to the
665
+ // project read from there points nowhere.
666
+ const said = (text) => (before !== "" ? `${before}\n${text}` : text);
432
667
  const failed = (why) => {
433
668
  const tail = logTail(log);
434
- return { ok: false, text: `${input.name} ${why}.${tail !== "" ? `\nThe end of its output (${shortPath(log)}):\n${tail}` : ""}`, process: started };
669
+ return { ok: false, text: said(`${input.name} ${why}.${tail !== "" ? `\nThe end of its output (${log}):\n${tail}` : ""}`), process: started };
435
670
  };
436
671
  const ended = () => `exited${started.exited?.code !== null && started.exited?.code !== undefined ? ` with ${started.exited.code}` : ""} before it was ready`;
437
672
  if (url === undefined) {
438
673
  await sleep(ALIVE_AFTER_MS);
439
674
  if (started.exited !== undefined)
440
675
  return failed(ended());
441
- return { ok: true, text: `${input.name} is running (pid ${started.pid}); its output is in ${shortPath(log)}.`, process: started };
676
+ return { ok: true, text: said(`${input.name} is running (pid ${started.pid}); its output is in ${log}.`), process: started };
442
677
  }
443
678
  const deadline = Date.now() + READY_TIMEOUT_MS;
444
679
  while (Date.now() < deadline) {
445
680
  if (started.exited !== undefined)
446
681
  return failed(ended());
447
682
  if (await answers(url.href))
448
- return { ok: true, text: `${input.name} is up at ${url.href} (pid ${started.pid}); its output is in ${shortPath(log)}.`, process: started };
683
+ return { ok: true, text: said(`${input.name} is up at ${url.href} (pid ${started.pid}); its output is in ${log}.`), process: started };
449
684
  await sleep(1000);
450
685
  }
451
686
  return failed(`is running, but nothing answered at ${url.href} in ${Math.round(READY_TIMEOUT_MS / 1000)}s`);
@@ -102,6 +102,22 @@ export type LedgerEvent = {
102
102
  module: string;
103
103
  url?: string;
104
104
  }>;
105
+ } | {
106
+ kind: "launch.freed";
107
+ launch: string;
108
+ held: string;
109
+ stopped: Array<{
110
+ name: string;
111
+ pid: number;
112
+ module: string;
113
+ url?: string;
114
+ launch?: string;
115
+ }>;
116
+ } | {
117
+ kind: "launch.replaced";
118
+ launch: string;
119
+ by: string;
120
+ byModule: string;
105
121
  } | {
106
122
  kind: "sentinel.concluded";
107
123
  verdict: string;
@@ -1,6 +1,6 @@
1
1
  import { Box, Text } from "@earendil-works/pi-tui";
2
2
  import { projectModels, readProjectConfig, roleModel } from "./config.js";
3
- import { concludedNote, concludeTool, keepGuidanceTool, notifyTool, resumeTool, sentinelFileTools } from "./sentinel.js";
3
+ import { concludedNote, concludeTool, keepGuidanceTool, notifyTool, resumeTool, sentinelFileTools, whoHoldsTool } from "./sentinel.js";
4
4
  /**
5
5
  * The sentinel in a chat: its tools in place of the chat's - the project to read, its shell behind the walls, notices,
6
6
  * its guidance, a host's own - its model, and, in every chat, the notices it puts to the person: a card in the chat and,
@@ -27,6 +27,7 @@ export function registerSentinel(pi, session, cwd, hostTools, allowed, resume) {
27
27
  }));
28
28
  pi.registerTool(concludeTool((conclusion) => session.concluded(conclusion)));
29
29
  pi.registerTool(keepGuidanceTool(cwd));
30
+ pi.registerTool(whoHoldsTool(cwd));
30
31
  pi.registerTool(resumeTool(resume));
31
32
  for (const tool of hostTools)
32
33
  pi.registerTool(tool);
@@ -1,7 +1,7 @@
1
1
  import { type ToolDefinition } from "@earendil-works/pi-coding-agent";
2
2
  import { type SentinelSetting } from "./config.ts";
3
3
  import { type Job } from "./regenerate/jobs.ts";
4
- import type { LaunchedProcess } from "./regenerate/launch.ts";
4
+ import { type LaunchedProcess } from "./regenerate/launch.ts";
5
5
  import { type PulseLaunch } from "./launch-session.ts";
6
6
  import { type Conclusion, type Notice, type NoticeInput, type SentinelCheck } from "./notice.ts";
7
7
  import type { CheckedSpec } from "./sentinel-check.ts";
@@ -99,4 +99,9 @@ export declare function concludedNote(conclusion: Conclusion, options?: {
99
99
  }): string;
100
100
  /** Bring a module up again once the sentinel fixed what stopped its pulse: what is left there is regenerated, its scripts run. */
101
101
  export declare function resumeTool(resume: (plainFile: string) => Promise<string>): ToolDefinition;
102
+ /**
103
+ * who_holds: what holds a TCP port, and whose it is - one of turri's launches, another turri's, or a program turri did not
104
+ * start - as turri's records say it. The sentinel's shell is sandboxed from every other process, so it cannot ask itself.
105
+ */
106
+ export declare function whoHoldsTool(cwd: string): ToolDefinition;
102
107
  export declare function keepGuidanceTool(cwd: string): ToolDefinition;
package/dist/sentinel.js CHANGED
@@ -11,7 +11,10 @@ import { formatDuration, pulseName } from "./regenerate/jobs.js";
11
11
  import { readLedger } from "./regenerate/ledger.js";
12
12
  import { describePulseView, pulseView } from "./regenerate/ledger-view.js";
13
13
  import { MODULES_DIR, ensureInScratch } from "./regenerate/paths.js";
14
+ import { describeHolder, howToFree, launchLogDir, listenersOf, whoHolds } from "./regenerate/launch.js";
15
+ import { projectDirOf } from "./regenerate/paths.js";
14
16
  import { LAUNCHED_ONLY, launchedDir, whatRuns } from "./launch-session.js";
17
+ import { launchText } from "./launch-track.js";
15
18
  import { SENTINEL, SENTINEL_START, wentWrong } from "./notice.js";
16
19
  export * from "./notice.js";
17
20
  /**
@@ -215,7 +218,8 @@ export function sentinelPrompt(cwd, options = {}) {
215
218
  "",
216
219
  "You fix the project's tooling and nothing else. Your file tools read the whole project; write and edit reach only the",
217
220
  "testing scripts and config.turri.yaml - and in it only where the scripts are, and toolchains:. Your shell runs with",
218
- "the project read only; the files you try a launch with go in $TMPDIR - /tmp is outside what it may write. You never change ***plain - it is the person's intent, never yours to fix - and never steer,",
221
+ "the project read only; the files you try a launch with go in $TMPDIR - /tmp is outside what it may write. It sees no",
222
+ "other process: ps and lsof do not run there - who_holds says what holds a port and whose it is. You never change ***plain - it is the person's intent, never yours to fix - and never steer,",
219
223
  "launch, or regenerate but by resume after a fix of yours. You install nothing on this machine and change none of",
220
224
  "its settings, nor the person's shell - under no circumstances: that is always the person's, said in a notice. You",
221
225
  "never ask the person questions - a notice is how you reach them.",
@@ -298,10 +302,10 @@ function launchLines(job, launch) {
298
302
  const what = launch.launch;
299
303
  const later = launch.later.map((other) => `${other.id} (${pulseName(other)})`);
300
304
  const lines = [
301
- `Its commit is ${commit}. It was launched in the background (launch-after-pulse): what runs is ${what.codebase} at ${what.short} (${what.id}), which holds it${later.length > 0 ? ` and the pulses that landed after it - ${later.join(", ")}` : ""}.`,
305
+ `Its commit is ${commit}. It was launched in the background (launch-after-pulse): what runs is ${what.codebase} at ${what.short} (${what.id}), which holds it${what.codebase !== job.module && job.module !== undefined ? ` - ${what.codebase} is built on ${job.module}, and holds its code` : ""}${later.length > 0 ? ` and the pulses that landed after it - ${later.join(", ")}` : ""}.`,
302
306
  ];
303
307
  if (what.status === "failed") {
304
- lines.push(`That launch did not come up: ${what.summary ?? "the launch agent did not say why"}`, "That is what you find out about: the launch did not come up. Test nothing in its place.", LAUNCHED_ONLY);
308
+ lines.push(`That launch did not come up: ${launchText(what) || "the launch agent did not say why"}`, "That is what you find out about: the launch did not come up. Test nothing in its place.", LAUNCHED_ONLY);
305
309
  return lines;
306
310
  }
307
311
  lines.push("What runs now:", ...whatRuns(launch.running, launchedDir(what)), LAUNCHED_ONLY);
@@ -345,7 +349,7 @@ export function sentinelCheckBrief(check, context) {
345
349
  * The tools the sentinel's agent may call: what reads, write and edit for the project's tooling alone, resume, its
346
350
  * notices and its guidance - and what a host gives it.
347
351
  */
348
- export const SENTINEL_TOOLS = ["read", "ls", "grep", "find", "write", "edit", "bash", "read_output", "pulses", "parse", "doctor", "web_search", "web_fetch", "resume", "notify_person", "conclude", "keep_guidance"];
352
+ export const SENTINEL_TOOLS = ["read", "ls", "grep", "find", "write", "edit", "bash", "read_output", "pulses", "parse", "doctor", "web_search", "web_fetch", "resume", "notify_person", "conclude", "keep_guidance", "who_holds"];
349
353
  /** A testing script by its name - `run_unittests_python.sh`, `prepare_environment_node.sh` - and a config file of turri's. */
350
354
  const SCRIPT_FILE = /^(run_|prepare_environment).*\.(sh|ps1|bat|cmd)$/;
351
355
  const CONFIG_FILE_NAME = /^config\.turri(\..+)?\.yaml$/;
@@ -557,6 +561,30 @@ export function resumeTool(resume) {
557
561
  },
558
562
  });
559
563
  }
564
+ /**
565
+ * who_holds: what holds a TCP port, and whose it is - one of turri's launches, another turri's, or a program turri did not
566
+ * start - as turri's records say it. The sentinel's shell is sandboxed from every other process, so it cannot ask itself.
567
+ */
568
+ export function whoHoldsTool(cwd) {
569
+ return defineTool({
570
+ name: "who_holds",
571
+ label: "Who holds",
572
+ description: "What listens on a TCP port on this machine, and whose it is: a server one of turri's launches started (which launch, " +
573
+ "which module, which commit), one another turri started, or a program turri did not start - with how the person " +
574
+ "frees it. Use it when what answers at a launch's URL is not what you expect, or nothing does: your shell cannot " +
575
+ "see other processes. It stops nothing.",
576
+ parameters: Type.Object({ port: Type.Integer({ minimum: 1, maximum: 65535, description: "The port, e.g. 8000" }) }),
577
+ async execute(_id, params) {
578
+ const pids = listenersOf(params.port);
579
+ const text = pids === undefined
580
+ ? `turri cannot tell what holds port ${params.port} here: there is no lsof.`
581
+ : pids.length === 0
582
+ ? `Nothing listens on port ${params.port}.`
583
+ : [`Port ${params.port} is held by:`, ...pids.map((pid) => whoHolds(pid, launchLogDir(projectDirOf(join(cwd, "turri.plain"))))).map((holder) => `- ${describeHolder(holder)}. ${howToFree(holder)}`)].join("\n");
584
+ return { content: [{ type: "text", text }], details: {} };
585
+ },
586
+ });
587
+ }
560
588
  export function keepGuidanceTool(cwd) {
561
589
  return defineTool({
562
590
  name: "keep_guidance",
package/docs/hosting.md CHANGED
@@ -151,7 +151,7 @@ await turri.dispose(); // every chat let go, what launches start
151
151
  - **The record.** The chats are recorded in `.turri/chats.json` as the terminal records them, and `restore: true` reopens the last ended session's - without it, a host starts with none and deletes nothing. A chat closed is deleted; a session's chats are kept until five newer sessions have recorded theirs.
152
152
  - **The jobs.** The host is told of each job as it changes, and has the registry and the loop themselves, so it shows the very jobs the chats run. Its buttons are best a chat's commands - `session.prompt("/regenerate app.plain")`, `session.prompt("/conform app.plain app:add-task")` - so the plan is the chats', and no model turn stands between the button and the pulse. A job's \*\*\*plain diff is `job.diff`, and `job.diffWhere` places its lines in the `.plain` files: by a line's place in the diff, its `file`, its `line` there, the `section` it is in and `written` - the line as the file has it. The diff is \*\*\*plain as read, a link `[text](path)` in it as `` `[resource]text` ``, so a host that finds the lines again in a file's text - after an edit since the pulse started - matches them by `written`, never by the diff's text. A `job.diff` in a ledger written before `written` was added has none. `job.cases` is the functional specs the pulse covers, as planned, by what it does to each - `{ add, patch, again, delete }`, each a list of `{ module, funcId }`, `module` the pulse's own or one below it: new, changed, regenerated again with its text unchanged, taken out. A host lights those specs from it, and marks a line of the diff as regenerated again from `again` - never from the diff, where such a line is unchanged. A pulse of none is mechanical - reqs, or definitions none uses; a job that is not a pulse has no `cases`. The ledger's `job.queued` carries them too. `job.building` is the one functional spec a job is on now, when it is on one: `{ spec: { module, funcId }, label, text, since }` - `spec` the functional spec as data, `label` and `text` what the terminal shows (`core:add-task, functional spec of 3`, its text with its scenarios). Only a conformance run of one named functional spec sets it; a pulse the work loop plans covers its functional specs together and leaves it unset - light those from `cases`.
153
153
  - **The questions.** `dialogs(chat)` gives a chat's two dialogs: `select(title, options, context, at, { signal })` and `input(title, context, { signal })`, each resolving with the answer, or undefined when the person dismissed it. `signal` is aborted when the question is over without the dialog's answer - declined by `decline`, or its turn stopped (`interrupt`, `session.abort()`): the host closes the dialog it opened for it, whatever it resolves with then being ignored. A host may leave it unread. The chat's questions, a skill's interview and a review gate's escalation are put in them; without them, in the `uiContext`'s own dialogs.
154
- - **The surface.** What turri tells the model of where the person watches the work is the terminal's by default: regen, the side panel on `ctrl+h`, `/pulses`. In a host none of that is there, and the model would send the person to keys and panels that do not exist. `surface` is the host's own description of its UI - the views it has in place of the terminal's, what its marks and buttons mean, where questions appear - in its own words. Given, turri leaves every terminal instruction out of what the model is told and puts the surface in turri's identity, as a `<surface>` block, where the identity speaks of regen. It reaches the side questions and the tools' own words too: a pulse not found says the `pulses` tool lists them, not `/pulses`. Text only the person sees in the terminal - the job panel, the side panel - is the terminal's and stays as it is. Without `surface`, the prompt is the terminal's, byte for byte. What the conversation is to do once something is launched belongs there too - open it in the host's preview, say what to test: it is told once each launch it asked for ends, and - with `sentinel: false` - each launch after a pulse under `launch-after-pulse`, and does then what it was told to do once something is launched. With the sentinel on, the sentinel tests what is launched after a pulse, and the conversation only says it landed. With `sentinel: false`, the chat that asked for a pulse that lands under `launch-after-pulse` is told as it lands that its commit is being launched in the background - to say so in a line and offer nothing else - and then told the launch's end. Every launch, as it is asked for, starts and ends, comes to the host as `onLaunch(launch)` - its codebase, commit, status and summary. One whose code runs already - the chat asking for what runs, a pulse that landed only tests - comes once, `status: "launched"` with `already: true`, its own cause and the commit it was asked for; the launch that started what runs is not told again. One that ended with a newer launch of its codebase waiting comes with its real status and `replacedBy`, the newer one's id: that one starts at once and stops what it started, so draw it as replaced rather than as running - the chat that asked for it is told so, and hears the newer one's end instead, as for one `superseded` as it waited (`supersededBy`). What a launch started, halted on request (`/halt launched`, the `halt` tool) with nothing of it left running, comes again as `status: "stopped"`, "Stopped on request.": nothing of the codebase is launched from then on, and its next launch launches anew. A launch that said a server runs is `launched` only while one it started itself runs: something else answering at its port - a server an earlier session left, another program - makes it `failed`, its summary saying what holds the port. What an earlier turri's launches left running - a host that quit without `dispose`, a turri killed outright - is stopped as the session starts and before each launch of its codebase, and the next launch's `summary` begins with what was stopped (see [what an earlier session left running](launch.md#what-an-earlier-session-left-running)).
154
+ - **The surface.** What turri tells the model of where the person watches the work is the terminal's by default: regen, the side panel on `ctrl+h`, `/pulses`. In a host none of that is there, and the model would send the person to keys and panels that do not exist. `surface` is the host's own description of its UI - the views it has in place of the terminal's, what its marks and buttons mean, where questions appear - in its own words. Given, turri leaves every terminal instruction out of what the model is told and puts the surface in turri's identity, as a `<surface>` block, where the identity speaks of regen. It reaches the side questions and the tools' own words too: a pulse not found says the `pulses` tool lists them, not `/pulses`. Text only the person sees in the terminal - the job panel, the side panel - is the terminal's and stays as it is. Without `surface`, the prompt is the terminal's, byte for byte. What the conversation is to do once something is launched belongs there too - open it in the host's preview, say what to test: it is told once each launch it asked for ends, and - with `sentinel: false` - each launch after a pulse under `launch-after-pulse`, and does then what it was told to do once something is launched. With the sentinel on, the sentinel tests what is launched after a pulse, and the conversation only says it landed. With `sentinel: false`, the chat that asked for a pulse that lands under `launch-after-pulse` is told as it lands that its commit is being launched in the background - to say so in a line and offer nothing else - and then told the launch's end. Every launch, as it is asked for, starts and ends, comes to the host as `onLaunch(launch)` - its codebase, commit, status and summary. `summary` is what the launch agent said - where it runs, or why it did not come up - and nothing of turri's: show its first line as the launch's line. What turri stopped for the launch comes apart, in `stopped`, one entry a process, as it stops them - while the launch runs too: `why` (`below` - a launch of a module below it in its chain, whose code it holds; `held` - a server of another module's launch that held what it needs, `held` saying what, "port 5173"; `left-behind` - one an earlier turri session left running), the `module` whose launch started it, that `launch` and its `commit` when known, the process's `name`, `pid` and `url`. Show it beside the launch from those fields - "stopped bestiary's launch at befa07f - upgrades holds its code" - never by reading a sentence. `launchText(launch)`, exported beside the type, is the two together as the chat and the terminal read them - turri's lines, then the summary - for a host that shows the whole at a click. One whose code runs already - the chat asking for what runs, a pulse that landed only tests - comes once, `status: "launched"` with `already: true`, its own cause and the commit it was asked for; the launch that started what runs is not told again. One that ended with a newer launch of its codebase - or of a module built on it - waiting comes with its real status and `replacedBy`, the newer one's id: that one starts at once and stops what it started, so draw it as replaced rather than as running - the chat that asked for it is told so, and hears the newer one's end instead, as for one `superseded` as it waited (`supersededBy`). A launch whose servers a newer launch stopped later - one of a module built on it, which holds its code, or one that needed a port or anything else they held - comes again too, with `replacedBy` set: nothing of it runs, and the newer launch's `stopped` says what it stopped, whose it was and why (see [across a project](launch.md#across-a-project)). The newer launch may be of another codebase: what runs of a module is its own newest launch's unless one has `replacedBy`, and then the launch that id names. What a launch started, halted on request (`/halt launched`, the `halt` tool) with nothing of it left running, comes again as `status: "stopped"`, "Stopped on request.": nothing of the codebase is launched from then on, and its next launch launches anew. A launch that said a server runs is `launched` only while one it started itself runs: something else answering at its port - another turri's server, another program - makes it `failed`, its summary saying what holds the port, whose it is and how to free it. What an earlier turri's launches left running - a host that quit without `dispose`, a turri killed outright - is stopped as the session starts and before each launch of its codebase, and the next launch's `stopped` has it, `why: "left-behind"` (see [what an earlier session left running](launch.md#what-an-earlier-session-left-running)).
155
155
  - **The banner.** The first chat's session starts with turri's banner, an entry `customType: "turri_banner"`. Its `data.config` is what turri says of the project's config files, a line each - `{ kind, file, text }`, `text` as the terminal shows it: `renamed`, a key turri renamed in the file itself, its value kept (`release-after-pulse` to `launch-after-pulse`) - information, nothing to do; `old-beside-new`, a file that sets an old name beside its new one, the old doing nothing - take it out; `unknown`, keys turri does not read - a setting it no longer has, a misspelt one. Draw `renamed` as information, the others as warnings, by `kind`, never by the words. `ConfigLine` and `ConfigLineKind` are exported.
156
156
  - **The system prompt.** `systemPrompt(prompt)` gets the whole system prompt for the turn - [pi](https://pi.dev)'s, turri's identity and blocks, the rules - after turri's own `before_agent_start` work, and returns what is sent. It is for what `surface` does not cover; to describe the UI, use `surface`, rather than words appended after turri's that contradict them.
157
157
  - **The mode.** Each chat is bound in [pi](https://pi.dev)'s `tui` mode: the work runs in the background and keeps the chat free, as the terminal does. Its other UI calls - its notices, its working line, a confirm - come to `uiContext(chat)`, as [pi](https://pi.dev)'s [SDK](https://github.com/earendil-works/pi) describes it.