paseo-office 0.2.0 → 0.2.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 (143) hide show
  1. package/OVERVIEW.md +27 -0
  2. package/README.md +65 -134
  3. package/client/action-button.tsx +4 -1
  4. package/client/activity-panel.tsx +6 -4
  5. package/client/agent-appearance.tsx +257 -0
  6. package/client/agent-card.tsx +2 -1
  7. package/client/agent-picker-text.ts +23 -4
  8. package/client/agent-picker.tsx +5 -8
  9. package/client/board-sheet.tsx +48 -16
  10. package/client/board-text.ts +12 -2
  11. package/client/brand.ts +1 -0
  12. package/client/chat-chrome.tsx +318 -0
  13. package/client/chat-compose-tools.tsx +314 -0
  14. package/client/chat-dictation.tsx +133 -0
  15. package/client/chat-more.tsx +119 -0
  16. package/client/chat-panel.tsx +401 -146
  17. package/client/chat-quick.tsx +198 -0
  18. package/client/chat-text.ts +25 -6
  19. package/client/column-sheet.tsx +93 -23
  20. package/client/conversation-model.ts +19 -5
  21. package/client/duty-sheet.tsx +321 -0
  22. package/client/duty-text.ts +20 -0
  23. package/client/fullscreen-header.tsx +28 -13
  24. package/client/fullscreen-theme.ts +38 -0
  25. package/client/host-details.tsx +269 -0
  26. package/client/host-styles.ts +129 -0
  27. package/client/host-switches.tsx +212 -83
  28. package/client/incidents-card.tsx +2 -1
  29. package/client/janitor-card.tsx +1 -1
  30. package/client/library-card.tsx +2 -1
  31. package/client/list-text.ts +8 -6
  32. package/client/lobby-board.tsx +73 -53
  33. package/client/machine-card.tsx +225 -85
  34. package/client/messenger-styles.ts +216 -0
  35. package/client/new-agent-form.tsx +153 -61
  36. package/client/new-agent-model.ts +2 -0
  37. package/client/notes-card.tsx +111 -83
  38. package/client/notes-days.tsx +1 -1
  39. package/client/office-brand-context.ts +44 -0
  40. package/client/office-column.tsx +2 -1
  41. package/client/office-keyboard.ts +79 -0
  42. package/client/office-link.ts +7 -1
  43. package/client/office-mark.tsx +29 -0
  44. package/client/office-modal.tsx +440 -0
  45. package/client/office-settings.tsx +75 -30
  46. package/client/office-state.ts +12 -2
  47. package/client/office-surface.tsx +591 -81
  48. package/client/pixel/actors.ts +2 -1
  49. package/client/pixel/art.ts +33 -19
  50. package/client/pixel/pixel-office.tsx +2 -2
  51. package/client/prompt-coach.tsx +152 -0
  52. package/client/qa-card.tsx +2 -1
  53. package/client/review-card.tsx +2 -1
  54. package/client/room-board.tsx +26 -2
  55. package/client/scene-picker.tsx +158 -0
  56. package/client/scene-previews.ts +10 -0
  57. package/client/session-pane.tsx +25 -5
  58. package/client/session-panel-detail.tsx +238 -0
  59. package/client/session-panel.tsx +222 -137
  60. package/client/session-styles.ts +224 -1
  61. package/client/session-transcript.tsx +243 -0
  62. package/client/sessions-panel.tsx +181 -22
  63. package/client/sessions-text.ts +18 -0
  64. package/client/settings-sections.tsx +126 -0
  65. package/client/sidebar-launcher.ts +29 -0
  66. package/client/ssh-hosts.tsx +331 -0
  67. package/client/ssh-metrics.ts +76 -0
  68. package/client/standup-card.tsx +2 -1
  69. package/client/structure-view.tsx +20 -3
  70. package/client/styles.ts +170 -62
  71. package/client/team-chat-preview.tsx +96 -0
  72. package/client/tracker-connections.tsx +252 -0
  73. package/client/transcript-styles.ts +90 -0
  74. package/client/use-device-switch.ts +21 -12
  75. package/client/use-duty-actions.ts +43 -0
  76. package/client/use-group-photo.ts +48 -0
  77. package/client/use-new-agent.ts +4 -0
  78. package/client/use-street.ts +8 -0
  79. package/client/workspace-office-tools.tsx +102 -0
  80. package/client/workspace-overlay-route.web.ts +47 -0
  81. package/client/workspace-overlay.tsx +195 -0
  82. package/client/world/adapter.ts +37 -2
  83. package/client/world/escape.ts +58 -0
  84. package/client/world/use-world-feed.ts +6 -2
  85. package/client/world/workspace-dock.ts +6 -0
  86. package/client/world/world-api.ts +45 -4
  87. package/client/world/world-bridge-page.ts +14 -3
  88. package/client/world/world-bridge.ts +50 -5
  89. package/client/world/world-frame.web.ts +8 -0
  90. package/client/world/world-view-native.tsx +31 -10
  91. package/client/world/world-view-shared.ts +36 -7
  92. package/client/world/world-view.tsx +93 -21
  93. package/docs/office.md +165 -64
  94. package/index.client.tsx +13 -6
  95. package/index.server.ts +232 -16
  96. package/package.json +2 -1
  97. package/server/activity.ts +42 -19
  98. package/server/agent-tools.ts +11 -5
  99. package/server/board-service.ts +381 -10
  100. package/server/brand-logo.ts +34 -0
  101. package/server/chat-group.ts +83 -0
  102. package/server/chat-service.ts +406 -62
  103. package/server/chat-store.ts +1 -4
  104. package/server/directory.ts +22 -7
  105. package/server/duty-service.ts +230 -0
  106. package/server/group-photo.ts +39 -0
  107. package/server/home-departure.ts +47 -0
  108. package/server/hub.ts +43 -1
  109. package/server/incidents-jira.ts +19 -7
  110. package/server/incidents-schedule.ts +10 -10
  111. package/server/incidents-sentry.ts +34 -8
  112. package/server/live-ports.ts +114 -18
  113. package/server/lobby-pickup.ts +170 -0
  114. package/server/machine/details.ts +91 -0
  115. package/server/mention-queue.ts +14 -0
  116. package/server/office.ts +110 -6
  117. package/server/paths.ts +14 -0
  118. package/server/ssh/LICENSE.paseo +211 -0
  119. package/server/ssh/client.ts +401 -0
  120. package/server/ssh/discovery.ts +230 -0
  121. package/server/ssh/installed.ts +104 -0
  122. package/server/ssh/monitor.ts +104 -0
  123. package/server/ssh/pid-files.ts +194 -0
  124. package/server/ssh/read.ts +136 -0
  125. package/server/subagent-names.ts +4 -0
  126. package/server/tracker-credentials.ts +141 -0
  127. package/server/words.generated.ts +1 -1
  128. package/server/world.generated.ts +1 -1
  129. package/shared/appearance.ts +43 -0
  130. package/shared/branding.ts +53 -0
  131. package/shared/chat-words.ts +2 -2
  132. package/shared/contracts.ts +199 -5
  133. package/shared/duties.ts +100 -0
  134. package/shared/host-details.ts +25 -0
  135. package/shared/lobby-assignment.ts +34 -0
  136. package/shared/model.ts +9 -1
  137. package/shared/names.ts +2 -0
  138. package/shared/settings.ts +14 -3
  139. package/shared/ssh.ts +34 -0
  140. package/shared/upstream/README.md +1 -3
  141. package/shared/upstream/chat-engine.d.ts +4 -0
  142. package/shared/upstream/prompt-coach.d.ts +6 -0
  143. package/shared/upstream/prompt-coach.js +178 -0
@@ -0,0 +1,104 @@
1
+ import { constants } from "node:fs";
2
+ import { access, readFile, readdir, stat } from "node:fs/promises";
3
+ import { basename, delimiter, isAbsolute, join } from "node:path";
4
+
5
+ interface Launch {
6
+ command: string;
7
+ args: string[];
8
+ }
9
+
10
+ async function usable(file: string, mode: number): Promise<boolean> {
11
+ try {
12
+ await access(file, mode);
13
+ return (await stat(file)).isFile();
14
+ } catch {
15
+ return false;
16
+ }
17
+ }
18
+
19
+ async function fromPath(command: string, env: NodeJS.ProcessEnv): Promise<string | null> {
20
+ const candidates = isAbsolute(command)
21
+ ? [command]
22
+ : (env.PATH ?? "")
23
+ .split(delimiter)
24
+ .filter(isAbsolute)
25
+ .map((dir) => join(dir, command));
26
+ for (const file of candidates) if (await usable(file, constants.X_OK)) return file;
27
+ return null;
28
+ }
29
+
30
+ // Resolve an npx declaration to an existing installation. Launching npx itself can download
31
+ // and execute a package just because someone opened the Host card.
32
+ async function installedPackage(
33
+ version: string | undefined,
34
+ env: NodeJS.ProcessEnv,
35
+ ): Promise<string | null> {
36
+ if (!version) {
37
+ const binary = await fromPath("ssh-mcp", env);
38
+ if (binary) return binary;
39
+ }
40
+ const cache = env.npm_config_cache ?? (env.HOME && join(env.HOME, ".npm"));
41
+ if (!cache) return null;
42
+ const root = join(cache, "_npx");
43
+ const directories = await readdir(root, { withFileTypes: true }).catch(() => []);
44
+ for (const dir of directories) {
45
+ if (!dir.isDirectory()) continue;
46
+ const modules = join(root, dir.name, "node_modules");
47
+ try {
48
+ const pkg = JSON.parse(await readFile(join(modules, "ssh-mcp", "package.json"), "utf8"));
49
+ if (pkg.name !== "ssh-mcp" || (version && pkg.version !== version)) continue;
50
+ const binary = join(modules, ".bin", "ssh-mcp");
51
+ if (await usable(binary, constants.X_OK)) return binary;
52
+ } catch {
53
+ /* A cache entry may hold any package. */
54
+ }
55
+ }
56
+ return null;
57
+ }
58
+
59
+ const packageName = /^ssh-mcp(?:@(\d+\.\d+\.\d+(?:-[\w.-]+)?))?$/;
60
+ // Some trusted workspaces use a shell only to expand HOME in the config path. Recognise that
61
+ // declaration without executing shell code, redirects, substitutions, or other commands.
62
+ const shellDeclaration =
63
+ /^(?:exec )?npx (?:-y |--yes )?(ssh-mcp(?:@[\w.-]+)?) --config="\$HOME(\/[\w./ -]+)"$/;
64
+
65
+ async function npxLaunch(args: string[], env: NodeJS.ProcessEnv): Promise<Launch | null> {
66
+ const offset = args[0] === "-y" || args[0] === "--yes" ? 1 : 0;
67
+ const match = packageName.exec(args[offset] ?? "");
68
+ if (!match) return null;
69
+ const binary = await installedPackage(match[1], env);
70
+ if (!binary) return null;
71
+ const start = offset + 1;
72
+ return { command: binary, args: args.slice(args[start] === "--" ? start + 1 : start) };
73
+ }
74
+
75
+ export async function installedLaunch(
76
+ command: string,
77
+ args: string[],
78
+ env: NodeJS.ProcessEnv,
79
+ ): Promise<Launch | null> {
80
+ const name = basename(command);
81
+ if (name === "ssh-mcp") {
82
+ const binary = await fromPath(command, env);
83
+ return binary ? { command: binary, args } : null;
84
+ }
85
+ if (
86
+ name === "node" &&
87
+ args[0] &&
88
+ isAbsolute(args[0]) &&
89
+ /[/\\]ssh-mcp[/\\](build|dist)[/\\]index\.js$/.test(args[0])
90
+ ) {
91
+ return (await usable(args[0], constants.R_OK)) ? { command: process.execPath, args } : null;
92
+ }
93
+ if (
94
+ (name === "sh" || name === "bash") &&
95
+ (args[0] === "-c" || args[0] === "-lc") &&
96
+ args.length === 2
97
+ ) {
98
+ const match = shellDeclaration.exec(args[1]);
99
+ if (!match || !env.HOME) return null;
100
+ return installedLaunch("npx", [match[1], "--config=" + join(env.HOME, match[2])], env);
101
+ }
102
+ if (name !== "npx") return null;
103
+ return npxLaunch(args, env);
104
+ }
@@ -0,0 +1,104 @@
1
+ import { join } from "node:path";
2
+ import type { SshDiscovery, SshReading } from "../../shared/ssh.js";
3
+ import type { Paseo } from "../paseo-holder.js";
4
+ import { officeDir, claudeConfigFile } from "../paths.js";
5
+ import { startMcpStdioClient, serverEnv } from "./client.js";
6
+ import { discoverSshServers, type SshServer } from "./discovery.js";
7
+ import { listPidFiles, reclaimPidFile } from "./pid-files.js";
8
+ import { readSshHosts, UNAVAILABLE } from "./read.js";
9
+
10
+ export function createSshMonitor(env: NodeJS.ProcessEnv, home: string, procRoot: string) {
11
+ const runDir = join(officeDir(env, home), "ssh-run");
12
+ const active = new Map<string, { cancel: AbortController; result: Promise<SshReading> }>();
13
+ let stopped = false;
14
+ let reclaiming: Promise<unknown> | undefined;
15
+ async function findServers(paseo: Paseo) {
16
+ const directories = new Set<string>();
17
+ let cursor: string | undefined;
18
+ let incomplete = false;
19
+ try {
20
+ do {
21
+ const page = await paseo.workspaces.list({ page: { limit: 200, cursor } });
22
+ for (const entry of page.entries)
23
+ directories.add(entry.workspaceDirectory ?? entry.projectRootPath);
24
+ cursor = page.pageInfo.hasMore ? (page.pageInfo.nextCursor ?? undefined) : undefined;
25
+ } while (cursor);
26
+ } catch {
27
+ incomplete = true;
28
+ }
29
+ const result = await discoverSshServers({
30
+ claudeConfigFile: claudeConfigFile(env, home),
31
+ workspaceDirectories: [...directories],
32
+ env: serverEnv({}, env),
33
+ });
34
+ return {
35
+ servers: result.servers,
36
+ discoveryIncomplete: incomplete || result.problems.length > 0,
37
+ };
38
+ }
39
+
40
+ // The UI reads each entry separately. Concurrent requests share the same filesystem scan.
41
+ let scanning: ReturnType<typeof findServers> | null = null;
42
+ function discover(paseo: Paseo) {
43
+ scanning ??= findServers(paseo).finally(() => {
44
+ scanning = null;
45
+ });
46
+ return scanning;
47
+ }
48
+
49
+ async function poll(server: SshServer, signal: AbortSignal): Promise<SshReading> {
50
+ try {
51
+ reclaiming ??= Promise.all(
52
+ listPidFiles(runDir).map((name) => reclaimPidFile(join(runDir, name), procRoot)),
53
+ );
54
+ await reclaiming;
55
+ const client = await startMcpStdioClient(
56
+ server,
57
+ {
58
+ runDir,
59
+ procRoot,
60
+ name: server.id,
61
+ baseEnv: env,
62
+ startTimeoutMs: 8_000,
63
+ requestTimeoutMs: 12_000,
64
+ },
65
+ signal,
66
+ );
67
+ const close = () => {
68
+ void client.close();
69
+ };
70
+ signal.addEventListener("abort", close, { once: true });
71
+ try {
72
+ return signal.aborted ? UNAVAILABLE : await readSshHosts(client, server.name);
73
+ } finally {
74
+ signal.removeEventListener("abort", close);
75
+ await client.close();
76
+ }
77
+ } catch {
78
+ return UNAVAILABLE;
79
+ }
80
+ }
81
+ return {
82
+ async list(paseo: Paseo): Promise<SshDiscovery> {
83
+ const { servers, discoveryIncomplete } = await discover(paseo);
84
+ return { servers: servers.map(({ id, name }) => ({ id, name })), discoveryIncomplete };
85
+ },
86
+ async read(paseo: Paseo, id: string): Promise<SshReading> {
87
+ const { servers } = await discover(paseo);
88
+ const server = servers.find((entry) => entry.id === id);
89
+ if (stopped || !server || server.missingVariables.length) return UNAVAILABLE;
90
+ const key = server.id + server.fingerprint;
91
+ const current = active.get(key);
92
+ if (current) return current.result;
93
+ const cancel = new AbortController();
94
+ const result = poll(server, cancel.signal).finally(() => active.delete(key));
95
+ active.set(key, { cancel, result });
96
+ return result;
97
+ },
98
+ async stop() {
99
+ stopped = true;
100
+ for (const work of active.values()) work.cancel.abort();
101
+ await Promise.all([...active.values()].map((work) => work.result));
102
+ },
103
+ };
104
+ }
@@ -0,0 +1,194 @@
1
+ // Adapted from Paseo Resource Manager. See LICENSE.paseo.
2
+ import {
3
+ readdirSync,
4
+ readFileSync,
5
+ readlinkSync,
6
+ renameSync,
7
+ rmSync,
8
+ writeFileSync,
9
+ } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { setTimeout as delay } from "node:timers/promises";
12
+ import { z } from "zod";
13
+ import { parseStat } from "../machine/proc.js";
14
+
15
+ // The record shared-mcp writes (plugins/shared-mcp/server/process-runner.ts:56-64), so one reader
16
+ // serves both plugins' files. startTime is field 22 of /proc/<pid>/stat: with ownerPid it tells a
17
+ // file left by a dead daemon from one a live daemon owns, and a group from a later process that
18
+ // reuses its pid. pidNamespace, bootId and initStartTime say which processes the pids name: after
19
+ // a container restart or a reboot the same pids name others. A record lacking any of them is stale.
20
+ export const PidRecordSchema = z.object({
21
+ pgid: z.number().int(),
22
+ startTime: z.number().int().nullable(),
23
+ ownerPid: z.number().int().positive(),
24
+ ownerStartTime: z.number().int().nullable(),
25
+ pidNamespace: z.string().nullish(),
26
+ bootId: z.string().nullish(),
27
+ initStartTime: z.number().int().nullish(),
28
+ });
29
+ export type PidRecord = z.output<typeof PidRecordSchema>;
30
+
31
+ export interface PidSpace {
32
+ pidNamespace: string | null;
33
+ bootId: string | null;
34
+ initStartTime: number | null;
35
+ }
36
+
37
+ export type ReclaimOutcome = "kept" | "stale" | "killed";
38
+
39
+ const KILL_GRACE_MS = 2_000;
40
+ const POLL_MS = 50;
41
+ const PID_FILE = /\.pid$/;
42
+
43
+ function readOrNull(read: () => string): string | null {
44
+ try {
45
+ return read();
46
+ } catch {
47
+ return null;
48
+ }
49
+ }
50
+
51
+ export function readStartTime(pid: number, procRoot: string): number | null {
52
+ const stat = readOrNull(() => readFileSync(join(procRoot, String(pid), "stat"), "utf8"));
53
+ if (stat === null) return null;
54
+ return parseStat(stat)?.startTime ?? null;
55
+ }
56
+
57
+ // The pid namespace (`pid:[<inode>]`), the boot this process runs in, and the start time of the
58
+ // namespace's pid 1 (a namespace inode can be reissued to a restarted container on the same boot,
59
+ // whose pid 1 starts later). Each is null without /proc.
60
+ export function readPidSpace(procRoot: string): PidSpace {
61
+ return {
62
+ pidNamespace: readOrNull(() => readlinkSync(join(procRoot, "self", "ns", "pid"))),
63
+ bootId: readOrNull(() =>
64
+ readFileSync(join(procRoot, "sys", "kernel", "random", "boot_id"), "utf8").trim(),
65
+ ),
66
+ initStartTime: readStartTime(1, procRoot),
67
+ };
68
+ }
69
+
70
+ // False when the record comes from another pid namespace, boot or container run, does not say,
71
+ // or this process cannot tell its own.
72
+ export function isCurrentPidSpace(record: PidRecord, procRoot: string): boolean {
73
+ const current = readPidSpace(procRoot);
74
+ return (
75
+ current.pidNamespace !== null &&
76
+ current.bootId !== null &&
77
+ current.initStartTime !== null &&
78
+ record.pidNamespace === current.pidNamespace &&
79
+ record.bootId === current.bootId &&
80
+ record.initStartTime === current.initStartTime
81
+ );
82
+ }
83
+
84
+ // false when the target is gone (ESRCH) or belongs to someone else (EPERM).
85
+ export function sendSignal(target: number, signal: NodeJS.Signals | 0): boolean {
86
+ try {
87
+ process.kill(target, signal);
88
+ return true;
89
+ } catch {
90
+ return false;
91
+ }
92
+ }
93
+
94
+ // The same pid as this process means an earlier plugin run in this daemon, or a dead daemon whose
95
+ // pid this one reused: both are gone.
96
+ export function ownerIsAlive(record: PidRecord, procRoot: string, selfPid = process.pid): boolean {
97
+ if (record.ownerPid === selfPid) return false;
98
+ if (record.ownerStartTime === null) return sendSignal(record.ownerPid, 0);
99
+ return readStartTime(record.ownerPid, procRoot) === record.ownerStartTime;
100
+ }
101
+
102
+ // A live leader must match the recorded start time. A live group whose leader has exited is taken
103
+ // to be the recorded one: the kernel does not reuse a pid while a group with that id exists, so
104
+ // this holds only while the group has never emptied. Same rule, and same limit, as shared-mcp's
105
+ // isRecordedGroup in process-runner.ts.
106
+ export function isRecordedGroup(record: PidRecord, procRoot: string): boolean {
107
+ if (record.startTime === null || !sendSignal(-record.pgid, 0)) return false;
108
+ const leaderStartTime = readStartTime(record.pgid, procRoot);
109
+ return leaderStartTime === null || leaderStartTime === record.startTime;
110
+ }
111
+
112
+ // Written through a rename, so a daemon that dies mid-write leaves a stray .tmp file and never a
113
+ // truncated pid file. Throws when the file cannot be written; the caller kills the group then.
114
+ export function writePidFile(file: string, pgid: number, procRoot: string): void {
115
+ const record: PidRecord = {
116
+ pgid,
117
+ startTime: readStartTime(pgid, procRoot),
118
+ ownerPid: process.pid,
119
+ ownerStartTime: readStartTime(process.pid, procRoot),
120
+ ...readPidSpace(procRoot),
121
+ };
122
+ const tmpFile = `${file}.tmp`;
123
+ writeFileSync(tmpFile, `${JSON.stringify(record)}\n`, { mode: 0o600 });
124
+ renameSync(tmpFile, file);
125
+ }
126
+
127
+ function parseJson(text: string): unknown {
128
+ try {
129
+ return JSON.parse(text);
130
+ } catch {
131
+ return undefined;
132
+ }
133
+ }
134
+
135
+ // null for a missing file and for one that does not hold a record.
136
+ export function readPidRecord(file: string): PidRecord | null {
137
+ const text = readOrNull(() => readFileSync(file, "utf8"));
138
+ if (text === null) return null;
139
+ const record = PidRecordSchema.safeParse(parseJson(text));
140
+ return record.success ? record.data : null;
141
+ }
142
+
143
+ // Throws when an existing file cannot be removed (EACCES, or a directory named *.pid).
144
+ export function removePidFile(file: string): void {
145
+ rmSync(file, { force: true });
146
+ }
147
+
148
+ export function listPidFiles(dir: string): string[] {
149
+ let names: string[];
150
+ try {
151
+ names = readdirSync(dir);
152
+ } catch {
153
+ return [];
154
+ }
155
+ return names.filter((name) => PID_FILE.test(name)).sort();
156
+ }
157
+
158
+ // SIGTERM to the group, then SIGKILL once graceMs passes with a member left. A pgid of 1 or less
159
+ // is never signalled: kill(-0) would reach this daemon's own group, kill(-1) every process the
160
+ // daemon may signal, and a negative pgid a single pid. The waits are unref'd, so a pending kill
161
+ // never holds the daemon open.
162
+ export async function killGroup(pgid: number, graceMs = KILL_GRACE_MS): Promise<void> {
163
+ if (pgid <= 1 || !sendSignal(-pgid, "SIGTERM")) return;
164
+ const deadline = Date.now() + graceMs;
165
+ while (sendSignal(-pgid, 0)) {
166
+ if (Date.now() >= deadline) {
167
+ sendSignal(-pgid, "SIGKILL");
168
+ return;
169
+ }
170
+ await delay(POLL_MS, undefined, { ref: false });
171
+ }
172
+ }
173
+
174
+ // A file from another pid space, or naming no live recorded group, is stale and only removed. A
175
+ // file whose owner is dead and whose group is still the recorded one gets the group killed first.
176
+ // A file whose owner lives is left alone: another daemon on the same PASEO_HOME owns it.
177
+ // Rejects when the file cannot be removed (removePidFile).
178
+ export async function reclaimPidFile(
179
+ file: string,
180
+ procRoot: string,
181
+ selfPid = process.pid,
182
+ ): Promise<ReclaimOutcome> {
183
+ const record = readPidRecord(file);
184
+ if (record !== null && record.pgid > 1 && isCurrentPidSpace(record, procRoot)) {
185
+ if (ownerIsAlive(record, procRoot, selfPid)) return "kept";
186
+ if (isRecordedGroup(record, procRoot)) {
187
+ await killGroup(record.pgid);
188
+ removePidFile(file);
189
+ return "killed";
190
+ }
191
+ }
192
+ removePidFile(file);
193
+ return "stale";
194
+ }
@@ -0,0 +1,136 @@
1
+ // Adapted from Paseo Resource Manager. See LICENSE.paseo.
2
+ import type { SshHost, SshReading } from "../../shared/ssh.js";
3
+ import { parseMeminfo } from "../machine/proc.js";
4
+ import type { McpStdioClient } from "./client.js";
5
+
6
+ type Reader = Pick<McpStdioClient, "listTools" | "callTool">;
7
+
8
+ // Only aggregate metrics. No client input, process lists, file contents, or config values enter
9
+ // this command. Markers delimit the Linux proc and POSIX df output exactly as in Resources.
10
+ export const METRICS =
11
+ "echo @@mem; cat /proc/meminfo; echo @@load; cat /proc/loadavg; echo @@cores; nproc; echo @@disk; LC_ALL=C df -Pk";
12
+ export const UNAVAILABLE: SshReading = { status: "unavailable", hosts: [] };
13
+
14
+ function empty(name: string): SshHost {
15
+ return {
16
+ name,
17
+ reachable: false,
18
+ memoryUsedBytes: null,
19
+ memoryTotalBytes: null,
20
+ load1: null,
21
+ load5: null,
22
+ load15: null,
23
+ cores: null,
24
+ diskMount: null,
25
+ diskUsedBytes: null,
26
+ diskTotalBytes: null,
27
+ };
28
+ }
29
+
30
+ function parse(name: string, text: string): SshHost {
31
+ const host = empty(name);
32
+ const sections = new Map<string, string[]>();
33
+ let section: string[] | undefined;
34
+ for (const line of text.split(/\r?\n/)) {
35
+ if (line === "[stderr]" || /^\[(exit |killed by SIG)/.test(line)) break;
36
+ if (/^@@(mem|load|cores|disk)$/.test(line)) {
37
+ section = [];
38
+ sections.set(line, section);
39
+ } else {
40
+ section?.push(line);
41
+ }
42
+ }
43
+ const memory = parseMeminfo((sections.get("@@mem") ?? []).join("\n"));
44
+ if (memory && Number.isSafeInteger(memory.totalBytes) && Number.isSafeInteger(memory.usedBytes)) {
45
+ host.memoryUsedBytes = memory.usedBytes;
46
+ host.memoryTotalBytes = memory.totalBytes;
47
+ }
48
+ const loads = sections.get("@@load")?.[0]?.trim().split(/\s+/).slice(0, 3).map(Number);
49
+ if (loads?.length === 3 && loads.every((value) => Number.isFinite(value) && value >= 0)) {
50
+ [host.load1, host.load5, host.load15] = loads;
51
+ }
52
+ const cores = Number(sections.get("@@cores")?.[0]);
53
+ if (Number.isSafeInteger(cores) && cores > 0) host.cores = cores;
54
+ fullestDisk(host, sections.get("@@disk") ?? []);
55
+ host.reachable = [host.memoryTotalBytes, host.load1, host.cores, host.diskTotalBytes].some(
56
+ (metric) => metric !== null,
57
+ );
58
+ return host;
59
+ }
60
+
61
+ function fullestDisk(host: SshHost, lines: string[]): void {
62
+ let highest = -1;
63
+ for (const row of lines) {
64
+ const [device, total, used, , percent, ...mount] = row.trim().split(/\s+/);
65
+ if (
66
+ !mount.length ||
67
+ !/^\d+%$/.test(percent) ||
68
+ /^(tmpfs|devtmpfs|shm|udev|none|efivarfs)$/.test(device)
69
+ )
70
+ continue;
71
+ const totalBytes = Number(total) * 1024;
72
+ const usedBytes = Number(used) * 1024;
73
+ if (
74
+ !Number.isSafeInteger(totalBytes) ||
75
+ totalBytes <= 0 ||
76
+ !Number.isSafeInteger(usedBytes) ||
77
+ usedBytes < 0
78
+ )
79
+ continue;
80
+ const fraction = usedBytes / totalBytes;
81
+ if (fraction <= highest) continue;
82
+ highest = fraction;
83
+ host.diskMount = mount.join(" ");
84
+ host.diskUsedBytes = usedBytes;
85
+ host.diskTotalBytes = totalBytes;
86
+ }
87
+ }
88
+
89
+ async function readHost(
90
+ client: Reader,
91
+ run: string,
92
+ name: string,
93
+ profile?: string,
94
+ ): Promise<SshHost> {
95
+ try {
96
+ const result = await client.callTool(
97
+ run,
98
+ profile ? { command: METRICS, profile } : { command: METRICS },
99
+ );
100
+ return parse(name, result.text);
101
+ } catch {
102
+ return empty(name);
103
+ }
104
+ }
105
+
106
+ export async function readSshHosts(client: Reader, name: string): Promise<SshReading> {
107
+ const tools = await client.listTools();
108
+ const run = ["run-command", "exec"].find((tool) => tools.includes(tool));
109
+ if (!run) return UNAVAILABLE;
110
+ if (!tools.includes("list-connections"))
111
+ return { status: "ok", hosts: [await readHost(client, run, name)] };
112
+ const result = await client.callTool("list-connections", {});
113
+ if (result.isError) {
114
+ if (result.text.includes("No config file found and missing required --host/--user."))
115
+ return { status: "ok", hosts: [] };
116
+ return UNAVAILABLE;
117
+ }
118
+ const profiles = new Set<string>();
119
+ for (const line of result.text.split(/\r?\n/)) {
120
+ if (!line.trim()) continue;
121
+ const profile = /^(.+?): \S+@\S+:\d+ \[[^\]]*\] sessions=\d+ role=.*$/.exec(line)?.[1];
122
+ if (!profile) return UNAVAILABLE;
123
+ profiles.add(profile);
124
+ }
125
+ // Bound simultaneous SSH connections while retaining the MCP profile order in the card.
126
+ const names = [...profiles];
127
+ const hosts: SshHost[] = [];
128
+ const concurrency = 4;
129
+ for (let start = 0; start < names.length; start += concurrency) {
130
+ const batch = names.slice(start, start + concurrency);
131
+ hosts.push(
132
+ ...(await Promise.all(batch.map((profile) => readHost(client, run, profile, profile)))),
133
+ );
134
+ }
135
+ return { status: "ok", hosts };
136
+ }
@@ -72,6 +72,10 @@ export function officeNames(agents: readonly OfficeAgent[]): Map<string, string>
72
72
  const byId = new Map(agents.map((agent) => [agent.id, agent]));
73
73
  const names = new Map<string, string>();
74
74
  const nameOf = (agent: OfficeAgent, seen: Set<string>): string | null => {
75
+ if (agent.appearance?.name) {
76
+ names.set(agent.id, agent.appearance.name);
77
+ return agent.appearance.name;
78
+ }
75
79
  const known = names.get(agent.id);
76
80
  if (known !== undefined) return known;
77
81
  const parentId = agent.parentAgentId;
@@ -0,0 +1,141 @@
1
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
2
+ import { dirname } from "node:path";
3
+ import { z } from "zod";
4
+ import type { IncidentSource, TrackersChange } from "../shared/contracts.js";
5
+ import { isTokenSafe } from "../shared/settings.js";
6
+ import { jiraEnv, type JiraEnv } from "./incidents-jira.js";
7
+ import { sentryToken } from "./incidents-sentry.js";
8
+
9
+ const SavedTrackersSchema = z.object({
10
+ version: z.literal(1),
11
+ jira: z.object({ baseUrl: z.string(), email: z.string(), token: z.string() }).optional(),
12
+ sentry: z.object({ token: z.string() }).optional(),
13
+ });
14
+ /** The connections saved from the settings. They hold tokens: never sent to a client or logged. */
15
+ export type SavedTrackers = z.output<typeof SavedTrackersSchema>;
16
+
17
+ export const NO_SAVED_TRACKERS: SavedTrackers = { version: 1 };
18
+
19
+ export interface TrackerCredentialsStore {
20
+ /** A missing or unreadable file is no saved connection; any other read error rejects. */
21
+ load(): Promise<SavedTrackers>;
22
+ /** Rejects when the write fails. */
23
+ save(saved: SavedTrackers): Promise<void>;
24
+ }
25
+
26
+ function isMissing(error: unknown): boolean {
27
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
28
+ }
29
+
30
+ /** The file is written for its owner only, and replaced whole so its mode is always that. */
31
+ export function createTrackerCredentialsStore(options: {
32
+ file: string;
33
+ log(message: string): void;
34
+ }): TrackerCredentialsStore {
35
+ const { file, log } = options;
36
+ let temp = 0;
37
+
38
+ async function load(): Promise<SavedTrackers> {
39
+ let text: string;
40
+ try {
41
+ text = await readFile(file, "utf8");
42
+ } catch (error) {
43
+ if (isMissing(error)) return NO_SAVED_TRACKERS;
44
+ throw error;
45
+ }
46
+ let json: unknown;
47
+ try {
48
+ json = JSON.parse(text);
49
+ } catch (error) {
50
+ if (!(error instanceof SyntaxError)) throw error;
51
+ json = null;
52
+ }
53
+ const parsed = SavedTrackersSchema.safeParse(json);
54
+ if (parsed.success) return parsed.data;
55
+ // Only that it is unreadable: a parse error's message quotes the file, which holds tokens.
56
+ log(`[office] ${file} is unreadable; no tracker connection is saved until the next save`);
57
+ return NO_SAVED_TRACKERS;
58
+ }
59
+
60
+ async function save(saved: SavedTrackers): Promise<void> {
61
+ temp += 1;
62
+ const tempFile = `${file}.tmp-${temp}`;
63
+ await mkdir(dirname(file), { recursive: true });
64
+ try {
65
+ await writeFile(tempFile, `${JSON.stringify(saved)}\n`, { encoding: "utf8", mode: 0o600 });
66
+ await rename(tempFile, file);
67
+ } catch (error) {
68
+ await rm(tempFile, { force: true }).catch(() => undefined);
69
+ throw error;
70
+ }
71
+ }
72
+
73
+ return { load, save };
74
+ }
75
+
76
+ /** Where a tracker's sign-in comes from: the settings' saved connection, or the daemon's environment. */
77
+ export type CredentialSource = "saved" | "env";
78
+
79
+ interface Sourced {
80
+ source: CredentialSource;
81
+ /** What a refused token's message tells the owner to check. */
82
+ tokenVariable: string;
83
+ }
84
+
85
+ export interface TrackerCredentials {
86
+ jira: (JiraEnv & Sourced) | null;
87
+ sentry: ({ token: string } & Sourced) | null;
88
+ }
89
+
90
+ /** Each tracker's sign-in: the saved connection, else the daemon's environment, else none. */
91
+ export function trackerCredentials(
92
+ saved: SavedTrackers,
93
+ env: NodeJS.ProcessEnv,
94
+ ): TrackerCredentials {
95
+ const fromEnv = jiraEnv(env);
96
+ const envToken = sentryToken(env);
97
+ let jira: TrackerCredentials["jira"] = null;
98
+ if (saved.jira !== undefined) {
99
+ jira = { ...saved.jira, source: "saved", tokenVariable: "the saved Jira token" };
100
+ } else if (fromEnv !== null) {
101
+ jira = { ...fromEnv, source: "env", tokenVariable: "ATLASSIAN_API_TOKEN" };
102
+ }
103
+ let sentry: TrackerCredentials["sentry"] = null;
104
+ if (saved.sentry !== undefined) {
105
+ sentry = { ...saved.sentry, source: "saved", tokenVariable: "the saved Sentry token" };
106
+ } else if (envToken !== null) {
107
+ sentry = { token: envToken, source: "env", tokenVariable: "SENTRY_AUTH_TOKEN" };
108
+ }
109
+ return { jira, sentry };
110
+ }
111
+
112
+ export type SavedChange = { saved: SavedTrackers } | { problem: string };
113
+
114
+ function without(saved: SavedTrackers, tracker: IncidentSource): SavedTrackers {
115
+ const { [tracker]: _removed, ...kept } = saved;
116
+ return kept;
117
+ }
118
+
119
+ /**
120
+ * `saved` after a change from the settings, or why the change is refused. A Jira save with no
121
+ * token keeps the saved one, so the address or email can change without typing it again.
122
+ */
123
+ export function changeSavedTrackers(saved: SavedTrackers, change: TrackersChange): SavedChange {
124
+ if (change.action === "clear") return { saved: without(saved, change.tracker) };
125
+ const token = change.token.trim();
126
+ if (change.action === "save-sentry") {
127
+ if (token === "") return { problem: "Enter the Sentry auth token" };
128
+ return { saved: { ...saved, sentry: { token } } };
129
+ }
130
+ const baseUrl = change.baseUrl.trim().replace(/\/+$/, "");
131
+ const email = change.email.trim();
132
+ const kept = token === "" ? (saved.jira?.token ?? "") : token;
133
+ if (!isTokenSafe(baseUrl)) {
134
+ return {
135
+ problem: "The Jira address must be an https address (plain http only on this machine)",
136
+ };
137
+ }
138
+ if (email === "") return { problem: "Enter the Jira account's email" };
139
+ if (kept === "") return { problem: "Enter the Jira API token" };
140
+ return { saved: { ...saved, jira: { baseUrl, email, token: kept } } };
141
+ }