@procedures/peer 0.0.0-stage → 0.1.0

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 (135) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/LICENSE +21 -0
  3. package/README.md +725 -2
  4. package/dist/.tsbuildinfo +1 -0
  5. package/dist/connection/index.d.ts +45 -0
  6. package/dist/connection/index.d.ts.map +1 -0
  7. package/dist/connection/index.js +148 -0
  8. package/dist/connection/index.js.map +1 -0
  9. package/dist/discovery/index.d.ts +30 -0
  10. package/dist/discovery/index.d.ts.map +1 -0
  11. package/dist/discovery/index.js +101 -0
  12. package/dist/discovery/index.js.map +1 -0
  13. package/dist/expose.d.ts +14 -0
  14. package/dist/expose.d.ts.map +1 -0
  15. package/dist/expose.js +16 -0
  16. package/dist/expose.js.map +1 -0
  17. package/dist/index.d.ts +15 -0
  18. package/dist/index.d.ts.map +1 -0
  19. package/dist/index.js +20 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/input-schemas.d.ts +21 -0
  22. package/dist/input-schemas.d.ts.map +1 -0
  23. package/dist/input-schemas.js +80 -0
  24. package/dist/input-schemas.js.map +1 -0
  25. package/dist/lockfile.d.ts +48 -0
  26. package/dist/lockfile.d.ts.map +1 -0
  27. package/dist/lockfile.js +115 -0
  28. package/dist/lockfile.js.map +1 -0
  29. package/dist/manifest/index.d.ts +8 -0
  30. package/dist/manifest/index.d.ts.map +1 -0
  31. package/dist/manifest/index.js +8 -0
  32. package/dist/manifest/index.js.map +1 -0
  33. package/dist/manifest/json.d.ts +27 -0
  34. package/dist/manifest/json.d.ts.map +1 -0
  35. package/dist/manifest/json.js +24 -0
  36. package/dist/manifest/json.js.map +1 -0
  37. package/dist/manifest/typescript.d.ts +17 -0
  38. package/dist/manifest/typescript.d.ts.map +1 -0
  39. package/dist/manifest/typescript.js +123 -0
  40. package/dist/manifest/typescript.js.map +1 -0
  41. package/dist/module.d.ts +20 -0
  42. package/dist/module.d.ts.map +1 -0
  43. package/dist/module.js +42 -0
  44. package/dist/module.js.map +1 -0
  45. package/dist/output-schemas.d.ts +21 -0
  46. package/dist/output-schemas.d.ts.map +1 -0
  47. package/dist/output-schemas.js +85 -0
  48. package/dist/output-schemas.js.map +1 -0
  49. package/dist/peer/index.d.ts +47 -0
  50. package/dist/peer/index.d.ts.map +1 -0
  51. package/dist/peer/index.js +234 -0
  52. package/dist/peer/index.js.map +1 -0
  53. package/dist/peer/security.d.ts +25 -0
  54. package/dist/peer/security.d.ts.map +1 -0
  55. package/dist/peer/security.js +58 -0
  56. package/dist/peer/security.js.map +1 -0
  57. package/dist/procedures/index.d.ts +24 -0
  58. package/dist/procedures/index.d.ts.map +1 -0
  59. package/dist/procedures/index.js +15 -0
  60. package/dist/procedures/index.js.map +1 -0
  61. package/dist/procedures/manifest.generate.d.ts +11 -0
  62. package/dist/procedures/manifest.generate.d.ts.map +1 -0
  63. package/dist/procedures/manifest.generate.js +97 -0
  64. package/dist/procedures/manifest.generate.js.map +1 -0
  65. package/dist/procedures/server.call.d.ts +30 -0
  66. package/dist/procedures/server.call.d.ts.map +1 -0
  67. package/dist/procedures/server.call.js +60 -0
  68. package/dist/procedures/server.call.js.map +1 -0
  69. package/dist/procedures/server.connect.d.ts +11 -0
  70. package/dist/procedures/server.connect.d.ts.map +1 -0
  71. package/dist/procedures/server.connect.js +35 -0
  72. package/dist/procedures/server.connect.js.map +1 -0
  73. package/dist/procedures/server.connections.d.ts +22 -0
  74. package/dist/procedures/server.connections.d.ts.map +1 -0
  75. package/dist/procedures/server.connections.js +38 -0
  76. package/dist/procedures/server.connections.js.map +1 -0
  77. package/dist/procedures/server.create.d.ts +20 -0
  78. package/dist/procedures/server.create.d.ts.map +1 -0
  79. package/dist/procedures/server.create.js +64 -0
  80. package/dist/procedures/server.create.js.map +1 -0
  81. package/dist/procedures/server.disconnect.d.ts +11 -0
  82. package/dist/procedures/server.disconnect.d.ts.map +1 -0
  83. package/dist/procedures/server.disconnect.js +22 -0
  84. package/dist/procedures/server.disconnect.js.map +1 -0
  85. package/dist/procedures/server.start.d.ts +13 -0
  86. package/dist/procedures/server.start.d.ts.map +1 -0
  87. package/dist/procedures/server.start.js +179 -0
  88. package/dist/procedures/server.start.js.map +1 -0
  89. package/dist/procedures/server.status.d.ts +12 -0
  90. package/dist/procedures/server.status.d.ts.map +1 -0
  91. package/dist/procedures/server.status.js +116 -0
  92. package/dist/procedures/server.status.js.map +1 -0
  93. package/dist/procedures/server.stop.d.ts +11 -0
  94. package/dist/procedures/server.stop.d.ts.map +1 -0
  95. package/dist/procedures/server.stop.js +96 -0
  96. package/dist/procedures/server.stop.js.map +1 -0
  97. package/dist/register.d.ts +8 -0
  98. package/dist/register.d.ts.map +1 -0
  99. package/dist/register.js +14 -0
  100. package/dist/register.js.map +1 -0
  101. package/dist/schema.d.ts +14 -0
  102. package/dist/schema.d.ts.map +1 -0
  103. package/dist/schema.js +14 -0
  104. package/dist/schema.js.map +1 -0
  105. package/dist/types.d.ts +192 -0
  106. package/dist/types.d.ts.map +1 -0
  107. package/dist/types.js +5 -0
  108. package/dist/types.js.map +1 -0
  109. package/package.json +87 -3
  110. package/src/connection/index.ts +219 -0
  111. package/src/discovery/index.ts +137 -0
  112. package/src/expose.ts +17 -0
  113. package/src/index.ts +69 -0
  114. package/src/input-schemas.ts +121 -0
  115. package/src/lockfile.ts +129 -0
  116. package/src/manifest/index.ts +8 -0
  117. package/src/manifest/json.ts +39 -0
  118. package/src/manifest/typescript.ts +148 -0
  119. package/src/module.ts +46 -0
  120. package/src/output-schemas.ts +110 -0
  121. package/src/peer/index.ts +325 -0
  122. package/src/peer/security.ts +58 -0
  123. package/src/procedures/index.ts +32 -0
  124. package/src/procedures/manifest.generate.ts +113 -0
  125. package/src/procedures/server.call.ts +96 -0
  126. package/src/procedures/server.connect.ts +45 -0
  127. package/src/procedures/server.connections.ts +64 -0
  128. package/src/procedures/server.create.ts +84 -0
  129. package/src/procedures/server.disconnect.ts +31 -0
  130. package/src/procedures/server.start.ts +209 -0
  131. package/src/procedures/server.status.ts +139 -0
  132. package/src/procedures/server.stop.ts +121 -0
  133. package/src/register.ts +17 -0
  134. package/src/schema.ts +15 -0
  135. package/src/types.ts +257 -0
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Procedure: server.connections
3
+ * List all outbound connections to remote peers
4
+ */
5
+
6
+ import { createProcedure, type Procedure } from "@procedures/client";
7
+ import { wrapSchema } from "../schema.js";
8
+ import { ServerConnectionsOutputSchema } from "../output-schemas.js";
9
+ import { serverConnectionsInputSchema } from "../input-schemas.js";
10
+ import { getConnectionIds, getConnection } from "../connection/index.js";
11
+
12
+ // =============================================================================
13
+ // Types
14
+ // =============================================================================
15
+
16
+ export interface ServerConnectionsInput {
17
+ // No input required
18
+ }
19
+
20
+ export interface ServerConnectionsOutput {
21
+ connections: Array<{
22
+ connectionId: string;
23
+ remotePeerId: string;
24
+ transport: string;
25
+ state: string;
26
+ remoteProcedureCount: number;
27
+ connectedAt?: string | undefined;
28
+ }>;
29
+ }
30
+
31
+ // =============================================================================
32
+ // Procedure
33
+ // =============================================================================
34
+
35
+ const serverConnectionsOutputSchema = wrapSchema<ServerConnectionsOutput>(ServerConnectionsOutputSchema);
36
+
37
+ export const serverConnectionsProcedure: Procedure<
38
+ ServerConnectionsInput,
39
+ ServerConnectionsOutput,
40
+ { description: string; output: string }
41
+ > = createProcedure()
42
+ .path(["server", "connections"])
43
+ .input(serverConnectionsInputSchema)
44
+ .output(serverConnectionsOutputSchema)
45
+ .meta({
46
+ description: "List outbound connections to remote peers",
47
+ output: "json",
48
+ })
49
+ .handler(async (): Promise<ServerConnectionsOutput> => {
50
+ const ids = getConnectionIds();
51
+ const connections = ids.map((id) => {
52
+ const conn = getConnection(id)!;
53
+ return {
54
+ connectionId: conn.id,
55
+ remotePeerId: conn.remote.remotePeerId,
56
+ transport: conn.remote.transport,
57
+ state: conn.remote.state,
58
+ remoteProcedureCount: conn.remote.remoteProcedures.length,
59
+ connectedAt: conn.remote.connectedAt?.toISOString(),
60
+ };
61
+ });
62
+ return { connections };
63
+ })
64
+ .build();
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Procedure: server.create
3
+ * Creates a transport-agnostic peer that exposes procedures
4
+ */
5
+
6
+ import { createProcedure, type Procedure, PROCEDURE_REGISTRY } from "@procedures/client";
7
+ import { wrapSchema } from "../schema.js";
8
+ import { ServerCreateOutputSchema } from "../output-schemas.js";
9
+ import { serverCreateInputSchema } from "../input-schemas.js";
10
+ import type { ServerCreateInput, ServerCreateOutput } from "../types.js";
11
+ import { createPeer, type Peer } from "../peer/index.js";
12
+ import { exposeRule } from "../expose.js";
13
+
14
+ // Use pass-through schemas for simplicity (validation happens at Zod level if needed)
15
+ const serverCreateOutputSchema = wrapSchema<ServerCreateOutput>(ServerCreateOutputSchema);
16
+
17
+ // Active peers (module-level state for now, could be in context)
18
+ const activePeers = new Map<string, Peer>();
19
+
20
+ export const serverCreateProcedure: Procedure<
21
+ ServerCreateInput,
22
+ ServerCreateOutput,
23
+ { description: string }
24
+ > = createProcedure()
25
+ .path(["server", "create"])
26
+ .input(serverCreateInputSchema)
27
+ .output(serverCreateOutputSchema)
28
+ .meta({ description: "Create a transport-agnostic peer that exposes procedures" })
29
+ .handler(async (input: ServerCreateInput) => {
30
+ // Generate unique server ID
31
+ const serverId = `peer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
32
+
33
+ // Default transports if not specified
34
+ // A server-wide token goes to each transport that has none of its own
35
+ const transports = (input.transports ?? [{ type: "http" as const, port: 3000 }]).map((transport) =>
36
+ transport.type === "local" || input.token === undefined || transport.token !== undefined
37
+ ? transport
38
+ : { ...transport, token: input.token }
39
+ );
40
+ const autoRegister = input.autoRegister ?? true;
41
+
42
+ // Create peer with configured transports
43
+ const peer = await createPeer({
44
+ id: serverId,
45
+ transports,
46
+ autoRegister,
47
+ registry: PROCEDURE_REGISTRY,
48
+ ...(input.expose ? { expose: exposeRule(input.expose) } : {}),
49
+ });
50
+
51
+ // Start the peer
52
+ await peer.start();
53
+
54
+ // Store for later reference
55
+ activePeers.set(serverId, peer);
56
+
57
+ // Get procedure count
58
+ const procedureCount = input.autoRegister
59
+ ? PROCEDURE_REGISTRY.getAll().filter((p) => p.handler).length
60
+ : 0;
61
+
62
+ return {
63
+ serverId,
64
+ endpoints: peer.getEndpoints(),
65
+ procedureCount,
66
+ };
67
+ })
68
+ .build();
69
+
70
+ /**
71
+ * Get an active peer by ID
72
+ */
73
+ export function getPeer(serverId: string): Peer | undefined {
74
+ return activePeers.get(serverId);
75
+ }
76
+
77
+ /**
78
+ * Get all active peer IDs
79
+ */
80
+ export function getActivePeerIds(): string[] {
81
+ return Array.from(activePeers.keys());
82
+ }
83
+
84
+ export type { ServerCreateInput, ServerCreateOutput };
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Procedure: server.disconnect
3
+ * Disconnects from a remote peer
4
+ */
5
+
6
+ import { createProcedure, type Procedure } from "@procedures/client";
7
+ import { wrapSchema } from "../schema.js";
8
+ import { ServerDisconnectOutputSchema } from "../output-schemas.js";
9
+ import { serverDisconnectInputSchema } from "../input-schemas.js";
10
+ import type { ServerDisconnectInput, ServerDisconnectOutput } from "../types.js";
11
+ import { disconnect } from "../connection/index.js";
12
+
13
+ // Use pass-through schemas
14
+ const serverDisconnectOutputSchema = wrapSchema<ServerDisconnectOutput>(ServerDisconnectOutputSchema);
15
+
16
+ export const serverDisconnectProcedure: Procedure<
17
+ ServerDisconnectInput,
18
+ ServerDisconnectOutput,
19
+ { description: string }
20
+ > = createProcedure()
21
+ .path(["server", "disconnect"])
22
+ .input(serverDisconnectInputSchema)
23
+ .output(serverDisconnectOutputSchema)
24
+ .meta({ description: "Disconnect from a remote peer", args: ["connectionId"] })
25
+ .handler(async (input: ServerDisconnectInput) => {
26
+ const success = await disconnect(input.connectionId);
27
+ return { success };
28
+ })
29
+ .build();
30
+
31
+ export type { ServerDisconnectInput, ServerDisconnectOutput };
@@ -0,0 +1,209 @@
1
+ /**
2
+ * Procedure: server.start
3
+ * Starts the CLI server as a background daemon
4
+ */
5
+
6
+ import { spawn } from "node:child_process";
7
+ import * as fs from "node:fs";
8
+ import * as path from "node:path";
9
+ import * as os from "node:os";
10
+ import { createProcedure, type Procedure } from "@procedures/client";
11
+ import { wrapSchema } from "../schema.js";
12
+ import { ServerStartOutputSchema } from "../output-schemas.js";
13
+ import { serverStartInputSchema } from "../input-schemas.js";
14
+ import { checkServer, readLockfileForPort } from "../lockfile.js";
15
+ import type { ServerStartInput, ServerStartOutput } from "../types.js";
16
+
17
+ const MARK_DIR = path.join(os.homedir(), ".mark");
18
+ const SERVERS_DIR = path.join(MARK_DIR, "servers");
19
+ const LOG_PATH = path.join(MARK_DIR, "server.log");
20
+ const LOG_PREV_PATH = path.join(MARK_DIR, "server.log.1");
21
+
22
+ const serverStartOutputSchema = wrapSchema<ServerStartOutput>(ServerStartOutputSchema);
23
+
24
+
25
+ /**
26
+ * Check if process is alive
27
+ */
28
+ function isProcessAlive(pid: number): boolean {
29
+ try {
30
+ process.kill(pid, 0);
31
+ return true;
32
+ } catch {
33
+ return false;
34
+ }
35
+ }
36
+
37
+ /**
38
+ * Rotate log file
39
+ */
40
+ function rotateLog(): void {
41
+ try {
42
+ fs.mkdirSync(MARK_DIR, { recursive: true });
43
+ if (fs.existsSync(LOG_PATH)) {
44
+ fs.renameSync(LOG_PATH, LOG_PREV_PATH);
45
+ }
46
+ } catch {
47
+ // Ignore rotation errors
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Find the CLI entry point
53
+ */
54
+ function findCliPath(): string {
55
+ // First, try to use the currently running script if it's the CLI
56
+ const currentScript = process.argv[1];
57
+ if (currentScript) {
58
+ // Normalize path for cross-platform check
59
+ const normalized = currentScript.replace(/\\/g, "/");
60
+ // mark runs as dist/bin.js (its bin) or dist/cli.js
61
+ if (normalized.endsWith("/dist/bin.js") || normalized.endsWith("cli.js") || normalized.includes("cli/dist")) {
62
+ // Return absolute path
63
+ return path.resolve(currentScript);
64
+ }
65
+ }
66
+
67
+ // Try to find the mark CLI in node_modules or as a direct path
68
+ const candidates = [
69
+ path.join(process.cwd(), "node_modules", "@procedures", "mark", "dist", "cli.js"),
70
+ path.join(process.cwd(), "node_modules", ".bin", "mark"),
71
+ // Check parent directories for monorepo setups
72
+ path.join(process.cwd(), "..", "cli", "dist", "cli.js"),
73
+ // Direct check in current directory
74
+ path.join(process.cwd(), "dist", "cli.js"),
75
+ ];
76
+
77
+ // Check which candidate exists
78
+ for (const candidate of candidates) {
79
+ if (fs.existsSync(candidate)) {
80
+ return candidate;
81
+ }
82
+ }
83
+
84
+ // Fallback: try mark in PATH (will fail if not installed globally)
85
+ return "mark";
86
+ }
87
+
88
+ export const serverStartProcedure: Procedure<
89
+ ServerStartInput,
90
+ ServerStartOutput,
91
+ { description: string; args: string[]; shorts: Record<string, string> }
92
+ > = createProcedure()
93
+ .path(["server", "start"])
94
+ .input(serverStartInputSchema)
95
+ .output(serverStartOutputSchema)
96
+ .meta({
97
+ description: "Start CLI server as background daemon",
98
+ args: [],
99
+ shorts: { port: "p", host: "h" },
100
+ })
101
+ .handler(async (input: ServerStartInput): Promise<ServerStartOutput> => {
102
+ const port = input.port ?? 3000;
103
+ // Loopback by default; pass host: "0.0.0.0" to expose on the LAN deliberately.
104
+ // See documentation/BUGS-2026-07.md (H19).
105
+ const host = input.host ?? "127.0.0.1";
106
+ const transport = input.transport ?? "http";
107
+
108
+ // Check if server is already running on this port
109
+ const existing = readLockfileForPort(port);
110
+ if (existing && (await checkServer(existing)) === "alive") {
111
+ return {
112
+ success: false,
113
+ message: `Server already running on port ${port} (PID ${existing.pid})`,
114
+ };
115
+ }
116
+
117
+ // Rotate log file
118
+ rotateLog();
119
+
120
+ // Ensure directories exist
121
+ fs.mkdirSync(SERVERS_DIR, { recursive: true });
122
+
123
+ // Open log file for writing
124
+ const logFd = fs.openSync(LOG_PATH, "a");
125
+
126
+ // Find CLI path
127
+ const cliPath = findCliPath();
128
+
129
+ // Build arguments
130
+ const args = ["--server", "--port", String(port), "--host", host];
131
+ if (transport !== "http") {
132
+ args.push("--transport", transport);
133
+ }
134
+
135
+ // Determine how to spawn
136
+ let spawnCmd: string;
137
+ let spawnArgs: string[];
138
+
139
+ if (cliPath === "mark" || cliPath.endsWith(".bin/mark") || cliPath.endsWith(".bin\\mark")) {
140
+ // Use mark command directly
141
+ spawnCmd = cliPath;
142
+ spawnArgs = args;
143
+ } else {
144
+ // Use node to run the JS file
145
+ spawnCmd = process.execPath;
146
+ spawnArgs = [cliPath, ...args];
147
+ }
148
+
149
+ // Spawn daemon process
150
+ const child = spawn(spawnCmd, spawnArgs, {
151
+ detached: true,
152
+ stdio: ["ignore", logFd, logFd],
153
+ env: { ...process.env },
154
+ cwd: process.cwd(),
155
+ // No console window on Windows (deep dive CLI-16)
156
+ windowsHide: true,
157
+ });
158
+
159
+ // Unref so parent can exit
160
+ child.unref();
161
+ fs.closeSync(logFd);
162
+
163
+ // Poll for lockfile (server takes ~4-8s to load ecosystem)
164
+ const maxWait = 15000;
165
+ const pollInterval = 500;
166
+ const startTime = Date.now();
167
+
168
+ while (Date.now() - startTime < maxWait) {
169
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
170
+
171
+ // Check if child died
172
+ if (child.pid && !isProcessAlive(child.pid)) {
173
+ break;
174
+ }
175
+
176
+ // Check for lockfile
177
+ const lockfile = readLockfileForPort(port);
178
+ if (lockfile && (await checkServer(lockfile)) === "alive") {
179
+ return {
180
+ success: true,
181
+ pid: lockfile.pid,
182
+ port: lockfile.port,
183
+ endpoint: lockfile.endpoint,
184
+ logFile: LOG_PATH,
185
+ message: `Server started (PID ${lockfile.pid})`,
186
+ };
187
+ }
188
+ }
189
+
190
+ // Timed out waiting for lockfile, but child may still be alive
191
+ if (child.pid && isProcessAlive(child.pid)) {
192
+ return {
193
+ success: true,
194
+ pid: child.pid,
195
+ port,
196
+ endpoint: `http://${host === "0.0.0.0" ? "localhost" : host}:${port}/api`,
197
+ logFile: LOG_PATH,
198
+ message: `Server starting (PID ${child.pid}, still loading...)`,
199
+ };
200
+ }
201
+
202
+ return {
203
+ success: false,
204
+ message: `Failed to start server. Check ${LOG_PATH} for details.`,
205
+ };
206
+ })
207
+ .build();
208
+
209
+ export type { ServerStartInput, ServerStartOutput };
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Procedure: server.status
3
+ * Gets the current CLI server status
4
+ */
5
+
6
+ import * as path from "node:path";
7
+ import * as os from "node:os";
8
+ import { createProcedure, type Procedure } from "@procedures/client";
9
+ import { wrapSchema } from "../schema.js";
10
+ import { ServerStatusOutputSchema } from "../output-schemas.js";
11
+ import { serverStatusInputSchema } from "../input-schemas.js";
12
+ import { checkServer, readAllLockfiles, readLockfileForPort, removeLockfileForPort, type LockfileData } from "../lockfile.js";
13
+ import type { ServerStatusInput, ServerStatusOutput } from "../types.js";
14
+
15
+ const MARK_DIR = path.join(os.homedir(), ".mark");
16
+ const LOG_PATH = path.join(MARK_DIR, "server.log");
17
+
18
+ const serverStatusOutputSchema = wrapSchema<ServerStatusOutput>(ServerStatusOutputSchema);
19
+
20
+
21
+
22
+
23
+
24
+ /**
25
+ * Format uptime as human-readable string
26
+ */
27
+ function formatUptime(startedAt: string): string {
28
+ const start = new Date(startedAt).getTime();
29
+ const now = Date.now();
30
+ const diff = Math.floor((now - start) / 1000);
31
+
32
+ if (diff < 60) {
33
+ return `${diff}s`;
34
+ }
35
+ if (diff < 3600) {
36
+ const mins = Math.floor(diff / 60);
37
+ const secs = diff % 60;
38
+ return `${mins}m ${secs}s`;
39
+ }
40
+ if (diff < 86400) {
41
+ const hours = Math.floor(diff / 3600);
42
+ const mins = Math.floor((diff % 3600) / 60);
43
+ return `${hours}h ${mins}m`;
44
+ }
45
+ const days = Math.floor(diff / 86400);
46
+ const hours = Math.floor((diff % 86400) / 3600);
47
+ return `${days}d ${hours}h`;
48
+ }
49
+
50
+ export const serverStatusProcedure: Procedure<
51
+ ServerStatusInput,
52
+ ServerStatusOutput,
53
+ { description: string; output: string }
54
+ > = createProcedure()
55
+ .path(["server", "status"])
56
+ .input(serverStatusInputSchema)
57
+ .output(serverStatusOutputSchema)
58
+ .meta({
59
+ description: "Get CLI server status",
60
+ args: [],
61
+ shorts: { port: "p" },
62
+ output: "text",
63
+ })
64
+ .handler(async (input: ServerStatusInput): Promise<ServerStatusOutput> => {
65
+ // Get target servers
66
+ let targets: LockfileData[];
67
+ if (input.port !== undefined) {
68
+ const lockfile = readLockfileForPort(input.port);
69
+ targets = lockfile ? [lockfile] : [];
70
+ } else {
71
+ targets = readAllLockfiles();
72
+ }
73
+
74
+ if (targets.length === 0) {
75
+ return {
76
+ running: false,
77
+ message: input.port
78
+ ? `No server found on port ${input.port}`
79
+ : "No servers running",
80
+ };
81
+ }
82
+
83
+ // For single server, return detailed info
84
+ if (targets.length === 1) {
85
+ const lockfile = targets[0]!;
86
+ const { pid, port, endpoint, startedAt, transport } = lockfile;
87
+
88
+ if ((await checkServer(lockfile)) !== "alive") {
89
+ removeLockfileForPort(port);
90
+ return {
91
+ running: false,
92
+ message: "Server is not running (cleaned up stale lockfile)",
93
+ };
94
+ }
95
+
96
+ const uptime = formatUptime(startedAt);
97
+ return {
98
+ running: true,
99
+ pid,
100
+ port,
101
+ endpoint,
102
+ transport,
103
+ startedAt,
104
+ uptime,
105
+ logFile: LOG_PATH,
106
+ message: `Server running (PID ${pid}, port ${port}, uptime ${uptime})`,
107
+ };
108
+ }
109
+
110
+ // Multiple servers - summarize
111
+ const lines: string[] = [];
112
+ let anyRunning = false;
113
+
114
+ for (const lockfile of targets) {
115
+ const { pid, port, endpoint, startedAt } = lockfile;
116
+ if ((await checkServer(lockfile)) !== "alive") {
117
+ removeLockfileForPort(port);
118
+ continue;
119
+ }
120
+ anyRunning = true;
121
+ const uptime = formatUptime(startedAt);
122
+ lines.push(` Port ${port}: PID ${pid}, uptime ${uptime}, ${endpoint}`);
123
+ }
124
+
125
+ if (!anyRunning) {
126
+ return {
127
+ running: false,
128
+ message: "No servers running (cleaned up stale lockfiles)",
129
+ };
130
+ }
131
+
132
+ return {
133
+ running: true,
134
+ message: `${lines.length} server(s) running:\n${lines.join("\n")}`,
135
+ };
136
+ })
137
+ .build();
138
+
139
+ export type { ServerStatusInput, ServerStatusOutput };
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Procedure: server.stop
3
+ * Stops the running CLI server daemon
4
+ */
5
+
6
+ import { createProcedure, type Procedure } from "@procedures/client";
7
+ import { wrapSchema } from "../schema.js";
8
+ import { ServerStopOutputSchema } from "../output-schemas.js";
9
+ import { serverStopInputSchema } from "../input-schemas.js";
10
+ import { checkServer, readAllLockfiles, readLockfileForPort, removeLockfileForPort, type LockfileData } from "../lockfile.js";
11
+ import type { ServerStopInput, ServerStopOutput } from "../types.js";
12
+
13
+
14
+ const serverStopOutputSchema = wrapSchema<ServerStopOutput>(ServerStopOutputSchema);
15
+
16
+
17
+
18
+
19
+
20
+ /**
21
+ * Kill process by PID
22
+ */
23
+ function killProcess(pid: number, signal: NodeJS.Signals = "SIGTERM"): boolean {
24
+ try {
25
+ process.kill(pid, signal);
26
+ return true;
27
+ } catch {
28
+ return false;
29
+ }
30
+ }
31
+
32
+ export const serverStopProcedure: Procedure<
33
+ ServerStopInput,
34
+ ServerStopOutput,
35
+ { description: string }
36
+ > = createProcedure()
37
+ .path(["server", "stop"])
38
+ .input(serverStopInputSchema)
39
+ .output(serverStopOutputSchema)
40
+ .meta({
41
+ description: "Stop running CLI server",
42
+ args: [],
43
+ shorts: { port: "p" },
44
+ })
45
+ .handler(async (input: ServerStopInput): Promise<ServerStopOutput> => {
46
+ const force = input.force ?? false;
47
+ const signal: NodeJS.Signals = force ? "SIGKILL" : "SIGTERM";
48
+
49
+ // Get target servers
50
+ let targets: LockfileData[];
51
+ if (input.port !== undefined) {
52
+ const lockfile = readLockfileForPort(input.port);
53
+ targets = lockfile ? [lockfile] : [];
54
+ } else {
55
+ targets = readAllLockfiles();
56
+ }
57
+
58
+ if (targets.length === 0) {
59
+ return {
60
+ success: false,
61
+ message: input.port
62
+ ? `No server found on port ${input.port}`
63
+ : "No servers running",
64
+ };
65
+ }
66
+
67
+ const results: string[] = [];
68
+ let allSuccess = true;
69
+
70
+ for (const lockfile of targets) {
71
+ const { pid, port } = lockfile;
72
+
73
+ // Signal the PID only when the server answers as the peer of this lockfile: Windows reuses
74
+ // PIDs, and before, a stale lockfile made this kill an unrelated process (deep dive CLI-4)
75
+ const state = await checkServer(lockfile);
76
+ if (state !== "alive") {
77
+ removeLockfileForPort(port);
78
+ results.push(
79
+ state === "dead"
80
+ ? `Port ${port}: cleaned up stale lockfile`
81
+ : `Port ${port}: another process answers on this port; nothing stopped (stale lockfile removed)`
82
+ );
83
+ continue;
84
+ }
85
+
86
+ const sent = killProcess(pid, signal);
87
+ if (!sent) {
88
+ allSuccess = false;
89
+ results.push(`Port ${port}: failed to send ${signal} to PID ${pid}`);
90
+ continue;
91
+ }
92
+
93
+ // Wait for process to die
94
+ const maxWait = force ? 500 : 5000;
95
+ const startTime = Date.now();
96
+ let stopped = false;
97
+
98
+ while (Date.now() - startTime < maxWait) {
99
+ if ((await checkServer(lockfile, 300)) === "dead") {
100
+ removeLockfileForPort(port);
101
+ results.push(`Port ${port}: stopped (PID ${pid})`);
102
+ stopped = true;
103
+ break;
104
+ }
105
+ await new Promise((resolve) => setTimeout(resolve, 100));
106
+ }
107
+
108
+ if (!stopped) {
109
+ allSuccess = false;
110
+ results.push(`Port ${port}: PID ${pid} did not stop${force ? "" : " (try --force)"}`);
111
+ }
112
+ }
113
+
114
+ return {
115
+ success: allSuccess,
116
+ message: results.join("\n"),
117
+ };
118
+ })
119
+ .build();
120
+
121
+ export type { ServerStopInput, ServerStopOutput };
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Importing this file registers the procedures of @procedures/peer in the global registry
3
+ * (DECISIONS-2026-10, "Every package root registers its procedures"). The procedures as data
4
+ * are in `module.ts`, which registers nothing: a host with its own registry uses that one.
5
+ */
6
+
7
+ import { registerProcedures } from "@procedures/client";
8
+ import { serverModule } from "./module.js";
9
+
10
+ export * from "./module.js";
11
+
12
+ export function registerServerProcedures(): void {
13
+ registerProcedures(serverModule.procedures);
14
+ }
15
+
16
+ // Auto-register when this module is loaded
17
+ registerServerProcedures();
package/src/schema.ts ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Schema Helpers
3
+ *
4
+ * Wraps Zod schemas for the client procedure system.
5
+ */
6
+
7
+ /**
8
+ * Wrap a Zod schema for use with client procedures
9
+ */
10
+ export { zodAdapter as wrapSchema } from "@procedures/client";
11
+
12
+ /**
13
+ * Create a pass-through schema for type T (no validation)
14
+ */
15
+ export { outputSchema as schema } from "@procedures/client";