dsh-hello 0.1.6 → 0.1.8

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
@@ -6186,7 +6186,14 @@ var Config = Schema.object({
6186
6186
  apnsEnvironment: Schema.union(["sandbox", "production"]).default("production"),
6187
6187
  notifyTurnEnd: Schema.boolean().default(true),
6188
6188
  notifyApproval: Schema.boolean().default(true),
6189
- notifyQuestion: Schema.boolean().default(true)
6189
+ notifyQuestion: Schema.boolean().default(true),
6190
+ webhooks: Schema.array(Schema.object({
6191
+ name: Schema.string().default("webhook"),
6192
+ url: Schema.string().required(),
6193
+ format: Schema.union(["wecom", "serverchan", "ntfy", "bark", "generic"]).default("generic")
6194
+ })).default([]),
6195
+ webhookCooldownMs: Schema.number().default(60 * 1e3),
6196
+ webhookContent: Schema.union(["minimal", "standard"]).default("minimal")
6190
6197
  }).default({})
6191
6198
  });
6192
6199
  function normalizeConfig(input) {
@@ -6223,7 +6230,14 @@ function normalizeConfig(input) {
6223
6230
  apnsEnvironment: push2.apnsEnvironment ?? "production",
6224
6231
  notifyTurnEnd: push2.notifyTurnEnd ?? true,
6225
6232
  notifyApproval: push2.notifyApproval ?? true,
6226
- notifyQuestion: push2.notifyQuestion ?? true
6233
+ notifyQuestion: push2.notifyQuestion ?? true,
6234
+ webhooks: (push2.webhooks ?? []).map((target) => ({
6235
+ name: target.name ?? "webhook",
6236
+ url: target.url.trim(),
6237
+ format: target.format ?? "generic"
6238
+ })).filter((target) => target.url.length > 0),
6239
+ webhookCooldownMs: push2.webhookCooldownMs ?? 60 * 1e3,
6240
+ webhookContent: push2.webhookContent ?? "minimal"
6227
6241
  }
6228
6242
  };
6229
6243
  if (raw.pairingCode !== void 0) config.pairingCode = raw.pairingCode;
@@ -6248,6 +6262,16 @@ function normalizeBasePath(value) {
6248
6262
  if (withoutTrailing.length === 0) throw new Error('dsh-hello: basePath may not be "/"');
6249
6263
  return withoutTrailing;
6250
6264
  }
6265
+ var defaultPushConfig = {
6266
+ provider: "none",
6267
+ apnsEnvironment: "production",
6268
+ notifyTurnEnd: true,
6269
+ notifyApproval: true,
6270
+ notifyQuestion: true,
6271
+ webhooks: [],
6272
+ webhookCooldownMs: 60 * 1e3,
6273
+ webhookContent: "minimal"
6274
+ };
6251
6275
 
6252
6276
  // src/util.ts
6253
6277
  import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
@@ -6900,6 +6924,7 @@ var InteractionBroker = class {
6900
6924
  expiresAt
6901
6925
  };
6902
6926
  this.hub.broadcast("question", envelope);
6927
+ this.push.notify("question", envelope);
6903
6928
  return envelope;
6904
6929
  }
6905
6930
  listQuestions() {
@@ -7464,6 +7489,11 @@ var PairingManager = class {
7464
7489
  // src/push.ts
7465
7490
  import { createPrivateKey, createSign, sign as cryptoSign } from "node:crypto";
7466
7491
  import { connect } from "node:http2";
7492
+ var MINIMAL_BODY = {
7493
+ approval: "A tool call needs approval",
7494
+ question: "The agent is waiting for an answer",
7495
+ "turn-end": "The agent finished its turn"
7496
+ };
7467
7497
  var PushManager = class {
7468
7498
  constructor(config, devices, logger, credentials, hostId = "") {
7469
7499
  this.config = config;
@@ -7480,6 +7510,8 @@ var PushManager = class {
7480
7510
  fcmToken;
7481
7511
  apnsToken;
7482
7512
  remote = {};
7513
+ /** Last send per `url|kind`, so a burst does not spam one target. */
7514
+ lastWebhook = /* @__PURE__ */ new Map();
7483
7515
  /**
7484
7516
  * Prefer a `dsh-hello/push` credential record over configuration. Push
7485
7517
  * service-account JSON and APNs keys are secrets, so a deployment that
@@ -7548,15 +7580,37 @@ var PushManager = class {
7548
7580
  }
7549
7581
  }
7550
7582
  notify(kind, payload) {
7551
- if (!this.isConfigured()) return;
7552
7583
  const push2 = this.push;
7553
- if (kind === "approval" && !push2.notifyApproval) return;
7554
- if (kind === "question" && !push2.notifyQuestion) return;
7555
- if (kind === "turn-end" && !push2.notifyTurnEnd) return;
7584
+ const enabled = kind === "approval" ? push2.notifyApproval : kind === "question" ? push2.notifyQuestion : push2.notifyTurnEnd;
7585
+ if (!enabled) return;
7586
+ const toApp = this.isConfigured();
7587
+ if (!toApp && push2.webhooks.length === 0) return;
7556
7588
  const message = render(kind, payload, this.hostId);
7557
- void this.send(message, kind).catch((error) => {
7558
- this.logger.warn(`[dsh-hello] push failed: ${shortError(error)}`);
7559
- });
7589
+ if (toApp) {
7590
+ void this.send(message, kind).catch((error) => {
7591
+ this.logger.warn(`[dsh-hello] push failed: ${shortError(error)}`);
7592
+ });
7593
+ }
7594
+ for (const target of push2.webhooks) {
7595
+ void this.sendWebhook(target, kind, message).catch((error) => {
7596
+ this.logger.warn(`[dsh-hello] webhook ${target.name} failed: ${shortError(error)}`);
7597
+ });
7598
+ }
7599
+ }
7600
+ async sendWebhook(target, kind, message) {
7601
+ const push2 = this.push;
7602
+ const key = `${target.url}|${kind}`;
7603
+ const last = this.lastWebhook.get(key) ?? 0;
7604
+ if (Date.now() - last < push2.webhookCooldownMs) return;
7605
+ this.lastWebhook.set(key, Date.now());
7606
+ const body = push2.webhookContent === "standard" ? message.body : MINIMAL_BODY[kind];
7607
+ const signal = AbortSignal.timeout(8e3);
7608
+ const request = webhookRequest(target.format, target.url, message, body, signal);
7609
+ const response = await fetch(request.endpoint, request.init);
7610
+ if (!response.ok) {
7611
+ const text = await response.text().catch(() => "");
7612
+ throw new Error(`${target.format} ${response.status}: ${text.slice(0, 200)}`);
7613
+ }
7560
7614
  }
7561
7615
  async send(message, kind) {
7562
7616
  if (this.push.provider === "relay") {
@@ -7766,6 +7820,62 @@ function render(kind, payload, hostId) {
7766
7820
  function truncate2(value, max) {
7767
7821
  return value.length <= max ? value : `${value.slice(0, max - 1)}\u2026`;
7768
7822
  }
7823
+ function webhookRequest(format, url, message, body, signal) {
7824
+ const post = (payload) => ({
7825
+ endpoint: url,
7826
+ init: {
7827
+ method: "POST",
7828
+ headers: { "content-type": "application/json" },
7829
+ body: JSON.stringify(payload),
7830
+ signal
7831
+ }
7832
+ });
7833
+ switch (format) {
7834
+ case "wecom":
7835
+ return post({ msgtype: "markdown", markdown: { content: `**${message.title}**
7836
+ ${body}` } });
7837
+ case "serverchan":
7838
+ return {
7839
+ endpoint: url,
7840
+ init: {
7841
+ method: "POST",
7842
+ headers: { "content-type": "application/x-www-form-urlencoded" },
7843
+ body: new URLSearchParams({ title: message.title, desp: body }).toString(),
7844
+ signal
7845
+ }
7846
+ };
7847
+ case "ntfy":
7848
+ return {
7849
+ endpoint: url,
7850
+ init: {
7851
+ method: "POST",
7852
+ headers: { "content-type": "text/plain", Title: message.title, Tags: "dsh" },
7853
+ body,
7854
+ signal
7855
+ }
7856
+ };
7857
+ case "bark": {
7858
+ const parsed = new URL(url);
7859
+ const segment = parsed.pathname.split("/").filter(Boolean).pop() ?? "";
7860
+ return {
7861
+ endpoint: segment === "push" ? url : new URL("/push", parsed.origin).toString(),
7862
+ init: {
7863
+ method: "POST",
7864
+ headers: { "content-type": "application/json" },
7865
+ body: JSON.stringify({
7866
+ ...segment === "push" ? {} : { device_key: segment },
7867
+ title: message.title,
7868
+ body,
7869
+ group: "dsh"
7870
+ }),
7871
+ signal
7872
+ }
7873
+ };
7874
+ }
7875
+ default:
7876
+ return post({ kind: message.data.kind ?? "", title: message.title, body, data: message.data });
7877
+ }
7878
+ }
7769
7879
 
7770
7880
  // src/routes.ts
7771
7881
  import { open as open2, readFile } from "node:fs/promises";
@@ -8554,6 +8664,14 @@ function scheduleCode(result) {
8554
8664
 
8555
8665
  // src/terminal-routes.ts
8556
8666
  function registerTerminalRoutes(router, deps) {
8667
+ router.add({
8668
+ method: "GET",
8669
+ pattern: "/terminals/shells",
8670
+ auth: "device",
8671
+ handler: async (rc) => {
8672
+ sendJson(rc.res, 200, await deps.terminals.shells());
8673
+ }
8674
+ });
8557
8675
  router.add({
8558
8676
  method: "GET",
8559
8677
  pattern: "/sessions/:id/terminals",
@@ -8576,7 +8694,8 @@ function registerTerminalRoutes(router, deps) {
8576
8694
  }
8577
8695
  const created = await deps.terminals.create(sessionId, cwd, {
8578
8696
  ...typeof body?.cols === "number" ? { cols: body.cols } : {},
8579
- ...typeof body?.rows === "number" ? { rows: body.rows } : {}
8697
+ ...typeof body?.rows === "number" ? { rows: body.rows } : {},
8698
+ ...typeof body?.shell === "string" && body.shell.trim().length > 0 ? { shell: body.shell.trim() } : {}
8580
8699
  });
8581
8700
  sendJson(rc.res, 201, created);
8582
8701
  }
@@ -9116,6 +9235,51 @@ function registerRoutes(router, deps) {
9116
9235
  await sendFile(rc, file);
9117
9236
  }
9118
9237
  });
9238
+ router.add({
9239
+ method: "GET",
9240
+ pattern: "/sessions/:id/attachment",
9241
+ auth: "device",
9242
+ handler: async (rc) => {
9243
+ const attachmentId = rc.query.get("attachmentId");
9244
+ const mediaType = rc.query.get("mediaType");
9245
+ const bytes = numberParam(rc.query.get("bytes"));
9246
+ const width = numberParam(rc.query.get("width"));
9247
+ const height = numberParam(rc.query.get("height"));
9248
+ if (attachmentId === null || attachmentId.length === 0 || mediaType === null) {
9249
+ throw new HttpError(400, "bad-attachment", "attachmentId and mediaType are required");
9250
+ }
9251
+ if (!["image/png", "image/jpeg", "image/webp", "image/gif"].includes(mediaType)) {
9252
+ throw new HttpError(400, "bad-media-type", "unsupported image media type");
9253
+ }
9254
+ if (bytes === void 0 || width === void 0 || height === void 0) {
9255
+ throw new HttpError(400, "bad-attachment", "bytes, width and height are required to verify the attachment");
9256
+ }
9257
+ if (bytes > 24 * 1024 * 1024) throw new HttpError(413, "attachment-too-large", "the image is larger than 24 MiB");
9258
+ const controller = deps.ctx.sessionController;
9259
+ if (controller.attachment === void 0) {
9260
+ throw new HttpError(501, "attachment-unsupported", "this Host cannot read image attachments");
9261
+ }
9262
+ const name2 = rc.query.get("name") ?? void 0;
9263
+ const value = await controller.attachment({
9264
+ sessionId: rc.params.id,
9265
+ attachment: {
9266
+ attachmentId,
9267
+ mediaType,
9268
+ bytes,
9269
+ width,
9270
+ height,
9271
+ ...name2 !== void 0 && name2.length > 0 ? { name: name2 } : {}
9272
+ }
9273
+ });
9274
+ const data = Buffer.from(value.data, "base64");
9275
+ rc.res.statusCode = 200;
9276
+ rc.res.setHeader("Content-Type", value.attachment.mediaType);
9277
+ rc.res.setHeader("Content-Length", String(data.byteLength));
9278
+ rc.res.setHeader("Cache-Control", "private, max-age=86400, immutable");
9279
+ rc.res.setHeader("X-Content-Type-Options", "nosniff");
9280
+ rc.res.end(data);
9281
+ }
9282
+ });
9119
9283
  router.add({
9120
9284
  method: "GET",
9121
9285
  pattern: "/workspaces/:id/image",
@@ -9594,7 +9758,8 @@ function createSessionFacade(ctx) {
9594
9758
  async list(signal) {
9595
9759
  const rowState = sessionRowState(ctx);
9596
9760
  const value = await controller.list({}, signal);
9597
- return Promise.all(value.items.map((item) => toListItem(ctx, item, signal, rowState)));
9761
+ const rows = [...value.items].sort((left, right) => right.updatedAt - left.updatedAt || left.sessionId.localeCompare(right.sessionId));
9762
+ return rows.map((item) => toListItem(item, rowState));
9598
9763
  },
9599
9764
  async transcript(sessionId, options, signal) {
9600
9765
  const snapshot2 = await readProjectionSnapshot(ctx, sessionId, signal);
@@ -9659,7 +9824,7 @@ function createSessionFacade(ctx) {
9659
9824
  running: state.running,
9660
9825
  agentAvailable: state.active,
9661
9826
  blank: false
9662
- } : await toListItem(ctx, summary, signal, sessionRowState(ctx))
9827
+ } : toListItem(summary, sessionRowState(ctx))
9663
9828
  };
9664
9829
  },
9665
9830
  create(input) {
@@ -9704,8 +9869,8 @@ function createSessionFacade(ctx) {
9704
9869
  }
9705
9870
  };
9706
9871
  }
9707
- async function toListItem(ctx, summary, signal, rowState) {
9708
- const projections = await readProjections(ctx, summary.sessionId, signal);
9872
+ function toListItem(summary, rowState) {
9873
+ const projections = normalizeProjections(summary.projections);
9709
9874
  const vitals = toVitals(projections);
9710
9875
  const manualOrder = rowState?.manualOrder.get(summary.sessionId);
9711
9876
  return {
@@ -9904,6 +10069,45 @@ var TerminalManager = class {
9904
10069
  available() {
9905
10070
  return this.subprocess() !== void 0;
9906
10071
  }
10072
+ /** Shell choices the Host can actually execute, plus its default. */
10073
+ async shells() {
10074
+ const subprocess = this.subprocess();
10075
+ if (subprocess === void 0) {
10076
+ throw new HttpError(501, "terminal-unavailable", "this dsh profile has no subprocess provider");
10077
+ }
10078
+ const signal = new AbortController().signal;
10079
+ const environment = await subprocess.terminalEnvironment(signal);
10080
+ const candidates = environment.platform === "windows" ? ["cmd.exe", "powershell", "pwsh", "bash"] : ["bash", "sh", "pwsh", "zsh"];
10081
+ const shells = [];
10082
+ const seen = /* @__PURE__ */ new Set();
10083
+ const remember = async (id) => {
10084
+ try {
10085
+ const path = await subprocess.resolveExecutable(id, void 0, signal);
10086
+ const key = environment.platform === "windows" ? path.toLowerCase() : path;
10087
+ if (seen.has(key)) return null;
10088
+ seen.add(key);
10089
+ return path;
10090
+ } catch {
10091
+ return null;
10092
+ }
10093
+ };
10094
+ let defaultShell = null;
10095
+ if (environment.defaultShell !== void 0) {
10096
+ const path = await remember(environment.defaultShell);
10097
+ if (path !== null) {
10098
+ const parts = environment.defaultShell.split(/[\\/]/);
10099
+ defaultShell = parts[parts.length - 1] ?? environment.defaultShell;
10100
+ shells.push({ id: defaultShell, label: defaultShell, path });
10101
+ }
10102
+ }
10103
+ for (const id of candidates) {
10104
+ if (id === defaultShell) continue;
10105
+ const path = await remember(id);
10106
+ if (path === null) continue;
10107
+ shells.push({ id, label: id, path });
10108
+ }
10109
+ return { platform: environment.platform, defaultShell, shells };
10110
+ }
9907
10111
  list(sessionId) {
9908
10112
  return [...this.terminals.values()].filter((record) => record.info.sessionId === sessionId).map((record) => record.info);
9909
10113
  }
@@ -9919,8 +10123,14 @@ var TerminalManager = class {
9919
10123
  const rows = clamp(options.rows ?? DEFAULT_ROWS, 10, MAX_ROWS);
9920
10124
  const signal = new AbortController().signal;
9921
10125
  const environment = await subprocess.terminalEnvironment(signal);
9922
- const shellCandidate = environment.defaultShell ?? (environment.platform === "windows" ? "cmd.exe" : "/bin/bash");
9923
- const shell = await subprocess.resolveExecutable(shellCandidate, void 0, signal);
10126
+ const shellCandidate = options.shell ?? environment.defaultShell ?? (environment.platform === "windows" ? "cmd.exe" : "/bin/bash");
10127
+ let shell;
10128
+ try {
10129
+ shell = await subprocess.resolveExecutable(shellCandidate, void 0, signal);
10130
+ } catch (error) {
10131
+ if (options.shell === void 0) throw error;
10132
+ throw new HttpError(400, "terminal-shell-not-found", `shell "${options.shell}" is not available on this Host`);
10133
+ }
9924
10134
  const handle = await subprocess.spawnTerminal({
9925
10135
  argv: [shell],
9926
10136
  cwd,