pi-pocket 0.29.0 → 0.30.0-beta.2

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 (67) hide show
  1. package/README.md +58 -1
  2. package/SECURITY.md +1 -0
  3. package/docs/architecture.md +9 -4
  4. package/docs/desktop-app.md +54 -0
  5. package/docs/examples/approval-monitor.ts +82 -0
  6. package/docs/extensions/people-values.md +8 -0
  7. package/docs/extensions/policies/api-stability.md +1 -0
  8. package/docs/extensions/reference/api-versions.md +3 -0
  9. package/docs/extensions/reference/host.md +92 -1
  10. package/docs/extensions/tools.md +1 -0
  11. package/docs/features.md +4 -4
  12. package/docs/index.md +3 -0
  13. package/docs/macos.md +90 -0
  14. package/docs/map.md +9 -5
  15. package/docs/windows.md +73 -0
  16. package/npm-shrinkwrap.json +71 -67
  17. package/package.json +9 -9
  18. package/src/launcher/desktop.ts +45 -0
  19. package/src/launcher/main.ts +81 -17
  20. package/src/launcher/options.ts +59 -2
  21. package/src/server/alerts.ts +2 -2
  22. package/src/server/app.ts +2 -0
  23. package/src/server/auth.ts +40 -0
  24. package/src/server/background.ts +109 -241
  25. package/src/server/commands.ts +28 -17
  26. package/src/server/design/scan-fig-container.ts +3 -2
  27. package/src/server/design/scan-files.ts +3 -11
  28. package/src/server/design/system.ts +3 -4
  29. package/src/server/design/tokens-io.ts +2 -3
  30. package/src/server/docs.ts +9 -0
  31. package/src/server/errors.ts +12 -0
  32. package/src/server/extension-document-compat.ts +4 -0
  33. package/src/server/extensions/artifacts.ts +2 -6
  34. package/src/server/extensions/codemode.ts +27 -1
  35. package/src/server/extensions/guard.ts +9 -1
  36. package/src/server/extensions/pocket-relay/files.ts +10 -3
  37. package/src/server/extensions/pocket-relay/runtime.ts +6 -0
  38. package/src/server/extensions/pocket-relay.ts +31 -3
  39. package/src/server/extensions/schedules.ts +9 -2
  40. package/src/server/host.ts +25 -0
  41. package/src/server/http/api.ts +21 -4
  42. package/src/server/http/browser-routes.ts +5 -2
  43. package/src/server/http/conversation-routes.ts +4 -3
  44. package/src/server/http/events.ts +9 -4
  45. package/src/server/http/io.ts +5 -2
  46. package/src/server/http/sign-in.ts +9 -3
  47. package/src/server/limit-gate.ts +257 -65
  48. package/src/server/limits.ts +80 -4
  49. package/src/server/main.ts +71 -16
  50. package/src/server/no-follow.ts +67 -0
  51. package/src/server/pending-approvals.ts +174 -0
  52. package/src/server/processes.ts +1480 -0
  53. package/src/server/projection.ts +7 -6
  54. package/src/server/room.ts +2 -0
  55. package/src/server/schedules.ts +226 -4
  56. package/src/server/secrets.ts +6 -4
  57. package/src/server/socket-path.ts +167 -0
  58. package/src/server/themes.ts +2 -4
  59. package/src/server/worktrees.ts +16 -17
  60. package/types/pocket.d.ts +74 -0
  61. package/web/agent-now.js +2 -2
  62. package/web/notify.js +1 -5
  63. package/web/peeks.js +1 -1
  64. package/web/sessions.js +2 -3
  65. package/web/sheets/schedules.js +18 -0
  66. package/web/store.js +126 -13
  67. package/web/transcript.js +4 -30
@@ -17,7 +17,7 @@
17
17
  * politely, then by force. A sweep, apart from the watches, keeps each log under its limit. The background extension
18
18
  * (`extensions/background.ts`) installs the task and gives Pi its tool; while it is off, the watches wait.
19
19
  */
20
- import { spawn, spawnSync } from "node:child_process";
20
+ import { spawnSync } from "node:child_process";
21
21
  import { randomUUID } from "node:crypto";
22
22
  import {
23
23
  closeSync,
@@ -45,6 +45,7 @@ import { DEFAULT_QUIET_MINUTES, DEFAULT_TASK_QUIET_MINUTES } from "./deadline.ts
45
45
  import { BackgroundDoc, type BackgroundTask } from "./docs.ts";
46
46
  import { HttpError } from "./errors.ts";
47
47
  import { defang, quoted } from "./fence.ts";
48
+ import { BACKGROUND_MARKER, type TaskProcesses, type TaskRef, taskProcesses } from "./processes.ts";
48
49
  import { requestFor } from "./requests.ts";
49
50
 
50
51
  export type { BackgroundTask } from "./docs.ts";
@@ -55,8 +56,7 @@ const context = BACKGROUND_CONTEXT;
55
56
  export const BACKGROUND_EXTENSION = "pocket-background";
56
57
  /** How a background task's message to Pi starts, so Pi (and people reading along) know where it came from. */
57
58
  export const BACKGROUND_PREFIX = "[background] ";
58
- /** The environment variable that marks each process of a task: `<data folder>#<conversation>/<id>`. */
59
- export const BACKGROUND_MARKER = "PI_POCKET_BACKGROUND";
59
+ export { BACKGROUND_MARKER } from "./processes.ts";
60
60
 
61
61
  /** What the owner can change in Extensions: how many tasks may run at once in one session. */
62
62
  /**
@@ -137,156 +137,6 @@ export type BackgroundStart = {
137
137
  key?: string;
138
138
  };
139
139
 
140
- // ─── Processes ──────────────────────────────────────────────────────────────
141
-
142
- const PROC = "/proc";
143
- const hasProc = existsSync(`${PROC}/self/stat`);
144
-
145
- /** This boot of the machine: a task from another boot has no process left, whatever pid it had. */
146
- const BOOT = (() => {
147
- try {
148
- return readFileSync(`${PROC}/sys/kernel/random/boot_id`, "utf8").trim();
149
- } catch {
150
- return undefined;
151
- }
152
- })();
153
-
154
- type ProcInfo = { pid: number; pgid: number; state: string; start: number };
155
-
156
- /** A process's group, state, and start time, from `/proc/<pid>/stat`. */
157
- function procStat(pid: number): ProcInfo | undefined {
158
- try {
159
- const text = readFileSync(`${PROC}/${pid}/stat`, "utf8");
160
- // After the name, which can hold spaces and parentheses: state (3), ppid (4), pgrp (5), …, starttime (22).
161
- const rest = text.slice(text.lastIndexOf(")") + 2).split(" ");
162
-
163
- return { pid, pgid: Number(rest[2]), state: rest[0] ?? "", start: Number(rest[19]) };
164
- } catch {
165
- return undefined;
166
- }
167
- }
168
-
169
- const gone = (info: ProcInfo) => info.state === "Z" || info.state === "X";
170
-
171
- /** Every process's stat, read once for all the watches that look in the same moment. */
172
- let scan: { at: number; all: ProcInfo[] } | undefined;
173
-
174
- function processes(fresh = false): ProcInfo[] {
175
- const now = Date.now();
176
-
177
- if (!fresh && scan !== undefined && now - scan.at < 250) {
178
- return scan.all;
179
- }
180
-
181
- const all: ProcInfo[] = [];
182
-
183
- for (const name of readdirSync(PROC)) {
184
- if (/^\d+$/.test(name)) {
185
- const info = procStat(Number(name));
186
-
187
- if (info !== undefined && !gone(info)) {
188
- all.push(info);
189
- }
190
- }
191
- }
192
-
193
- scan = { at: now, all };
194
-
195
- return all;
196
- }
197
-
198
- /** Whether a process carries a marker in its environment; false for a process not ours to read. */
199
- function marked(pid: number, marker: string): boolean {
200
- try {
201
- return readFileSync(`${PROC}/${pid}/environ`, "utf8")
202
- .split("\0")
203
- .includes(`${BACKGROUND_MARKER}=${marker}`);
204
- } catch {
205
- return false;
206
- }
207
- }
208
-
209
- /**
210
- * The live processes of a task's group. While its leader runs (the same pid, started at the same time), the group is
211
- * the task's; once the leader is gone, a member counts only while one carries the task's marker, so a group id that a
212
- * new process took after the task's ended is not taken for it.
213
- */
214
- function members(item: BackgroundTask, marker: string, fresh = false): number[] {
215
- if (item.pid <= 0 || (item.boot !== undefined && item.boot !== BOOT)) {
216
- return [];
217
- }
218
-
219
- if (!hasProc) {
220
- try {
221
- process.kill(-item.pid, 0);
222
-
223
- return [item.pid];
224
- } catch (error) {
225
- return (error as NodeJS.ErrnoException).code === "EPERM" ? [item.pid] : [];
226
- }
227
- }
228
-
229
- // Cheap first, as most looks go: no process in the group at all, or its leader still the same.
230
- try {
231
- process.kill(-item.pid, 0);
232
- } catch (error) {
233
- if ((error as NodeJS.ErrnoException).code !== "EPERM") {
234
- return [];
235
- }
236
- }
237
-
238
- const first = procStat(item.pid);
239
-
240
- if (
241
- first !== undefined &&
242
- !gone(first) &&
243
- first.pgid === item.pid &&
244
- item.startTicks !== undefined &&
245
- first.start === item.startTicks
246
- ) {
247
- return [item.pid];
248
- }
249
-
250
- // The leader is gone and the group is not: what is left of it, from a scan.
251
- let group = processes(fresh).filter((each) => each.pgid === item.pid);
252
-
253
- // A scan from before the task started does not know it yet.
254
- if (group.length === 0 && !fresh) {
255
- group = processes(true).filter((each) => each.pgid === item.pid);
256
- }
257
-
258
- const leader = group.find((each) => each.pid === item.pid);
259
-
260
- if (
261
- leader !== undefined &&
262
- (item.startTicks === undefined || leader.start === item.startTicks)
263
- ) {
264
- return group.map((each) => each.pid);
265
- }
266
-
267
- return group.some((each) => marked(each.pid, marker)) ? group.map((each) => each.pid) : [];
268
- }
269
-
270
- /**
271
- * Every live process that carries a task's marker, wherever it is: its group, or one that left it (`setsid`, a daemon).
272
- * Reads each process's environment, so it is for the moments that need it: the end of a group, a stop, a recovery.
273
- */
274
- function markedProcesses(marker: string): ProcInfo[] {
275
- if (!hasProc) {
276
- return [];
277
- }
278
-
279
- return processes(true).filter((each) => marked(each.pid, marker));
280
- }
281
-
282
- function kill(pid: number, name: NodeJS.Signals): void {
283
- try {
284
- process.kill(pid, name);
285
- } catch {
286
- // Gone already, or never ours.
287
- }
288
- }
289
-
290
140
  // ─── Words ──────────────────────────────────────────────────────────────────
291
141
 
292
142
  /** A length of time in words: 45s, 3m 12s, 3m 05s, 2h 05m. */
@@ -438,6 +288,8 @@ export class BackgroundTasks {
438
288
  #sweeper: ReturnType<typeof setInterval> | undefined;
439
289
  /** Whether `split` was found. */
440
290
  #split = false;
291
+ /** How this platform finds, follows, and stops a task's processes. */
292
+ readonly #procs: TaskProcesses = taskProcesses();
441
293
  /** The durable task behind each background command; the background extension installs it. */
442
294
  readonly task: Task<WatchInput, WatchState, null, object>;
443
295
 
@@ -518,6 +370,7 @@ export class BackgroundTasks {
518
370
  /** Stop the sweep: the server closes. Its tasks' processes run on. */
519
371
  close(): void {
520
372
  clearInterval(this.#sweeper);
373
+ this.#procs.close();
521
374
  this.#sweeper = undefined;
522
375
  }
523
376
 
@@ -629,51 +482,60 @@ export class BackgroundTasks {
629
482
  return items !== undefined && Object.hasOwn(items, id) ? items[id] : undefined;
630
483
  }
631
484
 
485
+ /** What a task's processes are known by. */
486
+ #ref(conversationId: ConversationId, item: BackgroundTask): TaskRef {
487
+ return {
488
+ pid: item.pid,
489
+ ...(item.startTicks === undefined ? {} : { startTicks: item.startTicks }),
490
+ ...(item.boot === undefined ? {} : { boot: item.boot }),
491
+ marker: this.#marker(conversationId, item.id),
492
+ files: join(this.#dir(conversationId), item.id),
493
+ startedAt: item.startedAt,
494
+ };
495
+ }
496
+
632
497
  /**
633
498
  * Whether a task still runs: any process of its group. A process that left the group (a daemon, `setsid`) does not
634
499
  * keep it running, or a build tool's daemon would hold one of the session's places for good and its end would never
635
500
  * be told; it is named when the task ends (`#left`), and a stop ends it, also after.
636
501
  */
637
- #alive(conversationId: ConversationId, item: BackgroundTask, fresh = false): boolean {
638
- return members(item, this.#marker(conversationId, item.id), fresh).length > 0;
502
+ async #alive(
503
+ conversationId: ConversationId,
504
+ item: BackgroundTask,
505
+ fresh = false,
506
+ ): Promise<boolean> {
507
+ return (await this.#procs.members(this.#ref(conversationId, item), fresh)).length > 0;
639
508
  }
640
509
 
641
510
  /** The processes with a task's marker that still run outside its group: what it left behind. */
642
- #left(conversationId: ConversationId, item: BackgroundTask): number[] {
643
- return markedProcesses(this.#marker(conversationId, item.id))
644
- .filter((each) => each.pgid !== item.pid)
645
- .map((each) => each.pid);
511
+ #left(conversationId: ConversationId, item: BackgroundTask): Promise<number[]> {
512
+ return this.#procs.left(this.#ref(conversationId, item));
646
513
  }
647
514
 
648
515
  /** Send a signal to every process of a task: its group, and each process with its marker, found afresh. */
649
- #signal(conversationId: ConversationId, item: BackgroundTask, name: NodeJS.Signals): void {
650
- const marker = this.#marker(conversationId, item.id);
651
-
652
- if (members(item, marker, true).length > 0) {
653
- kill(-item.pid, name);
654
- }
655
-
656
- for (const each of markedProcesses(marker)) {
657
- kill(each.pid === each.pgid ? -each.pid : each.pid, name);
658
- }
659
-
660
- scan = undefined;
516
+ #signal(
517
+ conversationId: ConversationId,
518
+ item: BackgroundTask,
519
+ name: "SIGTERM" | "SIGKILL",
520
+ ): Promise<void> {
521
+ return this.#procs.signal(this.#ref(conversationId, item), name);
661
522
  }
662
523
 
663
524
  /** Ask every process of a task to stop, and force what is left after the grace period. */
664
525
  async #kill(conversationId: ConversationId, item: BackgroundTask): Promise<void> {
665
- this.#signal(conversationId, item, "SIGTERM");
526
+ await this.#signal(conversationId, item, "SIGTERM");
666
527
 
667
528
  const until = Date.now() + this.timing.grace;
668
529
 
669
530
  while (
670
531
  Date.now() < until &&
671
- (this.#alive(conversationId, item, true) || this.#left(conversationId, item).length > 0)
532
+ ((await this.#alive(conversationId, item, true)) ||
533
+ (await this.#left(conversationId, item)).length > 0)
672
534
  ) {
673
535
  await wait(100);
674
536
  }
675
537
 
676
- this.#signal(conversationId, item, "SIGKILL");
538
+ await this.#signal(conversationId, item, "SIGKILL");
677
539
  }
678
540
 
679
541
  /** Wait while any process of the task runs, then record how it ended. */
@@ -720,13 +582,13 @@ export class BackgroundTasks {
720
582
  // An end is looked at twice, a moment apart, with a fresh scan: a child a command leaves can be in the middle of
721
583
  // starting its program as the command ends, when its environment, and so its marker, reads empty.
722
584
  const ended = async () => {
723
- if (this.#alive(conversationId, watched)) {
585
+ if (await this.#alive(conversationId, watched)) {
724
586
  return false;
725
587
  }
726
588
 
727
589
  await wait(Math.min(200, this.timing.look * 2), aborted);
728
590
 
729
- return !this.#alive(conversationId, watched, true);
591
+ return !(await this.#alive(conversationId, watched, true));
730
592
  };
731
593
 
732
594
  // Its log is kept short at each tick, apart from the looks at its processes: a command that writes faster than
@@ -765,11 +627,11 @@ export class BackgroundTasks {
765
627
  ? `it wrote more than ${Math.round((this.sizes.maxLog * this.sizes.sustained) / 1024 / 1024)} MB of output in ${SUSTAINED_MS / 1000} seconds, more than its log can keep`
766
628
  : `it wrote more than ${Math.round(this.sizes.runaway / 1024 / 1024)} MB of output in ${tick} ms, faster than its log can be kept`;
767
629
  // At once, with no grace: a writer that took its time to stop would write on all the while.
768
- this.#signal(conversationId, watched, "SIGKILL");
630
+ await this.#signal(conversationId, watched, "SIGKILL");
769
631
 
770
632
  for (
771
633
  let wait_ = 0;
772
- wait_ < 20 && this.#alive(conversationId, watched, true);
634
+ wait_ < 20 && (await this.#alive(conversationId, watched, true));
773
635
  wait_++
774
636
  ) {
775
637
  this.#trimLog(conversationId, watched.id);
@@ -808,7 +670,7 @@ export class BackgroundTasks {
808
670
 
809
671
  // The wrapper's file: a command stopped or killed with its wrapper leaves none.
810
672
  const codes = this.#exitCodes(conversationId, id);
811
- const left = this.#left(conversationId, watched);
673
+ const left = await this.#left(conversationId, watched);
812
674
  let pruned: string[] = [];
813
675
 
814
676
  await runtime.commit(async (tx) => {
@@ -898,14 +760,9 @@ export class BackgroundTasks {
898
760
  */
899
761
  async #recover(runtime: Runtime, item: BackgroundTask, context: Context): Promise<boolean> {
900
762
  const conversationId = runtime.conversationId;
901
- const marker = this.#marker(conversationId, item.id);
902
- const found = markedProcesses(marker);
903
-
904
- if (found.length > 0) {
905
- const leader =
906
- found.find((each) => each.pid === each.pgid) ??
907
- (found[0] === undefined ? undefined : procStat(found[0].pgid));
763
+ const found = await this.#procs.find(this.#ref(conversationId, item));
908
764
 
765
+ if (found !== undefined) {
909
766
  await this.#app.harness.commit(async (tx) => {
910
767
  const stored = (await tx.doc(BackgroundDoc, conversationId)).items[item.id];
911
768
 
@@ -914,11 +771,10 @@ export class BackgroundTasks {
914
771
  }
915
772
 
916
773
  stored.status = "running";
917
- stored.pid = leader?.pid ?? found[0]!.pgid;
774
+ stored.pid = found.pid;
918
775
 
919
- // A leader that carries the marker is known for sure; a group whose leader is gone counts by its members.
920
- if (leader !== undefined && marked(leader.pid, marker)) {
921
- stored.startTicks = leader.start;
776
+ if (found.start !== undefined) {
777
+ stored.startTicks = found.start;
922
778
  }
923
779
  }, context);
924
780
 
@@ -1287,6 +1143,9 @@ export class BackgroundTasks {
1287
1143
  #removeFiles(conversationId: ConversationId, ids: readonly string[] | undefined): void {
1288
1144
  for (const id of ids ?? []) {
1289
1145
  rmSync(this.#exitFile(conversationId, id), { force: true });
1146
+ // Windows: the pid its bash wrote, and the processes found of it.
1147
+ rmSync(join(this.#dir(conversationId), `${id}.pid`), { force: true });
1148
+ rmSync(join(this.#dir(conversationId), `${id}.pids`), { force: true });
1290
1149
  // A log of one file, as builds of 0.24.0 before its release wrote.
1291
1150
  rmSync(join(this.#dir(conversationId), `${id}.log`), { force: true });
1292
1151
 
@@ -1302,14 +1161,6 @@ export class BackgroundTasks {
1302
1161
  throw new HttpError(409, "Background tasks are turned off in Extensions.");
1303
1162
  }
1304
1163
 
1305
- // Without /proc a task's processes cannot be told from others that took their ids: a stop could hit those.
1306
- if (!hasProc) {
1307
- throw new HttpError(
1308
- 501,
1309
- "Background tasks need Linux: they follow their processes through /proc.",
1310
- );
1311
- }
1312
-
1313
1164
  const meta = this.#app.sessionMeta(conversationId);
1314
1165
 
1315
1166
  if (meta === undefined) {
@@ -1334,6 +1185,13 @@ export class BackgroundTasks {
1334
1185
 
1335
1186
  this.#check(conversationId);
1336
1187
 
1188
+ // Where a task's processes cannot be told from others that took their ids, a stop could hit those: none starts.
1189
+ const unsupported = await this.#procs.unsupported();
1190
+
1191
+ if (unsupported !== undefined) {
1192
+ throw new HttpError(501, unsupported);
1193
+ }
1194
+
1337
1195
  const command = request.command.trim();
1338
1196
 
1339
1197
  if (command === "") {
@@ -1397,7 +1255,7 @@ export class BackgroundTasks {
1397
1255
  command,
1398
1256
  cwd,
1399
1257
  pid: 0,
1400
- ...(BOOT === undefined ? {} : { boot: BOOT }),
1258
+ ...(this.#procs.boot === undefined ? {} : { boot: this.#procs.boot }),
1401
1259
  segment: this.sizes.segment,
1402
1260
  startedAt: app.now(),
1403
1261
  status: "starting",
@@ -1442,12 +1300,12 @@ export class BackgroundTasks {
1442
1300
  await this.beforeSpawn?.();
1443
1301
  this.#needsSplit();
1444
1302
 
1445
- const spawned = this.#spawn(conversationId, item, added);
1303
+ const { pid: spawned, start } = await this.#spawn(conversationId, item, added);
1446
1304
 
1447
1305
  pid = spawned;
1448
1306
  await this.beforeRecord?.();
1449
1307
 
1450
- const startTicks = procStat(spawned)?.start;
1308
+ const startTicks = start ?? (await this.#procs.startOf(spawned));
1451
1309
  const recorded = await app.harness.commit(async (tx) => {
1452
1310
  const stored = (await tx.doc(BackgroundDoc, conversationId)).items[item.id];
1453
1311
 
@@ -1467,7 +1325,7 @@ export class BackgroundTasks {
1467
1325
  }, context);
1468
1326
 
1469
1327
  if (!recorded) {
1470
- kill(-spawned, "SIGKILL");
1328
+ await this.#procs.killSpawned(this.#ref(conversationId, item), spawned);
1471
1329
  }
1472
1330
 
1473
1331
  return (await this.#stored(conversationId, item.id)) ?? item;
@@ -1483,8 +1341,12 @@ export class BackgroundTasks {
1483
1341
 
1484
1342
  /** Throws when `split`, which writes the logs, is not on this machine; looked for again until it is found. */
1485
1343
  #needsSplit(): void {
1344
+ const shell = this.#procs.shell();
1345
+
1486
1346
  this.#split ||=
1487
- spawnSync("bash", ["-c", "command -v split"], { stdio: "ignore" }).status === 0;
1347
+ shell !== undefined &&
1348
+ spawnSync(shell, ["-c", "command -v split"], { stdio: "ignore", windowsHide: true })
1349
+ .status === 0;
1488
1350
 
1489
1351
  if (!this.#split) {
1490
1352
  throw new HttpError(
@@ -1494,32 +1356,31 @@ export class BackgroundTasks {
1494
1356
  }
1495
1357
  }
1496
1358
 
1497
- #spawn(conversationId: ConversationId, item: BackgroundTask, added: Record<string, string>) {
1359
+ async #spawn(
1360
+ conversationId: ConversationId,
1361
+ item: BackgroundTask,
1362
+ added: Record<string, string>,
1363
+ ): Promise<{ pid: number; start?: number }> {
1498
1364
  mkdirSync(this.#dir(conversationId), { recursive: true });
1499
1365
 
1500
- const child = spawn("bash", ["-c", WRAPPER], {
1501
- cwd: item.cwd,
1502
- detached: true,
1503
- stdio: "ignore",
1504
- env: {
1505
- ...process.env,
1506
- ...added,
1507
- [BACKGROUND_MARKER]: this.#marker(conversationId, item.id),
1508
- PI_POCKET_BACKGROUND_COMMAND: item.command,
1509
- PI_POCKET_BACKGROUND_EXIT: this.#exitFile(conversationId, item.id),
1510
- PI_POCKET_BACKGROUND_LOG: this.#logPrefix(conversationId, item.id),
1511
- PI_POCKET_BACKGROUND_SEGMENT: String(item.segment ?? SEGMENT_BYTES),
1512
- },
1513
- });
1514
-
1515
- child.on("error", () => {});
1516
- child.unref();
1517
-
1518
- if (child.pid === undefined) {
1519
- throw new HttpError(500, "The command could not start: no bash on this machine?");
1366
+ try {
1367
+ return await this.#procs.spawn(
1368
+ WRAPPER,
1369
+ item.cwd,
1370
+ {
1371
+ ...process.env,
1372
+ ...added,
1373
+ [BACKGROUND_MARKER]: this.#marker(conversationId, item.id),
1374
+ PI_POCKET_BACKGROUND_COMMAND: item.command,
1375
+ PI_POCKET_BACKGROUND_EXIT: this.#exitFile(conversationId, item.id),
1376
+ PI_POCKET_BACKGROUND_LOG: this.#logPrefix(conversationId, item.id),
1377
+ PI_POCKET_BACKGROUND_SEGMENT: String(item.segment ?? SEGMENT_BYTES),
1378
+ },
1379
+ this.#ref(conversationId, item),
1380
+ );
1381
+ } catch (error) {
1382
+ throw new HttpError(500, (error as Error).message);
1520
1383
  }
1521
-
1522
- return child.pid;
1523
1384
  }
1524
1385
 
1525
1386
  /** Take back a reservation whose start failed: its watch, its record, its files, and any process it has. */
@@ -1529,10 +1390,10 @@ export class BackgroundTasks {
1529
1390
  pid?: number,
1530
1391
  ): Promise<void> {
1531
1392
  if (pid !== undefined) {
1532
- kill(-pid, "SIGKILL");
1393
+ await this.#procs.killSpawned(this.#ref(conversationId, item), pid);
1533
1394
  }
1534
1395
 
1535
- this.#signal(conversationId, item, "SIGKILL");
1396
+ await this.#signal(conversationId, item, "SIGKILL");
1536
1397
 
1537
1398
  await this.#app.harness.commit(async (tx) => {
1538
1399
  delete (await tx.doc(BackgroundDoc, conversationId)).items[item.id];
@@ -1588,7 +1449,10 @@ export class BackgroundTasks {
1588
1449
  }
1589
1450
 
1590
1451
  return {
1591
- item: { ...this.#current(conversationId, item), read: Math.max(item.read, range.to) },
1452
+ item: {
1453
+ ...(await this.#current(conversationId, item)),
1454
+ read: Math.max(item.read, range.to),
1455
+ },
1592
1456
  text,
1593
1457
  skipped,
1594
1458
  };
@@ -1686,7 +1550,7 @@ export class BackgroundTasks {
1686
1550
  }
1687
1551
 
1688
1552
  return {
1689
- item: this.#current(conversationId, item),
1553
+ item: await this.#current(conversationId, item),
1690
1554
  text,
1691
1555
  from: at,
1692
1556
  to: end,
@@ -1711,7 +1575,10 @@ export class BackgroundTasks {
1711
1575
 
1712
1576
  // Ended: what it left running (a daemon) is stopped, found again by its marker.
1713
1577
  if (item.status !== "running" && item.status !== "starting") {
1714
- if (this.#left(conversationId, item).length > 0 || (item.left?.length ?? 0) > 0) {
1578
+ if (
1579
+ (await this.#left(conversationId, item)).length > 0 ||
1580
+ (item.left?.length ?? 0) > 0
1581
+ ) {
1715
1582
  await this.#kill(conversationId, { ...item, pid: 0 });
1716
1583
  await this.#app.harness.commit(async (tx) => {
1717
1584
  const stored = (await tx.doc(BackgroundDoc, conversationId)).items[id];
@@ -1780,25 +1647,21 @@ export class BackgroundTasks {
1780
1647
  const live = (item: BackgroundTask) =>
1781
1648
  Number(item.status === "running" || item.status === "starting");
1782
1649
 
1783
- return items
1784
- .map((item) => this.#current(conversationId, item))
1785
- .sort(
1786
- (a, b) =>
1787
- live(b) - live(a) || (b.endedAt ?? b.startedAt) - (a.endedAt ?? a.startedAt),
1788
- );
1650
+ return (await Promise.all(items.map((item) => this.#current(conversationId, item)))).sort(
1651
+ (a, b) => live(b) - live(a) || (b.endedAt ?? b.startedAt) - (a.endedAt ?? a.startedAt),
1652
+ );
1789
1653
  }
1790
1654
 
1791
1655
  /**
1792
1656
  * A task as it is now: of what it left running when it ended, only what still runs (by its marker, so a pid used
1793
1657
  * again by another process does not count).
1794
1658
  */
1795
- #current(conversationId: ConversationId, item: BackgroundTask): BackgroundTask {
1659
+ async #current(conversationId: ConversationId, item: BackgroundTask): Promise<BackgroundTask> {
1796
1660
  if (item.left === undefined) {
1797
1661
  return item;
1798
1662
  }
1799
1663
 
1800
- const marker = this.#marker(conversationId, item.id);
1801
- const left = item.left.filter((pid) => marked(pid, marker));
1664
+ const left = await this.#procs.stillLeft(this.#ref(conversationId, item), item.left);
1802
1665
  const { left: _was, ...rest } = item;
1803
1666
 
1804
1667
  return left.length === 0 ? rest : { ...item, left };
@@ -1812,8 +1675,13 @@ export class BackgroundTasks {
1812
1675
  return (await this.list(conversationId)).find((item) => String(item.taskId) === taskId);
1813
1676
  }
1814
1677
 
1815
- /** Whether any process of a task's group runs: for tests and checks. */
1678
+ /** Whether any process of a task's group runs, from what is known at once: for a count, tests, and checks. */
1816
1679
  alive(conversationId: ConversationId, item: BackgroundTask): boolean {
1680
+ return this.#procs.aliveSync(this.#ref(conversationId, item));
1681
+ }
1682
+
1683
+ /** Whether any process of a task runs, from a fresh look. */
1684
+ aliveNow(conversationId: ConversationId, item: BackgroundTask): Promise<boolean> {
1817
1685
  return this.#alive(conversationId, item, true);
1818
1686
  }
1819
1687
  }