dsh-hello 0.1.5 → 0.1.7

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,9 +7820,65 @@ 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
- import { open as open2 } from "node:fs/promises";
7881
+ import { open as open2, readFile } from "node:fs/promises";
7772
7882
 
7773
7883
  // src/catalogs.ts
7774
7884
  function workspacesAvailable(ctx) {
@@ -8837,10 +8947,10 @@ function speechCatalog(ctx) {
8837
8947
  async function transcribeSpeech(ctx, input, signal) {
8838
8948
  const controller = getSpeechController(ctx);
8839
8949
  if (controller === void 0) throw new HttpError(503, "speech-unavailable", "this dsh profile has no speech transcription service");
8840
- if (input.audioBase64.length === 0) throw new HttpError(400, "empty-audio", "audioBase64 is required");
8950
+ if (input.audio.byteLength === 0) throw new HttpError(400, "empty-audio", "the request body must carry WAV bytes");
8841
8951
  try {
8842
8952
  return await controller.transcribe({
8843
- audioBase64: input.audioBase64,
8953
+ audioBase64: input.audio.toString("base64"),
8844
8954
  ...input.providerId === void 0 ? {} : { providerId: input.providerId },
8845
8955
  ...input.language === void 0 ? {} : { language: input.language }
8846
8956
  }, signal);
@@ -9041,17 +9151,20 @@ function registerRoutes(router, deps) {
9041
9151
  method: "POST",
9042
9152
  pattern: "/speech/transcribe",
9043
9153
  auth: "device",
9044
- // 4 MiB WAV becomes roughly 5.33 MiB of canonical base64 plus JSON.
9045
- maxBodyBytes: 6 * 1024 * 1024,
9154
+ rawBody: true,
9155
+ // Raw 16 kHz mono WAV above dsh's own audio budget; no base64 inflation.
9156
+ maxBodyBytes: 5 * 1024 * 1024,
9046
9157
  handler: async (rc) => {
9047
- const body = rc.body;
9048
- if (body === void 0 || typeof body.audioBase64 !== "string") {
9049
- throw new HttpError(400, "empty-audio", "audioBase64 is required");
9158
+ const audio = rc.body;
9159
+ if (!Buffer.isBuffer(audio) || audio.byteLength === 0) {
9160
+ throw new HttpError(400, "empty-audio", "the request body must carry WAV bytes");
9050
9161
  }
9162
+ const providerId = rc.query.get("providerId") ?? void 0;
9163
+ const language = rc.query.get("language") ?? void 0;
9051
9164
  const result = await transcribeSpeech(deps.ctx, {
9052
- audioBase64: body.audioBase64,
9053
- ...typeof body.providerId === "string" && body.providerId.length > 0 ? { providerId: body.providerId } : {},
9054
- ...typeof body.language === "string" && body.language.length > 0 ? { language: body.language } : {}
9165
+ audio,
9166
+ ...providerId === void 0 || providerId.length === 0 ? {} : { providerId },
9167
+ ...language === void 0 || language.length === 0 ? {} : { language }
9055
9168
  }, rc.signal);
9056
9169
  sendJson(rc.res, 200, result);
9057
9170
  }
@@ -9102,6 +9215,73 @@ function registerRoutes(router, deps) {
9102
9215
  await sendBinary(rc, file);
9103
9216
  }
9104
9217
  });
9218
+ router.add({
9219
+ method: "GET",
9220
+ pattern: "/sessions/:id/image",
9221
+ auth: "device",
9222
+ handler: async (rc) => {
9223
+ const path = rc.query.get("path");
9224
+ if (path === null || path.length === 0) throw new HttpError(400, "empty-path", "path is required");
9225
+ const file = await resolveWorkspaceBinary(deps.ctx, { sessionId: rc.params.id }, path, rc.signal);
9226
+ await sendFile(rc, file);
9227
+ }
9228
+ });
9229
+ router.add({
9230
+ method: "GET",
9231
+ pattern: "/sessions/:id/attachment",
9232
+ auth: "device",
9233
+ handler: async (rc) => {
9234
+ const attachmentId = rc.query.get("attachmentId");
9235
+ const mediaType = rc.query.get("mediaType");
9236
+ const bytes = numberParam(rc.query.get("bytes"));
9237
+ const width = numberParam(rc.query.get("width"));
9238
+ const height = numberParam(rc.query.get("height"));
9239
+ if (attachmentId === null || attachmentId.length === 0 || mediaType === null) {
9240
+ throw new HttpError(400, "bad-attachment", "attachmentId and mediaType are required");
9241
+ }
9242
+ if (!["image/png", "image/jpeg", "image/webp", "image/gif"].includes(mediaType)) {
9243
+ throw new HttpError(400, "bad-media-type", "unsupported image media type");
9244
+ }
9245
+ if (bytes === void 0 || width === void 0 || height === void 0) {
9246
+ throw new HttpError(400, "bad-attachment", "bytes, width and height are required to verify the attachment");
9247
+ }
9248
+ if (bytes > 24 * 1024 * 1024) throw new HttpError(413, "attachment-too-large", "the image is larger than 24 MiB");
9249
+ const controller = deps.ctx.sessionController;
9250
+ if (controller.attachment === void 0) {
9251
+ throw new HttpError(501, "attachment-unsupported", "this Host cannot read image attachments");
9252
+ }
9253
+ const name2 = rc.query.get("name") ?? void 0;
9254
+ const value = await controller.attachment({
9255
+ sessionId: rc.params.id,
9256
+ attachment: {
9257
+ attachmentId,
9258
+ mediaType,
9259
+ bytes,
9260
+ width,
9261
+ height,
9262
+ ...name2 !== void 0 && name2.length > 0 ? { name: name2 } : {}
9263
+ }
9264
+ });
9265
+ const data = Buffer.from(value.data, "base64");
9266
+ rc.res.statusCode = 200;
9267
+ rc.res.setHeader("Content-Type", value.attachment.mediaType);
9268
+ rc.res.setHeader("Content-Length", String(data.byteLength));
9269
+ rc.res.setHeader("Cache-Control", "private, max-age=86400, immutable");
9270
+ rc.res.setHeader("X-Content-Type-Options", "nosniff");
9271
+ rc.res.end(data);
9272
+ }
9273
+ });
9274
+ router.add({
9275
+ method: "GET",
9276
+ pattern: "/workspaces/:id/image",
9277
+ auth: "device",
9278
+ handler: async (rc) => {
9279
+ const path = rc.query.get("path");
9280
+ if (path === null || path.length === 0) throw new HttpError(400, "empty-path", "path is required");
9281
+ const file = await resolveWorkspaceBinary(deps.ctx, { workspaceId: rc.params.id }, path, rc.signal);
9282
+ await sendFile(rc, file);
9283
+ }
9284
+ });
9105
9285
  router.add({
9106
9286
  method: "GET",
9107
9287
  pattern: "/workspaces/:id/files",
@@ -9486,6 +9666,17 @@ function randomPairingToken() {
9486
9666
  globalThis.crypto.getRandomValues(bytes);
9487
9667
  return `dshd_${Buffer.from(bytes).toString("base64url")}`;
9488
9668
  }
9669
+ async function sendFile(rc, file) {
9670
+ const maxBytes = 24 * 1024 * 1024;
9671
+ if (file.size > maxBytes) throw new HttpError(413, "file-too-large", "the image is larger than 24 MiB");
9672
+ const bytes = await readFile(file.filename);
9673
+ rc.res.statusCode = 200;
9674
+ rc.res.setHeader("Content-Type", file.contentType);
9675
+ rc.res.setHeader("Content-Length", String(bytes.byteLength));
9676
+ rc.res.setHeader("Cache-Control", "private, max-age=300");
9677
+ rc.res.setHeader("X-Content-Type-Options", "nosniff");
9678
+ rc.res.end(bytes);
9679
+ }
9489
9680
  async function sendBinary(rc, file) {
9490
9681
  const offset = numberParam(rc.query.get("offset")) ?? 0;
9491
9682
  const limit = Math.min(Math.max(numberParam(rc.query.get("limit")) ?? 512 * 1024, 1), 2 * 1024 * 1024);
@@ -9558,7 +9749,8 @@ function createSessionFacade(ctx) {
9558
9749
  async list(signal) {
9559
9750
  const rowState = sessionRowState(ctx);
9560
9751
  const value = await controller.list({}, signal);
9561
- return Promise.all(value.items.map((item) => toListItem(ctx, item, signal, rowState)));
9752
+ const rows = [...value.items].sort((left, right) => right.updatedAt - left.updatedAt || left.sessionId.localeCompare(right.sessionId));
9753
+ return rows.map((item) => toListItem(item, rowState));
9562
9754
  },
9563
9755
  async transcript(sessionId, options, signal) {
9564
9756
  const snapshot2 = await readProjectionSnapshot(ctx, sessionId, signal);
@@ -9623,7 +9815,7 @@ function createSessionFacade(ctx) {
9623
9815
  running: state.running,
9624
9816
  agentAvailable: state.active,
9625
9817
  blank: false
9626
- } : await toListItem(ctx, summary, signal, sessionRowState(ctx))
9818
+ } : toListItem(summary, sessionRowState(ctx))
9627
9819
  };
9628
9820
  },
9629
9821
  create(input) {
@@ -9668,8 +9860,8 @@ function createSessionFacade(ctx) {
9668
9860
  }
9669
9861
  };
9670
9862
  }
9671
- async function toListItem(ctx, summary, signal, rowState) {
9672
- const projections = await readProjections(ctx, summary.sessionId, signal);
9863
+ function toListItem(summary, rowState) {
9864
+ const projections = normalizeProjections(summary.projections);
9673
9865
  const vitals = toVitals(projections);
9674
9866
  const manualOrder = rowState?.manualOrder.get(summary.sessionId);
9675
9867
  return {
@@ -10054,7 +10246,7 @@ function shortMessage(error) {
10054
10246
 
10055
10247
  // src/version.ts
10056
10248
  var import_semver = __toESM(require_semver2(), 1);
10057
- import { readFile } from "node:fs/promises";
10249
+ import { readFile as readFile2 } from "node:fs/promises";
10058
10250
  import { createRequire } from "node:module";
10059
10251
  import { dirname, join, parse, resolve as resolve3 } from "node:path";
10060
10252
  async function checkDshVersion(range, logger) {
@@ -10120,7 +10312,7 @@ async function resolveVersion() {
10120
10312
  }
10121
10313
  async function versionOf(filename) {
10122
10314
  try {
10123
- const manifest = JSON.parse(await readFile(filename, "utf8"));
10315
+ const manifest = JSON.parse(await readFile2(filename, "utf8"));
10124
10316
  if (typeof manifest.name === "string" && !manifest.name.startsWith("@deepseek-ai/dsh")) return null;
10125
10317
  if (typeof manifest.version === "string" && import_semver.default.valid(manifest.version) !== null) return manifest.version;
10126
10318
  } catch {