pubblue 0.4.10 → 0.4.11

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/dist/index.js CHANGED
@@ -11,18 +11,51 @@ import {
11
11
  CHANNELS,
12
12
  CONTROL_CHANNEL,
13
13
  generateMessageId
14
- } from "./chunk-MW35LBNH.js";
14
+ } from "./chunk-4YTJ2WKF.js";
15
15
 
16
- // src/index.ts
17
- import * as fs3 from "fs";
18
- import * as path3 from "path";
19
- import { createInterface } from "readline/promises";
16
+ // src/lib/cli-error.ts
17
+ import { CommanderError } from "commander";
18
+ var CliError = class extends Error {
19
+ exitCode;
20
+ constructor(message, exitCode = 1) {
21
+ super(message);
22
+ this.name = "CliError";
23
+ this.exitCode = exitCode;
24
+ }
25
+ };
26
+ function failCli(message, exitCode = 1) {
27
+ throw new CliError(message, exitCode);
28
+ }
29
+ function toCliFailure(error) {
30
+ if (error instanceof CommanderError) {
31
+ return {
32
+ exitCode: error.exitCode,
33
+ message: ""
34
+ };
35
+ }
36
+ if (error instanceof CliError) {
37
+ return {
38
+ exitCode: error.exitCode,
39
+ message: error.message
40
+ };
41
+ }
42
+ if (error instanceof Error) {
43
+ return {
44
+ exitCode: 1,
45
+ message: error.message
46
+ };
47
+ }
48
+ return {
49
+ exitCode: 1,
50
+ message: String(error)
51
+ };
52
+ }
53
+
54
+ // src/program.ts
20
55
  import { Command } from "commander";
21
56
 
22
- // src/commands/tunnel.ts
23
- import { fork } from "child_process";
24
- import * as fs2 from "fs";
25
- import * as path2 from "path";
57
+ // src/commands/configure.ts
58
+ import { createInterface } from "readline/promises";
26
59
 
27
60
  // src/lib/config.ts
28
61
  import * as fs from "fs";
@@ -79,833 +112,712 @@ function getConfig(homeDir) {
79
112
  };
80
113
  }
81
114
 
82
- // src/commands/tunnel.ts
83
- var TEXT_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
84
- ".txt",
85
- ".md",
86
- ".markdown",
87
- ".json",
88
- ".csv",
89
- ".xml",
90
- ".yaml",
91
- ".yml",
92
- ".js",
93
- ".mjs",
94
- ".cjs",
95
- ".ts",
96
- ".tsx",
97
- ".jsx",
98
- ".css",
99
- ".scss",
100
- ".sass",
101
- ".less",
102
- ".log"
103
- ]);
104
- function getMimeType(filePath) {
105
- const ext = path2.extname(filePath).toLowerCase();
106
- const mimeByExt = {
107
- ".html": "text/html; charset=utf-8",
108
- ".htm": "text/html; charset=utf-8",
109
- ".txt": "text/plain; charset=utf-8",
110
- ".md": "text/markdown; charset=utf-8",
111
- ".markdown": "text/markdown; charset=utf-8",
112
- ".json": "application/json",
113
- ".csv": "text/csv; charset=utf-8",
114
- ".xml": "application/xml",
115
- ".yaml": "application/x-yaml",
116
- ".yml": "application/x-yaml",
117
- ".png": "image/png",
118
- ".jpg": "image/jpeg",
119
- ".jpeg": "image/jpeg",
120
- ".gif": "image/gif",
121
- ".webp": "image/webp",
122
- ".svg": "image/svg+xml",
123
- ".pdf": "application/pdf",
124
- ".zip": "application/zip",
125
- ".mp3": "audio/mpeg",
126
- ".wav": "audio/wav",
127
- ".mp4": "video/mp4"
128
- };
129
- return mimeByExt[ext] || "application/octet-stream";
130
- }
131
- function tunnelInfoDir() {
132
- const dir = path2.join(
133
- process.env.HOME || process.env.USERPROFILE || "/tmp",
134
- ".config",
135
- "pubblue",
136
- "tunnels"
137
- );
138
- if (!fs2.existsSync(dir)) fs2.mkdirSync(dir, { recursive: true });
139
- return dir;
115
+ // src/commands/shared.ts
116
+ import * as fs2 from "fs";
117
+ import * as path2 from "path";
118
+
119
+ // src/lib/api.ts
120
+ var PubApiClient = class {
121
+ constructor(baseUrl, apiKey) {
122
+ this.baseUrl = baseUrl;
123
+ this.apiKey = apiKey;
124
+ }
125
+ async request(path6, options = {}) {
126
+ const url = new URL(path6, this.baseUrl);
127
+ const res = await fetch(url, {
128
+ ...options,
129
+ headers: {
130
+ "Content-Type": "application/json",
131
+ Authorization: `Bearer ${this.apiKey}`,
132
+ ...options.headers
133
+ }
134
+ });
135
+ const data = await res.json();
136
+ if (!res.ok) {
137
+ throw new Error(data.error || `Request failed with status ${res.status}`);
138
+ }
139
+ return data;
140
+ }
141
+ async create(opts) {
142
+ return this.request("/api/v1/publications", {
143
+ method: "POST",
144
+ body: JSON.stringify(opts)
145
+ });
146
+ }
147
+ async get(slug) {
148
+ const data = await this.request(`/api/v1/publications/${encodeURIComponent(slug)}`);
149
+ return data.publication;
150
+ }
151
+ async listPage(cursor, limit) {
152
+ const params = new URLSearchParams();
153
+ if (cursor) params.set("cursor", cursor);
154
+ if (limit) params.set("limit", String(limit));
155
+ const qs = params.toString();
156
+ return this.request(`/api/v1/publications${qs ? `?${qs}` : ""}`);
157
+ }
158
+ async list() {
159
+ const all = [];
160
+ let cursor;
161
+ do {
162
+ const result = await this.listPage(cursor, 100);
163
+ all.push(...result.publications);
164
+ cursor = result.hasMore ? result.cursor : void 0;
165
+ } while (cursor);
166
+ return all;
167
+ }
168
+ async update(opts) {
169
+ const { slug, newSlug, ...rest } = opts;
170
+ const body = { ...rest };
171
+ if (newSlug) body.slug = newSlug;
172
+ return this.request(`/api/v1/publications/${encodeURIComponent(slug)}`, {
173
+ method: "PATCH",
174
+ body: JSON.stringify(body)
175
+ });
176
+ }
177
+ async remove(slug) {
178
+ await this.request(`/api/v1/publications/${encodeURIComponent(slug)}`, {
179
+ method: "DELETE"
180
+ });
181
+ }
182
+ };
183
+
184
+ // src/commands/shared.ts
185
+ function createClient() {
186
+ const config = getConfig();
187
+ return new PubApiClient(config.baseUrl, config.apiKey);
140
188
  }
141
- function tunnelInfoPath(tunnelId) {
142
- return path2.join(tunnelInfoDir(), `${tunnelId}.json`);
189
+ async function readFromStdin() {
190
+ const chunks = [];
191
+ for await (const chunk of process.stdin) {
192
+ chunks.push(chunk);
193
+ }
194
+ return Buffer.concat(chunks).toString("utf-8").trim();
143
195
  }
144
- function tunnelLogPath(tunnelId) {
145
- return path2.join(tunnelInfoDir(), `${tunnelId}.log`);
196
+ function formatVisibility(isPublic) {
197
+ return isPublic ? "public" : "private";
146
198
  }
147
- function bridgeInfoPath(tunnelId) {
148
- return path2.join(tunnelInfoDir(), `${tunnelId}.bridge.json`);
199
+ function resolveVisibilityFlags(opts) {
200
+ if (opts.public && opts.private) {
201
+ throw new Error(`Use only one of --public or --private for ${opts.commandName}.`);
202
+ }
203
+ if (opts.public) return true;
204
+ if (opts.private) return false;
205
+ return void 0;
149
206
  }
150
- function bridgeLogPath(tunnelId) {
151
- return path2.join(tunnelInfoDir(), `${tunnelId}.bridge.log`);
207
+ function readFile(filePath) {
208
+ const resolved = path2.resolve(filePath);
209
+ if (!fs2.existsSync(resolved)) {
210
+ failCli(`File not found: ${resolved}`);
211
+ }
212
+ return {
213
+ content: fs2.readFileSync(resolved, "utf-8"),
214
+ basename: path2.basename(resolved)
215
+ };
152
216
  }
153
- function createApiClient(configOverride) {
154
- const config = configOverride || getConfig();
155
- return new TunnelApiClient(config.baseUrl, config.apiKey);
217
+
218
+ // src/commands/configure.ts
219
+ function readApiKeyFromPrompt() {
220
+ const rl = createInterface({
221
+ input: process.stdin,
222
+ output: process.stdout
223
+ });
224
+ return rl.question("Enter API key: ").then((answer) => answer.trim()).finally(() => {
225
+ rl.close();
226
+ });
156
227
  }
157
- function buildBridgeProcessEnv(bridgeConfig) {
158
- const env = { ...process.env };
159
- if (!bridgeConfig) return env;
160
- const setIfMissing = (key, value) => {
161
- if (value === void 0 || value === null) return;
162
- const current = env[key];
163
- if (typeof current === "string" && current.length > 0) return;
164
- env[key] = String(value);
165
- };
166
- setIfMissing("OPENCLAW_PATH", bridgeConfig.openclawPath);
167
- setIfMissing("OPENCLAW_SESSION_ID", bridgeConfig.sessionId);
168
- setIfMissing("OPENCLAW_THREAD_ID", bridgeConfig.threadId);
169
- if (bridgeConfig.deliver !== void 0) {
170
- setIfMissing("OPENCLAW_DELIVER", bridgeConfig.deliver ? "1" : "0");
228
+ async function resolveConfigureApiKey(opts) {
229
+ if (opts.apiKey && opts.apiKeyStdin) {
230
+ throw new Error("Use only one of --api-key or --api-key-stdin.");
171
231
  }
172
- setIfMissing("OPENCLAW_DELIVER_CHANNEL", bridgeConfig.deliverChannel);
173
- setIfMissing("OPENCLAW_REPLY_TO", bridgeConfig.replyTo);
174
- if (bridgeConfig.deliverTimeoutMs !== void 0) {
175
- setIfMissing("OPENCLAW_DELIVER_TIMEOUT_MS", bridgeConfig.deliverTimeoutMs);
232
+ if (opts.apiKey) {
233
+ return opts.apiKey.trim();
176
234
  }
177
- return env;
235
+ if (opts.apiKeyStdin) {
236
+ return readFromStdin();
237
+ }
238
+ const envKey = process.env.PUBBLUE_API_KEY?.trim();
239
+ if (envKey) return envKey;
240
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
241
+ throw new Error(
242
+ "No TTY available. Provide --api-key, --api-key-stdin, or PUBBLUE_API_KEY for configure."
243
+ );
244
+ }
245
+ return readApiKeyFromPrompt();
178
246
  }
179
- async function ensureNodeDatachannelAvailable() {
180
- try {
181
- await import("node-datachannel");
182
- } catch (error) {
183
- const message = error instanceof Error ? error.message : String(error);
184
- console.error("node-datachannel native module is not available.");
185
- console.error("Run `pnpm rebuild node-datachannel` in the cli package and retry.");
186
- console.error(`Details: ${message}`);
187
- process.exit(1);
247
+ function collectValues(value, previous) {
248
+ previous.push(value);
249
+ return previous;
250
+ }
251
+ function parseSetInput(raw) {
252
+ const sepIndex = raw.indexOf("=");
253
+ if (sepIndex <= 0 || sepIndex === raw.length - 1) {
254
+ throw new Error(`Invalid --set entry "${raw}". Use key=value.`);
188
255
  }
256
+ return {
257
+ key: raw.slice(0, sepIndex).trim(),
258
+ value: raw.slice(sepIndex + 1).trim()
259
+ };
189
260
  }
190
- function isDaemonRunning(tunnelId) {
191
- const infoPath = tunnelInfoPath(tunnelId);
192
- if (!fs2.existsSync(infoPath)) return false;
193
- try {
194
- const info = JSON.parse(fs2.readFileSync(infoPath, "utf-8"));
195
- process.kill(info.pid, 0);
261
+ function parseBooleanValue(raw, key) {
262
+ const normalized = raw.trim().toLowerCase();
263
+ if (normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on")
196
264
  return true;
197
- } catch {
198
- try {
199
- fs2.unlinkSync(infoPath);
200
- } catch {
201
- }
265
+ if (normalized === "0" || normalized === "false" || normalized === "no" || normalized === "off")
202
266
  return false;
203
- }
267
+ throw new Error(`Invalid boolean value for ${key}: ${raw}`);
204
268
  }
205
- function readBridgeProcessInfo(tunnelId) {
206
- const infoPath = bridgeInfoPath(tunnelId);
207
- if (!fs2.existsSync(infoPath)) return null;
208
- try {
209
- return JSON.parse(fs2.readFileSync(infoPath, "utf-8"));
210
- } catch {
211
- return null;
212
- }
269
+ function parseBridgeModeValue(raw) {
270
+ const normalized = raw.trim().toLowerCase();
271
+ if (normalized === "openclaw" || normalized === "none") return normalized;
272
+ throw new Error(`Invalid bridge mode: ${raw}. Use openclaw or none.`);
213
273
  }
214
- function isBridgeRunning(tunnelId) {
215
- const infoPath = bridgeInfoPath(tunnelId);
216
- if (!fs2.existsSync(infoPath)) return false;
217
- try {
218
- const info = JSON.parse(fs2.readFileSync(infoPath, "utf-8"));
219
- process.kill(info.pid, 0);
220
- return true;
221
- } catch {
222
- try {
223
- fs2.unlinkSync(infoPath);
224
- } catch {
225
- }
226
- return false;
227
- }
228
- }
229
- function stopBridgeProcess(tunnelId) {
230
- const info = readBridgeProcessInfo(tunnelId);
231
- if (!info || !Number.isFinite(info.pid)) return;
232
- try {
233
- process.kill(info.pid, "SIGTERM");
234
- } catch {
235
- }
236
- }
237
- function buildBridgeForkStdio(logFd) {
238
- return ["ignore", logFd, logFd, "ipc"];
239
- }
240
- function getFollowReadDelayMs(disconnected, consecutiveFailures) {
241
- if (!disconnected) return 1e3;
242
- return Math.min(5e3, 1e3 * 2 ** Math.min(consecutiveFailures, 3));
243
- }
244
- function resolveTunnelIdSelection(tunnelIdArg, tunnelOpt) {
245
- return tunnelOpt || tunnelIdArg;
246
- }
247
- function buildDaemonForkStdio(logFd) {
248
- return ["ignore", logFd, logFd, "ipc"];
249
- }
250
- function parsePositiveIntegerOption(raw, optionName) {
274
+ function parsePositiveInteger(raw, key) {
251
275
  const parsed = Number.parseInt(raw, 10);
252
276
  if (!Number.isFinite(parsed) || parsed <= 0) {
253
- throw new Error(`${optionName} must be a positive integer. Received: ${raw}`);
277
+ throw new Error(`${key} must be a positive integer. Received: ${raw}`);
254
278
  }
255
279
  return parsed;
256
280
  }
257
- function parseBridgeMode(raw) {
258
- const normalized = raw.trim().toLowerCase();
259
- if (normalized === "openclaw" || normalized === "none") {
260
- return normalized;
281
+ function applyBridgeSet(bridge, key, value) {
282
+ switch (key) {
283
+ case "bridge.mode":
284
+ bridge.mode = parseBridgeModeValue(value);
285
+ return;
286
+ case "openclaw.path":
287
+ bridge.openclawPath = value;
288
+ return;
289
+ case "openclaw.sessionId":
290
+ bridge.sessionId = value;
291
+ return;
292
+ case "openclaw.threadId":
293
+ bridge.threadId = value;
294
+ return;
295
+ case "openclaw.deliver":
296
+ bridge.deliver = parseBooleanValue(value, key);
297
+ return;
298
+ case "openclaw.deliverChannel":
299
+ bridge.deliverChannel = value;
300
+ return;
301
+ case "openclaw.replyTo":
302
+ bridge.replyTo = value;
303
+ return;
304
+ case "openclaw.deliverTimeoutMs":
305
+ bridge.deliverTimeoutMs = parsePositiveInteger(value, key);
306
+ return;
307
+ case "openclaw.attachmentDir":
308
+ bridge.attachmentDir = value;
309
+ return;
310
+ case "openclaw.attachmentMaxBytes":
311
+ bridge.attachmentMaxBytes = parsePositiveInteger(value, key);
312
+ return;
313
+ default:
314
+ throw new Error(
315
+ [
316
+ `Unknown config key: ${key}`,
317
+ "Supported keys:",
318
+ " bridge.mode",
319
+ " openclaw.path",
320
+ " openclaw.sessionId",
321
+ " openclaw.threadId",
322
+ " openclaw.deliver",
323
+ " openclaw.deliverChannel",
324
+ " openclaw.replyTo",
325
+ " openclaw.deliverTimeoutMs",
326
+ " openclaw.attachmentDir",
327
+ " openclaw.attachmentMaxBytes"
328
+ ].join("\n")
329
+ );
261
330
  }
262
- throw new Error(`--bridge must be one of: openclaw, none. Received: ${raw}`);
263
- }
264
- function messageContainsPong(payload) {
265
- if (!payload || typeof payload !== "object") return false;
266
- const message = payload.msg;
267
- if (!message || typeof message !== "object") return false;
268
- const type = message.type;
269
- const data = message.data;
270
- return type === "text" && typeof data === "string" && data.trim().toLowerCase() === "pong";
271
331
  }
272
- function getPublicTunnelUrl(tunnelId) {
273
- const base = process.env.PUBBLUE_PUBLIC_URL || "https://pub.blue";
274
- return `${base.replace(/\/$/, "")}/t/${tunnelId}`;
332
+ function applyBridgeUnset(bridge, key) {
333
+ switch (key) {
334
+ case "bridge.mode":
335
+ delete bridge.mode;
336
+ return;
337
+ case "openclaw.path":
338
+ delete bridge.openclawPath;
339
+ return;
340
+ case "openclaw.sessionId":
341
+ delete bridge.sessionId;
342
+ return;
343
+ case "openclaw.threadId":
344
+ delete bridge.threadId;
345
+ return;
346
+ case "openclaw.deliver":
347
+ delete bridge.deliver;
348
+ return;
349
+ case "openclaw.deliverChannel":
350
+ delete bridge.deliverChannel;
351
+ return;
352
+ case "openclaw.replyTo":
353
+ delete bridge.replyTo;
354
+ return;
355
+ case "openclaw.deliverTimeoutMs":
356
+ delete bridge.deliverTimeoutMs;
357
+ return;
358
+ case "openclaw.attachmentDir":
359
+ delete bridge.attachmentDir;
360
+ return;
361
+ case "openclaw.attachmentMaxBytes":
362
+ delete bridge.attachmentMaxBytes;
363
+ return;
364
+ default:
365
+ throw new Error(`Unknown config key for --unset: ${key}`);
366
+ }
275
367
  }
276
- function pickReusableTunnel(tunnels, nowMs = Date.now()) {
277
- const active = tunnels.filter((t) => t.status === "active" && t.expiresAt > nowMs).sort((a, b) => b.createdAt - a.createdAt);
278
- return active[0] ?? null;
368
+ function hasBridgeValues(bridge) {
369
+ return Object.values(bridge).some((value) => value !== void 0);
279
370
  }
280
- function readLogTail(logPath, maxChars = 4e3) {
281
- if (!fs2.existsSync(logPath)) return null;
282
- try {
283
- const content = fs2.readFileSync(logPath, "utf-8");
284
- if (content.length <= maxChars) return content;
285
- return content.slice(-maxChars);
286
- } catch {
287
- return null;
288
- }
371
+ function maskApiKey(apiKey) {
372
+ if (apiKey.length <= 8) return "********";
373
+ return `${apiKey.slice(0, 4)}...${apiKey.slice(-4)}`;
289
374
  }
290
- function formatApiError(error) {
291
- if (error instanceof TunnelApiError) {
292
- if (error.status === 429 && error.retryAfterSeconds !== void 0) {
293
- return `Rate limit exceeded. Retry after ${error.retryAfterSeconds}s.`;
294
- }
295
- return `${error.message} (HTTP ${error.status})`;
375
+ function printConfigSummary(saved) {
376
+ if (!saved) {
377
+ console.log("Saved config: none");
378
+ return;
296
379
  }
297
- return error instanceof Error ? error.message : String(error);
298
- }
299
- async function cleanupCreatedTunnelOnStartFailure(apiClient, target) {
300
- if (!target.createdNew) return;
301
- try {
302
- await apiClient.close(target.tunnelId);
303
- } catch (closeError) {
304
- console.error(
305
- `Failed to clean up newly created tunnel ${target.tunnelId}: ${formatApiError(closeError)}`
306
- );
380
+ console.log("Saved config:");
381
+ console.log(` apiKey: ${maskApiKey(saved.apiKey)}`);
382
+ if (!saved.bridge || !hasBridgeValues(saved.bridge)) {
383
+ console.log(" bridge: none");
384
+ return;
307
385
  }
386
+ console.log(` bridge.mode: ${saved.bridge.mode ?? "(unset)"}`);
387
+ if (saved.bridge.openclawPath) console.log(` openclaw.path: ${saved.bridge.openclawPath}`);
388
+ if (saved.bridge.sessionId) console.log(` openclaw.sessionId: ${saved.bridge.sessionId}`);
389
+ if (saved.bridge.threadId) console.log(` openclaw.threadId: ${saved.bridge.threadId}`);
390
+ if (saved.bridge.deliver !== void 0)
391
+ console.log(` openclaw.deliver: ${saved.bridge.deliver ? "true" : "false"}`);
392
+ if (saved.bridge.deliverChannel)
393
+ console.log(` openclaw.deliverChannel: ${saved.bridge.deliverChannel}`);
394
+ if (saved.bridge.replyTo) console.log(` openclaw.replyTo: ${saved.bridge.replyTo}`);
395
+ if (saved.bridge.deliverTimeoutMs !== void 0)
396
+ console.log(` openclaw.deliverTimeoutMs: ${saved.bridge.deliverTimeoutMs}`);
397
+ if (saved.bridge.attachmentDir)
398
+ console.log(` openclaw.attachmentDir: ${saved.bridge.attachmentDir}`);
399
+ if (saved.bridge.attachmentMaxBytes !== void 0)
400
+ console.log(` openclaw.attachmentMaxBytes: ${saved.bridge.attachmentMaxBytes}`);
308
401
  }
309
- function registerTunnelCommands(program2) {
310
- const tunnel = program2.command("tunnel").description("P2P encrypted tunnel to browser");
311
- tunnel.command("start").description("Start a tunnel daemon (reuses existing tunnel when possible)").option("--expires <duration>", "Auto-close after duration (e.g. 4h, 1d)", "24h").option("-t, --tunnel <tunnelId>", "Attach/start daemon for an existing tunnel").option("--new", "Always create a new tunnel (skip single-tunnel reuse)").option("--bridge <mode>", "Bridge mode: openclaw|none").option("--foreground", "Run in foreground (don't fork, no managed bridge)").action(
402
+ function registerConfigureCommand(program2) {
403
+ program2.command("configure").description("Configure the CLI with your API key").option("--api-key <key>", "Your API key (less secure: appears in shell history)").option("--api-key-stdin", "Read API key from stdin").option(
404
+ "--set <key=value>",
405
+ "Set advanced config (repeatable). Example: --set openclaw.sessionId=<id>",
406
+ collectValues,
407
+ []
408
+ ).option("--unset <key>", "Unset advanced config key (repeatable)", collectValues, []).option("--show", "Show saved configuration").action(
312
409
  async (opts) => {
313
- await ensureNodeDatachannelAvailable();
314
- const runtimeConfig = getConfig();
315
- const apiClient = createApiClient(runtimeConfig);
316
- let target = null;
317
- let bridgeMode;
318
- try {
319
- bridgeMode = parseBridgeMode(opts.bridge || runtimeConfig.bridge?.mode || "openclaw");
320
- } catch (error) {
321
- console.error(error instanceof Error ? error.message : String(error));
322
- process.exit(1);
410
+ const saved = loadConfig();
411
+ const hasApiUpdate = Boolean(opts.apiKey || opts.apiKeyStdin);
412
+ const hasSet = opts.set.length > 0;
413
+ const hasUnset = opts.unset.length > 0;
414
+ const hasMutation = hasApiUpdate || hasSet || hasUnset;
415
+ if (!hasMutation && opts.show) {
416
+ printConfigSummary(saved);
417
+ return;
323
418
  }
324
- const bridgeProcessEnv = buildBridgeProcessEnv(runtimeConfig.bridge);
325
- if (opts.tunnel) {
326
- try {
327
- const existing = await apiClient.get(opts.tunnel);
328
- if (existing.status === "closed" || existing.expiresAt <= Date.now()) {
329
- console.error(`Tunnel ${opts.tunnel} is closed or expired.`);
330
- process.exit(1);
331
- }
332
- target = {
333
- createdNew: false,
334
- expiresAt: existing.expiresAt,
335
- mode: "existing",
336
- tunnelId: existing.tunnelId,
337
- url: getPublicTunnelUrl(existing.tunnelId)
338
- };
339
- } catch (error) {
340
- console.error(`Failed to use tunnel ${opts.tunnel}: ${formatApiError(error)}`);
341
- process.exit(1);
342
- }
343
- } else if (!opts.new) {
344
- try {
345
- const listed = await apiClient.list();
346
- const active = listed.filter((t) => t.status === "active" && t.expiresAt > Date.now()).sort((a, b) => b.createdAt - a.createdAt);
347
- const reusable = pickReusableTunnel(listed);
348
- if (reusable) {
349
- target = {
350
- createdNew: false,
351
- expiresAt: reusable.expiresAt,
352
- mode: "existing",
353
- tunnelId: reusable.tunnelId,
354
- url: getPublicTunnelUrl(reusable.tunnelId)
355
- };
356
- if (active.length > 1) {
357
- console.error(
358
- [
359
- `Multiple active tunnels found: ${active.map((t) => t.tunnelId).join(", ")}`,
360
- `Reusing most recent active tunnel ${reusable.tunnelId}.`,
361
- "Use --tunnel <id> to choose explicitly or --new to force creation."
362
- ].join("\n")
363
- );
364
- } else {
365
- console.error(
366
- `Reusing existing active tunnel ${reusable.tunnelId}. Use --new to force creation.`
367
- );
368
- }
369
- }
370
- } catch (error) {
371
- console.error(`Failed to list tunnels for reuse check: ${formatApiError(error)}`);
372
- process.exit(1);
419
+ let apiKey = saved?.apiKey;
420
+ if (hasApiUpdate || !hasMutation) {
421
+ apiKey = await resolveConfigureApiKey(opts);
422
+ }
423
+ if (!apiKey) {
424
+ const envKey = process.env.PUBBLUE_API_KEY?.trim();
425
+ if (envKey) {
426
+ apiKey = envKey;
427
+ } else {
428
+ throw new Error(
429
+ "No API key available. Provide --api-key/--api-key-stdin (or run plain `pubblue configure` first)."
430
+ );
373
431
  }
374
432
  }
375
- if (!target) {
376
- try {
377
- const created = await apiClient.create({
378
- expiresIn: opts.expires
379
- });
380
- target = {
381
- createdNew: true,
382
- expiresAt: created.expiresAt,
383
- mode: "created",
384
- tunnelId: created.tunnelId,
385
- url: created.url
386
- };
387
- } catch (error) {
388
- console.error(`Failed to create tunnel: ${formatApiError(error)}`);
389
- process.exit(1);
390
- }
433
+ const nextBridge = { ...saved?.bridge ?? {} };
434
+ for (const entry of opts.set) {
435
+ const { key, value } = parseSetInput(entry);
436
+ applyBridgeSet(nextBridge, key, value);
391
437
  }
392
- if (!target) {
393
- console.error("Failed to resolve tunnel target.");
394
- process.exit(1);
438
+ for (const key of opts.unset) {
439
+ applyBridgeUnset(nextBridge, key.trim());
395
440
  }
396
- const socketPath = getSocketPath(target.tunnelId);
397
- const infoPath = tunnelInfoPath(target.tunnelId);
398
- const logPath = tunnelLogPath(target.tunnelId);
399
- if (opts.foreground) {
400
- if (bridgeMode !== "none") {
401
- console.error(
402
- "Foreground mode disables managed bridge process. Use background mode for --bridge openclaw."
403
- );
404
- }
405
- const { startDaemon } = await import("./tunnel-daemon-4LV6HLYN.js");
406
- console.log(`Tunnel started: ${target.url}`);
407
- console.log(`Tunnel ID: ${target.tunnelId}`);
408
- console.log(`Expires: ${new Date(target.expiresAt).toISOString()}`);
409
- if (target.mode === "existing") console.log("Mode: attached existing tunnel");
410
- console.log("Running in foreground. Press Ctrl+C to stop.");
411
- try {
412
- await startDaemon({
413
- tunnelId: target.tunnelId,
414
- apiClient,
415
- socketPath,
416
- infoPath
417
- });
418
- } catch (error) {
419
- const message = error instanceof Error ? error.message : String(error);
420
- console.error(`Daemon failed: ${message}`);
421
- process.exit(1);
422
- }
423
- } else {
424
- if (isDaemonRunning(target.tunnelId)) {
425
- try {
426
- const status = await ipcCall(socketPath, { method: "status", params: {} });
427
- if (!status.ok) throw new Error(String(status.error || "status check failed"));
428
- } catch (error) {
429
- console.error(
430
- `Daemon process exists but is not responding: ${error instanceof Error ? error.message : String(error)}`
431
- );
432
- console.error("Run `pubblue tunnel close <id>` and start again.");
433
- process.exit(1);
434
- }
435
- if (bridgeMode !== "none") {
436
- const bridgeReady = await ensureBridgeReady({
437
- bridgeMode,
438
- tunnelId: target.tunnelId,
439
- socketPath,
440
- bridgeProcessEnv,
441
- timeoutMs: 8e3
442
- });
443
- if (!bridgeReady.ok) {
444
- console.error(
445
- `Bridge failed to start for running tunnel: ${bridgeReady.reason ?? "unknown reason"}`
446
- );
447
- const existingBridgeLog = bridgeLogPath(target.tunnelId);
448
- if (fs2.existsSync(existingBridgeLog)) {
449
- console.error(`Bridge log: ${existingBridgeLog}`);
450
- const bridgeTail = readLogTail(existingBridgeLog);
451
- if (bridgeTail) {
452
- console.error("---- bridge log tail ----");
453
- console.error(bridgeTail.trimEnd());
454
- console.error("---- end bridge log tail ----");
455
- }
456
- }
457
- process.exit(1);
458
- }
459
- }
460
- console.log(`Tunnel started: ${target.url}`);
461
- console.log(`Tunnel ID: ${target.tunnelId}`);
462
- console.log(`Expires: ${new Date(target.expiresAt).toISOString()}`);
463
- console.log("Daemon already running for this tunnel.");
464
- console.log(`Daemon log: ${logPath}`);
465
- if (bridgeMode !== "none") {
466
- console.log("Bridge mode: openclaw");
467
- console.log(`Bridge log: ${bridgeLogPath(target.tunnelId)}`);
468
- }
469
- return;
470
- }
471
- const daemonScript = path2.join(import.meta.dirname, "tunnel-daemon-entry.js");
472
- const config = getConfig();
473
- const daemonLogFd = fs2.openSync(logPath, "a");
474
- const child = fork(daemonScript, [], {
475
- detached: true,
476
- stdio: buildDaemonForkStdio(daemonLogFd),
477
- env: {
478
- ...process.env,
479
- PUBBLUE_DAEMON_TUNNEL_ID: target.tunnelId,
480
- PUBBLUE_DAEMON_BASE_URL: config.baseUrl,
481
- PUBBLUE_DAEMON_API_KEY: config.apiKey,
482
- PUBBLUE_DAEMON_SOCKET: socketPath,
483
- PUBBLUE_DAEMON_INFO: infoPath
484
- }
485
- });
486
- fs2.closeSync(daemonLogFd);
487
- if (child.connected) {
488
- child.disconnect();
489
- }
490
- child.unref();
491
- console.log(`Starting daemon for tunnel ${target.tunnelId}...`);
492
- const ready = await waitForDaemonReady({
493
- child,
494
- infoPath,
495
- socketPath,
496
- timeoutMs: 8e3
497
- });
498
- if (!ready.ok) {
499
- console.error(`Daemon failed to start: ${ready.reason ?? "unknown reason"}`);
500
- console.error(`Daemon log: ${logPath}`);
501
- const tail = readLogTail(logPath);
502
- if (tail) {
503
- console.error("---- daemon log tail ----");
504
- console.error(tail.trimEnd());
505
- console.error("---- end daemon log tail ----");
506
- }
507
- await cleanupCreatedTunnelOnStartFailure(apiClient, target);
508
- process.exit(1);
509
- }
510
- const offerReady = await waitForAgentOffer({
511
- apiClient,
512
- tunnelId: target.tunnelId,
513
- timeoutMs: 5e3
514
- });
515
- if (!offerReady.ok) {
516
- console.error(`Daemon started but signaling is not ready: ${offerReady.reason}`);
517
- console.error(`Daemon log: ${logPath}`);
518
- const tail = readLogTail(logPath);
519
- if (tail) {
520
- console.error("---- daemon log tail ----");
521
- console.error(tail.trimEnd());
522
- console.error("---- end daemon log tail ----");
523
- }
524
- await cleanupCreatedTunnelOnStartFailure(apiClient, target);
525
- process.exit(1);
526
- }
527
- if (bridgeMode !== "none") {
528
- const bridgeReady = await ensureBridgeReady({
529
- bridgeMode,
530
- tunnelId: target.tunnelId,
531
- socketPath,
532
- bridgeProcessEnv,
533
- timeoutMs: 8e3
534
- });
535
- if (!bridgeReady.ok) {
536
- console.error(`Bridge failed to start: ${bridgeReady.reason ?? "unknown reason"}`);
537
- const bridgeLog = bridgeLogPath(target.tunnelId);
538
- if (fs2.existsSync(bridgeLog)) {
539
- console.error(`Bridge log: ${bridgeLog}`);
540
- const bridgeTail = readLogTail(bridgeLog);
541
- if (bridgeTail) {
542
- console.error("---- bridge log tail ----");
543
- console.error(bridgeTail.trimEnd());
544
- console.error("---- end bridge log tail ----");
545
- }
546
- }
547
- try {
548
- await ipcCall(socketPath, { method: "close", params: {} });
549
- } catch {
550
- }
551
- await cleanupCreatedTunnelOnStartFailure(apiClient, target);
552
- process.exit(1);
553
- }
554
- }
555
- console.log(`Tunnel started: ${target.url}`);
556
- console.log(`Tunnel ID: ${target.tunnelId}`);
557
- console.log(`Expires: ${new Date(target.expiresAt).toISOString()}`);
558
- if (target.mode === "existing") console.log("Mode: attached existing tunnel");
559
- console.log("Daemon health: OK");
560
- console.log(`Daemon log: ${logPath}`);
561
- if (bridgeMode !== "none") {
562
- console.log("Bridge mode: openclaw");
563
- console.log(`Bridge log: ${bridgeLogPath(target.tunnelId)}`);
564
- }
441
+ const nextConfig = {
442
+ apiKey,
443
+ bridge: hasBridgeValues(nextBridge) ? nextBridge : void 0
444
+ };
445
+ saveConfig(nextConfig);
446
+ console.log("Configuration saved.");
447
+ if (opts.show || hasSet || hasUnset) {
448
+ printConfigSummary(nextConfig);
565
449
  }
566
450
  }
567
451
  );
568
- tunnel.command("write").description("Write data to a channel").argument("[message]", "Text message (or use --file)").option("-t, --tunnel <tunnelId>", "Tunnel ID (auto-detected if one active)").option("-c, --channel <channel>", "Channel name", "chat").option("-f, --file <file>", "Read content from file").action(
569
- async (messageArg, opts) => {
570
- let msg;
571
- let binaryBase64;
572
- if (opts.file) {
573
- const filePath = path2.resolve(opts.file);
574
- const ext = path2.extname(filePath).toLowerCase();
575
- const bytes = fs2.readFileSync(filePath);
576
- const filename = path2.basename(filePath);
577
- if (ext === ".html" || ext === ".htm") {
578
- msg = {
579
- id: generateMessageId(),
580
- type: "html",
581
- data: bytes.toString("utf-8"),
582
- meta: { title: filename, filename, mime: getMimeType(filePath), size: bytes.length }
583
- };
584
- } else if (TEXT_FILE_EXTENSIONS.has(ext)) {
585
- msg = {
586
- id: generateMessageId(),
587
- type: "text",
588
- data: bytes.toString("utf-8"),
589
- meta: { filename, mime: getMimeType(filePath), size: bytes.length }
590
- };
591
- } else {
592
- msg = {
593
- id: generateMessageId(),
594
- type: "binary",
595
- meta: { filename, mime: getMimeType(filePath), size: bytes.length }
596
- };
597
- binaryBase64 = bytes.toString("base64");
598
- }
599
- } else if (messageArg) {
600
- msg = {
601
- id: generateMessageId(),
602
- type: "text",
603
- data: messageArg
604
- };
452
+ }
453
+
454
+ // src/commands/publications.ts
455
+ function registerPublicationCommands(program2) {
456
+ program2.command("create").description("Create a new publication").argument("[file]", "Path to the file (reads stdin if omitted)").option("--slug <slug>", "Custom slug for the URL").option("--title <title>", "Title for the publication").option("--public", "Make the publication public").option("--private", "Make the publication private (default)").option("--expires <duration>", "Auto-delete after duration (e.g. 1h, 24h, 7d)").action(
457
+ async (fileArg, opts) => {
458
+ const client = createClient();
459
+ let content;
460
+ let filename;
461
+ if (fileArg) {
462
+ const file = readFile(fileArg);
463
+ content = file.content;
464
+ filename = file.basename;
605
465
  } else {
606
- const chunks = [];
607
- for await (const chunk of process.stdin) chunks.push(chunk);
608
- msg = {
609
- id: generateMessageId(),
610
- type: "text",
611
- data: Buffer.concat(chunks).toString("utf-8").trim()
612
- };
466
+ content = await readFromStdin();
613
467
  }
614
- const tunnelId = opts.tunnel || await resolveActiveTunnel();
615
- const socketPath = getSocketPath(tunnelId);
616
- const response = await ipcCall(socketPath, {
617
- method: "write",
618
- params: { channel: opts.channel, msg, binaryBase64 }
468
+ const resolvedVisibility = resolveVisibilityFlags({
469
+ public: opts.public,
470
+ private: opts.private,
471
+ commandName: "create"
619
472
  });
620
- if (!response.ok) {
621
- console.error(`Failed: ${response.error}`);
622
- process.exit(1);
623
- }
624
- }
625
- );
626
- tunnel.command("read").description("Read buffered messages from channels").argument("[tunnelId]", "Tunnel ID (auto-detected if one active)").option("-t, --tunnel <tunnelId>", "Tunnel ID (alternative to positional arg)").option("-c, --channel <channel>", "Filter by channel").option("--follow", "Stream messages continuously").option("--all", "With --follow, include all channels instead of chat-only default").action(
627
- async (tunnelIdArg, opts) => {
628
- const tunnelId = resolveTunnelIdSelection(tunnelIdArg, opts.tunnel) || await resolveActiveTunnel();
629
- const socketPath = getSocketPath(tunnelId);
630
- const readChannel = opts.channel || (opts.follow && !opts.all ? CHANNELS.CHAT : void 0);
631
- if (opts.follow) {
632
- if (!opts.channel && !opts.all) {
633
- console.error(
634
- "Following chat channel by default. Use `--all` to include binary/file channels."
635
- );
636
- }
637
- let consecutiveFailures = 0;
638
- let warnedDisconnected = false;
639
- while (true) {
640
- try {
641
- const response = await ipcCall(socketPath, {
642
- method: "read",
643
- params: { channel: readChannel }
644
- });
645
- if (warnedDisconnected) {
646
- console.error("Daemon reconnected.");
647
- warnedDisconnected = false;
648
- }
649
- consecutiveFailures = 0;
650
- if (response.messages && response.messages.length > 0) {
651
- for (const m of response.messages) {
652
- console.log(JSON.stringify(m));
653
- }
654
- }
655
- } catch (error) {
656
- consecutiveFailures += 1;
657
- if (!warnedDisconnected) {
658
- const detail = error instanceof Error ? ` ${error.message}` : "";
659
- console.error(`Daemon disconnected. Waiting for recovery...${detail}`);
660
- warnedDisconnected = true;
661
- }
662
- }
663
- const delayMs = getFollowReadDelayMs(warnedDisconnected, consecutiveFailures);
664
- await new Promise((r) => setTimeout(r, delayMs));
665
- }
666
- } else {
667
- const response = await ipcCall(socketPath, {
668
- method: "read",
669
- params: { channel: readChannel }
670
- });
671
- if (!response.ok) {
672
- console.error(`Failed: ${response.error}`);
673
- process.exit(1);
674
- }
675
- console.log(JSON.stringify(response.messages || [], null, 2));
473
+ const result = await client.create({
474
+ content,
475
+ filename,
476
+ title: opts.title,
477
+ slug: opts.slug,
478
+ isPublic: resolvedVisibility ?? false,
479
+ expiresIn: opts.expires
480
+ });
481
+ console.log(`Created: ${result.url}`);
482
+ if (result.expiresAt) {
483
+ console.log(` Expires: ${new Date(result.expiresAt).toISOString()}`);
676
484
  }
677
485
  }
678
486
  );
679
- tunnel.command("channels").description("List active channels").argument("[tunnelId]", "Tunnel ID").option("-t, --tunnel <tunnelId>", "Tunnel ID (alternative to positional arg)").action(async (tunnelIdArg, opts) => {
680
- const tunnelId = resolveTunnelIdSelection(tunnelIdArg, opts.tunnel) || await resolveActiveTunnel();
681
- const socketPath = getSocketPath(tunnelId);
682
- const response = await ipcCall(socketPath, { method: "channels", params: {} });
683
- if (response.channels) {
684
- for (const ch of response.channels) {
685
- console.log(` ${ch.name} [${ch.direction}]`);
686
- }
487
+ program2.command("get").description("Get details of a publication").argument("<slug>", "Slug of the publication").option("--content", "Output raw content to stdout (no metadata, pipeable)").action(async (slug, opts) => {
488
+ const client = createClient();
489
+ const pub = await client.get(slug);
490
+ if (opts.content) {
491
+ process.stdout.write(pub.content);
492
+ return;
687
493
  }
494
+ console.log(` Slug: ${pub.slug}`);
495
+ console.log(` Type: ${pub.contentType}`);
496
+ if (pub.title) console.log(` Title: ${pub.title}`);
497
+ console.log(` Status: ${formatVisibility(pub.isPublic)}`);
498
+ if (pub.expiresAt) console.log(` Expires: ${new Date(pub.expiresAt).toISOString()}`);
499
+ console.log(` Created: ${new Date(pub.createdAt).toLocaleDateString()}`);
500
+ console.log(` Updated: ${new Date(pub.updatedAt).toLocaleDateString()}`);
501
+ console.log(` Size: ${pub.content.length} bytes`);
688
502
  });
689
- tunnel.command("status").description("Check tunnel connection status").argument("[tunnelId]", "Tunnel ID").option("-t, --tunnel <tunnelId>", "Tunnel ID (alternative to positional arg)").action(async (tunnelIdArg, opts) => {
690
- const tunnelId = resolveTunnelIdSelection(tunnelIdArg, opts.tunnel) || await resolveActiveTunnel();
691
- const socketPath = getSocketPath(tunnelId);
692
- const response = await ipcCall(socketPath, { method: "status", params: {} });
693
- console.log(` Status: ${response.connected ? "connected" : "waiting"}`);
694
- console.log(` Uptime: ${response.uptime}s`);
695
- const chNames = Array.isArray(response.channels) ? response.channels.map((c) => typeof c === "string" ? c : String(c)) : [];
696
- console.log(` Channels: ${chNames.join(", ")}`);
697
- console.log(` Buffered: ${response.bufferedMessages ?? 0} messages`);
698
- if (typeof response.lastError === "string" && response.lastError.length > 0) {
699
- console.log(` Last error: ${response.lastError}`);
700
- }
701
- const logPath = tunnelLogPath(tunnelId);
702
- if (fs2.existsSync(logPath)) {
703
- console.log(` Log: ${logPath}`);
704
- }
705
- const bridgeInfo = readBridgeProcessInfo(tunnelId);
706
- if (bridgeInfo) {
707
- const bridgeRunning = isBridgeRunning(tunnelId);
708
- const bridgeState = bridgeInfo.status || (bridgeRunning ? "running" : "stopped");
709
- console.log(` Bridge: ${bridgeInfo.mode} (${bridgeState})`);
710
- if (bridgeInfo.sessionId) {
711
- console.log(` Bridge session: ${bridgeInfo.sessionId}`);
712
- }
713
- if (!bridgeRunning && bridgeInfo.lastError) {
714
- console.log(` Bridge error: ${bridgeInfo.lastError}`);
503
+ program2.command("update").description("Update a publication's content and/or metadata").argument("<slug>", "Slug of the publication to update").option("--file <file>", "New content from file").option("--title <title>", "New title").option("--public", "Make the publication public").option("--private", "Make the publication private").option("--slug <newSlug>", "Rename the slug").action(
504
+ async (slug, opts) => {
505
+ const client = createClient();
506
+ let content;
507
+ let filename;
508
+ if (opts.file) {
509
+ const file = readFile(opts.file);
510
+ content = file.content;
511
+ filename = file.basename;
715
512
  }
513
+ const isPublic = resolveVisibilityFlags({
514
+ public: opts.public,
515
+ private: opts.private,
516
+ commandName: "update"
517
+ });
518
+ const result = await client.update({
519
+ slug,
520
+ content,
521
+ filename,
522
+ title: opts.title,
523
+ isPublic,
524
+ newSlug: opts.slug
525
+ });
526
+ console.log(`Updated: ${result.slug}`);
527
+ if (result.title) console.log(` Title: ${result.title}`);
528
+ console.log(` Status: ${formatVisibility(result.isPublic)}`);
716
529
  }
717
- const bridgeLog = bridgeLogPath(tunnelId);
718
- if (fs2.existsSync(bridgeLog)) {
719
- console.log(` Bridge log: ${bridgeLog}`);
530
+ );
531
+ program2.command("list").description("List your publications").action(async () => {
532
+ const client = createClient();
533
+ const pubs = await client.list();
534
+ if (pubs.length === 0) {
535
+ console.log("No publications.");
536
+ return;
537
+ }
538
+ for (const pub of pubs) {
539
+ const date = new Date(pub.createdAt).toLocaleDateString();
540
+ const expires = pub.expiresAt ? ` expires:${new Date(pub.expiresAt).toISOString()}` : "";
541
+ console.log(
542
+ ` ${pub.slug} [${pub.contentType}] ${formatVisibility(pub.isPublic)} ${date}${expires}`
543
+ );
720
544
  }
721
545
  });
722
- tunnel.command("doctor").description("Run strict end-to-end tunnel checks (daemon, channels, chat/canvas ping)").option("-t, --tunnel <tunnelId>", "Tunnel ID (auto-detected if one active)").option("--timeout <seconds>", "Timeout for pong wait and repeated reads", "30").option("--wait-pong", "Wait for user to reply with exact text 'pong' on chat channel").option("--skip-chat", "Skip chat ping check").option("--skip-canvas", "Skip canvas ping check").action(
723
- async (opts) => {
724
- const timeoutSeconds = parsePositiveIntegerOption(opts.timeout, "--timeout");
725
- const timeoutMs = timeoutSeconds * 1e3;
726
- const tunnelId = opts.tunnel || await resolveActiveTunnel();
727
- const socketPath = getSocketPath(tunnelId);
728
- const apiClient = createApiClient();
729
- const fail = (message) => {
730
- console.error(`Doctor failed: ${message}`);
731
- process.exit(1);
732
- };
733
- console.log(`Doctor tunnel: ${tunnelId}`);
734
- let statusResponse = null;
735
- try {
736
- statusResponse = await ipcCall(socketPath, {
737
- method: "status",
738
- params: {}
739
- });
740
- } catch (error) {
741
- fail(
742
- `daemon is unreachable (${error instanceof Error ? error.message : String(error)}).`
743
- );
744
- }
745
- if (!statusResponse) {
746
- fail("daemon status returned no response.");
747
- }
748
- const daemonStatus = statusResponse;
749
- if (!daemonStatus.ok) {
750
- fail(`daemon returned non-ok status: ${String(daemonStatus.error || "unknown error")}`);
751
- }
752
- if (!daemonStatus.connected) {
753
- fail("daemon is running but browser is not connected.");
754
- }
755
- const channelNames = Array.isArray(daemonStatus.channels) ? daemonStatus.channels.map((entry) => String(entry)) : [];
756
- for (const required of [CONTROL_CHANNEL, CHANNELS.CHAT, CHANNELS.CANVAS]) {
757
- if (!channelNames.includes(required)) {
758
- fail(`required channel is missing: ${required}`);
759
- }
760
- }
761
- console.log("Daemon/channel check: OK");
762
- let tunnelInfo = null;
763
- try {
764
- tunnelInfo = await apiClient.get(tunnelId);
765
- } catch (error) {
766
- fail(`failed to fetch tunnel info from API: ${formatApiError(error)}`);
767
- }
768
- if (!tunnelInfo) {
769
- fail("API returned no tunnel payload.");
770
- }
771
- const apiTunnel = tunnelInfo;
772
- if (apiTunnel.status !== "active") {
773
- fail(`API reports tunnel is not active (status: ${apiTunnel.status})`);
774
- }
775
- if (apiTunnel.expiresAt <= Date.now()) {
776
- fail("API reports tunnel is expired.");
777
- }
778
- if (!apiTunnel.hasConnection) {
779
- fail("API reports no browser connection.");
780
- }
781
- if (typeof apiTunnel.agentOffer !== "string" || apiTunnel.agentOffer.length === 0) {
782
- fail("agent offer was not published.");
783
- }
784
- console.log("API/signaling check: OK");
785
- if (!opts.skipChat) {
786
- const pingText = "This is a ping test. Reply with 'pong'.";
787
- const pingMsg = {
788
- id: generateMessageId(),
789
- type: "text",
790
- data: pingText
791
- };
792
- const writeResponse = await ipcCall(socketPath, {
793
- method: "write",
794
- params: { channel: CHANNELS.CHAT, msg: pingMsg }
795
- });
796
- if (!writeResponse.ok) {
797
- fail(`chat ping failed: ${String(writeResponse.error || "unknown write error")}`);
798
- }
799
- console.log("Chat ping write ACK: OK");
800
- if (opts.waitPong) {
801
- const startedAt = Date.now();
802
- let receivedPong = false;
803
- while (Date.now() - startedAt < timeoutMs) {
804
- const readResponse = await ipcCall(socketPath, {
805
- method: "read",
806
- params: { channel: CHANNELS.CHAT }
807
- });
808
- if (!readResponse.ok) {
809
- fail(
810
- `chat read failed while waiting for pong: ${String(readResponse.error || "unknown read error")}`
811
- );
812
- }
813
- const messages = Array.isArray(readResponse.messages) ? readResponse.messages : [];
814
- if (messages.some((entry) => messageContainsPong(entry))) {
815
- receivedPong = true;
816
- break;
817
- }
818
- await new Promise((resolve3) => setTimeout(resolve3, 1e3));
819
- }
820
- if (!receivedPong) {
821
- fail(
822
- `timed out after ${timeoutSeconds}s waiting for exact 'pong' reply on chat channel.`
823
- );
824
- }
825
- console.log("Chat pong roundtrip: OK");
826
- }
827
- }
828
- if (!opts.skipCanvas) {
829
- const stamp = (/* @__PURE__ */ new Date()).toISOString();
830
- const canvasMsg = {
831
- id: generateMessageId(),
832
- type: "html",
833
- data: `<!doctype html><html><body style="margin:0;padding:24px;font-family:system-ui;background:#111;color:#f5f5f5">Canvas ping OK<br><small>${stamp}</small></body></html>`
834
- };
835
- const canvasResponse = await ipcCall(socketPath, {
836
- method: "write",
837
- params: { channel: CHANNELS.CANVAS, msg: canvasMsg }
838
- });
839
- if (!canvasResponse.ok) {
840
- fail(`canvas ping failed: ${String(canvasResponse.error || "unknown write error")}`);
841
- }
842
- console.log("Canvas ping write ACK: OK");
843
- }
844
- console.log("Tunnel doctor: PASS");
845
- }
846
- );
847
- tunnel.command("list").description("List active tunnels").action(async () => {
848
- const apiClient = createApiClient();
849
- const tunnels = await apiClient.list();
850
- if (tunnels.length === 0) {
851
- console.log("No active tunnels.");
852
- return;
853
- }
854
- for (const t of tunnels) {
855
- const age = Math.floor((Date.now() - t.createdAt) / 6e4);
856
- const running = isDaemonRunning(t.tunnelId) ? "running" : "no daemon";
857
- const bridgeInfo = readBridgeProcessInfo(t.tunnelId);
858
- const bridge = bridgeInfo ? isBridgeRunning(t.tunnelId) ? `${bridgeInfo.mode}:running` : `${bridgeInfo.mode}:stopped` : "none";
859
- const conn = t.hasConnection ? "connected" : "waiting";
860
- console.log(` ${t.tunnelId} ${conn} ${running} bridge=${bridge} ${age}m ago`);
861
- }
862
- });
863
- tunnel.command("close").description("Close a tunnel and stop its daemon").argument("<tunnelId>", "Tunnel ID").action(async (tunnelId) => {
864
- stopBridgeProcess(tunnelId);
865
- try {
866
- fs2.unlinkSync(bridgeInfoPath(tunnelId));
867
- } catch {
868
- }
869
- const socketPath = getSocketPath(tunnelId);
870
- try {
871
- await ipcCall(socketPath, { method: "close", params: {} });
872
- } catch {
873
- }
874
- const apiClient = createApiClient();
875
- try {
876
- await apiClient.close(tunnelId);
877
- } catch (error) {
878
- const message = formatApiError(error);
879
- if (!/Tunnel not found/i.test(message)) {
880
- console.error(`Failed to close tunnel ${tunnelId}: ${message}`);
881
- process.exit(1);
882
- }
883
- }
884
- console.log(`Closed: ${tunnelId}`);
546
+ program2.command("delete").description("Delete a publication").argument("<slug>", "Slug of the publication to delete").action(async (slug) => {
547
+ const client = createClient();
548
+ await client.remove(slug);
549
+ console.log(`Deleted: ${slug}`);
885
550
  });
886
551
  }
887
- async function resolveActiveTunnel() {
888
- const dir = tunnelInfoDir();
889
- const files = fs2.readdirSync(dir).filter((f) => f.endsWith(".json") && !f.endsWith(".bridge.json"));
890
- const active = [];
891
- for (const f of files) {
892
- const tunnelId = f.replace(".json", "");
893
- if (isDaemonRunning(tunnelId)) active.push(tunnelId);
552
+
553
+ // src/commands/tunnel/management-commands.ts
554
+ import * as fs4 from "fs";
555
+
556
+ // src/commands/tunnel-helpers.ts
557
+ import { fork } from "child_process";
558
+ import * as fs3 from "fs";
559
+ import * as path3 from "path";
560
+ var TEXT_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
561
+ ".txt",
562
+ ".md",
563
+ ".markdown",
564
+ ".json",
565
+ ".csv",
566
+ ".xml",
567
+ ".yaml",
568
+ ".yml",
569
+ ".js",
570
+ ".mjs",
571
+ ".cjs",
572
+ ".ts",
573
+ ".tsx",
574
+ ".jsx",
575
+ ".css",
576
+ ".scss",
577
+ ".sass",
578
+ ".less",
579
+ ".log"
580
+ ]);
581
+ function getMimeType(filePath) {
582
+ const ext = path3.extname(filePath).toLowerCase();
583
+ const mimeByExt = {
584
+ ".html": "text/html; charset=utf-8",
585
+ ".htm": "text/html; charset=utf-8",
586
+ ".txt": "text/plain; charset=utf-8",
587
+ ".md": "text/markdown; charset=utf-8",
588
+ ".markdown": "text/markdown; charset=utf-8",
589
+ ".json": "application/json",
590
+ ".csv": "text/csv; charset=utf-8",
591
+ ".xml": "application/xml",
592
+ ".yaml": "application/x-yaml",
593
+ ".yml": "application/x-yaml",
594
+ ".png": "image/png",
595
+ ".jpg": "image/jpeg",
596
+ ".jpeg": "image/jpeg",
597
+ ".gif": "image/gif",
598
+ ".webp": "image/webp",
599
+ ".svg": "image/svg+xml",
600
+ ".pdf": "application/pdf",
601
+ ".zip": "application/zip",
602
+ ".mp3": "audio/mpeg",
603
+ ".wav": "audio/wav",
604
+ ".mp4": "video/mp4"
605
+ };
606
+ return mimeByExt[ext] || "application/octet-stream";
607
+ }
608
+ function tunnelInfoDir() {
609
+ const dir = path3.join(
610
+ process.env.HOME || process.env.USERPROFILE || "/tmp",
611
+ ".config",
612
+ "pubblue",
613
+ "tunnels"
614
+ );
615
+ if (!fs3.existsSync(dir)) fs3.mkdirSync(dir, { recursive: true });
616
+ return dir;
617
+ }
618
+ function tunnelInfoPath(tunnelId) {
619
+ return path3.join(tunnelInfoDir(), `${tunnelId}.json`);
620
+ }
621
+ function tunnelLogPath(tunnelId) {
622
+ return path3.join(tunnelInfoDir(), `${tunnelId}.log`);
623
+ }
624
+ function bridgeInfoPath(tunnelId) {
625
+ return path3.join(tunnelInfoDir(), `${tunnelId}.bridge.json`);
626
+ }
627
+ function bridgeLogPath(tunnelId) {
628
+ return path3.join(tunnelInfoDir(), `${tunnelId}.bridge.log`);
629
+ }
630
+ function createApiClient(configOverride) {
631
+ const config = configOverride || getConfig();
632
+ return new TunnelApiClient(config.baseUrl, config.apiKey);
633
+ }
634
+ function buildBridgeProcessEnv(bridgeConfig) {
635
+ const env = { ...process.env };
636
+ if (!bridgeConfig) return env;
637
+ const setIfMissing = (key, value) => {
638
+ if (value === void 0 || value === null) return;
639
+ const current = env[key];
640
+ if (typeof current === "string" && current.length > 0) return;
641
+ env[key] = String(value);
642
+ };
643
+ setIfMissing("OPENCLAW_PATH", bridgeConfig.openclawPath);
644
+ setIfMissing("OPENCLAW_SESSION_ID", bridgeConfig.sessionId);
645
+ setIfMissing("OPENCLAW_THREAD_ID", bridgeConfig.threadId);
646
+ if (bridgeConfig.deliver !== void 0) {
647
+ setIfMissing("OPENCLAW_DELIVER", bridgeConfig.deliver ? "1" : "0");
894
648
  }
895
- if (active.length === 0) {
896
- console.error("No active tunnels. Run `pubblue tunnel start` first.");
897
- process.exit(1);
649
+ setIfMissing("OPENCLAW_DELIVER_CHANNEL", bridgeConfig.deliverChannel);
650
+ setIfMissing("OPENCLAW_REPLY_TO", bridgeConfig.replyTo);
651
+ if (bridgeConfig.deliverTimeoutMs !== void 0) {
652
+ setIfMissing("OPENCLAW_DELIVER_TIMEOUT_MS", bridgeConfig.deliverTimeoutMs);
898
653
  }
899
- if (active.length === 1) return active[0];
900
- console.error(`Multiple active tunnels: ${active.join(", ")}. Specify one.`);
901
- process.exit(1);
654
+ setIfMissing("OPENCLAW_ATTACHMENT_DIR", bridgeConfig.attachmentDir);
655
+ if (bridgeConfig.attachmentMaxBytes !== void 0) {
656
+ setIfMissing("OPENCLAW_ATTACHMENT_MAX_BYTES", bridgeConfig.attachmentMaxBytes);
657
+ }
658
+ return env;
902
659
  }
903
- function waitForDaemonReady({
904
- child,
905
- infoPath,
906
- socketPath,
907
- timeoutMs
908
- }) {
660
+ async function ensureNodeDatachannelAvailable() {
661
+ try {
662
+ await import("node-datachannel");
663
+ } catch (error) {
664
+ const message = error instanceof Error ? error.message : String(error);
665
+ failCli(
666
+ [
667
+ "node-datachannel native module is not available.",
668
+ "Run `pnpm rebuild node-datachannel` in the cli package and retry.",
669
+ `Details: ${message}`
670
+ ].join("\n")
671
+ );
672
+ }
673
+ }
674
+ function isDaemonRunning(tunnelId) {
675
+ return readDaemonProcessInfo(tunnelId) !== null;
676
+ }
677
+ function readDaemonProcessInfo(tunnelId) {
678
+ const infoPath = tunnelInfoPath(tunnelId);
679
+ if (!fs3.existsSync(infoPath)) return null;
680
+ try {
681
+ const info = JSON.parse(fs3.readFileSync(infoPath, "utf-8"));
682
+ if (!Number.isFinite(info.pid)) throw new Error("invalid daemon pid");
683
+ process.kill(info.pid, 0);
684
+ return info;
685
+ } catch {
686
+ try {
687
+ fs3.unlinkSync(infoPath);
688
+ } catch {
689
+ }
690
+ return null;
691
+ }
692
+ }
693
+ function readBridgeProcessInfo(tunnelId) {
694
+ const infoPath = bridgeInfoPath(tunnelId);
695
+ if (!fs3.existsSync(infoPath)) return null;
696
+ try {
697
+ return JSON.parse(fs3.readFileSync(infoPath, "utf-8"));
698
+ } catch {
699
+ return null;
700
+ }
701
+ }
702
+ function isBridgeRunning(tunnelId) {
703
+ const infoPath = bridgeInfoPath(tunnelId);
704
+ if (!fs3.existsSync(infoPath)) return false;
705
+ try {
706
+ const info = JSON.parse(fs3.readFileSync(infoPath, "utf-8"));
707
+ process.kill(info.pid, 0);
708
+ return true;
709
+ } catch {
710
+ try {
711
+ fs3.unlinkSync(infoPath);
712
+ } catch {
713
+ }
714
+ return false;
715
+ }
716
+ }
717
+ function stopBridgeProcess(tunnelId) {
718
+ const info = readBridgeProcessInfo(tunnelId);
719
+ if (!info || !Number.isFinite(info.pid)) return;
720
+ try {
721
+ process.kill(info.pid, "SIGTERM");
722
+ } catch {
723
+ }
724
+ }
725
+ function buildBridgeForkStdio(logFd) {
726
+ return ["ignore", logFd, logFd, "ipc"];
727
+ }
728
+ function getFollowReadDelayMs(disconnected, consecutiveFailures) {
729
+ if (!disconnected) return 1e3;
730
+ return Math.min(5e3, 1e3 * 2 ** Math.min(consecutiveFailures, 3));
731
+ }
732
+ function resolveTunnelIdSelection(tunnelIdArg, tunnelOpt) {
733
+ return tunnelOpt || tunnelIdArg;
734
+ }
735
+ function buildDaemonForkStdio(logFd) {
736
+ return ["ignore", logFd, logFd, "ipc"];
737
+ }
738
+ function parsePositiveIntegerOption(raw, optionName) {
739
+ const parsed = Number.parseInt(raw, 10);
740
+ if (!Number.isFinite(parsed) || parsed <= 0) {
741
+ throw new Error(`${optionName} must be a positive integer. Received: ${raw}`);
742
+ }
743
+ return parsed;
744
+ }
745
+ function parseBridgeMode(raw) {
746
+ const normalized = raw.trim().toLowerCase();
747
+ if (normalized === "openclaw" || normalized === "none") {
748
+ return normalized;
749
+ }
750
+ throw new Error(`--bridge must be one of: openclaw, none. Received: ${raw}`);
751
+ }
752
+ function shouldRestartDaemonForCliUpgrade(daemonCliVersion, currentCliVersion) {
753
+ if (!daemonCliVersion || daemonCliVersion.trim().length === 0) return true;
754
+ return daemonCliVersion.trim() !== currentCliVersion;
755
+ }
756
+ function messageContainsPong(payload) {
757
+ if (!payload || typeof payload !== "object") return false;
758
+ const message = payload.msg;
759
+ if (!message || typeof message !== "object") return false;
760
+ const type = message.type;
761
+ const data = message.data;
762
+ return type === "text" && typeof data === "string" && data.trim().toLowerCase() === "pong";
763
+ }
764
+ function getPublicTunnelUrl(tunnelId) {
765
+ const base = process.env.PUBBLUE_PUBLIC_URL || "https://pub.blue";
766
+ return `${base.replace(/\/$/, "")}/t/${tunnelId}`;
767
+ }
768
+ function pickReusableTunnel(tunnels, nowMs = Date.now()) {
769
+ const active = tunnels.filter((t) => t.status === "active" && t.expiresAt > nowMs).sort((a, b) => b.createdAt - a.createdAt);
770
+ return active[0] ?? null;
771
+ }
772
+ function readLogTail(logPath, maxChars = 4e3) {
773
+ if (!fs3.existsSync(logPath)) return null;
774
+ try {
775
+ const content = fs3.readFileSync(logPath, "utf-8");
776
+ if (content.length <= maxChars) return content;
777
+ return content.slice(-maxChars);
778
+ } catch {
779
+ return null;
780
+ }
781
+ }
782
+ function formatApiError(error) {
783
+ if (error instanceof TunnelApiError) {
784
+ if (error.status === 429 && error.retryAfterSeconds !== void 0) {
785
+ return `Rate limit exceeded. Retry after ${error.retryAfterSeconds}s.`;
786
+ }
787
+ return `${error.message} (HTTP ${error.status})`;
788
+ }
789
+ return error instanceof Error ? error.message : String(error);
790
+ }
791
+ async function cleanupCreatedTunnelOnStartFailure(apiClient, target) {
792
+ if (!target.createdNew) return;
793
+ try {
794
+ await apiClient.close(target.tunnelId);
795
+ } catch (closeError) {
796
+ console.error(
797
+ `Failed to clean up newly created tunnel ${target.tunnelId}: ${formatApiError(closeError)}`
798
+ );
799
+ }
800
+ }
801
+ async function resolveActiveTunnel() {
802
+ const dir = tunnelInfoDir();
803
+ const files = fs3.readdirSync(dir).filter((f) => f.endsWith(".json") && !f.endsWith(".bridge.json"));
804
+ const active = [];
805
+ for (const f of files) {
806
+ const tunnelId = f.replace(".json", "");
807
+ if (isDaemonRunning(tunnelId)) active.push(tunnelId);
808
+ }
809
+ if (active.length === 0) {
810
+ failCli("No active tunnels. Run `pubblue tunnel start` first.");
811
+ }
812
+ if (active.length === 1) return active[0];
813
+ failCli(`Multiple active tunnels: ${active.join(", ")}. Specify one.`);
814
+ }
815
+ function waitForDaemonReady({
816
+ child,
817
+ infoPath,
818
+ socketPath,
819
+ timeoutMs
820
+ }) {
909
821
  return new Promise((resolve3) => {
910
822
  let settled = false;
911
823
  let pollInFlight = false;
@@ -924,7 +836,7 @@ function waitForDaemonReady({
924
836
  };
925
837
  child.on("exit", onExit);
926
838
  const poll = setInterval(() => {
927
- if (pollInFlight || !fs2.existsSync(infoPath)) return;
839
+ if (pollInFlight || !fs3.existsSync(infoPath)) return;
928
840
  pollInFlight = true;
929
841
  void ipcCall(socketPath, { method: "status", params: {} }).then((status) => {
930
842
  if (status.ok) done({ ok: true });
@@ -971,9 +883,9 @@ async function ensureBridgeReady(params) {
971
883
  timeoutMs: params.timeoutMs
972
884
  });
973
885
  }
974
- const bridgeScript = path2.join(import.meta.dirname, "tunnel-bridge-entry.js");
886
+ const bridgeScript = path3.join(import.meta.dirname, "tunnel-bridge-entry.js");
975
887
  const logPath = bridgeLogPath(params.tunnelId);
976
- const logFd = fs2.openSync(logPath, "a");
888
+ const logFd = fs3.openSync(logPath, "a");
977
889
  const child = fork(bridgeScript, [], {
978
890
  detached: true,
979
891
  stdio: buildBridgeForkStdio(logFd),
@@ -985,7 +897,7 @@ async function ensureBridgeReady(params) {
985
897
  PUBBLUE_BRIDGE_INFO: infoPath
986
898
  }
987
899
  });
988
- fs2.closeSync(logFd);
900
+ fs3.closeSync(logFd);
989
901
  if (child.connected) {
990
902
  child.disconnect();
991
903
  }
@@ -1025,7 +937,7 @@ function waitForBridgeReady({
1025
937
  child.on("exit", onExit);
1026
938
  }
1027
939
  const poll = setInterval(() => {
1028
- if (!fs2.existsSync(infoPath)) return;
940
+ if (!fs3.existsSync(infoPath)) return;
1029
941
  const info = readBridgeProcessInfo(tunnelId);
1030
942
  if (!info) return;
1031
943
  lastState = info.status;
@@ -1048,424 +960,714 @@ function waitForBridgeReady({
1048
960
  });
1049
961
  }
1050
962
 
1051
- // src/lib/api.ts
1052
- var PubApiClient = class {
1053
- constructor(baseUrl, apiKey) {
1054
- this.baseUrl = baseUrl;
1055
- this.apiKey = apiKey;
1056
- }
1057
- async request(path4, options = {}) {
1058
- const url = new URL(path4, this.baseUrl);
1059
- const res = await fetch(url, {
1060
- ...options,
1061
- headers: {
1062
- "Content-Type": "application/json",
1063
- Authorization: `Bearer ${this.apiKey}`,
1064
- ...options.headers
963
+ // src/commands/tunnel/management-commands.ts
964
+ function registerTunnelManagementCommands(tunnel) {
965
+ tunnel.command("channels").description("List active channels").argument("[tunnelId]", "Tunnel ID").option("-t, --tunnel <tunnelId>", "Tunnel ID (alternative to positional arg)").action(async (tunnelIdArg, opts) => {
966
+ const tunnelId = resolveTunnelIdSelection(tunnelIdArg, opts.tunnel) || await resolveActiveTunnel();
967
+ const socketPath = getSocketPath(tunnelId);
968
+ const response = await ipcCall(socketPath, { method: "channels", params: {} });
969
+ if (response.channels) {
970
+ for (const ch of response.channels) {
971
+ console.log(` ${ch.name} [${ch.direction}]`);
1065
972
  }
1066
- });
1067
- const data = await res.json();
1068
- if (!res.ok) {
1069
- throw new Error(data.error || `Request failed with status ${res.status}`);
1070
973
  }
1071
- return data;
1072
- }
1073
- async create(opts) {
1074
- return this.request("/api/v1/publications", {
1075
- method: "POST",
1076
- body: JSON.stringify(opts)
1077
- });
1078
- }
1079
- async get(slug) {
1080
- const data = await this.request(`/api/v1/publications/${encodeURIComponent(slug)}`);
1081
- return data.publication;
1082
- }
1083
- async listPage(cursor, limit) {
1084
- const params = new URLSearchParams();
1085
- if (cursor) params.set("cursor", cursor);
1086
- if (limit) params.set("limit", String(limit));
1087
- const qs = params.toString();
1088
- return this.request(`/api/v1/publications${qs ? `?${qs}` : ""}`);
1089
- }
1090
- async list() {
1091
- const all = [];
1092
- let cursor;
1093
- do {
1094
- const result = await this.listPage(cursor, 100);
1095
- all.push(...result.publications);
1096
- cursor = result.hasMore ? result.cursor : void 0;
1097
- } while (cursor);
1098
- return all;
1099
- }
1100
- async update(opts) {
1101
- const { slug, newSlug, ...rest } = opts;
1102
- const body = { ...rest };
1103
- if (newSlug) body.slug = newSlug;
1104
- return this.request(`/api/v1/publications/${encodeURIComponent(slug)}`, {
1105
- method: "PATCH",
1106
- body: JSON.stringify(body)
1107
- });
1108
- }
1109
- async remove(slug) {
1110
- await this.request(`/api/v1/publications/${encodeURIComponent(slug)}`, {
1111
- method: "DELETE"
1112
- });
1113
- }
1114
- };
1115
-
1116
- // src/index.ts
1117
- var program = new Command();
1118
- function createClient() {
1119
- const config = getConfig();
1120
- return new PubApiClient(config.baseUrl, config.apiKey);
1121
- }
1122
- async function readFromStdin() {
1123
- const chunks = [];
1124
- for await (const chunk of process.stdin) {
1125
- chunks.push(chunk);
1126
- }
1127
- return Buffer.concat(chunks).toString("utf-8").trim();
1128
- }
1129
- function formatVisibility(isPublic) {
1130
- return isPublic ? "public" : "private";
1131
- }
1132
- async function readApiKeyFromPrompt() {
1133
- const rl = createInterface({
1134
- input: process.stdin,
1135
- output: process.stdout
1136
974
  });
1137
- try {
1138
- const answer = await rl.question("Enter API key: ");
1139
- return answer.trim();
1140
- } finally {
1141
- rl.close();
1142
- }
1143
- }
1144
- async function resolveConfigureApiKey(opts) {
1145
- if (opts.apiKey && opts.apiKeyStdin) {
1146
- throw new Error("Use only one of --api-key or --api-key-stdin.");
1147
- }
1148
- if (opts.apiKey) {
1149
- return opts.apiKey.trim();
1150
- }
1151
- if (opts.apiKeyStdin) {
1152
- return readFromStdin();
1153
- }
1154
- const envKey = process.env.PUBBLUE_API_KEY?.trim();
1155
- if (envKey) return envKey;
1156
- if (!process.stdin.isTTY || !process.stdout.isTTY) {
1157
- throw new Error(
1158
- "No TTY available. Provide --api-key, --api-key-stdin, or PUBBLUE_API_KEY for configure."
1159
- );
1160
- }
1161
- return readApiKeyFromPrompt();
1162
- }
1163
- function collectValues(value, previous) {
1164
- previous.push(value);
1165
- return previous;
1166
- }
1167
- function parseSetInput(raw) {
1168
- const sepIndex = raw.indexOf("=");
1169
- if (sepIndex <= 0 || sepIndex === raw.length - 1) {
1170
- throw new Error(`Invalid --set entry "${raw}". Use key=value.`);
1171
- }
1172
- return {
1173
- key: raw.slice(0, sepIndex).trim(),
1174
- value: raw.slice(sepIndex + 1).trim()
1175
- };
1176
- }
1177
- function parseBooleanValue(raw, key) {
1178
- const normalized = raw.trim().toLowerCase();
1179
- if (normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on")
1180
- return true;
1181
- if (normalized === "0" || normalized === "false" || normalized === "no" || normalized === "off")
1182
- return false;
1183
- throw new Error(`Invalid boolean value for ${key}: ${raw}`);
1184
- }
1185
- function parseBridgeModeValue(raw) {
1186
- const normalized = raw.trim().toLowerCase();
1187
- if (normalized === "openclaw" || normalized === "none") return normalized;
1188
- throw new Error(`Invalid bridge mode: ${raw}. Use openclaw or none.`);
1189
- }
1190
- function parsePositiveInteger(raw, key) {
1191
- const parsed = Number.parseInt(raw, 10);
1192
- if (!Number.isFinite(parsed) || parsed <= 0) {
1193
- throw new Error(`${key} must be a positive integer. Received: ${raw}`);
1194
- }
1195
- return parsed;
1196
- }
1197
- function applyBridgeSet(bridge, key, value) {
1198
- switch (key) {
1199
- case "bridge.mode":
1200
- bridge.mode = parseBridgeModeValue(value);
1201
- return;
1202
- case "openclaw.path":
1203
- bridge.openclawPath = value;
1204
- return;
1205
- case "openclaw.sessionId":
1206
- bridge.sessionId = value;
1207
- return;
1208
- case "openclaw.threadId":
1209
- bridge.threadId = value;
1210
- return;
1211
- case "openclaw.deliver":
1212
- bridge.deliver = parseBooleanValue(value, key);
1213
- return;
1214
- case "openclaw.deliverChannel":
1215
- bridge.deliverChannel = value;
1216
- return;
1217
- case "openclaw.replyTo":
1218
- bridge.replyTo = value;
1219
- return;
1220
- case "openclaw.deliverTimeoutMs":
1221
- bridge.deliverTimeoutMs = parsePositiveInteger(value, key);
1222
- return;
1223
- default:
1224
- throw new Error(
1225
- [
1226
- `Unknown config key: ${key}`,
1227
- "Supported keys:",
1228
- " bridge.mode",
1229
- " openclaw.path",
1230
- " openclaw.sessionId",
1231
- " openclaw.threadId",
1232
- " openclaw.deliver",
1233
- " openclaw.deliverChannel",
1234
- " openclaw.replyTo",
1235
- " openclaw.deliverTimeoutMs"
1236
- ].join("\n")
1237
- );
1238
- }
1239
- }
1240
- function applyBridgeUnset(bridge, key) {
1241
- switch (key) {
1242
- case "bridge.mode":
1243
- delete bridge.mode;
1244
- return;
1245
- case "openclaw.path":
1246
- delete bridge.openclawPath;
1247
- return;
1248
- case "openclaw.sessionId":
1249
- delete bridge.sessionId;
1250
- return;
1251
- case "openclaw.threadId":
1252
- delete bridge.threadId;
1253
- return;
1254
- case "openclaw.deliver":
1255
- delete bridge.deliver;
1256
- return;
1257
- case "openclaw.deliverChannel":
1258
- delete bridge.deliverChannel;
1259
- return;
1260
- case "openclaw.replyTo":
1261
- delete bridge.replyTo;
1262
- return;
1263
- case "openclaw.deliverTimeoutMs":
1264
- delete bridge.deliverTimeoutMs;
975
+ tunnel.command("status").description("Check tunnel connection status").argument("[tunnelId]", "Tunnel ID").option("-t, --tunnel <tunnelId>", "Tunnel ID (alternative to positional arg)").action(async (tunnelIdArg, opts) => {
976
+ const tunnelId = resolveTunnelIdSelection(tunnelIdArg, opts.tunnel) || await resolveActiveTunnel();
977
+ const socketPath = getSocketPath(tunnelId);
978
+ const response = await ipcCall(socketPath, { method: "status", params: {} });
979
+ console.log(` Status: ${response.connected ? "connected" : "waiting"}`);
980
+ console.log(` Uptime: ${response.uptime}s`);
981
+ const chNames = Array.isArray(response.channels) ? response.channels.map((c) => typeof c === "string" ? c : String(c)) : [];
982
+ console.log(` Channels: ${chNames.join(", ")}`);
983
+ console.log(` Buffered: ${response.bufferedMessages ?? 0} messages`);
984
+ if (typeof response.lastError === "string" && response.lastError.length > 0) {
985
+ console.log(` Last error: ${response.lastError}`);
986
+ }
987
+ const logPath = tunnelLogPath(tunnelId);
988
+ if (fs4.existsSync(logPath)) {
989
+ console.log(` Log: ${logPath}`);
990
+ }
991
+ const bridgeInfo = readBridgeProcessInfo(tunnelId);
992
+ if (bridgeInfo) {
993
+ const bridgeRunning = isBridgeRunning(tunnelId);
994
+ const bridgeState = bridgeInfo.status || (bridgeRunning ? "running" : "stopped");
995
+ console.log(` Bridge: ${bridgeInfo.mode} (${bridgeState})`);
996
+ if (bridgeInfo.sessionId) {
997
+ console.log(` Bridge session: ${bridgeInfo.sessionId}`);
998
+ }
999
+ if (bridgeInfo.sessionSource) {
1000
+ console.log(` Bridge session source: ${bridgeInfo.sessionSource}`);
1001
+ }
1002
+ if (bridgeInfo.sessionKey) {
1003
+ console.log(` Bridge session key: ${bridgeInfo.sessionKey}`);
1004
+ }
1005
+ if (bridgeInfo.lastError) {
1006
+ console.log(` Bridge last error: ${bridgeInfo.lastError}`);
1007
+ }
1008
+ }
1009
+ const bridgeLog = bridgeLogPath(tunnelId);
1010
+ if (fs4.existsSync(bridgeLog)) {
1011
+ console.log(` Bridge log: ${bridgeLog}`);
1012
+ }
1013
+ });
1014
+ tunnel.command("doctor").description("Run strict end-to-end tunnel checks (daemon, channels, chat/canvas ping)").option("-t, --tunnel <tunnelId>", "Tunnel ID (auto-detected if one active)").option("--timeout <seconds>", "Timeout for pong wait and repeated reads", "30").option("--wait-pong", "Wait for user to reply with exact text 'pong' on chat channel").option("--skip-chat", "Skip chat ping check").option("--skip-canvas", "Skip canvas ping check").action(
1015
+ async (opts) => {
1016
+ const timeoutSeconds = parsePositiveIntegerOption(opts.timeout, "--timeout");
1017
+ const timeoutMs = timeoutSeconds * 1e3;
1018
+ const tunnelId = opts.tunnel || await resolveActiveTunnel();
1019
+ const socketPath = getSocketPath(tunnelId);
1020
+ const apiClient = createApiClient();
1021
+ const fail = (message) => failCli(`Doctor failed: ${message}`);
1022
+ console.log(`Doctor tunnel: ${tunnelId}`);
1023
+ let statusResponse = null;
1024
+ try {
1025
+ statusResponse = await ipcCall(socketPath, {
1026
+ method: "status",
1027
+ params: {}
1028
+ });
1029
+ } catch (error) {
1030
+ fail(
1031
+ `daemon is unreachable (${error instanceof Error ? error.message : String(error)}).`
1032
+ );
1033
+ }
1034
+ if (!statusResponse) {
1035
+ fail("daemon status returned no response.");
1036
+ }
1037
+ const daemonStatus = statusResponse;
1038
+ if (!daemonStatus.ok) {
1039
+ fail(`daemon returned non-ok status: ${String(daemonStatus.error || "unknown error")}`);
1040
+ }
1041
+ if (!daemonStatus.connected) {
1042
+ fail("daemon is running but browser is not connected.");
1043
+ }
1044
+ const channelNames = Array.isArray(daemonStatus.channels) ? daemonStatus.channels.map((entry) => String(entry)) : [];
1045
+ for (const required of [CONTROL_CHANNEL, CHANNELS.CHAT, CHANNELS.CANVAS]) {
1046
+ if (!channelNames.includes(required)) {
1047
+ fail(`required channel is missing: ${required}`);
1048
+ }
1049
+ }
1050
+ console.log("Daemon/channel check: OK");
1051
+ let apiTunnel;
1052
+ try {
1053
+ apiTunnel = await apiClient.get(tunnelId);
1054
+ } catch (error) {
1055
+ fail(`failed to fetch tunnel info from API: ${formatApiError(error)}`);
1056
+ }
1057
+ if (apiTunnel.status !== "active") {
1058
+ fail(`API reports tunnel is not active (status: ${apiTunnel.status})`);
1059
+ }
1060
+ if (apiTunnel.expiresAt <= Date.now()) {
1061
+ fail("API reports tunnel is expired.");
1062
+ }
1063
+ if (!apiTunnel.hasConnection) {
1064
+ fail("API reports no browser connection.");
1065
+ }
1066
+ if (typeof apiTunnel.agentOffer !== "string" || apiTunnel.agentOffer.length === 0) {
1067
+ fail("agent offer was not published.");
1068
+ }
1069
+ console.log("API/signaling check: OK");
1070
+ if (!opts.skipChat) {
1071
+ const pingText = "This is a ping test. Reply with 'pong'.";
1072
+ const pingMsg = {
1073
+ id: generateMessageId(),
1074
+ type: "text",
1075
+ data: pingText
1076
+ };
1077
+ const writeResponse = await ipcCall(socketPath, {
1078
+ method: "write",
1079
+ params: { channel: CHANNELS.CHAT, msg: pingMsg }
1080
+ });
1081
+ if (!writeResponse.ok) {
1082
+ fail(`chat ping failed: ${String(writeResponse.error || "unknown write error")}`);
1083
+ }
1084
+ console.log("Chat ping write ACK: OK");
1085
+ if (opts.waitPong) {
1086
+ const startedAt = Date.now();
1087
+ let receivedPong = false;
1088
+ while (Date.now() - startedAt < timeoutMs) {
1089
+ const readResponse = await ipcCall(socketPath, {
1090
+ method: "read",
1091
+ params: { channel: CHANNELS.CHAT }
1092
+ });
1093
+ if (!readResponse.ok) {
1094
+ fail(
1095
+ `chat read failed while waiting for pong: ${String(readResponse.error || "unknown read error")}`
1096
+ );
1097
+ }
1098
+ const messages = Array.isArray(readResponse.messages) ? readResponse.messages : [];
1099
+ if (messages.some((entry) => messageContainsPong(entry))) {
1100
+ receivedPong = true;
1101
+ break;
1102
+ }
1103
+ await new Promise((resolve3) => setTimeout(resolve3, 1e3));
1104
+ }
1105
+ if (!receivedPong) {
1106
+ fail(
1107
+ `timed out after ${timeoutSeconds}s waiting for exact 'pong' reply on chat channel.`
1108
+ );
1109
+ }
1110
+ console.log("Chat pong roundtrip: OK");
1111
+ }
1112
+ }
1113
+ if (!opts.skipCanvas) {
1114
+ const stamp = (/* @__PURE__ */ new Date()).toISOString();
1115
+ const canvasMsg = {
1116
+ id: generateMessageId(),
1117
+ type: "html",
1118
+ data: `<!doctype html><html><body style="margin:0;padding:24px;font-family:system-ui;background:#111;color:#f5f5f5">Canvas ping OK<br><small>${stamp}</small></body></html>`
1119
+ };
1120
+ const canvasResponse = await ipcCall(socketPath, {
1121
+ method: "write",
1122
+ params: { channel: CHANNELS.CANVAS, msg: canvasMsg }
1123
+ });
1124
+ if (!canvasResponse.ok) {
1125
+ fail(`canvas ping failed: ${String(canvasResponse.error || "unknown write error")}`);
1126
+ }
1127
+ console.log("Canvas ping write ACK: OK");
1128
+ }
1129
+ console.log("Tunnel doctor: PASS");
1130
+ }
1131
+ );
1132
+ tunnel.command("list").description("List active tunnels").action(async () => {
1133
+ const apiClient = createApiClient();
1134
+ const tunnels = await apiClient.list();
1135
+ if (tunnels.length === 0) {
1136
+ console.log("No active tunnels.");
1265
1137
  return;
1266
- default:
1267
- throw new Error(`Unknown config key for --unset: ${key}`);
1268
- }
1269
- }
1270
- function hasBridgeValues(bridge) {
1271
- return Object.values(bridge).some((value) => value !== void 0);
1272
- }
1273
- function maskApiKey(apiKey) {
1274
- if (apiKey.length <= 8) return "********";
1275
- return `${apiKey.slice(0, 4)}...${apiKey.slice(-4)}`;
1138
+ }
1139
+ for (const t of tunnels) {
1140
+ const age = Math.floor((Date.now() - t.createdAt) / 6e4);
1141
+ const running = isDaemonRunning(t.tunnelId) ? "running" : "no daemon";
1142
+ const bridgeInfo = readBridgeProcessInfo(t.tunnelId);
1143
+ const bridge = bridgeInfo ? isBridgeRunning(t.tunnelId) ? `${bridgeInfo.mode}:running` : `${bridgeInfo.mode}:stopped` : "none";
1144
+ const conn = t.hasConnection ? "connected" : "waiting";
1145
+ console.log(` ${t.tunnelId} ${conn} ${running} bridge=${bridge} ${age}m ago`);
1146
+ }
1147
+ });
1148
+ tunnel.command("close").description("Close a tunnel and stop its daemon").argument("<tunnelId>", "Tunnel ID").action(async (tunnelId) => {
1149
+ stopBridgeProcess(tunnelId);
1150
+ try {
1151
+ fs4.unlinkSync(bridgeInfoPath(tunnelId));
1152
+ } catch {
1153
+ }
1154
+ const socketPath = getSocketPath(tunnelId);
1155
+ try {
1156
+ await ipcCall(socketPath, { method: "close", params: {} });
1157
+ } catch {
1158
+ }
1159
+ const apiClient = createApiClient();
1160
+ try {
1161
+ await apiClient.close(tunnelId);
1162
+ } catch (error) {
1163
+ const message = formatApiError(error);
1164
+ if (!/Tunnel not found/i.test(message)) {
1165
+ failCli(`Failed to close tunnel ${tunnelId}: ${message}`);
1166
+ }
1167
+ }
1168
+ console.log(`Closed: ${tunnelId}`);
1169
+ });
1276
1170
  }
1277
- function printConfigSummary(saved) {
1278
- if (!saved) {
1279
- console.log("Saved config: none");
1280
- return;
1281
- }
1282
- console.log("Saved config:");
1283
- console.log(` apiKey: ${maskApiKey(saved.apiKey)}`);
1284
- if (!saved.bridge || !hasBridgeValues(saved.bridge)) {
1285
- console.log(" bridge: none");
1286
- return;
1287
- }
1288
- console.log(` bridge.mode: ${saved.bridge.mode ?? "(unset)"}`);
1289
- if (saved.bridge.openclawPath) console.log(` openclaw.path: ${saved.bridge.openclawPath}`);
1290
- if (saved.bridge.sessionId) console.log(` openclaw.sessionId: ${saved.bridge.sessionId}`);
1291
- if (saved.bridge.threadId) console.log(` openclaw.threadId: ${saved.bridge.threadId}`);
1292
- if (saved.bridge.deliver !== void 0)
1293
- console.log(` openclaw.deliver: ${saved.bridge.deliver ? "true" : "false"}`);
1294
- if (saved.bridge.deliverChannel)
1295
- console.log(` openclaw.deliverChannel: ${saved.bridge.deliverChannel}`);
1296
- if (saved.bridge.replyTo) console.log(` openclaw.replyTo: ${saved.bridge.replyTo}`);
1297
- if (saved.bridge.deliverTimeoutMs !== void 0)
1298
- console.log(` openclaw.deliverTimeoutMs: ${saved.bridge.deliverTimeoutMs}`);
1171
+
1172
+ // src/commands/tunnel/message-commands.ts
1173
+ import * as fs5 from "fs";
1174
+ import * as path4 from "path";
1175
+ function registerTunnelMessageCommands(tunnel) {
1176
+ tunnel.command("write").description("Write data to a channel").argument("[message]", "Text message (or use --file)").option("-t, --tunnel <tunnelId>", "Tunnel ID (auto-detected if one active)").option("-c, --channel <channel>", "Channel name", "chat").option("-f, --file <file>", "Read content from file").action(
1177
+ async (messageArg, opts) => {
1178
+ let msg;
1179
+ let binaryBase64;
1180
+ if (opts.file) {
1181
+ const filePath = path4.resolve(opts.file);
1182
+ const ext = path4.extname(filePath).toLowerCase();
1183
+ const bytes = fs5.readFileSync(filePath);
1184
+ const filename = path4.basename(filePath);
1185
+ if (ext === ".html" || ext === ".htm") {
1186
+ msg = {
1187
+ id: generateMessageId(),
1188
+ type: "html",
1189
+ data: bytes.toString("utf-8"),
1190
+ meta: { title: filename, filename, mime: getMimeType(filePath), size: bytes.length }
1191
+ };
1192
+ } else if (TEXT_FILE_EXTENSIONS.has(ext)) {
1193
+ msg = {
1194
+ id: generateMessageId(),
1195
+ type: "text",
1196
+ data: bytes.toString("utf-8"),
1197
+ meta: { filename, mime: getMimeType(filePath), size: bytes.length }
1198
+ };
1199
+ } else {
1200
+ msg = {
1201
+ id: generateMessageId(),
1202
+ type: "binary",
1203
+ meta: { filename, mime: getMimeType(filePath), size: bytes.length }
1204
+ };
1205
+ binaryBase64 = bytes.toString("base64");
1206
+ }
1207
+ } else if (messageArg) {
1208
+ msg = {
1209
+ id: generateMessageId(),
1210
+ type: "text",
1211
+ data: messageArg
1212
+ };
1213
+ } else {
1214
+ const chunks = [];
1215
+ for await (const chunk of process.stdin) chunks.push(chunk);
1216
+ msg = {
1217
+ id: generateMessageId(),
1218
+ type: "text",
1219
+ data: Buffer.concat(chunks).toString("utf-8").trim()
1220
+ };
1221
+ }
1222
+ const tunnelId = opts.tunnel || await resolveActiveTunnel();
1223
+ const socketPath = getSocketPath(tunnelId);
1224
+ const response = await ipcCall(socketPath, {
1225
+ method: "write",
1226
+ params: { channel: opts.channel, msg, binaryBase64 }
1227
+ });
1228
+ if (!response.ok) {
1229
+ failCli(`Failed: ${response.error}`);
1230
+ }
1231
+ }
1232
+ );
1233
+ tunnel.command("read").description("Read buffered messages from channels").argument("[tunnelId]", "Tunnel ID (auto-detected if one active)").option("-t, --tunnel <tunnelId>", "Tunnel ID (alternative to positional arg)").option("-c, --channel <channel>", "Filter by channel").option("--follow", "Stream messages continuously").option("--all", "With --follow, include all channels instead of chat-only default").action(
1234
+ async (tunnelIdArg, opts) => {
1235
+ const tunnelId = resolveTunnelIdSelection(tunnelIdArg, opts.tunnel) || await resolveActiveTunnel();
1236
+ const socketPath = getSocketPath(tunnelId);
1237
+ const readChannel = opts.channel || (opts.follow && !opts.all ? CHANNELS.CHAT : void 0);
1238
+ if (opts.follow) {
1239
+ if (!opts.channel && !opts.all) {
1240
+ console.error(
1241
+ "Following chat channel by default. Use `--all` to include binary/file channels."
1242
+ );
1243
+ }
1244
+ let consecutiveFailures = 0;
1245
+ let warnedDisconnected = false;
1246
+ while (true) {
1247
+ try {
1248
+ const response = await ipcCall(socketPath, {
1249
+ method: "read",
1250
+ params: { channel: readChannel }
1251
+ });
1252
+ if (warnedDisconnected) {
1253
+ console.error("Daemon reconnected.");
1254
+ warnedDisconnected = false;
1255
+ }
1256
+ consecutiveFailures = 0;
1257
+ if (response.messages && response.messages.length > 0) {
1258
+ for (const m of response.messages) {
1259
+ console.log(JSON.stringify(m));
1260
+ }
1261
+ }
1262
+ } catch (error) {
1263
+ consecutiveFailures += 1;
1264
+ if (!warnedDisconnected) {
1265
+ const detail = error instanceof Error ? ` ${error.message}` : "";
1266
+ console.error(`Daemon disconnected. Waiting for recovery...${detail}`);
1267
+ warnedDisconnected = true;
1268
+ }
1269
+ }
1270
+ const delayMs = getFollowReadDelayMs(warnedDisconnected, consecutiveFailures);
1271
+ await new Promise((resolve3) => setTimeout(resolve3, delayMs));
1272
+ }
1273
+ } else {
1274
+ const response = await ipcCall(socketPath, {
1275
+ method: "read",
1276
+ params: { channel: readChannel }
1277
+ });
1278
+ if (!response.ok) {
1279
+ failCli(`Failed: ${response.error}`);
1280
+ }
1281
+ console.log(JSON.stringify(response.messages || [], null, 2));
1282
+ }
1283
+ }
1284
+ );
1299
1285
  }
1300
- function resolveVisibilityFlags(opts) {
1301
- if (opts.public && opts.private) {
1302
- throw new Error(`Use only one of --public or --private for ${opts.commandName}.`);
1286
+
1287
+ // src/commands/tunnel/start-command.ts
1288
+ import { fork as fork2 } from "child_process";
1289
+ import * as fs6 from "fs";
1290
+ import * as path5 from "path";
1291
+
1292
+ // package.json
1293
+ var package_default = {
1294
+ name: "pubblue",
1295
+ version: "0.4.11",
1296
+ description: "CLI tool for publishing static content via pub.blue",
1297
+ type: "module",
1298
+ bin: {
1299
+ pubblue: "./dist/index.js"
1300
+ },
1301
+ scripts: {
1302
+ build: "tsup src/index.ts src/tunnel-daemon-entry.ts src/tunnel-bridge-entry.ts --format esm --dts --clean",
1303
+ dev: "tsup src/index.ts src/tunnel-daemon-entry.ts src/tunnel-bridge-entry.ts --format esm --watch",
1304
+ test: "vitest run",
1305
+ "test:watch": "vitest",
1306
+ lint: "tsc --noEmit"
1307
+ },
1308
+ dependencies: {
1309
+ commander: "^13.0.0",
1310
+ "node-datachannel": "^0.32.0"
1311
+ },
1312
+ devDependencies: {
1313
+ "@types/node": "22.10.2",
1314
+ tsup: "^8.3.6",
1315
+ typescript: "^5.7.2",
1316
+ vitest: "^3.0.0"
1317
+ },
1318
+ files: [
1319
+ "dist"
1320
+ ],
1321
+ repository: {
1322
+ type: "git",
1323
+ url: "git+https://github.com/xmanatee/pub.git",
1324
+ directory: "cli"
1325
+ },
1326
+ publishConfig: {
1327
+ access: "public"
1328
+ },
1329
+ pnpm: {
1330
+ onlyBuiltDependencies: [
1331
+ "esbuild",
1332
+ "node-datachannel"
1333
+ ]
1303
1334
  }
1304
- if (opts.public) return true;
1305
- if (opts.private) return false;
1306
- return void 0;
1335
+ };
1336
+
1337
+ // src/lib/version.ts
1338
+ var version = package_default.version;
1339
+ if (typeof version !== "string" || version.length === 0) {
1340
+ throw new Error("Invalid CLI version in package.json");
1307
1341
  }
1308
- function readFile(filePath) {
1309
- const resolved = path3.resolve(filePath);
1310
- if (!fs3.existsSync(resolved)) {
1311
- console.error(`File not found: ${resolved}`);
1312
- process.exit(1);
1342
+ var CLI_VERSION = version;
1343
+
1344
+ // src/commands/tunnel/start-command.ts
1345
+ async function waitForStopped(isRunning, timeoutMs, pollMs = 120) {
1346
+ const started = Date.now();
1347
+ while (Date.now() - started < timeoutMs) {
1348
+ if (!isRunning()) return true;
1349
+ await new Promise((resolve3) => setTimeout(resolve3, pollMs));
1313
1350
  }
1314
- return {
1315
- content: fs3.readFileSync(resolved, "utf-8"),
1316
- basename: path3.basename(resolved)
1317
- };
1351
+ return !isRunning();
1318
1352
  }
1319
- program.name("pubblue").description("Publish static content and get shareable URLs").version("0.4.10");
1320
- program.command("configure").description("Configure the CLI with your API key").option("--api-key <key>", "Your API key (less secure: appears in shell history)").option("--api-key-stdin", "Read API key from stdin").option(
1321
- "--set <key=value>",
1322
- "Set advanced config (repeatable). Example: --set openclaw.sessionId=<id>",
1323
- collectValues,
1324
- []
1325
- ).option("--unset <key>", "Unset advanced config key (repeatable)", collectValues, []).option("--show", "Show saved configuration").action(
1326
- async (opts) => {
1327
- try {
1328
- const saved = loadConfig();
1329
- const hasApiUpdate = Boolean(opts.apiKey || opts.apiKeyStdin);
1330
- const hasSet = opts.set.length > 0;
1331
- const hasUnset = opts.unset.length > 0;
1332
- const hasMutation = hasApiUpdate || hasSet || hasUnset;
1333
- if (!hasMutation && opts.show) {
1334
- printConfigSummary(saved);
1335
- return;
1353
+ function registerTunnelStartCommand(tunnel) {
1354
+ tunnel.command("start").description("Start a tunnel daemon (reuses existing tunnel when possible)").option("--expires <duration>", "Auto-close after duration (e.g. 4h, 1d)", "24h").option("-t, --tunnel <tunnelId>", "Attach/start daemon for an existing tunnel").option("--new", "Always create a new tunnel (skip single-tunnel reuse)").option("--bridge <mode>", "Bridge mode: openclaw|none").option("--foreground", "Run in foreground (don't fork, no managed bridge)").action(
1355
+ async (opts) => {
1356
+ await ensureNodeDatachannelAvailable();
1357
+ const runtimeConfig = getConfig();
1358
+ const apiClient = createApiClient(runtimeConfig);
1359
+ let target = null;
1360
+ const bridgeMode = parseBridgeMode(opts.bridge || runtimeConfig.bridge?.mode || "openclaw");
1361
+ const bridgeProcessEnv = buildBridgeProcessEnv(runtimeConfig.bridge);
1362
+ if (opts.tunnel) {
1363
+ try {
1364
+ const existing = await apiClient.get(opts.tunnel);
1365
+ if (existing.status === "closed" || existing.expiresAt <= Date.now()) {
1366
+ failCli(`Tunnel ${opts.tunnel} is closed or expired.`);
1367
+ }
1368
+ target = {
1369
+ createdNew: false,
1370
+ expiresAt: existing.expiresAt,
1371
+ mode: "existing",
1372
+ tunnelId: existing.tunnelId,
1373
+ url: getPublicTunnelUrl(existing.tunnelId)
1374
+ };
1375
+ } catch (error) {
1376
+ failCli(`Failed to use tunnel ${opts.tunnel}: ${formatApiError(error)}`);
1377
+ }
1378
+ } else if (!opts.new) {
1379
+ try {
1380
+ const listed = await apiClient.list();
1381
+ const active = listed.filter((t) => t.status === "active" && t.expiresAt > Date.now()).sort((a, b) => b.createdAt - a.createdAt);
1382
+ const reusable = pickReusableTunnel(listed);
1383
+ if (reusable) {
1384
+ target = {
1385
+ createdNew: false,
1386
+ expiresAt: reusable.expiresAt,
1387
+ mode: "existing",
1388
+ tunnelId: reusable.tunnelId,
1389
+ url: getPublicTunnelUrl(reusable.tunnelId)
1390
+ };
1391
+ if (active.length > 1) {
1392
+ console.error(
1393
+ [
1394
+ `Multiple active tunnels found: ${active.map((t) => t.tunnelId).join(", ")}`,
1395
+ `Reusing most recent active tunnel ${reusable.tunnelId}.`,
1396
+ "Use --tunnel <id> to choose explicitly or --new to force creation."
1397
+ ].join("\n")
1398
+ );
1399
+ } else {
1400
+ console.error(
1401
+ `Reusing existing active tunnel ${reusable.tunnelId}. Use --new to force creation.`
1402
+ );
1403
+ }
1404
+ }
1405
+ } catch (error) {
1406
+ failCli(`Failed to list tunnels for reuse check: ${formatApiError(error)}`);
1407
+ }
1336
1408
  }
1337
- let apiKey = saved?.apiKey;
1338
- if (hasApiUpdate || !hasMutation) {
1339
- apiKey = await resolveConfigureApiKey(opts);
1409
+ if (!target) {
1410
+ try {
1411
+ const created = await apiClient.create({
1412
+ expiresIn: opts.expires
1413
+ });
1414
+ target = {
1415
+ createdNew: true,
1416
+ expiresAt: created.expiresAt,
1417
+ mode: "created",
1418
+ tunnelId: created.tunnelId,
1419
+ url: created.url
1420
+ };
1421
+ } catch (error) {
1422
+ failCli(`Failed to create tunnel: ${formatApiError(error)}`);
1423
+ }
1340
1424
  }
1341
- if (!apiKey) {
1342
- const envKey = process.env.PUBBLUE_API_KEY?.trim();
1343
- if (envKey) {
1344
- apiKey = envKey;
1345
- } else {
1425
+ if (!target) {
1426
+ failCli("Failed to resolve tunnel target.");
1427
+ }
1428
+ const socketPath = getSocketPath(target.tunnelId);
1429
+ const infoPath = tunnelInfoPath(target.tunnelId);
1430
+ const logPath = tunnelLogPath(target.tunnelId);
1431
+ if (opts.foreground) {
1432
+ if (bridgeMode !== "none") {
1346
1433
  throw new Error(
1347
- "No API key available. Provide --api-key/--api-key-stdin (or run plain `pubblue configure` first)."
1434
+ "Foreground mode disables managed bridge process. Use background mode for --bridge openclaw."
1348
1435
  );
1349
1436
  }
1437
+ const { startDaemon } = await import("./tunnel-daemon-7B2QUHK5.js");
1438
+ console.log(`Tunnel started: ${target.url}`);
1439
+ console.log(`Tunnel ID: ${target.tunnelId}`);
1440
+ console.log(`Expires: ${new Date(target.expiresAt).toISOString()}`);
1441
+ if (target.mode === "existing") console.log("Mode: attached existing tunnel");
1442
+ console.log("Running in foreground. Press Ctrl+C to stop.");
1443
+ try {
1444
+ await startDaemon({
1445
+ cliVersion: CLI_VERSION,
1446
+ tunnelId: target.tunnelId,
1447
+ apiClient,
1448
+ socketPath,
1449
+ infoPath
1450
+ });
1451
+ } catch (error) {
1452
+ const message = error instanceof Error ? error.message : String(error);
1453
+ failCli(`Daemon failed: ${message}`);
1454
+ }
1455
+ return;
1350
1456
  }
1351
- const nextBridge = { ...saved?.bridge ?? {} };
1352
- for (const entry of opts.set) {
1353
- const { key, value } = parseSetInput(entry);
1354
- applyBridgeSet(nextBridge, key, value);
1457
+ const runningDaemonInfo = readDaemonProcessInfo(target.tunnelId);
1458
+ if (runningDaemonInfo) {
1459
+ const daemonVersion = runningDaemonInfo.cliVersion;
1460
+ const shouldRestartForUpgrade = shouldRestartDaemonForCliUpgrade(
1461
+ daemonVersion,
1462
+ CLI_VERSION
1463
+ );
1464
+ if (shouldRestartForUpgrade) {
1465
+ console.error(
1466
+ `Restarting daemon for CLI version ${CLI_VERSION} (running: ${daemonVersion || "unknown"}).`
1467
+ );
1468
+ if (isBridgeRunning(target.tunnelId)) {
1469
+ stopBridgeProcess(target.tunnelId);
1470
+ const bridgeStopped = await waitForStopped(
1471
+ () => isBridgeRunning(target.tunnelId),
1472
+ 5e3
1473
+ );
1474
+ if (!bridgeStopped) {
1475
+ failCli("Bridge process did not stop during daemon upgrade restart.");
1476
+ }
1477
+ }
1478
+ try {
1479
+ await ipcCall(socketPath, { method: "close", params: {} });
1480
+ } catch (error) {
1481
+ failCli(
1482
+ [
1483
+ `Failed to stop running daemon for upgrade: ${error instanceof Error ? error.message : String(error)}`,
1484
+ "Run `pubblue tunnel close <id>` and retry."
1485
+ ].join("\n")
1486
+ );
1487
+ }
1488
+ const daemonStopped = await waitForStopped(
1489
+ () => isDaemonRunning(target.tunnelId),
1490
+ 6e3
1491
+ );
1492
+ if (!daemonStopped) {
1493
+ failCli("Daemon did not stop in time during upgrade restart.");
1494
+ }
1495
+ } else {
1496
+ try {
1497
+ const status = await ipcCall(socketPath, { method: "status", params: {} });
1498
+ if (!status.ok) throw new Error(String(status.error || "status check failed"));
1499
+ } catch (error) {
1500
+ failCli(
1501
+ [
1502
+ `Daemon process exists but is not responding: ${error instanceof Error ? error.message : String(error)}`,
1503
+ "Run `pubblue tunnel close <id>` and start again."
1504
+ ].join("\n")
1505
+ );
1506
+ }
1507
+ if (bridgeMode !== "none") {
1508
+ const bridgeReady = await ensureBridgeReady({
1509
+ bridgeMode,
1510
+ tunnelId: target.tunnelId,
1511
+ socketPath,
1512
+ bridgeProcessEnv,
1513
+ timeoutMs: 8e3
1514
+ });
1515
+ if (!bridgeReady.ok) {
1516
+ const lines = [
1517
+ `Bridge failed to start for running tunnel: ${bridgeReady.reason ?? "unknown reason"}`
1518
+ ];
1519
+ const existingBridgeLog = bridgeLogPath(target.tunnelId);
1520
+ if (fs6.existsSync(existingBridgeLog)) {
1521
+ lines.push(`Bridge log: ${existingBridgeLog}`);
1522
+ const bridgeTail = readLogTail(existingBridgeLog);
1523
+ if (bridgeTail) {
1524
+ lines.push("---- bridge log tail ----");
1525
+ lines.push(bridgeTail.trimEnd());
1526
+ lines.push("---- end bridge log tail ----");
1527
+ }
1528
+ }
1529
+ failCli(lines.join("\n"));
1530
+ }
1531
+ }
1532
+ console.log(`Tunnel started: ${target.url}`);
1533
+ console.log(`Tunnel ID: ${target.tunnelId}`);
1534
+ console.log(`Expires: ${new Date(target.expiresAt).toISOString()}`);
1535
+ console.log("Daemon already running for this tunnel.");
1536
+ console.log(`Daemon log: ${logPath}`);
1537
+ if (bridgeMode !== "none") {
1538
+ console.log("Bridge mode: openclaw");
1539
+ console.log(`Bridge log: ${bridgeLogPath(target.tunnelId)}`);
1540
+ }
1541
+ return;
1542
+ }
1355
1543
  }
1356
- for (const key of opts.unset) {
1357
- applyBridgeUnset(nextBridge, key.trim());
1544
+ const daemonScript = path5.join(import.meta.dirname, "tunnel-daemon-entry.js");
1545
+ const daemonLogFd = fs6.openSync(logPath, "a");
1546
+ const child = fork2(daemonScript, [], {
1547
+ detached: true,
1548
+ stdio: buildDaemonForkStdio(daemonLogFd),
1549
+ env: {
1550
+ ...process.env,
1551
+ PUBBLUE_DAEMON_TUNNEL_ID: target.tunnelId,
1552
+ PUBBLUE_DAEMON_BASE_URL: runtimeConfig.baseUrl,
1553
+ PUBBLUE_DAEMON_API_KEY: runtimeConfig.apiKey,
1554
+ PUBBLUE_DAEMON_SOCKET: socketPath,
1555
+ PUBBLUE_DAEMON_INFO: infoPath,
1556
+ PUBBLUE_CLI_VERSION: CLI_VERSION
1557
+ }
1558
+ });
1559
+ fs6.closeSync(daemonLogFd);
1560
+ if (child.connected) {
1561
+ child.disconnect();
1358
1562
  }
1359
- const nextConfig = {
1360
- apiKey,
1361
- bridge: hasBridgeValues(nextBridge) ? nextBridge : void 0
1362
- };
1363
- saveConfig(nextConfig);
1364
- console.log("Configuration saved.");
1365
- if (opts.show || hasSet || hasUnset) {
1366
- printConfigSummary(nextConfig);
1563
+ child.unref();
1564
+ console.log(`Starting daemon for tunnel ${target.tunnelId}...`);
1565
+ const ready = await waitForDaemonReady({
1566
+ child,
1567
+ infoPath,
1568
+ socketPath,
1569
+ timeoutMs: 8e3
1570
+ });
1571
+ if (!ready.ok) {
1572
+ const lines = [
1573
+ `Daemon failed to start: ${ready.reason ?? "unknown reason"}`,
1574
+ `Daemon log: ${logPath}`
1575
+ ];
1576
+ const tail = readLogTail(logPath);
1577
+ if (tail) {
1578
+ lines.push("---- daemon log tail ----");
1579
+ lines.push(tail.trimEnd());
1580
+ lines.push("---- end daemon log tail ----");
1581
+ }
1582
+ await cleanupCreatedTunnelOnStartFailure(apiClient, target);
1583
+ failCli(lines.join("\n"));
1584
+ }
1585
+ const offerReady = await waitForAgentOffer({
1586
+ apiClient,
1587
+ tunnelId: target.tunnelId,
1588
+ timeoutMs: 5e3
1589
+ });
1590
+ if (!offerReady.ok) {
1591
+ const lines = [
1592
+ `Daemon started but signaling is not ready: ${offerReady.reason}`,
1593
+ `Daemon log: ${logPath}`
1594
+ ];
1595
+ const tail = readLogTail(logPath);
1596
+ if (tail) {
1597
+ lines.push("---- daemon log tail ----");
1598
+ lines.push(tail.trimEnd());
1599
+ lines.push("---- end daemon log tail ----");
1600
+ }
1601
+ await cleanupCreatedTunnelOnStartFailure(apiClient, target);
1602
+ failCli(lines.join("\n"));
1603
+ }
1604
+ if (bridgeMode !== "none") {
1605
+ const bridgeReady = await ensureBridgeReady({
1606
+ bridgeMode,
1607
+ tunnelId: target.tunnelId,
1608
+ socketPath,
1609
+ bridgeProcessEnv,
1610
+ timeoutMs: 8e3
1611
+ });
1612
+ if (!bridgeReady.ok) {
1613
+ const lines = [`Bridge failed to start: ${bridgeReady.reason ?? "unknown reason"}`];
1614
+ const bridgeLog = bridgeLogPath(target.tunnelId);
1615
+ if (fs6.existsSync(bridgeLog)) {
1616
+ lines.push(`Bridge log: ${bridgeLog}`);
1617
+ const bridgeTail = readLogTail(bridgeLog);
1618
+ if (bridgeTail) {
1619
+ lines.push("---- bridge log tail ----");
1620
+ lines.push(bridgeTail.trimEnd());
1621
+ lines.push("---- end bridge log tail ----");
1622
+ }
1623
+ }
1624
+ try {
1625
+ await ipcCall(socketPath, { method: "close", params: {} });
1626
+ } catch {
1627
+ }
1628
+ await cleanupCreatedTunnelOnStartFailure(apiClient, target);
1629
+ failCli(lines.join("\n"));
1630
+ }
1631
+ }
1632
+ console.log(`Tunnel started: ${target.url}`);
1633
+ console.log(`Tunnel ID: ${target.tunnelId}`);
1634
+ console.log(`Expires: ${new Date(target.expiresAt).toISOString()}`);
1635
+ if (target.mode === "existing") console.log("Mode: attached existing tunnel");
1636
+ console.log("Daemon health: OK");
1637
+ console.log(`Daemon log: ${logPath}`);
1638
+ if (bridgeMode !== "none") {
1639
+ console.log("Bridge mode: openclaw");
1640
+ console.log(`Bridge log: ${bridgeLogPath(target.tunnelId)}`);
1367
1641
  }
1368
- } catch (error) {
1369
- const message = error instanceof Error ? error.message : "Failed to configure CLI.";
1370
- console.error(message);
1371
- process.exit(1);
1372
- }
1373
- }
1374
- );
1375
- program.command("create").description("Create a new publication").argument("[file]", "Path to the file (reads stdin if omitted)").option("--slug <slug>", "Custom slug for the URL").option("--title <title>", "Title for the publication").option("--public", "Make the publication public").option("--private", "Make the publication private (default)").option("--expires <duration>", "Auto-delete after duration (e.g. 1h, 24h, 7d)").action(
1376
- async (fileArg, opts) => {
1377
- const client = createClient();
1378
- let content;
1379
- let filename;
1380
- if (fileArg) {
1381
- const file = readFile(fileArg);
1382
- content = file.content;
1383
- filename = file.basename;
1384
- } else {
1385
- content = await readFromStdin();
1386
- }
1387
- const resolvedVisibility = resolveVisibilityFlags({
1388
- public: opts.public,
1389
- private: opts.private,
1390
- commandName: "create"
1391
- });
1392
- const result = await client.create({
1393
- content,
1394
- filename,
1395
- title: opts.title,
1396
- slug: opts.slug,
1397
- isPublic: resolvedVisibility ?? false,
1398
- expiresIn: opts.expires
1399
- });
1400
- console.log(`Created: ${result.url}`);
1401
- if (result.expiresAt) {
1402
- console.log(` Expires: ${new Date(result.expiresAt).toISOString()}`);
1403
- }
1404
- }
1405
- );
1406
- program.command("get").description("Get details of a publication").argument("<slug>", "Slug of the publication").option("--content", "Output raw content to stdout (no metadata, pipeable)").action(async (slug, opts) => {
1407
- const client = createClient();
1408
- const pub = await client.get(slug);
1409
- if (opts.content) {
1410
- process.stdout.write(pub.content);
1411
- return;
1412
- }
1413
- console.log(` Slug: ${pub.slug}`);
1414
- console.log(` Type: ${pub.contentType}`);
1415
- if (pub.title) console.log(` Title: ${pub.title}`);
1416
- console.log(` Status: ${formatVisibility(pub.isPublic)}`);
1417
- if (pub.expiresAt) console.log(` Expires: ${new Date(pub.expiresAt).toISOString()}`);
1418
- console.log(` Created: ${new Date(pub.createdAt).toLocaleDateString()}`);
1419
- console.log(` Updated: ${new Date(pub.updatedAt).toLocaleDateString()}`);
1420
- console.log(` Size: ${pub.content.length} bytes`);
1421
- });
1422
- program.command("update").description("Update a publication's content and/or metadata").argument("<slug>", "Slug of the publication to update").option("--file <file>", "New content from file").option("--title <title>", "New title").option("--public", "Make the publication public").option("--private", "Make the publication private").option("--slug <newSlug>", "Rename the slug").action(
1423
- async (slug, opts) => {
1424
- const client = createClient();
1425
- let content;
1426
- let filename;
1427
- if (opts.file) {
1428
- const file = readFile(opts.file);
1429
- content = file.content;
1430
- filename = file.basename;
1431
1642
  }
1432
- const isPublic = resolveVisibilityFlags({
1433
- public: opts.public,
1434
- private: opts.private,
1435
- commandName: "update"
1436
- });
1437
- const result = await client.update({
1438
- slug,
1439
- content,
1440
- filename,
1441
- title: opts.title,
1442
- isPublic,
1443
- newSlug: opts.slug
1444
- });
1445
- console.log(`Updated: ${result.slug}`);
1446
- if (result.title) console.log(` Title: ${result.title}`);
1447
- console.log(` Status: ${formatVisibility(result.isPublic)}`);
1448
- }
1449
- );
1450
- program.command("list").description("List your publications").action(async () => {
1451
- const client = createClient();
1452
- const pubs = await client.list();
1453
- if (pubs.length === 0) {
1454
- console.log("No publications.");
1455
- return;
1456
- }
1457
- for (const pub of pubs) {
1458
- const date = new Date(pub.createdAt).toLocaleDateString();
1459
- const expires = pub.expiresAt ? ` expires:${new Date(pub.expiresAt).toISOString()}` : "";
1460
- console.log(
1461
- ` ${pub.slug} [${pub.contentType}] ${formatVisibility(pub.isPublic)} ${date}${expires}`
1462
- );
1643
+ );
1644
+ }
1645
+
1646
+ // src/commands/tunnel.ts
1647
+ function registerTunnelCommands(program2) {
1648
+ const tunnel = program2.command("tunnel").description("P2P encrypted tunnel to browser");
1649
+ registerTunnelStartCommand(tunnel);
1650
+ registerTunnelMessageCommands(tunnel);
1651
+ registerTunnelManagementCommands(tunnel);
1652
+ }
1653
+
1654
+ // src/program.ts
1655
+ function buildProgram() {
1656
+ const program2 = new Command();
1657
+ program2.exitOverride();
1658
+ program2.name("pubblue").description("Publish static content and get shareable URLs").version(CLI_VERSION);
1659
+ registerConfigureCommand(program2);
1660
+ registerPublicationCommands(program2);
1661
+ registerTunnelCommands(program2);
1662
+ return program2;
1663
+ }
1664
+
1665
+ // src/index.ts
1666
+ var program = buildProgram();
1667
+ await program.parseAsync(process.argv).catch((error) => {
1668
+ const failure = toCliFailure(error);
1669
+ if (failure.message) {
1670
+ console.error(failure.message);
1463
1671
  }
1672
+ process.exit(failure.exitCode);
1464
1673
  });
1465
- program.command("delete").description("Delete a publication").argument("<slug>", "Slug of the publication to delete").action(async (slug) => {
1466
- const client = createClient();
1467
- await client.remove(slug);
1468
- console.log(`Deleted: ${slug}`);
1469
- });
1470
- registerTunnelCommands(program);
1471
- program.parse();