@omercnet/paseo-omp 5.7.0 → 5.8.0-next.536.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/server/hub.ts CHANGED
@@ -1,10 +1,12 @@
1
1
  import type { Dirent } from "node:fs";
2
- import { readdir, readFile, realpath } from "node:fs/promises";
2
+ import { access, open, readdir, readFile, realpath } from "node:fs/promises";
3
3
  import { homedir } from "node:os";
4
4
  import { join, resolve } from "node:path";
5
+ import { DatabaseSync } from "node:sqlite";
5
6
  import type { RpcInput } from "@getpaseo/plugin";
6
7
  import { z } from "zod";
7
8
  import type { HubProcess, listHubProcesses, tailHubLog } from "../shared/hub";
9
+ import { ompDaemonDir } from "./paths";
8
10
  import { waitMs } from "./provider/omp-rpc-process";
9
11
 
10
12
  const MAX_LOG_BYTES = 64 * 1024;
@@ -48,6 +50,15 @@ function ompRunDir(): string {
48
50
  return process.env.PASEO_OMP_RUN_DIR ?? join(homedir(), ".omp", "run", "daemons");
49
51
  }
50
52
 
53
+ /**
54
+ * omp 19's per-user daemon directory; see {@link ompDaemonDir}. `PASEO_OMP_DAEMON_DIR` is a
55
+ * test-only override: set in production it makes the Hub read a different store than the one
56
+ * omp's own `ps stop` acts on.
57
+ */
58
+ function ompDaemonRunDir(): string {
59
+ return process.env.PASEO_OMP_DAEMON_DIR || ompDaemonDir();
60
+ }
61
+
51
62
  type Read<T> = { value: T } | { missing: true } | { unreadable: true };
52
63
 
53
64
  export function readFailure(error: unknown): { missing: true } | { unreadable: true } {
@@ -138,8 +149,16 @@ function toHubProcess(name: string, value: unknown, specFile: unknown): HubProce
138
149
  };
139
150
  }
140
151
 
152
+ export interface ScannedHubProcess extends HubProcess {
153
+ /**
154
+ * omp 19's unit id. `omp ps stop` resolves a bare name machine-wide (exact id first, then any
155
+ * single unit with that key in any project), so a daemon service is stopped by its id.
156
+ */
157
+ unitId?: string;
158
+ }
159
+
141
160
  export interface HubProcessScan {
142
- processes: HubProcess[];
161
+ processes: ScannedHubProcess[];
143
162
  /** Records that exist but could not be read or parsed: their state is unknown. */
144
163
  unreadable: string[];
145
164
  /**
@@ -149,9 +168,16 @@ export interface HubProcessScan {
149
168
  strays: string[];
150
169
  /** False when a directory that could hold this project's records could not be read. */
151
170
  complete: boolean;
171
+ /**
172
+ * Every key and label in omp 19's daemon store, across all projects and scopes: `undefined`
173
+ * when there is no store, `null` when it exists but could not be read. A 19 `omp ps stop
174
+ * <name>` matches any of them, so an 18.x broker service is only stopped by name when its
175
+ * name is provably absent here.
176
+ */
177
+ daemonUnitNames?: ReadonlySet<string> | null;
152
178
  }
153
179
 
154
- export async function scanHubProcessesFrom(root: string, cwd: string): Promise<HubProcessScan> {
180
+ async function scanBrokerProcessesFrom(root: string, cwd: string): Promise<HubProcessScan> {
155
181
  const found = await findProjectDaemonRoots(root, cwd);
156
182
  const scan: HubProcessScan = {
157
183
  processes: [],
@@ -187,18 +213,212 @@ export async function scanHubProcessesFrom(root: string, cwd: string): Promise<H
187
213
  );
188
214
  }),
189
215
  );
216
+ return scan;
217
+ }
218
+
219
+ /*
220
+ * omp 19 replaced the per-project brokers with one per-user daemon. It keeps every unit in a
221
+ * sqlite store, `<daemonDir>/daemon.db` (table `units`, one JSON `snapshot` per unit), and a
222
+ * unit's output in `<daemonDir>/units/<id>/output.log`. A named service is a `proc` unit in its
223
+ * session's project scope (`scope_key` `project:<canonical dir>`), keyed by the service name.
224
+ * Like the broker layout above this is unversioned, so every read degrades instead of throwing.
225
+ */
226
+ const DAEMON_SERVICE_KIND = "proc";
227
+ // A service runs as omp re-entering itself with this selector, its shell command last
228
+ // (pi-utils `SHELL_PROCESS_SELECTOR`); `omp ps` shows such a launch as just that command.
229
+ const SHELL_PROCESS_SELECTOR = "__omp_worker_shell_process";
230
+ const DaemonRowSchema = z.object({
231
+ id: z.string(),
232
+ key: z.string(),
233
+ snapshot: z.string(),
234
+ proc: z.string().nullable(),
235
+ });
236
+ const DaemonUnitSchema = z.object({
237
+ state: z.string(),
238
+ pids: z.array(z.number()).optional(),
239
+ owner: z.string().optional(),
240
+ restartCount: z.number().optional(),
241
+ policy: z.object({ hold: z.string().optional() }).optional(),
242
+ createdAt: z.number().optional(),
243
+ startedAt: z.number().optional(),
244
+ readyAt: z.number().optional(),
245
+ exitedAt: z.number().optional(),
246
+ exitCode: z.number().optional(),
247
+ command: z.string().optional(),
248
+ cwd: z.string().optional(),
249
+ });
250
+
251
+ interface DaemonService {
252
+ process: ScannedHubProcess;
253
+ log: string;
254
+ }
255
+
256
+ interface DaemonServiceScan {
257
+ services: DaemonService[];
258
+ unreadable: string[];
259
+ complete: boolean;
260
+ /** See {@link HubProcessScan.daemonUnitNames}. */
261
+ unitNames?: ReadonlySet<string> | null;
262
+ }
263
+
264
+ // omp names units with `crypto.randomUUID()`. A row id that is not a plain basename must never
265
+ // reach a log path or a CLI argument; the leading alphanumeric also rules out `.`, `..` and flags.
266
+ const UNIT_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
267
+
268
+ function processAlive(pid: number): boolean {
269
+ try {
270
+ process.kill(pid, 0);
271
+ return true;
272
+ } catch (error) {
273
+ // EPERM: the process exists but belongs to someone else.
274
+ return (error as NodeJS.ErrnoException | undefined)?.code === "EPERM";
275
+ }
276
+ }
277
+
278
+ function launchCommand(
279
+ spec: z.infer<typeof SpecSchema> | undefined,
280
+ command: string | undefined,
281
+ ): { application: string; args: string[] } {
282
+ if (!spec) return { application: command ?? "", args: [] };
283
+ const args = spec.args ?? [];
284
+ if (args.includes(SHELL_PROCESS_SELECTOR)) return { application: args.at(-1) ?? "", args: [] };
285
+ return { application: spec.application, args };
286
+ }
287
+
288
+ function toDaemonService(
289
+ daemonDir: string,
290
+ row: z.infer<typeof DaemonRowSchema>,
291
+ ): DaemonService | undefined {
292
+ let snapshot: unknown;
293
+ let proc: unknown;
294
+ try {
295
+ snapshot = JSON.parse(row.snapshot);
296
+ proc = row.proc === null ? undefined : JSON.parse(row.proc);
297
+ } catch {
298
+ return undefined;
299
+ }
300
+ const parsed = DaemonUnitSchema.safeParse(snapshot);
301
+ if (!parsed.success) return undefined;
302
+ const unit = parsed.data;
303
+ const spec = SpecSchema.safeParse(proc).data;
304
+ // The store keeps a unit's last persisted state, and a daemon that died took its services down
305
+ // with it (omp's own offline `ps` reports them exited), so a running state whose main process
306
+ // is gone is stale. Transitional states are left alone: a live daemon may be restarting the
307
+ // service or still ending its tree.
308
+ const mainPid = unit.pids?.[0];
309
+ const stale =
310
+ (unit.state === "running" || unit.state === "ready") &&
311
+ mainPid !== undefined &&
312
+ // kill(0)/kill(-n) would probe a process group, not this service.
313
+ mainPid > 0 &&
314
+ !processAlive(mainPid);
315
+ return {
316
+ log: join(daemonDir, "units", row.id, "output.log"),
317
+ process: {
318
+ name: row.key,
319
+ ...launchCommand(spec, unit.command),
320
+ cwd: spec?.cwd ?? unit.cwd ?? "",
321
+ state: stale ? "exited" : unit.state,
322
+ owner: unit.owner ?? null,
323
+ restartCount: unit.restartCount ?? 0,
324
+ persist: unit.policy?.hold === "persist",
325
+ detached: unit.policy?.hold === "detached",
326
+ createdAt: unit.createdAt ?? null,
327
+ startedAt: unit.startedAt ?? null,
328
+ readyAt: unit.readyAt ?? null,
329
+ exitedAt: unit.exitedAt ?? null,
330
+ exitCode: unit.exitCode ?? null,
331
+ unitId: row.id,
332
+ },
333
+ };
334
+ }
335
+
336
+ async function scanDaemonServicesFrom(daemonDir: string, cwd: string): Promise<DaemonServiceScan> {
337
+ const scan: DaemonServiceScan = { services: [], unreadable: [], complete: true };
338
+ const path = join(daemonDir, "daemon.db");
339
+ try {
340
+ await access(path);
341
+ } catch (error) {
342
+ // No store: omp 19 never ran here (or omp is older), so it owns no services.
343
+ if ("missing" in readFailure(error)) return scan;
344
+ return { ...scan, complete: false, unitNames: null };
345
+ }
346
+ // omp keys the scope by the same canonical directory (`daemon/paths.ts` canonicalProjectDir).
347
+ const projectDir = await canonicalProjectDir(cwd);
348
+ let rows: unknown[];
349
+ let names: unknown[];
350
+ try {
351
+ const database = new DatabaseSync(path, { readOnly: true, timeout: 500 });
352
+ try {
353
+ rows = database
354
+ .prepare("SELECT id, key, snapshot, proc FROM units WHERE kind = ? AND scope_key = ?")
355
+ .all(DAEMON_SERVICE_KIND, `project:${projectDir}`);
356
+ names = database.prepare("SELECT key, label FROM units").all();
357
+ } finally {
358
+ database.close();
359
+ }
360
+ } catch {
361
+ return { ...scan, complete: false, unitNames: null };
362
+ }
363
+ scan.unitNames = new Set(
364
+ names.flatMap((value) => {
365
+ const row = value as { key?: unknown; label?: unknown };
366
+ return [row.key, row.label].filter((name): name is string => typeof name === "string");
367
+ }),
368
+ );
369
+ for (const value of rows) {
370
+ const row = DaemonRowSchema.safeParse(value);
371
+ if (!row.success) {
372
+ scan.complete = false;
373
+ continue;
374
+ }
375
+ const service = UNIT_ID.test(row.data.id) ? toDaemonService(daemonDir, row.data) : undefined;
376
+ if (service) scan.services.push(service);
377
+ else scan.unreadable.push(row.data.key);
378
+ }
379
+ return scan;
380
+ }
381
+
382
+ /**
383
+ * Every hub process of `cwd`'s project: the 18.x per-project brokers under `root` and, when
384
+ * `daemonDir` is given, omp 19's per-user daemon. Both can hold services at once on a machine
385
+ * that upgraded, since omp 19 does not adopt the brokers' services.
386
+ */
387
+ export async function scanHubProcessesFrom(
388
+ root: string,
389
+ cwd: string,
390
+ daemonDir?: string,
391
+ ): Promise<HubProcessScan> {
392
+ const [brokers, daemon] = await Promise.all([
393
+ scanBrokerProcessesFrom(root, cwd),
394
+ daemonDir === undefined ? undefined : scanDaemonServicesFrom(daemonDir, cwd),
395
+ ]);
396
+ const scan: HubProcessScan = daemon
397
+ ? {
398
+ processes: [...brokers.processes, ...daemon.services.map((service) => service.process)],
399
+ unreadable: [...brokers.unreadable, ...daemon.unreadable],
400
+ strays: brokers.strays,
401
+ complete: brokers.complete && daemon.complete,
402
+ daemonUnitNames: daemon.unitNames,
403
+ }
404
+ : brokers;
190
405
  scan.processes.sort((a, b) => (b.startedAt ?? 0) - (a.startedAt ?? 0));
191
406
  return scan;
192
407
  }
193
408
 
194
- export async function listHubProcessesFrom(root: string, cwd: string): Promise<HubProcess[]> {
195
- return (await scanHubProcessesFrom(root, cwd)).processes;
409
+ export async function listHubProcessesFrom(
410
+ root: string,
411
+ cwd: string,
412
+ daemonDir?: string,
413
+ ): Promise<HubProcess[]> {
414
+ const { processes } = await scanHubProcessesFrom(root, cwd, daemonDir);
415
+ return processes.map(({ unitId: _unitId, ...process }) => process);
196
416
  }
197
417
 
198
418
  export async function resolveListHubProcesses({
199
419
  cwd,
200
420
  }: RpcInput<typeof listHubProcesses>): Promise<{ processes: HubProcess[] }> {
201
- return { processes: await listHubProcessesFrom(ompRunDir(), cwd) };
421
+ return { processes: await listHubProcessesFrom(ompRunDir(), cwd, ompDaemonRunDir()) };
202
422
  }
203
423
 
204
424
  // omp 18.18.9 made launch services persistent in RPC mode (`launch.persist` is forced on for
@@ -233,10 +453,10 @@ export interface OwnedHubCleanupDependencies {
233
453
  /** A timer that fires after `ms`; scans that outlive it count as incomplete. */
234
454
  expire(ms: number): { fired: Promise<void>; cancel(): void };
235
455
  /**
236
- * Asks omp's broker to stop one service within `timeoutMs`; resolves true only when the
237
- * command succeeded.
456
+ * Asks omp to stop one service, named by its omp 19 unit id or its 18.x broker name, within
457
+ * `timeoutMs`; resolves true only when the command succeeded.
238
458
  */
239
- stop(name: string, cwd: string, timeoutMs: number): Promise<boolean>;
459
+ stop(target: string, cwd: string, timeoutMs: number): Promise<boolean>;
240
460
  sleep(ms: number): Promise<void>;
241
461
  now(): number;
242
462
  }
@@ -264,21 +484,24 @@ function startedWhileOwned(process: HubProcess, ownedUntil: number | undefined):
264
484
  }
265
485
 
266
486
  function ownedPersistentServices(
267
- processes: readonly HubProcess[],
487
+ processes: readonly ScannedHubProcess[],
268
488
  owners: HubServiceOwners,
269
489
  states: Readonly<Record<string, true>>,
270
- ): string[] {
271
- return processes
272
- .filter(
273
- (process) =>
274
- HUB_SERVICE_NAME.test(process.name) &&
275
- process.owner !== null &&
276
- startedWhileOwned(process, owners.get(process.owner)) &&
277
- process.persist &&
278
- !process.detached &&
279
- states[process.state] === true,
280
- )
281
- .map((process) => process.name);
490
+ ): ScannedHubProcess[] {
491
+ return processes.filter(
492
+ (process) =>
493
+ HUB_SERVICE_NAME.test(process.name) &&
494
+ process.owner !== null &&
495
+ startedWhileOwned(process, owners.get(process.owner)) &&
496
+ process.persist &&
497
+ !process.detached &&
498
+ states[process.state] === true,
499
+ );
500
+ }
501
+
502
+ /** What `omp ps stop` is given: an omp 19 unit by its id, an 18.x broker service by its name. */
503
+ function stopTarget(process: ScannedHubProcess): string {
504
+ return process.unitId ?? process.name;
282
505
  }
283
506
 
284
507
  async function boundedScan(
@@ -312,15 +535,25 @@ export async function stopOwnedHubProcesses(
312
535
  // A record that cannot be read may be one of ours, so the lookup is not complete.
313
536
  const complete = initial.complete && initial.unreadable.length === 0;
314
537
  if (owned.length === 0) return { stopped: [], failed: [], complete };
315
- const failed = new Set<string>();
538
+ const failed = new Set<ScannedHubProcess>();
316
539
  const queue = [...owned];
317
540
  const stopDeadline = deadline - HUB_CLEANUP_VERIFY_RESERVE_MS;
541
+ // On a machine that has run omp 19, `omp` may now be the 19 CLI, which resolves a bare name
542
+ // against every unit in every project. An 18.x broker service is stopped by name only when no
543
+ // daemon unit anywhere could answer to it; otherwise it is left running and reported failed.
544
+ const daemonNames = initial.daemonUnitNames;
545
+ const stoppableByName = (service: ScannedHubProcess): boolean =>
546
+ service.unitId !== undefined ||
547
+ daemonNames === undefined ||
548
+ (daemonNames !== null && !daemonNames.has(service.name));
318
549
  const stopNext = async (): Promise<void> => {
319
- for (let name = queue.shift(); name !== undefined; name = queue.shift()) {
550
+ for (let service = queue.shift(); service !== undefined; service = queue.shift()) {
320
551
  const remaining = stopDeadline - dependencies.now();
321
552
  const stopped =
322
- remaining > 0 && (await dependencies.stop(name, cwd, remaining).catch(() => false));
323
- if (!stopped) failed.add(name);
553
+ remaining > 0 &&
554
+ stoppableByName(service) &&
555
+ (await dependencies.stop(stopTarget(service), cwd, remaining).catch(() => false));
556
+ if (!stopped) failed.add(service);
324
557
  }
325
558
  };
326
559
  await Promise.all(
@@ -328,27 +561,29 @@ export async function stopOwnedHubProcesses(
328
561
  );
329
562
  // Report success only for services omp's own state confirms have settled. A record that cannot
330
563
  // be read is unknown, not stopped.
331
- let unsettled: ReadonlySet<string>;
564
+ let unsettled: ScannedHubProcess[];
332
565
  while (true) {
333
566
  const current = await boundedScan(dependencies, cwd, deadline - dependencies.now());
334
- unsettled = new Set(
335
- current?.complete
336
- ? [
337
- ...ownedPersistentServices(current.processes, owners, UNSETTLED_HUB_STATES),
338
- ...current.unreadable,
339
- ...current.strays,
340
- ].filter((name) => owned.includes(name))
341
- : owned,
342
- );
343
- if (unsettled.size === 0 || dependencies.now() >= deadline) break;
567
+ if (current?.complete) {
568
+ const live = new Set(
569
+ ownedPersistentServices(current.processes, owners, UNSETTLED_HUB_STATES).map(stopTarget),
570
+ );
571
+ const unknown = new Set([...current.unreadable, ...current.strays]);
572
+ unsettled = owned.filter(
573
+ (service) => live.has(stopTarget(service)) || unknown.has(service.name),
574
+ );
575
+ } else {
576
+ unsettled = owned;
577
+ }
578
+ if (unsettled.length === 0 || dependencies.now() >= deadline) break;
344
579
  await dependencies.sleep(HUB_CLEANUP_POLL_MS);
345
580
  // Keep the last observation rather than scan with no time left.
346
581
  if (dependencies.now() >= deadline) break;
347
582
  }
348
- for (const name of unsettled) failed.add(name);
583
+ for (const service of unsettled) failed.add(service);
349
584
  return {
350
- stopped: owned.filter((name) => !failed.has(name)),
351
- failed: owned.filter((name) => failed.has(name)),
585
+ stopped: owned.filter((service) => !failed.has(service)).map((service) => service.name),
586
+ failed: owned.filter((service) => failed.has(service)).map((service) => service.name),
352
587
  complete,
353
588
  };
354
589
  }
@@ -356,32 +591,57 @@ export async function stopOwnedHubProcesses(
356
591
  export function ownedHubCleanupDependencies(
357
592
  runOmp: (args: readonly string[], timeoutMs: number) => Promise<boolean>,
358
593
  root = ompRunDir(),
594
+ daemonDir = ompDaemonRunDir(),
359
595
  ): OwnedHubCleanupDependencies {
360
596
  return {
361
- scan: (cwd) => scanHubProcessesFrom(root, cwd),
597
+ scan: (cwd) => scanHubProcessesFrom(root, cwd, daemonDir),
362
598
  expire: (ms) => {
363
599
  const fired = Promise.withResolvers<void>();
364
600
  const timer = setTimeout(fired.resolve, ms);
365
601
  return { fired: fired.promise, cancel: () => clearTimeout(timer) };
366
602
  },
367
- stop: (name, cwd, timeoutMs) => runOmp(["ps", "stop", "--dir", cwd, "--", name], timeoutMs),
603
+ stop: (target, cwd, timeoutMs) => runOmp(["ps", "stop", "--dir", cwd, "--", target], timeoutMs),
368
604
  sleep: waitMs,
369
605
  now: () => Date.now(),
370
606
  };
371
607
  }
372
608
 
609
+ // omp 19 lets a unit's log grow to 25 MiB before rotating it, so read only the tail.
610
+ async function readLogTail(path: string): Promise<{ content: string; truncated: boolean }> {
611
+ const file = await open(path, "r");
612
+ try {
613
+ const { size } = await file.stat();
614
+ const truncated = size > MAX_LOG_BYTES;
615
+ const length = Math.min(size, MAX_LOG_BYTES);
616
+ const buffer = Buffer.alloc(length);
617
+ const { bytesRead } = await file.read(buffer, 0, length, size - length);
618
+ return { content: buffer.subarray(0, bytesRead).toString("utf8"), truncated };
619
+ } finally {
620
+ await file.close();
621
+ }
622
+ }
623
+
373
624
  export async function tailHubLogFrom(
374
625
  root: string,
375
626
  cwd: string,
376
627
  name: string,
628
+ daemonDir?: string,
377
629
  ): Promise<{ content: string; truncated: boolean }> {
630
+ if (daemonDir !== undefined) {
631
+ // omp 19's daemon runs every current service, so its newest record of the name wins.
632
+ const { services } = await scanDaemonServicesFrom(daemonDir, cwd);
633
+ const newest = services
634
+ .filter((service) => service.process.name === name)
635
+ .sort((a, b) => (b.process.startedAt ?? 0) - (a.process.startedAt ?? 0))[0];
636
+ if (newest) {
637
+ // A unit that has not written output yet (or whose log was pruned) has no log to show.
638
+ return readLogTail(newest.log).catch(() => ({ content: "", truncated: false }));
639
+ }
640
+ }
378
641
  const { roots } = await findProjectDaemonRoots(root, cwd);
379
642
  for (const projectRoot of roots) {
380
643
  try {
381
- const buffer = await readFile(join(projectRoot, "daemons", name, "output.log"));
382
- const truncated = buffer.byteLength > MAX_LOG_BYTES;
383
- const slice = truncated ? buffer.subarray(buffer.byteLength - MAX_LOG_BYTES) : buffer;
384
- return { content: slice.toString("utf8"), truncated };
644
+ return await readLogTail(join(projectRoot, "daemons", name, "output.log"));
385
645
  } catch {
386
646
  // This root doesn't have that process (or its log vanished); try the next match.
387
647
  }
@@ -393,5 +653,5 @@ export async function resolveTailHubLog({
393
653
  cwd,
394
654
  name,
395
655
  }: RpcInput<typeof tailHubLog>): Promise<{ content: string; truncated: boolean }> {
396
- return tailHubLogFrom(ompRunDir(), cwd, name);
656
+ return tailHubLogFrom(ompRunDir(), cwd, name, ompDaemonRunDir());
397
657
  }
@@ -3,6 +3,7 @@ import { randomUUID } from "node:crypto";
3
3
  import { tmpdir } from "node:os";
4
4
  import { createInterface } from "node:readline";
5
5
  import { z } from "zod";
6
+ import { accountTags } from "../shared/account-tags";
6
7
  import {
7
8
  OMP_ACCOUNTS_SETTING_PATHS,
8
9
  type OmpAccount,
@@ -118,7 +119,16 @@ const UsageReportSchema = z.object({
118
119
  amount: z.object({ usedFraction: UsedFraction.nullish() }).nullish(),
119
120
  }),
120
121
  ).nullish(),
121
- metadata: z.object({ accountId: z.string().nullish(), orgId: z.string().nullish() }).nullish(),
122
+ metadata: z
123
+ .object({
124
+ accountId: z.string().nullish(),
125
+ orgId: z.string().nullish(),
126
+ email: z.string().nullish(),
127
+ plan: z.string().nullish(),
128
+ planType: z.string().nullish(),
129
+ orgName: z.string().nullish(),
130
+ })
131
+ .nullish(),
122
132
  });
123
133
  type UsageReport = z.infer<typeof UsageReportSchema>;
124
134
  const UsageSchema = z.object({ reports: entries(UsageReportSchema).nullish() });
@@ -578,6 +588,7 @@ export function joinAccounts(
578
588
  credentialId: login.credentialId,
579
589
  oauth: false,
580
590
  label: login.label,
591
+ tags: [],
581
592
  limits: [],
582
593
  usageAt: null,
583
594
  usageIsRecorded: false,
@@ -608,7 +619,7 @@ export function joinAccounts(
608
619
  provider: login.provider,
609
620
  credentialId: login.credentialId,
610
621
  oauth: true,
611
- label: login.label,
622
+ ...labelWithTags(login.label, report),
612
623
  limits: recorded?.limits ?? live,
613
624
  usageAt: recorded?.at ?? report?.fetchedAt ?? null,
614
625
  usageIsRecorded: recorded !== null,
@@ -621,6 +632,30 @@ export function joinAccounts(
621
632
  );
622
633
  }
623
634
 
635
+ /**
636
+ * Plan and organization badges from the login's usage report. OMP appends the organization to the
637
+ * label in parentheses (`email (org)`); once a badge shows it, the suffix only repeats it.
638
+ */
639
+ function labelWithTags(
640
+ label: string,
641
+ report: UsageReport | undefined,
642
+ ): Pick<OmpAccount, "label" | "tags"> {
643
+ const metadata = report?.metadata;
644
+ const orgName = metadata?.orgName?.trim() || null;
645
+ const tags = accountTags({
646
+ // A blank planType must not hide a plan the report names, as in the quota popover.
647
+ plan: metadata?.planType?.trim() || metadata?.plan?.trim() || null,
648
+ organization: orgName,
649
+ email: metadata?.email?.trim() || null,
650
+ });
651
+ const suffix = orgName ? ` (${orgName})` : null;
652
+ return {
653
+ label:
654
+ tags.length > 0 && suffix && label.endsWith(suffix) ? label.slice(0, -suffix.length) : label,
655
+ tags,
656
+ };
657
+ }
658
+
624
659
  /** Where new sessions would go right now, by OMP's own balancer. */
625
660
  async function previewBalance(
626
661
  command: OmpCommand,
@@ -1,2 +1,2 @@
1
1
  /** Release Please keeps this bundle-safe constant aligned with package.json. */
2
- export const PASEO_OMP_PACKAGE_VERSION = "5.7.0"; // x-release-please-version
2
+ export const PASEO_OMP_PACKAGE_VERSION = "5.8.0-next.536.1"; // x-release-please-version
package/server/paths.ts CHANGED
@@ -183,6 +183,27 @@ export function ompHubRunDir(
183
183
  return join(root, "run", "daemons");
184
184
  }
185
185
 
186
+ /**
187
+ * The run directory of omp 19's single per-user daemon, which owns every service a session
188
+ * starts. Unlike the 18.x brokers it ignores the profile and any agent-dir override, so every
189
+ * omp process on the machine agrees on it (pi-utils `getDaemonDir`, `OMP_DAEMON_DIR` first).
190
+ */
191
+ export function ompDaemonDir(
192
+ environment: NodeJS.ProcessEnv = currentOmpEnvironment(),
193
+ platform: NodeJS.Platform = process.platform,
194
+ ): string {
195
+ if (environment.OMP_DAEMON_DIR) return environment.OMP_DAEMON_DIR;
196
+ const xdgHome = environment.XDG_STATE_HOME;
197
+ if (xdgHome && (platform === "linux" || platform === "darwin")) {
198
+ const xdgRoot = join(xdgHome, "omp");
199
+ if (existsSync(xdgRoot)) return join(xdgRoot, "run", "daemon");
200
+ }
201
+ // OMP uses `os.homedir()`, evaluated in its own environment: libuv reads USERPROFILE first on
202
+ // Windows (a Git Bash HOME there does not count) and HOME first elsewhere.
203
+ const home = (platform === "win32" ? environment.USERPROFILE : environment.HOME) || homedir();
204
+ return join(home, environment.PI_CONFIG_DIR || ".omp", "run", "daemon");
205
+ }
206
+
186
207
  function configuredSessionDir(agentDir: string): string | undefined {
187
208
  for (const settingsPath of [
188
209
  join(agentDir, "settings.json"),
@@ -60,6 +60,9 @@ export const OMP_MESSAGE_REPLAY_POLICIES = {
60
60
  export const OMP_SESSION_EVENT_POLICIES = {
61
61
  agent_start: "lifecycle",
62
62
  agent_end: "lifecycle",
63
+ // OMP 18.21+: a model loop that stopped inside a run that goes on. The RPC wire re-encodes it as
64
+ // `agent_end` with `isTerminal: false`; it arrives raw only inside `subagent_event` payloads.
65
+ agent_pause: "lifecycle",
63
66
  turn_start: "lifecycle",
64
67
  turn_end: "lifecycle",
65
68
  message_start: "normalize",
@@ -231,6 +234,7 @@ export type OmpProtocolDiagnosticPhase = (typeof OMP_PROTOCOL_DIAGNOSTIC_PHASES)
231
234
  export const OMP_PROTOCOL_EVENT_TYPES = [
232
235
  "agent_start",
233
236
  "agent_end",
237
+ "agent_pause",
234
238
  "turn_start",
235
239
  "turn_end",
236
240
  "message_start",
@@ -1572,6 +1576,12 @@ const OmpAutoRetryEndEventSchema = z.object({
1572
1576
  });
1573
1577
  const OmpAgentSessionEventSchema = z.discriminatedUnion("type", [
1574
1578
  ...OmpCoreAgentEventSchema.options,
1579
+ z.object({
1580
+ type: z.literal("agent_pause"),
1581
+ messages: z.array(OmpMessageSchema).max(MAX_ARRAY_ITEMS),
1582
+ yielded: z.boolean(),
1583
+ awaiting: z.boolean(),
1584
+ }),
1575
1585
  z.object({ type: z.literal("config_warnings_changed") }),
1576
1586
  z.object({ type: z.literal("advisor_cost_changed") }),
1577
1587
  z.object({ type: z.literal("cache_warming_start") }),
@@ -1897,6 +1907,7 @@ function mapAgentEventDetails(
1897
1907
  case "tool_execution_end":
1898
1908
  return mapRecordField(frame, "result", map, frame.toolName === "task");
1899
1909
  case "agent_end":
1910
+ case "agent_pause":
1900
1911
  return mapRecordField(frame, "messages", (messages) => mapMessageList(messages, map));
1901
1912
  case "irc_message":
1902
1913
  return mapRecordField(frame, "message", map);
@@ -7,7 +7,7 @@ import {
7
7
  ownedHubCleanupDependencies,
8
8
  stopOwnedHubProcesses,
9
9
  } from "../hub";
10
- import { ompDataDir, ompHubRunDir } from "../paths";
10
+ import { ompDaemonDir, ompDataDir, ompHubRunDir } from "../paths";
11
11
  import { defaultSpawn, runBounded } from "../provider-diagnostics";
12
12
  import {
13
13
  buildOmpSpawnRequest,
@@ -189,6 +189,8 @@ export interface OmpRpcRuntimeOptions {
189
189
  timeoutMs: number,
190
190
  ) => Promise<boolean>;
191
191
  hubRunDir?: string;
192
+ /** omp 19's per-user daemon directory; defaults to the one the session's environment selects (`PASEO_OMP_DAEMON_DIR` is test-only). */
193
+ hubDaemonDir?: string;
192
194
  }
193
195
 
194
196
  const OMP_COMMAND_TIMEOUT_MS = 15_000;
@@ -710,6 +712,7 @@ export class OmpRpcRuntime implements OmpRuntime {
710
712
  (args, timeoutMs) =>
711
713
  run(request.command, [...prefix, ...args], env, request.cwd, timeoutMs),
712
714
  this.options.hubRunDir ?? process.env.PASEO_OMP_RUN_DIR ?? ompHubRunDir(env),
715
+ this.options.hubDaemonDir ?? (process.env.PASEO_OMP_DAEMON_DIR || ompDaemonDir(env)),
713
716
  ),
714
717
  );
715
718
  }