dsh-hello 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,4 +1,4 @@
1
- // dsh-door - bundled by esbuild; dsh services stay external.
1
+ // dsh-hello - bundled by esbuild; dsh services stay external.
2
2
  var __create = Object.create;
3
3
  var __defProp = Object.defineProperty;
4
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -4184,7 +4184,7 @@ defineMethod("transform", [
4184
4184
 
4185
4185
  // src/config.ts
4186
4186
  var Config = Schema.object({
4187
- basePath: Schema.string().default("/dsh-door"),
4187
+ basePath: Schema.string().default("/dsh-hello"),
4188
4188
  allowedHosts: Schema.array(Schema.string()).default([]),
4189
4189
  requireSecure: Schema.boolean().default(false),
4190
4190
  strictHostCheck: Schema.boolean().default(false),
@@ -4193,6 +4193,7 @@ var Config = Schema.object({
4193
4193
  pairingMaxAttempts: Schema.number().default(8),
4194
4194
  pairingCode: Schema.string(),
4195
4195
  logPairingCode: Schema.boolean().default(true),
4196
+ interactionTarget: Schema.union(["phone-first", "browser-first", "browser-only"]).default("browser-first"),
4196
4197
  approvalWaitTimeoutMs: Schema.number().default(2 * 60 * 1e3),
4197
4198
  questionWaitTimeoutMs: Schema.number().default(2 * 60 * 1e3),
4198
4199
  allowSessionWideGrants: Schema.boolean().default(true),
@@ -4225,7 +4226,7 @@ function normalizeConfig(input) {
4225
4226
  const raw = input ?? {};
4226
4227
  const push2 = { ...raw.push ?? {} };
4227
4228
  const config = {
4228
- basePath: normalizeBasePath(raw.basePath ?? "/dsh-door"),
4229
+ basePath: normalizeBasePath(raw.basePath ?? "/dsh-hello"),
4229
4230
  allowedHosts: (raw.allowedHosts ?? []).map((value) => value.trim().toLowerCase()).filter(Boolean),
4230
4231
  requireSecure: raw.requireSecure ?? false,
4231
4232
  strictHostCheck: raw.strictHostCheck ?? false,
@@ -4233,6 +4234,7 @@ function normalizeConfig(input) {
4233
4234
  pairingCodeLength: raw.pairingCodeLength ?? 4,
4234
4235
  pairingMaxAttempts: raw.pairingMaxAttempts ?? 8,
4235
4236
  logPairingCode: raw.logPairingCode ?? true,
4237
+ interactionTarget: raw.interactionTarget ?? "browser-first",
4236
4238
  approvalWaitTimeoutMs: raw.approvalWaitTimeoutMs ?? 2 * 60 * 1e3,
4237
4239
  questionWaitTimeoutMs: raw.questionWaitTimeoutMs ?? 2 * 60 * 1e3,
4238
4240
  allowSessionWideGrants: raw.allowSessionWideGrants ?? true,
@@ -4259,21 +4261,24 @@ function normalizeConfig(input) {
4259
4261
  };
4260
4262
  if (raw.pairingCode !== void 0) config.pairingCode = raw.pairingCode;
4261
4263
  if (!Number.isFinite(config.pairingTtlMs) || config.pairingTtlMs < 1e3) {
4262
- throw new Error("dsh-door: pairing.ttlMs must be at least 1000 ms");
4264
+ throw new Error("dsh-hello: pairing.ttlMs must be at least 1000 ms");
4263
4265
  }
4264
4266
  if (!Number.isInteger(config.pairingCodeLength) || config.pairingCodeLength < 4 || config.pairingCodeLength > 32) {
4265
- throw new Error("dsh-door: pairing.codeLength must be an integer from 4 to 32");
4267
+ throw new Error("dsh-hello: pairing.codeLength must be an integer from 4 to 32");
4266
4268
  }
4267
4269
  if (!Number.isFinite(config.maxBodyBytes) || config.maxBodyBytes < 1024) {
4268
- throw new Error("dsh-door: maxBodyBytes must be at least 1024");
4270
+ throw new Error("dsh-hello: maxBodyBytes must be at least 1024");
4271
+ }
4272
+ if (config.interactionTarget !== "phone-first" && config.interactionTarget !== "browser-first" && config.interactionTarget !== "browser-only") {
4273
+ throw new Error("dsh-hello: interactionTarget must be phone-first, browser-first, or browser-only");
4269
4274
  }
4270
4275
  return config;
4271
4276
  }
4272
4277
  function normalizeBasePath(value) {
4273
4278
  const trimmed = value.trim();
4274
- if (!trimmed.startsWith("/")) throw new Error('dsh-door: basePath must start with "/"');
4279
+ if (!trimmed.startsWith("/")) throw new Error('dsh-hello: basePath must start with "/"');
4275
4280
  const withoutTrailing = trimmed.replace(/\/+$/, "");
4276
- if (withoutTrailing.length === 0) throw new Error('dsh-door: basePath may not be "/"');
4281
+ if (withoutTrailing.length === 0) throw new Error('dsh-hello: basePath may not be "/"');
4277
4282
  return withoutTrailing;
4278
4283
  }
4279
4284
 
@@ -4317,7 +4322,7 @@ function shortError(error, max = 300) {
4317
4322
  }
4318
4323
 
4319
4324
  // src/devices.ts
4320
- var DEVICE_RECORD_KEY = "dsh-door/devices";
4325
+ var DEVICE_RECORD_KEY = "dsh-hello/devices";
4321
4326
  var DEFAULT_PUSH_SUBSCRIPTIONS = {
4322
4327
  approval: true,
4323
4328
  question: true,
@@ -4338,7 +4343,7 @@ var DeviceStore = class {
4338
4343
  if (this.loaded) return;
4339
4344
  if (this.credentials === void 0) {
4340
4345
  throw new Error(
4341
- "dsh-door: this deployment composes no credential store. Load @deepseek-ai/dsh-credentials-local so paired devices can be stored durably."
4346
+ "dsh-hello: this deployment composes no credential store. Load @deepseek-ai/dsh-credentials-local so paired devices can be stored durably."
4342
4347
  );
4343
4348
  }
4344
4349
  const record = await this.credentials.readRecord(DEVICE_RECORD_KEY);
@@ -4535,6 +4540,7 @@ var HttpRouter = class {
4535
4540
  return {
4536
4541
  kind: "prefix",
4537
4542
  path: this.config.basePath,
4543
+ auth: "anonymous",
4538
4544
  handler: (req, res) => this.handle(req, res)
4539
4545
  };
4540
4546
  }
@@ -4548,7 +4554,14 @@ var HttpRouter = class {
4548
4554
  const clientAddress = normalizeAddress(req.socket?.remoteAddress);
4549
4555
  const authority = header(req, "host")?.toLowerCase() ?? "";
4550
4556
  const origin = header(req, "origin");
4551
- if (origin !== void 0 && !sameOrigin(origin, authority)) {
4557
+ const extensionOrigin = origin !== void 0 && isExtensionOrigin(origin);
4558
+ if (extensionOrigin) this.applyCors(res, origin);
4559
+ if (extensionOrigin && (req.method ?? "GET").toUpperCase() === "OPTIONS") {
4560
+ res.writeHead(204);
4561
+ res.end();
4562
+ return;
4563
+ }
4564
+ if (origin !== void 0 && !sameOrigin(origin, authority) && !extensionOrigin) {
4552
4565
  throw new HttpError(403, "origin-refused", "cross-origin requests are not accepted");
4553
4566
  }
4554
4567
  const pathname = normalizePath(url.pathname.slice(this.config.basePath.length) || "/");
@@ -4606,17 +4619,17 @@ var HttpRouter = class {
4606
4619
  res.end();
4607
4620
  } catch {
4608
4621
  }
4609
- this.options.logger.warn(`[dsh-door] ${shortError(error)}`);
4622
+ this.options.logger.warn(`[dsh-hello] ${shortError(error)}`);
4610
4623
  return;
4611
4624
  }
4612
4625
  if (error instanceof HttpError) {
4613
4626
  sendJson(res, error.status, { error: { code: error.code, message: error.message, ...error.details } });
4614
4627
  } else {
4615
- this.options.logger.warn(`[dsh-door] request failed: ${shortError(error)}`);
4628
+ this.options.logger.warn(`[dsh-hello] request failed: ${shortError(error)}`);
4616
4629
  sendJson(res, 500, { error: { code: "internal", message: shortError(error) } });
4617
4630
  }
4618
4631
  } finally {
4619
- this.options.logger.debug?.(`[dsh-door] ${req.method ?? "GET"} ${url.pathname} ${Date.now() - started}ms`);
4632
+ this.options.logger.debug?.(`[dsh-hello] ${req.method ?? "GET"} ${url.pathname} ${Date.now() - started}ms`);
4620
4633
  }
4621
4634
  }
4622
4635
  match(method, pathname) {
@@ -4627,6 +4640,20 @@ var HttpRouter = class {
4627
4640
  }
4628
4641
  return void 0;
4629
4642
  }
4643
+ /**
4644
+ * Browser extensions are installed clients, not web pages: their
4645
+ * `chrome-extension://` origin can never be a DNS-rebinding or cross-site
4646
+ * target. The device token (or the one-time pairing code) remains the
4647
+ * authentication boundary. Echo only the extension's own origin; web
4648
+ * origins still receive no CORS headers.
4649
+ */
4650
+ applyCors(res, origin) {
4651
+ res.setHeader("Access-Control-Allow-Origin", origin);
4652
+ res.setHeader("Vary", "Origin");
4653
+ res.setHeader("Access-Control-Allow-Headers", "authorization, content-type");
4654
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
4655
+ res.setHeader("Access-Control-Max-Age", "600");
4656
+ }
4630
4657
  authenticate(req) {
4631
4658
  const authorization = header(req, "authorization");
4632
4659
  if (authorization === void 0) return void 0;
@@ -4778,6 +4805,9 @@ function authorityHostname(authority) {
4778
4805
  const colon = authority.lastIndexOf(":");
4779
4806
  return colon === -1 ? authority : authority.slice(0, colon);
4780
4807
  }
4808
+ function isExtensionOrigin(origin) {
4809
+ return origin.startsWith("chrome-extension://") || origin.startsWith("moz-extension://") || origin.startsWith("safari-web-extension://");
4810
+ }
4781
4811
  function sameOrigin(origin, authority) {
4782
4812
  try {
4783
4813
  const parsed = new URL(origin);
@@ -4815,16 +4845,22 @@ var InteractionBroker = class {
4815
4845
  presenceSweep = setInterval(() => this.releasePhoneHolds(), 15e3);
4816
4846
  register() {
4817
4847
  this.presenceSweep.unref?.();
4848
+ if (this.config.interactionTarget === "browser-only") {
4849
+ this.logger.info("[dsh-hello] interactionTarget browser-only: the app will not answer approvals or questions");
4850
+ return;
4851
+ }
4852
+ const listen = { global: true, prepend: true };
4818
4853
  this.ctx.on("approval/request", async (...args) => {
4819
4854
  const req = args[0];
4820
4855
  const next = args[1];
4856
+ this.logger.info(`[dsh-hello] approval/request ${req.toolName} reason=${req.reason ?? "-"} session=${req.agent?.id ?? "-"}`);
4821
4857
  return this.handleApproval(req, next);
4822
- });
4858
+ }, listen);
4823
4859
  this.ctx.on("user-questions/request", async (...args) => {
4824
4860
  const req = args[0];
4825
4861
  const next = args[1];
4826
4862
  return this.handleQuestion(req, next);
4827
- });
4863
+ }, listen);
4828
4864
  }
4829
4865
  listApprovals() {
4830
4866
  return [...this.approvals.values()].map(toApprovalItem);
@@ -4839,7 +4875,7 @@ var InteractionBroker = class {
4839
4875
  if (foreground) this.foreground.set(deviceId, Date.now());
4840
4876
  else this.foreground.delete(deviceId);
4841
4877
  const after = this.hasForegroundPhone();
4842
- if (before !== after) this.logger.info(`[dsh-door] foreground app ${after ? "claims" : "releases"} interactions`);
4878
+ if (before !== after) this.logger.info(`[dsh-hello] foreground app ${after ? "claims" : "releases"} interactions`);
4843
4879
  this.releasePhoneHolds();
4844
4880
  }
4845
4881
  /** Create a synthetic approval for the authenticated debug route. */
@@ -4923,7 +4959,7 @@ var InteractionBroker = class {
4923
4959
  if (decision === "always" && this.config.allowSessionWideGrants) {
4924
4960
  this.grants.add(grantKey(pending.sessionId, pending.toolName));
4925
4961
  }
4926
- pending.resolve(decision);
4962
+ pending.resolve(decision === "later" ? "timeout" : decision);
4927
4963
  this.hub.broadcast("approval-resolved", {
4928
4964
  id,
4929
4965
  sessionId: pending.sessionId,
@@ -4982,9 +5018,15 @@ var InteractionBroker = class {
4982
5018
  });
4983
5019
  return "allowed-once";
4984
5020
  }
4985
- const phoneHold = this.phoneWins();
4986
- if (!phoneHold && this.browserWins()) return next();
5021
+ const phoneHold = this.shouldHoldForPhone();
5022
+ if (!phoneHold) {
5023
+ this.logger.info(
5024
+ `[dsh-hello] approval ${req.toolName} stays with dsh (${this.config.interactionTarget}; browser=${this.browserWins()} phone=${this.phoneWins()})`
5025
+ );
5026
+ return next();
5027
+ }
4987
5028
  if (!this.appCanAnswer()) {
5029
+ this.logger.warn(`[dsh-hello] approval ${req.toolName} has no client to answer it`);
4988
5030
  return next();
4989
5031
  }
4990
5032
  if (req.signal?.aborted === true) return "cancelled";
@@ -5023,7 +5065,7 @@ var InteractionBroker = class {
5023
5065
  this.hub.broadcast("approval-resolved", { id, sessionId, decision: "cancelled", source: "signal" });
5024
5066
  resolve4("timeout");
5025
5067
  }, { once: true });
5026
- this.logger.info(`[dsh-door] approval ${id} for ${req.toolName} in ${sessionId}`);
5068
+ this.logger.info(`[dsh-hello] approval ${id} for ${req.toolName} in ${sessionId}`);
5027
5069
  });
5028
5070
  if (decision === "timeout") {
5029
5071
  return next();
@@ -5034,10 +5076,10 @@ var InteractionBroker = class {
5034
5076
  async handleQuestion(req, next) {
5035
5077
  const sessionId = req.agent?.id ?? "unknown";
5036
5078
  this.logger.info(
5037
- `[dsh-door] question request in ${sessionId}: phone=${this.phoneWins()} presence=${this.hasForegroundPhone()} hub=${this.hub.hasClients()} browser=${this.browserWins()}`
5079
+ `[dsh-hello] question request in ${sessionId}: phone=${this.phoneWins()} presence=${this.hasForegroundPhone()} hub=${this.hub.hasClients()} browser=${this.browserWins()}`
5038
5080
  );
5039
- const phoneHold = this.phoneWins();
5040
- if (!phoneHold && this.browserWins()) return next();
5081
+ const phoneHold = this.shouldHoldForPhone();
5082
+ if (!phoneHold) return next();
5041
5083
  if (!this.appCanAnswer()) return next();
5042
5084
  if (req.signal?.aborted === true) return next();
5043
5085
  const id = newId();
@@ -5079,7 +5121,7 @@ var InteractionBroker = class {
5079
5121
  this.hub.broadcast("question-resolved", { id, sessionId, callId: req.wait?.callId, decision: "cancelled", source: "signal" });
5080
5122
  resolve4("timeout");
5081
5123
  }, { once: true });
5082
- this.logger.info(`[dsh-door] question ${id} in ${sessionId} (${phoneHold ? "foreground app" : "app"})`);
5124
+ this.logger.info(`[dsh-hello] question ${id} in ${sessionId} (${phoneHold ? "foreground app" : "app"})`);
5083
5125
  });
5084
5126
  if (answer === "timeout") return next();
5085
5127
  return answer;
@@ -5124,6 +5166,20 @@ var InteractionBroker = class {
5124
5166
  const gateway = getService(this.ctx, "typertGateway");
5125
5167
  return gateway?.hasLiveClient() === true;
5126
5168
  }
5169
+ /**
5170
+ * Whether this plugin should take a request away from dsh's own answerers.
5171
+ * Only one answerer ever sees a request, so this is the whole policy:
5172
+ * `browser-first` yields whenever a browser is live, and `browser-only`
5173
+ * never registers a listener at all.
5174
+ */
5175
+ shouldHoldForPhone() {
5176
+ return shouldHoldInteraction({
5177
+ target: this.config.interactionTarget,
5178
+ browserLive: this.browserWins(),
5179
+ foregroundPhone: this.phoneWins(),
5180
+ appConnected: this.appCanAnswer()
5181
+ });
5182
+ }
5127
5183
  /** A foreground app only wins while its SSE connection can receive the card. */
5128
5184
  phoneWins() {
5129
5185
  return this.hasForegroundPhone() && this.hub.hasClients();
@@ -5185,7 +5241,7 @@ var InteractionBroker = class {
5185
5241
  this.questions.clear();
5186
5242
  }
5187
5243
  logFailure(error) {
5188
- this.logger.warn(`[dsh-door] interaction failed: ${shortError(error)}`);
5244
+ this.logger.warn(`[dsh-hello] interaction failed: ${shortError(error)}`);
5189
5245
  }
5190
5246
  };
5191
5247
  function toApprovalItem(pending) {
@@ -5302,6 +5358,16 @@ function getService(ctx, name2) {
5302
5358
  return void 0;
5303
5359
  }
5304
5360
  }
5361
+ function shouldHoldInteraction(input) {
5362
+ switch (input.target) {
5363
+ case "browser-only":
5364
+ return false;
5365
+ case "browser-first":
5366
+ return !input.browserLive && input.appConnected;
5367
+ case "phone-first":
5368
+ return input.foregroundPhone;
5369
+ }
5370
+ }
5305
5371
 
5306
5372
  // src/pairing.ts
5307
5373
  var PairingManager = class {
@@ -5321,6 +5387,8 @@ var PairingManager = class {
5321
5387
  code;
5322
5388
  expiresAt;
5323
5389
  fixedCode;
5390
+ /** A locked Host refuses new devices; paired devices keep working. */
5391
+ locked = false;
5324
5392
  attempts = /* @__PURE__ */ new Map();
5325
5393
  /** Current code and expiry; may regenerate an expired code. */
5326
5394
  current() {
@@ -5335,15 +5403,31 @@ var PairingManager = class {
5335
5403
  /** Human-readable status for `/health`. */
5336
5404
  status() {
5337
5405
  this.ensureValid();
5338
- return { pairingOpen: true, expiresAt: this.expiresAt, fixed: this.fixedCode !== null };
5406
+ return {
5407
+ pairingOpen: !this.locked,
5408
+ expiresAt: this.expiresAt,
5409
+ fixed: this.fixedCode !== null,
5410
+ locked: this.locked
5411
+ };
5339
5412
  }
5340
5413
  isFixed() {
5341
5414
  return this.fixedCode !== null;
5342
5415
  }
5416
+ isLocked() {
5417
+ return this.locked;
5418
+ }
5419
+ /** Close or reopen pairing. Existing devices are untouched. */
5420
+ async setLocked(locked, persist = true) {
5421
+ this.locked = locked;
5422
+ if (locked) this.logger.warn("[dsh-hello] pairing locked; no new devices will be accepted");
5423
+ else this.logger.info("[dsh-hello] pairing unlocked; new devices may pair again");
5424
+ if (persist) await this.safePersist();
5425
+ }
5343
5426
  /** Verify one submitted code; consumes it on success unless it is fixed. */
5344
5427
  verify(rawCode, clientAddress) {
5345
5428
  const now = Date.now();
5346
5429
  this.ensureValid();
5430
+ if (this.locked) return { ok: false, reason: "locked" };
5347
5431
  this.pruneAttempts(now);
5348
5432
  const record = this.attempts.get(clientAddress) ?? { count: 0, resetAt: now + this.config.pairingTtlMs };
5349
5433
  if (record.count >= this.config.pairingMaxAttempts) {
@@ -5370,7 +5454,7 @@ var PairingManager = class {
5370
5454
  this.code = this.generate();
5371
5455
  this.expiresAt = Date.now() + this.config.pairingTtlMs;
5372
5456
  this.onRotate?.(this.code, this.expiresAt);
5373
- this.logger.info(`[dsh-door] pairing code ${formatPairingCode(this.code)} (expires ${new Date(this.expiresAt).toISOString()})`);
5457
+ this.logger.info(`[dsh-hello] pairing code ${formatPairingCode(this.code)} (expires ${new Date(this.expiresAt).toISOString()})`);
5374
5458
  }
5375
5459
  return this.current();
5376
5460
  }
@@ -5384,8 +5468,8 @@ var PairingManager = class {
5384
5468
  this.fixedCode = null;
5385
5469
  this.code = this.generate();
5386
5470
  this.expiresAt = Date.now() + this.config.pairingTtlMs;
5387
- this.logger.info(`[dsh-door] fixed pairing code cleared; new one-time code ${formatPairingCode(this.code)}`);
5388
- if (persist) await this.safePersist(null);
5471
+ this.logger.info(`[dsh-hello] fixed pairing code cleared; new one-time code ${formatPairingCode(this.code)}`);
5472
+ if (persist) await this.safePersist();
5389
5473
  return this.current();
5390
5474
  }
5391
5475
  const normalized = normalizePairingCode(rawCode);
@@ -5395,8 +5479,8 @@ var PairingManager = class {
5395
5479
  this.fixedCode = normalized;
5396
5480
  this.code = normalized;
5397
5481
  this.expiresAt = Number.MAX_SAFE_INTEGER;
5398
- this.logger.warn(`[dsh-door] fixed pairing code set to ${formatPairingCode(normalized)}; it stays valid until changed`);
5399
- if (persist) await this.safePersist(normalized);
5482
+ this.logger.warn(`[dsh-hello] fixed pairing code set to ${formatPairingCode(normalized)}; it stays valid until changed`);
5483
+ if (persist) await this.safePersist();
5400
5484
  return this.current();
5401
5485
  }
5402
5486
  generate() {
@@ -5405,11 +5489,11 @@ var PairingManager = class {
5405
5489
  ensureValid() {
5406
5490
  if (this.fixedCode === null && Date.now() >= this.expiresAt) this.rotate();
5407
5491
  }
5408
- async safePersist(fixedCode) {
5492
+ async safePersist() {
5409
5493
  try {
5410
- await this.persist?.(fixedCode);
5494
+ await this.persist?.({ fixedCode: this.fixedCode, locked: this.locked });
5411
5495
  } catch (error) {
5412
- this.logger.warn(`[dsh-door] could not persist the fixed pairing code: ${error instanceof Error ? error.message : String(error)}`);
5496
+ this.logger.warn(`[dsh-hello] could not persist the pairing settings: ${error instanceof Error ? error.message : String(error)}`);
5413
5497
  }
5414
5498
  }
5415
5499
  pruneAttempts(now) {
@@ -5439,18 +5523,18 @@ var PushManager = class {
5439
5523
  apnsToken;
5440
5524
  remote = {};
5441
5525
  /**
5442
- * Prefer a `dsh-door/push` credential record over configuration. Push
5526
+ * Prefer a `dsh-hello/push` credential record over configuration. Push
5443
5527
  * service-account JSON and APNs keys are secrets, so a deployment that
5444
5528
  * keeps them in the credential store never writes them into cordis.yml.
5445
5529
  */
5446
5530
  async load() {
5447
5531
  if (this.credentials === void 0) return;
5448
5532
  try {
5449
- const record = await this.credentials.readRecord("dsh-door/push");
5533
+ const record = await this.credentials.readRecord("dsh-hello/push");
5450
5534
  const payload = record?.payload;
5451
5535
  if (typeof payload === "object" && payload !== null) this.remote = payload;
5452
5536
  } catch (error) {
5453
- this.logger.warn(`[dsh-door] could not read push credentials: ${shortError(error)}`);
5537
+ this.logger.warn(`[dsh-hello] could not read push credentials: ${shortError(error)}`);
5454
5538
  }
5455
5539
  }
5456
5540
  get push() {
@@ -5485,7 +5569,7 @@ var PushManager = class {
5485
5569
  throw new Error(`relay ${response.status}: ${text.slice(0, 200)}`);
5486
5570
  }
5487
5571
  } catch (error) {
5488
- this.logger.warn(`[dsh-door] relay device registration failed: ${shortError(error)}`);
5572
+ this.logger.warn(`[dsh-hello] relay device registration failed: ${shortError(error)}`);
5489
5573
  }
5490
5574
  }
5491
5575
  /** Remove a device binding from the relay. */
@@ -5502,7 +5586,7 @@ var PushManager = class {
5502
5586
  throw new Error(`relay ${response.status}: ${text.slice(0, 200)}`);
5503
5587
  }
5504
5588
  } catch (error) {
5505
- this.logger.warn(`[dsh-door] relay device removal failed: ${shortError(error)}`);
5589
+ this.logger.warn(`[dsh-hello] relay device removal failed: ${shortError(error)}`);
5506
5590
  }
5507
5591
  }
5508
5592
  notify(kind, payload) {
@@ -5513,7 +5597,7 @@ var PushManager = class {
5513
5597
  if (kind === "turn-end" && !push2.notifyTurnEnd) return;
5514
5598
  const message = render(kind, payload, this.hostId);
5515
5599
  void this.send(message, kind).catch((error) => {
5516
- this.logger.warn(`[dsh-door] push failed: ${shortError(error)}`);
5600
+ this.logger.warn(`[dsh-hello] push failed: ${shortError(error)}`);
5517
5601
  });
5518
5602
  }
5519
5603
  async send(message, kind) {
@@ -6237,7 +6321,7 @@ function registerRoutes(router, deps) {
6237
6321
  pattern: "/health",
6238
6322
  auth: "public",
6239
6323
  handler: (rc) => {
6240
- const facts = serverFacts(deps);
6324
+ const facts = serverFacts(deps, requestOrigin(deps, rc));
6241
6325
  const response = {
6242
6326
  ok: true,
6243
6327
  ...facts,
@@ -6256,7 +6340,7 @@ function registerRoutes(router, deps) {
6256
6340
  auth: "public",
6257
6341
  handler: async (rc) => {
6258
6342
  if (!adminAuthorized(deps, rc)) throw new HttpError(401, "admin-unauthorized", "open this page from an authenticated dsh browser");
6259
- sendJson(rc.res, 200, await adminData(deps));
6343
+ sendJson(rc.res, 200, await adminData(deps, requestBase(rc) ?? requestOrigin(deps, rc) ?? ""));
6260
6344
  }
6261
6345
  });
6262
6346
  router.add({
@@ -6280,7 +6364,19 @@ function registerRoutes(router, deps) {
6280
6364
  if (error instanceof HttpError) throw error;
6281
6365
  throw new HttpError(400, "bad-code", error instanceof Error ? error.message : String(error));
6282
6366
  }
6283
- sendJson(rc.res, 200, await adminData(deps));
6367
+ sendJson(rc.res, 200, await adminData(deps, requestBase(rc) ?? requestOrigin(deps, rc) ?? ""));
6368
+ }
6369
+ });
6370
+ router.add({
6371
+ method: "POST",
6372
+ pattern: "/admin/lock",
6373
+ auth: "public",
6374
+ handler: async (rc) => {
6375
+ if (!adminAuthorized(deps, rc)) throw new HttpError(401, "admin-unauthorized", "open this page from an authenticated dsh browser");
6376
+ const body = rc.body ?? {};
6377
+ if (typeof body.locked !== "boolean") throw new HttpError(400, "bad-lock", "locked must be true or false");
6378
+ await deps.pairing.setLocked(body.locked);
6379
+ sendJson(rc.res, 200, await adminData(deps, requestBase(rc) ?? requestOrigin(deps, rc) ?? ""));
6284
6380
  }
6285
6381
  });
6286
6382
  router.add({
@@ -6292,7 +6388,7 @@ function registerRoutes(router, deps) {
6292
6388
  const removed = await deps.devices.revoke(rc.params.id);
6293
6389
  if (!removed) throw new HttpError(404, "device-not-found", "no such device");
6294
6390
  deps.hub.closeDevice(rc.params.id);
6295
- sendJson(rc.res, 200, await adminData(deps));
6391
+ sendJson(rc.res, 200, await adminData(deps, requestBase(rc) ?? requestOrigin(deps, rc) ?? ""));
6296
6392
  }
6297
6393
  });
6298
6394
  router.add({
@@ -6306,7 +6402,17 @@ function registerRoutes(router, deps) {
6306
6402
  if (name2.length === 0) throw new HttpError(400, "bad-device-name", "a non-empty device name is required");
6307
6403
  const renamed = await deps.devices.rename(rc.params.id, name2);
6308
6404
  if (!renamed) throw new HttpError(404, "device-not-found", "no such device");
6309
- sendJson(rc.res, 200, await adminData(deps));
6405
+ sendJson(rc.res, 200, await adminData(deps, requestBase(rc) ?? requestOrigin(deps, rc) ?? ""));
6406
+ }
6407
+ });
6408
+ router.add({
6409
+ method: "GET",
6410
+ pattern: "/web-url",
6411
+ auth: "device",
6412
+ handler: (rc) => {
6413
+ const url = deps.webUrl?.() ?? null;
6414
+ if (url === null) throw new HttpError(503, "web-url-unavailable", "this Host does not expose its Web UI URL");
6415
+ sendJson(rc.res, 200, { url });
6310
6416
  }
6311
6417
  });
6312
6418
  router.add({
@@ -6316,7 +6422,7 @@ function registerRoutes(router, deps) {
6316
6422
  handler: (rc) => {
6317
6423
  const status = deps.pairing.status();
6318
6424
  sendJson(rc.res, 200, {
6319
- server: serverFacts(deps),
6425
+ server: serverFacts(deps, requestOrigin(deps, rc)),
6320
6426
  features: features(deps),
6321
6427
  pairing: { open: status.pairingOpen }
6322
6428
  });
@@ -6329,7 +6435,7 @@ function registerRoutes(router, deps) {
6329
6435
  handler: async (rc) => {
6330
6436
  assertLoopback(rc);
6331
6437
  const current = deps.pairing.current();
6332
- const origin = serverFacts(deps).origin ?? "";
6438
+ const origin = serverFacts(deps, requestOrigin(deps, rc)).origin ?? "";
6333
6439
  const payload = JSON.stringify({
6334
6440
  v: 1,
6335
6441
  url: `${origin}${config.basePath}`,
@@ -6366,8 +6472,9 @@ function registerRoutes(router, deps) {
6366
6472
  }
6367
6473
  const verification = deps.pairing.verify(body.code, rc.clientAddress);
6368
6474
  if (!verification.ok) {
6369
- const message = verification.reason === "rate-limited" ? "too many pairing attempts from this address" : verification.reason === "expired" ? "the pairing code has expired; read the new code from the dsh terminal" : "the pairing code is invalid";
6370
- throw new HttpError(verification.reason === "rate-limited" ? 429 : 401, `pair-${verification.reason}`, message);
6475
+ const message = verification.reason === "locked" ? "this Host is not accepting new devices; unlock pairing in the dsh settings first" : verification.reason === "rate-limited" ? "too many pairing attempts from this address" : verification.reason === "expired" ? "the pairing code has expired; read the new code from the dsh terminal" : "the pairing code is invalid";
6476
+ const status = verification.reason === "locked" ? 403 : verification.reason === "rate-limited" ? 429 : 401;
6477
+ throw new HttpError(status, `pair-${verification.reason}`, message);
6371
6478
  }
6372
6479
  const authority = rc.authority;
6373
6480
  if (authority.length === 0) throw new HttpError(400, "missing-host", "the Host header is required");
@@ -6385,10 +6492,10 @@ function registerRoutes(router, deps) {
6385
6492
  token,
6386
6493
  deviceName: device.deviceName,
6387
6494
  pairedAt: device.pairedAt,
6388
- server: serverFacts(deps),
6495
+ server: serverFacts(deps, requestOrigin(deps, rc)),
6389
6496
  features: features(deps)
6390
6497
  };
6391
- deps.logger.info(`[dsh-door] paired device "${device.deviceName}" (${device.deviceId.slice(0, 12)}\u2026) from ${rc.clientAddress}`);
6498
+ deps.logger.info(`[dsh-hello] paired device "${device.deviceName}" (${device.deviceId.slice(0, 12)}\u2026) from ${rc.clientAddress}`);
6392
6499
  sendJson(rc.res, 201, response);
6393
6500
  }
6394
6501
  });
@@ -6976,21 +7083,6 @@ function registerRoutes(router, deps) {
6976
7083
  }
6977
7084
  }
6978
7085
  });
6979
- router.add({
6980
- method: "GET",
6981
- pattern: "/sessions/:id/open",
6982
- auth: "device",
6983
- handler: (rc) => {
6984
- const facts = serverFacts(deps);
6985
- const base = `${facts.protocolName}://${rc.authority}`;
6986
- sendJson(rc.res, 200, {
6987
- url: `${base}/`,
6988
- sessionId: rc.params.id,
6989
- requiresBrowserLogin: true,
6990
- note: "Open this in a browser that already has a dsh web session; the mobile token is not a browser token."
6991
- });
6992
- }
6993
- });
6994
7086
  router.add({
6995
7087
  method: "POST",
6996
7088
  pattern: "/sessions/:id/questions/:callId/answer",
@@ -7153,7 +7245,7 @@ function registerRoutes(router, deps) {
7153
7245
  const clientId = newId();
7154
7246
  deps.hub.add(clientId, rc.device.deviceId, rc.res);
7155
7247
  writeSse(rc.res, "hello", {
7156
- server: serverFacts(deps),
7248
+ server: serverFacts(deps, requestOrigin(deps, rc)),
7157
7249
  features: features(deps),
7158
7250
  pendingApprovals: deps.interactions.listApprovals(),
7159
7251
  pendingQuestions: deps.interactions.listQuestions(),
@@ -7178,8 +7270,8 @@ function registerRoutes(router, deps) {
7178
7270
  handler: (rc) => {
7179
7271
  const body = rc.body;
7180
7272
  const decision = body?.decision;
7181
- if (decision !== "allow" && decision !== "deny" && decision !== "always") {
7182
- throw new HttpError(400, "bad-decision", "decision must be allow, deny, or always");
7273
+ if (decision !== "allow" && decision !== "deny" && decision !== "always" && decision !== "later") {
7274
+ throw new HttpError(400, "bad-decision", "decision must be allow, deny, always, or later");
7183
7275
  }
7184
7276
  const item = deps.interactions.decideApproval(rc.params.id, decision);
7185
7277
  if (item === void 0) throw new HttpError(404, "approval-not-found", "the approval is no longer pending");
@@ -7250,32 +7342,38 @@ function registerRoutes(router, deps) {
7250
7342
  sendJson(rc.res, 201, item);
7251
7343
  }
7252
7344
  });
7253
- deps.logger.warn("[dsh-door] debug interaction routes are enabled");
7345
+ deps.logger.warn("[dsh-hello] debug interaction routes are enabled");
7254
7346
  }
7255
7347
  deps.logger.info(
7256
- `[dsh-door] routes mounted at ${config.basePath} (protocol ${PROTOCOL_VERSION}, push ${config.push.provider})`
7348
+ `[dsh-hello] routes mounted at ${config.basePath} (protocol ${PROTOCOL_VERSION}, push ${config.push.provider})`
7257
7349
  );
7258
7350
  }
7259
- function serverFacts(deps) {
7351
+ function serverFacts(deps, originOverride) {
7260
7352
  const web = deps.ctx.webServer;
7261
- let origin = null;
7353
+ let fallback = null;
7262
7354
  try {
7263
- origin = typeof web.getOrigin === "function" ? web.getOrigin() : null;
7355
+ fallback = typeof web.getOrigin === "function" ? web.getOrigin() : null;
7264
7356
  } catch {
7265
- origin = null;
7357
+ fallback = null;
7266
7358
  }
7359
+ const origin = originOverride ?? fallback;
7267
7360
  return {
7268
- name: "dsh-door",
7361
+ name: "dsh-hello",
7269
7362
  version: deps.pluginVersion,
7270
7363
  protocol: PROTOCOL_VERSION,
7271
7364
  dshVersion: deps.version.version,
7272
7365
  dshCompatible: deps.version.compatible,
7273
7366
  origin,
7274
- protocolName: web.protocol === "https:" ? "https" : "http",
7367
+ protocolName: origin !== null && origin.startsWith("https://") ? "https" : web.protocol === "https:" ? "https" : "http",
7275
7368
  host: web.host ?? null,
7276
7369
  port: web.port ?? null
7277
7370
  };
7278
7371
  }
7372
+ function requestOrigin(deps, rc) {
7373
+ if (rc.authority.length === 0) return null;
7374
+ const scheme = deps.ctx.webServer.protocol === "https:" ? "https" : "http";
7375
+ return `${scheme}://${rc.authority}`;
7376
+ }
7279
7377
  function scheduleCode(result) {
7280
7378
  if (typeof result !== "object" || result === null) return void 0;
7281
7379
  const code = result.code;
@@ -7283,8 +7381,9 @@ function scheduleCode(result) {
7283
7381
  }
7284
7382
  function features(deps) {
7285
7383
  return {
7286
- approvals: true,
7287
- questions: true,
7384
+ approvals: deps.config.interactionTarget !== "browser-only",
7385
+ questions: deps.config.interactionTarget !== "browser-only",
7386
+ interactionTarget: deps.config.interactionTarget,
7288
7387
  presence: true,
7289
7388
  push: deps.push.isConfigured(),
7290
7389
  debugRoutes: deps.config.enableDebugRoutes,
@@ -7353,9 +7452,9 @@ function adminAuthorized(deps, rc) {
7353
7452
  }
7354
7453
  return rc.clientAddress === "127.0.0.1" || rc.clientAddress === "::1" || rc.clientAddress.startsWith("127.");
7355
7454
  }
7356
- async function adminData(deps) {
7455
+ async function adminData(deps, originBase) {
7357
7456
  const view = deps.pairing.current();
7358
- const origin = serverFacts(deps).origin ?? "";
7457
+ const origin = originBase;
7359
7458
  const payload = JSON.stringify({ v: 1, url: `${origin}${deps.config.basePath}`, code: view.code });
7360
7459
  const qr = await renderQr(payload);
7361
7460
  const qrSvg = await renderQrSvg(payload);
@@ -7363,6 +7462,7 @@ async function adminData(deps) {
7363
7462
  code: view.code,
7364
7463
  formatted: view.formatted,
7365
7464
  fixed: view.fixed,
7465
+ locked: deps.pairing.isLocked(),
7366
7466
  expiresAt: view.fixed ? null : view.expiresAt,
7367
7467
  origin,
7368
7468
  basePath: deps.config.basePath,
@@ -7381,6 +7481,18 @@ async function adminData(deps) {
7381
7481
  }))
7382
7482
  };
7383
7483
  }
7484
+ function requestBase(rc) {
7485
+ const value = rc.query.get("base");
7486
+ if (value === null || value.length === 0 || value.length > 2048) return null;
7487
+ try {
7488
+ const url = new URL(value);
7489
+ if (url.protocol !== "http:" && url.protocol !== "https:") return null;
7490
+ if (url.username !== "" || url.password !== "" || url.search !== "" || url.hash !== "") return null;
7491
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
7492
+ } catch {
7493
+ return null;
7494
+ }
7495
+ }
7384
7496
  async function sendBinary(rc, file) {
7385
7497
  const offset = numberParam(rc.query.get("offset")) ?? 0;
7386
7498
  const limit = Math.min(Math.max(numberParam(rc.query.get("limit")) ?? 512 * 1024, 1), 2 * 1024 * 1024);
@@ -7408,30 +7520,67 @@ async function sendBinary(rc, file) {
7408
7520
  });
7409
7521
  }
7410
7522
  async function renderQr(text) {
7523
+ const candidates = [];
7411
7524
  try {
7412
7525
  const mod = await Promise.resolve().then(() => __toESM(require_main(), 1));
7413
- const qrcode = mod.default ?? mod;
7414
- return await new Promise((resolve4) => {
7415
- ;
7416
- qrcode.generate(text, { small: true }, resolve4);
7417
- });
7526
+ candidates.push(mod.default, mod.default?.default, mod);
7418
7527
  } catch {
7419
- return null;
7420
7528
  }
7529
+ try {
7530
+ const { createRequire: createRequire2 } = await import("node:module");
7531
+ candidates.push(createRequire2(import.meta.url)("qrcode-terminal"));
7532
+ } catch {
7533
+ }
7534
+ for (const candidate of candidates) {
7535
+ const generate = candidate?.generate;
7536
+ if (typeof generate !== "function") continue;
7537
+ try {
7538
+ return await new Promise((resolve4) => {
7539
+ ;
7540
+ candidate.generate(text, { small: true }, resolve4);
7541
+ });
7542
+ } catch {
7543
+ continue;
7544
+ }
7545
+ }
7546
+ return null;
7421
7547
  }
7422
- async function renderQrSvg(text) {
7548
+ async function loadQrSvgApi() {
7549
+ const isApi = (value) => typeof value === "object" && value !== null && typeof value.toString === "function" && value.toString !== Object.prototype.toString;
7423
7550
  try {
7424
7551
  const mod = await import("qrcode");
7425
- const qrcode = mod.default ?? mod;
7426
- return await qrcode.toString(text, {
7552
+ for (const candidate of [mod.default, mod.default?.default, mod]) {
7553
+ if (isApi(candidate)) return candidate;
7554
+ }
7555
+ } catch (error) {
7556
+ console.warn("[dsh-hello] could not import qrcode through ESM:", error);
7557
+ }
7558
+ try {
7559
+ const { createRequire: createRequire2 } = await import("node:module");
7560
+ const required = createRequire2(import.meta.url)("qrcode");
7561
+ if (isApi(required)) return required;
7562
+ } catch (error) {
7563
+ console.warn("[dsh-hello] could not require qrcode:", error);
7564
+ }
7565
+ return null;
7566
+ }
7567
+ async function renderQrSvg(text) {
7568
+ const qrcode = await loadQrSvgApi();
7569
+ if (qrcode === null) {
7570
+ console.warn("[dsh-hello] qrcode is unavailable; the admin page will not show a QR code");
7571
+ return null;
7572
+ }
7573
+ try {
7574
+ const svg = await qrcode.toString(text, {
7427
7575
  type: "svg",
7428
7576
  margin: 1,
7429
7577
  width: 320,
7430
7578
  errorCorrectionLevel: "M",
7431
7579
  color: { dark: "#0b0e14", light: "#ffffff" }
7432
7580
  });
7581
+ return typeof svg === "string" && svg.trimStart().startsWith("<svg") ? svg : null;
7433
7582
  } catch (error) {
7434
- console.warn("[dsh-door] QR SVG generation failed:", error);
7583
+ console.warn("[dsh-hello] QR SVG generation failed:", error);
7435
7584
  return null;
7436
7585
  }
7437
7586
  }
@@ -7617,7 +7766,7 @@ async function toListItem(ctx, summary, signal, rowState) {
7617
7766
  running: summary.running,
7618
7767
  agentAvailable: summary.agentAvailable,
7619
7768
  blank: summary.blank,
7620
- ...summary.cwd === void 0 ? {} : { cwd: summary.cwd },
7769
+ ...summary.cwd === void 0 ? {} : { cwd: normalizeCwd(summary.cwd) },
7621
7770
  ...summary.parentSessionId === void 0 ? {} : { parentSessionId: summary.parentSessionId },
7622
7771
  ...summary.origin === void 0 ? {} : { origin: summary.origin },
7623
7772
  ...summary.formatStatus === void 0 ? {} : { formatStatus: summary.formatStatus },
@@ -7675,6 +7824,10 @@ function isNotFound(error) {
7675
7824
  const candidate = error;
7676
7825
  return candidate.code === "session/not-found" || typeof candidate.message === "string" && candidate.message.includes("not found");
7677
7826
  }
7827
+ function normalizeCwd(value) {
7828
+ const collapsed = value.replace(/\\{2,}/g, "\\").replace(/\/{2,}/g, "/");
7829
+ return collapsed.length > 3 ? collapsed.replace(/[\\/]+$/, "") : collapsed;
7830
+ }
7678
7831
 
7679
7832
  // src/streams.ts
7680
7833
  var SseHub = class {
@@ -7894,7 +8047,7 @@ var TerminalManager = class {
7894
8047
  try {
7895
8048
  await record.handle.terminate();
7896
8049
  } catch (error) {
7897
- this.logger.warn(`[dsh-door] terminal cleanup failed: ${shortMessage(error)}`);
8050
+ this.logger.warn(`[dsh-hello] terminal cleanup failed: ${shortMessage(error)}`);
7898
8051
  }
7899
8052
  return true;
7900
8053
  }
@@ -7924,12 +8077,12 @@ var TerminalManager = class {
7924
8077
  this.emit(record, { type: "output", data: text });
7925
8078
  });
7926
8079
  record.handle.output.on("error", (error) => {
7927
- this.logger.warn(`[dsh-door] terminal output failed: ${error.message}`);
8080
+ this.logger.warn(`[dsh-hello] terminal output failed: ${error.message}`);
7928
8081
  });
7929
8082
  void record.handle.done.then(
7930
8083
  (outcome) => this.finish(record, outcome.exitCode),
7931
8084
  (error) => {
7932
- this.logger.warn(`[dsh-door] terminal process failed: ${shortMessage(error)}`);
8085
+ this.logger.warn(`[dsh-hello] terminal process failed: ${shortMessage(error)}`);
7933
8086
  this.finish(record, null);
7934
8087
  }
7935
8088
  );
@@ -7995,7 +8148,7 @@ async function checkDshVersion(range, logger) {
7995
8148
  const version = await resolveVersion();
7996
8149
  if (version === null) {
7997
8150
  logger.warn(
7998
- `[dsh-door] could not read the running dsh version; this build targets "${range}". Continuing, but a mismatch may fail at runtime.`
8151
+ `[dsh-hello] could not read the running dsh version; this build targets "${range}". Continuing, but a mismatch may fail at runtime.`
7999
8152
  );
8000
8153
  return { version: null, compatible: true };
8001
8154
  }
@@ -8007,11 +8160,11 @@ async function checkDshVersion(range, logger) {
8007
8160
  }
8008
8161
  if (!compatible) {
8009
8162
  logger.warn(
8010
- `[dsh-door] running dsh ${version} is outside this build's tested range "${range}". The Host may refuse the plugin; update dsh-door to a release that supports this dsh.`
8163
+ `[dsh-hello] running dsh ${version} is outside this build's tested range "${range}". The Host may refuse the plugin; update dsh-hello to a release that supports this dsh.`
8011
8164
  );
8012
8165
  return { version, compatible: false };
8013
8166
  }
8014
- logger.info(`[dsh-door] dsh ${version} satisfies ${range}`);
8167
+ logger.info(`[dsh-hello] dsh ${version} satisfies ${range}`);
8015
8168
  return { version, compatible };
8016
8169
  }
8017
8170
  async function resolveVersion() {
@@ -8064,7 +8217,7 @@ async function versionOf(filename) {
8064
8217
  }
8065
8218
 
8066
8219
  // src/index.ts
8067
- var name = "dsh-door";
8220
+ var name = "dsh-hello";
8068
8221
  var inject = ["webServer", "sessionController", "credentials"];
8069
8222
  var PLUGIN_VERSION = readPluginVersion();
8070
8223
  async function apply(ctx, rawConfig) {
@@ -8074,8 +8227,8 @@ async function apply(ctx, rawConfig) {
8074
8227
  const webServer = ctx.webServer ?? ctx.get("webServer");
8075
8228
  const sessionController = ctx.sessionController ?? ctx.get("sessionController");
8076
8229
  const credentials = ctx.credentials ?? ctx.get("credentials");
8077
- if (webServer === void 0) throw new Error("dsh-door: the webServer service is required");
8078
- if (sessionController === void 0) throw new Error("dsh-door: the sessionController service is required");
8230
+ if (webServer === void 0) throw new Error("dsh-hello: the webServer service is required");
8231
+ if (sessionController === void 0) throw new Error("dsh-hello: the sessionController service is required");
8079
8232
  const host = ctx;
8080
8233
  const devices = new DeviceStore(host, credentials);
8081
8234
  await devices.load();
@@ -8083,12 +8236,12 @@ async function apply(ctx, rawConfig) {
8083
8236
  const hostOrigin = (host.webServer.getOrigin?.() ?? "").replace(/\/+$/, "");
8084
8237
  const push2 = new PushManager(config, devices, logger, credentials, hostOrigin.length > 0 ? `plugin:${hostOrigin}` : "");
8085
8238
  await push2.load();
8086
- const pairingRecordKey = "dsh-door/pairing";
8087
- const pairing = new PairingManager(config, logger, void 0, async (fixedCode) => {
8239
+ const pairingRecordKey = "dsh-hello/pairing";
8240
+ const pairing = new PairingManager(config, logger, void 0, async (state) => {
8088
8241
  if (credentials === void 0) return;
8089
8242
  await credentials.modifyRecord(pairingRecordKey, async () => ({
8090
8243
  kind: "grant",
8091
- payload: { fixedCode }
8244
+ payload: state
8092
8245
  }));
8093
8246
  });
8094
8247
  if (credentials !== void 0) {
@@ -8096,17 +8249,30 @@ async function apply(ctx, rawConfig) {
8096
8249
  const record = await credentials.readRecord(pairingRecordKey);
8097
8250
  const payload = record?.payload;
8098
8251
  if (typeof payload === "object" && payload !== null) {
8099
- const fixed = payload.fixedCode;
8100
- if (typeof fixed === "string") await pairing.setFixedCode(fixed, false);
8252
+ const { fixedCode, locked } = payload;
8253
+ if (typeof fixedCode === "string") await pairing.setFixedCode(fixedCode, false);
8254
+ if (locked === true) await pairing.setLocked(true, false);
8101
8255
  }
8102
8256
  } catch (error) {
8103
- logger.warn(`[dsh-door] could not load the fixed pairing code: ${shortError(error)}`);
8257
+ logger.warn(`[dsh-hello] could not load the pairing settings: ${shortError(error)}`);
8104
8258
  }
8105
8259
  }
8106
8260
  const interactions = new InteractionBroker(host, config, hub, push2, logger);
8107
8261
  interactions.register();
8108
8262
  const sessions = createSessionFacade(host);
8109
8263
  const terminals = new TerminalManager(host, logger);
8264
+ const connection = readService(ctx, "connection");
8265
+ const webApp = readService(ctx, "webApp");
8266
+ const webUrl = () => {
8267
+ const base = webApp?.getAdvertisedUrl?.() ?? (hostOrigin.length > 0 ? hostOrigin : void 0);
8268
+ if (base === void 0) return null;
8269
+ try {
8270
+ return connection?.authenticatedUrl?.(base) ?? base;
8271
+ } catch (error) {
8272
+ logger.warn(`[dsh-hello] could not mint the Web UI URL: ${shortError(error)}`);
8273
+ return base;
8274
+ }
8275
+ };
8110
8276
  const router = new HttpRouter(config, {
8111
8277
  authenticate: (token) => devices.authenticate(token),
8112
8278
  isKnownAuthority: (authority) => devices.list().some((device) => device.authorities.includes(authority)),
@@ -8125,36 +8291,37 @@ async function apply(ctx, rawConfig) {
8125
8291
  terminals,
8126
8292
  logger,
8127
8293
  version,
8128
- pluginVersion: PLUGIN_VERSION
8294
+ pluginVersion: PLUGIN_VERSION,
8295
+ webUrl
8129
8296
  });
8130
8297
  ctx.effect(() => {
8131
8298
  const dispose = webServer.register(router.hostRoute());
8132
- logger.info(`[dsh-door] listening at ${(host.webServer.getOrigin?.() ?? "") + config.basePath}`);
8299
+ logger.info(`[dsh-hello] listening at ${(host.webServer.getOrigin?.() ?? "") + config.basePath}`);
8133
8300
  return () => dispose();
8134
- }, "dsh-door: mobile routes");
8301
+ }, "dsh-hello: mobile routes");
8135
8302
  ctx.effect(() => {
8136
8303
  const off = ctx.on("webserver/index-inject", (table) => {
8137
8304
  const rows = table;
8138
8305
  rows.push({ kind: "global", name: "__DSH_DOOR__", value: { basePath: config.basePath } });
8139
8306
  }, { global: true });
8140
8307
  return () => off();
8141
- }, "dsh-door: index injection");
8308
+ }, "dsh-hello: index injection");
8142
8309
  registerSessionNotifications(host, hub, push2, sessions, logger, terminals);
8143
8310
  ctx.effect(() => () => {
8144
8311
  hub.dispose();
8145
8312
  interactions.dispose();
8146
8313
  terminals.dispose();
8147
- }, "dsh-door: streams and interactions");
8314
+ }, "dsh-hello: streams and interactions");
8148
8315
  const current = pairing.current();
8149
8316
  const expiryText = current.fixed || current.expiresAt === Number.MAX_SAFE_INTEGER ? "never (fixed code)" : new Date(current.expiresAt).toISOString();
8150
8317
  logger.info(
8151
- `[dsh-door] pairing code ${formatPairingCode(current.code)} \u2014 open the app, enter the server URL, then this code. Code expires ${expiryText}.`
8318
+ `[dsh-hello] pairing code ${formatPairingCode(current.code)} \u2014 open the app, enter the server URL, then this code. Code expires ${expiryText}.`
8152
8319
  );
8153
8320
  if (config.logPairingCode && config.pairingCode === void 0) {
8154
8321
  void printPairingQr(current.code, host, config).catch(() => void 0);
8155
8322
  }
8156
8323
  logger.info(
8157
- `[dsh-door] ${devices.count()} paired device(s); push provider "${config.push.provider}". Plain HTTP on a public address leaks the device token: use TLS or a private network.`
8324
+ `[dsh-hello] ${devices.count()} paired device(s); push provider "${config.push.provider}". Plain HTTP on a public address leaks the device token: use TLS or a private network.`
8158
8325
  );
8159
8326
  }
8160
8327
  function registerSessionNotifications(ctx, hub, push2, sessions, logger, terminals) {
@@ -8184,7 +8351,7 @@ function registerSessionNotifications(ctx, hub, push2, sessions, logger, termina
8184
8351
  if (hub.hasClients()) return;
8185
8352
  void sessions.titleOf(sessionId, new AbortController().signal).then((title) => {
8186
8353
  if (!hub.hasClients()) push2.notify("turn-end", { sessionId, title: title ?? void 0, eventId });
8187
- }).catch((error) => logger.warn(`[dsh-door] turn-end notification failed: ${shortError(error)}`));
8354
+ }).catch((error) => logger.warn(`[dsh-hello] turn-end notification failed: ${shortError(error)}`));
8188
8355
  }
8189
8356
  }, { global: true });
8190
8357
  ctx.on("api-session/error", (sessionId, message) => {
@@ -8192,6 +8359,13 @@ function registerSessionNotifications(ctx, hub, push2, sessions, logger, termina
8192
8359
  hub.broadcast("session", { action: "error", sessionId, message: typeof message === "string" ? message : "agent error" });
8193
8360
  }, { global: true });
8194
8361
  }
8362
+ function readService(ctx, name2) {
8363
+ try {
8364
+ return ctx.get(name2);
8365
+ } catch {
8366
+ return void 0;
8367
+ }
8368
+ }
8195
8369
  function createLogger(_ctx) {
8196
8370
  return {
8197
8371
  info: (message) => console.log(message),