@ours.network/messenger-server 2.0.4 → 2.1.1

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.
@@ -10,7 +10,7 @@ import {
10
10
  publicEngineError,
11
11
  publicInternalError,
12
12
  reportFailure
13
- } from "./chunk-JNUHR327.js";
13
+ } from "./chunk-HTCOS6QG.js";
14
14
 
15
15
  // node_modules/bn.js/lib/bn.js
16
16
  var require_bn = __commonJS({
@@ -3144,7 +3144,7 @@ var require_buffer = __commonJS({
3144
3144
  const isCompatible = typeof data === "object" && data.constructor.name === "EncoderBuffer" && typeof data.length === "number" && typeof data.join === "function";
3145
3145
  return isCompatible;
3146
3146
  };
3147
- EncoderBuffer.prototype.join = function join6(out, offset) {
3147
+ EncoderBuffer.prototype.join = function join7(out, offset) {
3148
3148
  if (!out)
3149
3149
  out = Buffer2.alloc(this.length);
3150
3150
  if (!offset)
@@ -3622,17 +3622,17 @@ var require_node = __commonJS({
3622
3622
  else
3623
3623
  return;
3624
3624
  }
3625
- let content = null;
3625
+ let content2 = null;
3626
3626
  let primitive = false;
3627
3627
  if (state.any) {
3628
3628
  result = this._createEncoderBuffer(data);
3629
3629
  } else if (state.choice) {
3630
3630
  result = this._encodeChoice(data, reporter);
3631
3631
  } else if (state.contains) {
3632
- content = this._getUse(state.contains, parent)._encode(data, reporter);
3632
+ content2 = this._getUse(state.contains, parent)._encode(data, reporter);
3633
3633
  primitive = true;
3634
3634
  } else if (state.children) {
3635
- content = state.children.map(function(child) {
3635
+ content2 = state.children.map(function(child) {
3636
3636
  if (child._baseState.tag === "null_")
3637
3637
  return child._encode(null, reporter, data);
3638
3638
  if (child._baseState.key === null)
@@ -3646,7 +3646,7 @@ var require_node = __commonJS({
3646
3646
  }, this).filter(function(child) {
3647
3647
  return child;
3648
3648
  });
3649
- content = this._createEncoderBuffer(content);
3649
+ content2 = this._createEncoderBuffer(content2);
3650
3650
  } else {
3651
3651
  if (state.tag === "seqof" || state.tag === "setof") {
3652
3652
  if (!(state.args && state.args.length === 1))
@@ -3655,14 +3655,14 @@ var require_node = __commonJS({
3655
3655
  return reporter.error("seqof/setof, but data is not Array");
3656
3656
  const child = this.clone();
3657
3657
  child._baseState.implicit = null;
3658
- content = this._createEncoderBuffer(data.map(function(item) {
3658
+ content2 = this._createEncoderBuffer(data.map(function(item) {
3659
3659
  const state2 = this._baseState;
3660
3660
  return this._getUse(state2.args[0], data)._encode(item, reporter);
3661
3661
  }, child));
3662
3662
  } else if (state.use !== null) {
3663
3663
  result = this._getUse(state.use, parent)._encode(data, reporter);
3664
3664
  } else {
3665
- content = this._encodePrimitive(state.tag, data);
3665
+ content2 = this._encodePrimitive(state.tag, data);
3666
3666
  primitive = true;
3667
3667
  }
3668
3668
  }
@@ -3674,7 +3674,7 @@ var require_node = __commonJS({
3674
3674
  reporter.error("Tag could be omitted only for .use()");
3675
3675
  } else {
3676
3676
  if (state.use === null)
3677
- result = this._encodeComposite(tag, primitive, cls, content);
3677
+ result = this._encodeComposite(tag, primitive, cls, content2);
3678
3678
  }
3679
3679
  }
3680
3680
  if (state.explicit !== null)
@@ -3803,23 +3803,23 @@ var require_der2 = __commonJS({
3803
3803
  Node.call(this, "der", parent);
3804
3804
  }
3805
3805
  inherits(DERNode, Node);
3806
- DERNode.prototype._encodeComposite = function encodeComposite(tag, primitive, cls, content) {
3806
+ DERNode.prototype._encodeComposite = function encodeComposite(tag, primitive, cls, content2) {
3807
3807
  const encodedTag = encodeTag(tag, primitive, cls, this.reporter);
3808
- if (content.length < 128) {
3808
+ if (content2.length < 128) {
3809
3809
  const header2 = Buffer2.alloc(2);
3810
3810
  header2[0] = encodedTag;
3811
- header2[1] = content.length;
3812
- return this._createEncoderBuffer([header2, content]);
3811
+ header2[1] = content2.length;
3812
+ return this._createEncoderBuffer([header2, content2]);
3813
3813
  }
3814
3814
  let lenOctets = 1;
3815
- for (let i = content.length; i >= 256; i >>= 8)
3815
+ for (let i = content2.length; i >= 256; i >>= 8)
3816
3816
  lenOctets++;
3817
3817
  const header = Buffer2.alloc(1 + 1 + lenOctets);
3818
3818
  header[0] = encodedTag;
3819
3819
  header[1] = 128 | lenOctets;
3820
- for (let i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8)
3820
+ for (let i = 1 + lenOctets, j = content2.length; j > 0; i--, j >>= 8)
3821
3821
  header[i] = j & 255;
3822
- return this._createEncoderBuffer([header, content]);
3822
+ return this._createEncoderBuffer([header, content2]);
3823
3823
  };
3824
3824
  DERNode.prototype._encodeStr = function encodeStr(str2, tag) {
3825
3825
  if (tag === "bitstr") {
@@ -6702,8 +6702,8 @@ var require_helpers = __commonJS({
6702
6702
  function req(url, opts = {}) {
6703
6703
  const href = typeof url === "string" ? url : url.href;
6704
6704
  const req2 = (href.startsWith("https:") ? https : http).request(url, opts);
6705
- const promise = new Promise((resolve4, reject) => {
6706
- req2.once("response", resolve4).once("error", reject).end();
6705
+ const promise = new Promise((resolve5, reject) => {
6706
+ req2.once("response", resolve5).once("error", reject).end();
6707
6707
  });
6708
6708
  req2.then = promise.then.bind(promise);
6709
6709
  return req2;
@@ -6882,7 +6882,7 @@ var require_parse_proxy_response = __commonJS({
6882
6882
  var debug_1 = __importDefault(require_src());
6883
6883
  var debug = (0, debug_1.default)("https-proxy-agent:parse-proxy-response");
6884
6884
  function parseProxyResponse(socket) {
6885
- return new Promise((resolve4, reject) => {
6885
+ return new Promise((resolve5, reject) => {
6886
6886
  let buffersLength = 0;
6887
6887
  const buffers = [];
6888
6888
  function read() {
@@ -6948,7 +6948,7 @@ var require_parse_proxy_response = __commonJS({
6948
6948
  }
6949
6949
  debug("got proxy server response: %o %o", firstLine, headers);
6950
6950
  cleanup2();
6951
- resolve4({
6951
+ resolve5({
6952
6952
  connect: {
6953
6953
  statusCode,
6954
6954
  statusText,
@@ -7346,7 +7346,7 @@ var require_web_push_lib = __commonJS({
7346
7346
  } catch (err) {
7347
7347
  return Promise.reject(err);
7348
7348
  }
7349
- return new Promise(function(resolve4, reject) {
7349
+ return new Promise(function(resolve5, reject) {
7350
7350
  const httpsOptions = {};
7351
7351
  const urlParts = url.parse(requestDetails.endpoint);
7352
7352
  httpsOptions.hostname = urlParts.hostname;
@@ -7379,7 +7379,7 @@ var require_web_push_lib = __commonJS({
7379
7379
  requestDetails.endpoint
7380
7380
  ));
7381
7381
  } else {
7382
- resolve4({
7382
+ resolve5({
7383
7383
  statusCode: pushResponse.statusCode,
7384
7384
  body: responseText,
7385
7385
  headers: pushResponse.headers
@@ -9679,7 +9679,7 @@ var require_websocket = __commonJS({
9679
9679
  var http = __require("http");
9680
9680
  var net = __require("net");
9681
9681
  var tls = __require("tls");
9682
- var { randomBytes: randomBytes3, createHash: createHash5 } = __require("crypto");
9682
+ var { randomBytes: randomBytes4, createHash: createHash6 } = __require("crypto");
9683
9683
  var { Duplex, Readable } = __require("stream");
9684
9684
  var { URL: URL2 } = __require("url");
9685
9685
  var PerMessageDeflate2 = require_permessage_deflate();
@@ -10230,7 +10230,7 @@ var require_websocket = __commonJS({
10230
10230
  }
10231
10231
  }
10232
10232
  const defaultPort = isSecure ? 443 : 80;
10233
- const key = randomBytes3(16).toString("base64");
10233
+ const key = randomBytes4(16).toString("base64");
10234
10234
  const request = isSecure ? https.request : http.request;
10235
10235
  const protocolSet = /* @__PURE__ */ new Set();
10236
10236
  let perMessageDeflate;
@@ -10360,7 +10360,7 @@ var require_websocket = __commonJS({
10360
10360
  abortHandshake(websocket, socket, "Invalid Upgrade header");
10361
10361
  return;
10362
10362
  }
10363
- const digest = createHash5("sha1").update(key + GUID).digest("base64");
10363
+ const digest = createHash6("sha1").update(key + GUID).digest("base64");
10364
10364
  if (res.headers["sec-websocket-accept"] !== digest) {
10365
10365
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
10366
10366
  return;
@@ -10732,7 +10732,7 @@ var require_websocket_server = __commonJS({
10732
10732
  var EventEmitter = __require("events");
10733
10733
  var http = __require("http");
10734
10734
  var { Duplex } = __require("stream");
10735
- var { createHash: createHash5 } = __require("crypto");
10735
+ var { createHash: createHash6 } = __require("crypto");
10736
10736
  var extension2 = require_extension();
10737
10737
  var PerMessageDeflate2 = require_permessage_deflate();
10738
10738
  var subprotocol2 = require_subprotocol();
@@ -11039,7 +11039,7 @@ var require_websocket_server = __commonJS({
11039
11039
  );
11040
11040
  }
11041
11041
  if (this._state > RUNNING) return abortHandshake(socket, 503);
11042
- const digest = createHash5("sha1").update(key + GUID).digest("base64");
11042
+ const digest = createHash6("sha1").update(key + GUID).digest("base64");
11043
11043
  const headers = [
11044
11044
  "HTTP/1.1 101 Switching Protocols",
11045
11045
  "Upgrade: websocket",
@@ -11141,13 +11141,22 @@ var contactIdentity = (id) => /^[a-f0-9]{64}$/i.test(id) ? id.toUpperCase() : id
11141
11141
  function contactTarget(value) {
11142
11142
  return object(value) && closed(value, ["kind", "contactId"]) && value.kind === "contact" && contactId(value.contactId);
11143
11143
  }
11144
+ var STATUS_ID = /^[A-Za-z0-9_.:-]{1,512}$/;
11145
+ function statusTarget(value) {
11146
+ return object(value) && closed(value, ["kind", "authorCid", "statusId"]) && value.kind === "status" && typeof value.authorCid === "string" && /^[A-F0-9]{64}$/.test(value.authorCid) && typeof value.statusId === "string" && STATUS_ID.test(value.statusId);
11147
+ }
11148
+ var statusEvent = (value) => statusTarget(value.target) && typeof value.eventId === "string" && value.eventId.startsWith(`status:${value.target.statusId}:`) && /^[1-9][0-9]{0,15}$/.test(value.eventId.slice(`status:${value.target.statusId}:`.length));
11144
11149
  function notificationInput(value) {
11145
- if (!object(value) || !closed(value, ["eventId", "title", "body", "target", "anchor"]) || !text(value.eventId, 512) || !text(value.title, 160) || !text(value.body, 512) || !contactTarget(value.target)) return false;
11150
+ if (!object(value) || !closed(value, ["eventId", "title", "body", "target", "anchor", "delivery"]) || !text(value.eventId, 512) || !text(value.title, 160) || !text(value.body, 512)) return false;
11151
+ if (statusTarget(value.target))
11152
+ return statusEvent(value) && value.anchor === void 0 && (value.delivery === void 0 || value.delivery === "inbox" || value.delivery === "until-resolved");
11153
+ if (!contactTarget(value.target) || value.delivery !== void 0) return false;
11146
11154
  return value.anchor === void 0 || object(value.anchor) && closed(value.anchor, ["kind", "wireId"]) && value.anchor.kind === "messenger-message" && text(value.anchor.wireId, 1024) && !/[\x00-\x1f\x7f]/.test(value.anchor.wireId);
11147
11155
  }
11148
11156
  var cleanup = (value) => object(value) && closed(value, ["target"]) && contactTarget(value.target);
11157
+ var resolution = (value) => object(value) && closed(value, ["eventId"]) && typeof value.eventId === "string" && /^status:[A-Za-z0-9_.:-]{1,512}:[1-9][0-9]{0,15}$/.test(value.eventId);
11149
11158
  var has = (entry, key) => Object.hasOwn(entry, key);
11150
- var supported = (entry) => object(entry) && typeof entry.id === "string" && (has(entry, "operation") ? entry.operation === "delete-target" && cleanup(entry.value) : has(entry, "payload") ? notificationInput(entry.payload) : entry.targetVersion === 1);
11159
+ var supported = (entry) => object(entry) && typeof entry.id === "string" && (has(entry, "operation") ? entry.operation === "delete-target" && cleanup(entry.value) || entry.operation === "resolve" && resolution(entry.value) : has(entry, "payload") ? notificationInput(entry.payload) : entry.targetVersion === 1);
11151
11160
  var same = (id) => (entry) => supported(entry) && entry.id === id;
11152
11161
  function producerConfig(env = process.env) {
11153
11162
  const origin = env.OURS_NOTIFICATIONS_ORIGIN, token = env.OURS_NOTIFICATIONS_PRODUCER_TOKEN;
@@ -11219,6 +11228,26 @@ var NotificationOutbox = class {
11219
11228
  this.persist([...this.entries, { id, value, targetVersion: 1 }], cursor);
11220
11229
  return true;
11221
11230
  }
11231
+ /**
11232
+ * A status event, fully projected when its change was committed (no later projection, so a crash replays the
11233
+ * identical payload and the service's event dedupe applies). Returns false only at capacity.
11234
+ */
11235
+ enqueueEvent(payload) {
11236
+ if (!notificationInput(payload) || !statusTarget(payload.target)) throw new Error("Invalid status notification");
11237
+ if (this.entries.some(same(payload.eventId))) return true;
11238
+ if (this.entries.filter(supported).length >= 2e3) return false;
11239
+ this.persist([...this.entries, { id: payload.eventId, value: { status: true }, payload }]);
11240
+ return true;
11241
+ }
11242
+ /**
11243
+ * End a pending status notification (answered, closed or superseded). Queued after its send, so the send is
11244
+ * delivered first; never dropped by send capacity, and never cancels another queued job.
11245
+ */
11246
+ enqueueResolve(eventId) {
11247
+ if (!resolution({ eventId })) throw new Error("Invalid status event");
11248
+ const id = `resolve:${eventId}`;
11249
+ if (!this.entries.some(same(id))) this.persist([...this.entries, { id, value: { eventId }, operation: "resolve" }]);
11250
+ }
11222
11251
  retireTarget(target, matches) {
11223
11252
  if (!contactTarget(target)) throw new Error("Invalid notification target");
11224
11253
  const id = `delete-target:${contactIdentity(target.contactId)}`;
@@ -11266,16 +11295,17 @@ var NotificationOutbox = class {
11266
11295
  continue;
11267
11296
  }
11268
11297
  }
11269
- const value = entry.operation === "delete-target" ? entry.value : entry.payload ?? await this.project(entry.value, entry.id);
11298
+ const value = entry.operation ? entry.value : entry.payload ?? await this.project(entry.value, entry.id);
11270
11299
  if (!this.entries.some(same(entry.id))) continue;
11271
11300
  if (value === void 0) {
11272
11301
  this.persist(this.entries.filter((current) => !same(entry.id)(current)));
11273
11302
  continue;
11274
11303
  }
11275
- if (entry.operation ? !cleanup(value) : !notificationInput(value)) continue;
11304
+ if (entry.operation === "delete-target" ? !cleanup(value) : entry.operation === "resolve" ? !resolution(value) : !notificationInput(value)) continue;
11276
11305
  attempts++;
11277
11306
  if (!entry.operation && !entry.payload) this.persist(this.entries.map((e2) => same(entry.id)(e2) ? { ...e2, payload: value } : e2));
11278
- const response = await fetch(this.config.origin + (entry.operation === "delete-target" ? "/api/v1/delete-target" : "/api/v1/send"), {
11307
+ const route = entry.operation === "delete-target" ? "/api/v1/delete-target" : entry.operation === "resolve" ? "/api/v1/resolve" : "/api/v1/send";
11308
+ const response = await fetch(this.config.origin + route, {
11279
11309
  method: "POST",
11280
11310
  redirect: "error",
11281
11311
  signal: AbortSignal.timeout(1e4),
@@ -11283,7 +11313,7 @@ var NotificationOutbox = class {
11283
11313
  body: JSON.stringify(value)
11284
11314
  });
11285
11315
  await response.body?.cancel();
11286
- if (!response.ok) throw new Error("notification service rejected event");
11316
+ if (!response.ok && !(entry.operation === "resolve" && response.status === 404)) throw new Error("notification service rejected event");
11287
11317
  this.persist(this.entries.filter((e2) => !same(entry.id)(e2)));
11288
11318
  } catch {
11289
11319
  this.failed = true;
@@ -11301,7 +11331,7 @@ var NotificationOutbox = class {
11301
11331
 
11302
11332
  // src/notification-producer.ts
11303
11333
  init_define_MESSENGER_BUILD_INFO();
11304
- import { join } from "node:path";
11334
+ import { join as join2 } from "node:path";
11305
11335
 
11306
11336
  // src/push-delivery.ts
11307
11337
  init_define_MESSENGER_BUILD_INFO();
@@ -11476,8 +11506,8 @@ function isCoworkRoomContact(announced) {
11476
11506
  return v04 || namedRoomLabel(announced) !== null || currentRoomMetadata(announced) !== null || legacyRoomId(announced) !== null;
11477
11507
  }
11478
11508
  function contactMessagePreview(announcedContact, text2) {
11479
- const line = roomLineForContact(announcedContact, text2);
11480
- return line ? roomMessagePreview(line) : String(text2 ?? "");
11509
+ const line2 = roomLineForContact(announcedContact, text2);
11510
+ return line2 ? roomMessagePreview(line2) : String(text2 ?? "");
11481
11511
  }
11482
11512
  function systemLine(kind, label, text2, extra = {}) {
11483
11513
  return { variant: "system", kind, author: "", role: "", label, text: text2, ...extra };
@@ -11509,10 +11539,10 @@ function membershipFallback(membership) {
11509
11539
  const who = isNonEmptyString(membership.alias) ? membership.alias : "A member";
11510
11540
  return membership.action === "remove" ? `${who} left the room.` : "The room membership changed.";
11511
11541
  }
11512
- function roomMessagePreview(line) {
11513
- if (!line) return "";
11514
- const lead = line.variant === "chat" ? line.author : line.label;
11515
- const text2 = collapse(line.text);
11542
+ function roomMessagePreview(line2) {
11543
+ if (!line2) return "";
11544
+ const lead = line2.variant === "chat" ? line2.author : line2.label;
11545
+ const text2 = collapse(line2.text);
11516
11546
  if (!lead) return text2;
11517
11547
  return text2 ? `${lead} \xB7 ${text2}` : lead;
11518
11548
  }
@@ -11725,6 +11755,827 @@ var PushDeliveryQueue = class {
11725
11755
  }
11726
11756
  };
11727
11757
 
11758
+ // src/status-service.ts
11759
+ init_define_MESSENGER_BUILD_INFO();
11760
+
11761
+ // src/statuses.ts
11762
+ init_define_MESSENGER_BUILD_INFO();
11763
+ import { createHash, randomBytes } from "node:crypto";
11764
+ import { closeSync as closeSync2, fsyncSync as fsyncSync2, mkdirSync as mkdirSync2, openSync as openSync2, readdirSync, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
11765
+ import { join, resolve } from "node:path";
11766
+ var STATUS_TITLE_MAX = 120;
11767
+ var STATUS_BODY_MAX_BYTES = 64 * 1024;
11768
+ var STATUS_ATTACHMENTS_MAX = 10;
11769
+ var STATUS_OPTIONS_MIN = 2;
11770
+ var STATUS_OPTIONS_MAX = 12;
11771
+ var STATUS_CLOSE_REASON_MAX = 500;
11772
+ var STATUS_ANSWER_TEXT_MAX = 8e3;
11773
+ var PUSH_TITLE_MAX = 160;
11774
+ var PUSH_BODY_MAX = 200;
11775
+ var STATUS_KINDS = Object.freeze({
11776
+ update: { answerable: false, push: "<Agent>: <title>" },
11777
+ question: { answerable: true, push: "<Agent> asks: <title>" },
11778
+ alert: { answerable: false, push: "<Agent> needs attention: <title>" }
11779
+ });
11780
+ var StatusError = class extends Error {
11781
+ constructor(code, message) {
11782
+ super(message);
11783
+ this.code = code;
11784
+ }
11785
+ };
11786
+ var CID = /^[A-F0-9]{64}$/;
11787
+ var STATUS_ID2 = /^st_[a-z0-9]{8,64}$/;
11788
+ var REQUEST_KEY = /^[A-Za-z0-9._:-]{1,128}$/;
11789
+ var OPTION_ID = /^[A-Za-z0-9_-]{1,64}$/;
11790
+ var SUBMISSION_ID = /^[A-Za-z0-9_-]{8,128}$/;
11791
+ var PUBLISH_FIELDS = ["kind", "title", "body", "attachments", "interaction", "supersedes", "request_key"];
11792
+ var codePoints = (value) => [...value].length;
11793
+ var invalid = (message) => {
11794
+ throw new StatusError("invalid_request", message);
11795
+ };
11796
+ var plain = (value) => !!value && typeof value === "object" && !Array.isArray(value);
11797
+ function closedObject(value, allowed, what) {
11798
+ if (!plain(value)) invalid(`${what} must be an object`);
11799
+ const extra = Object.keys(value).filter((key) => !allowed.includes(key));
11800
+ if (extra.length) invalid(`${what} has unsupported field ${extra[0]}`);
11801
+ return value;
11802
+ }
11803
+ function line(value, what, max) {
11804
+ if (typeof value !== "string" || !value.trim()) invalid(`${what} must be non-empty text`);
11805
+ const text2 = value;
11806
+ if (/[\x00-\x1f\x7f]/.test(text2)) invalid(`${what} must be one line without control characters`);
11807
+ if (codePoints(text2) > max) throw new StatusError("limit_exceeded", `${what} exceeds the ${max}-character limit`);
11808
+ return text2;
11809
+ }
11810
+ function clip(text2, max) {
11811
+ if (text2.length <= max) return text2;
11812
+ let end = max - 1;
11813
+ if (end > 0 && /[\uD800-\uDBFF]/.test(text2[end - 1])) end--;
11814
+ return text2.slice(0, end) + "\u2026";
11815
+ }
11816
+ function canonicalCid(value) {
11817
+ const cid = String(value ?? "").toUpperCase();
11818
+ if (!CID.test(cid)) throw new StatusError("forbidden", "a status author needs an authenticated identity CID");
11819
+ return cid;
11820
+ }
11821
+ function validInteraction(value) {
11822
+ const item = closedObject(value, ["mode", "options", "allowOther", "placeholder"], "interaction");
11823
+ if (item.mode !== "text" && item.mode !== "single" && item.mode !== "multi") invalid("interaction.mode must be text, single or multi");
11824
+ const result = { mode: item.mode };
11825
+ if (item.placeholder !== void 0) result.placeholder = line(item.placeholder, "interaction.placeholder", 200);
11826
+ if (item.mode === "text") {
11827
+ if (item.options !== void 0 || item.allowOther !== void 0) invalid("a text question has no options");
11828
+ return result;
11829
+ }
11830
+ if (!Array.isArray(item.options) || item.options.length < STATUS_OPTIONS_MIN || item.options.length > STATUS_OPTIONS_MAX)
11831
+ invalid(`a choice question needs ${STATUS_OPTIONS_MIN}-${STATUS_OPTIONS_MAX} options`);
11832
+ const ids = /* @__PURE__ */ new Set();
11833
+ result.options = item.options.map((raw, index) => {
11834
+ const option2 = closedObject(raw, ["id", "label", "description", "recommended"], `interaction.options[${index}]`);
11835
+ if (typeof option2.id !== "string" || !OPTION_ID.test(option2.id)) invalid('option id must be 1-64 letters, digits, "_" or "-"');
11836
+ if (ids.has(option2.id)) invalid(`option id ${option2.id} is not unique`);
11837
+ ids.add(option2.id);
11838
+ if (option2.recommended !== void 0 && typeof option2.recommended !== "boolean") invalid("option recommended must be a boolean");
11839
+ return {
11840
+ id: option2.id,
11841
+ label: line(option2.label, "option label", 200),
11842
+ ...option2.description === void 0 ? {} : { description: line(option2.description, "option description", 500) },
11843
+ ...option2.recommended === void 0 ? {} : { recommended: option2.recommended }
11844
+ };
11845
+ });
11846
+ if (item.allowOther !== void 0) {
11847
+ if (typeof item.allowOther !== "boolean") invalid("interaction.allowOther must be a boolean");
11848
+ result.allowOther = item.allowOther;
11849
+ }
11850
+ return result;
11851
+ }
11852
+ function validAttachments(value) {
11853
+ if (value === void 0) return [];
11854
+ if (!Array.isArray(value)) return invalid("attachments must be a list");
11855
+ if (value.length > STATUS_ATTACHMENTS_MAX) throw new StatusError("limit_exceeded", `a status can have at most ${STATUS_ATTACHMENTS_MAX} attachments`);
11856
+ return value.map((raw, index) => {
11857
+ const item = closedObject(raw, ["id", "name", "media_type", "size", "sha256"], `attachments[${index}]`);
11858
+ if (typeof item.id !== "string" || !/^[A-Za-z0-9_.:-]{1,256}$/.test(item.id)) invalid("attachment id must be a delivered file ID");
11859
+ const name = line(item.name, "attachment name", 240);
11860
+ if (/[\\/]/.test(name) || name === "." || name === "..") invalid("attachment name must not contain slashes");
11861
+ const mediaType = line(item.media_type, "attachment media_type", 255);
11862
+ if (!Number.isSafeInteger(item.size) || item.size < 0) invalid("attachment size must be a non-negative integer");
11863
+ if (typeof item.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(item.sha256)) invalid("attachment sha256 must be 64 lowercase hex characters");
11864
+ return { id: item.id, name, media_type: mediaType, size: item.size, sha256: item.sha256 };
11865
+ });
11866
+ }
11867
+ function validatePublish(raw) {
11868
+ if (!plain(raw)) return invalid("publish arguments must be an object");
11869
+ for (const key of ["author", "author_cid", "authorCid", "task_id", "taskId", "mission", "source"])
11870
+ if (key in raw) invalid(`${key} cannot be set: the author is the authenticated sender and external statuses have no mission`);
11871
+ const input = closedObject(raw, PUBLISH_FIELDS, "publish arguments");
11872
+ if (typeof input.kind !== "string" || !Object.hasOwn(STATUS_KINDS, input.kind))
11873
+ invalid(`kind must be one of ${Object.keys(STATUS_KINDS).join(", ")}`);
11874
+ const kind = input.kind;
11875
+ const title = line(input.title, "title", STATUS_TITLE_MAX);
11876
+ if (typeof input.body !== "string") invalid("body must be Markdown text");
11877
+ if (Buffer.byteLength(input.body, "utf8") > STATUS_BODY_MAX_BYTES)
11878
+ throw new StatusError("limit_exceeded", "body exceeds the 64 KiB Markdown limit");
11879
+ const attachments = validAttachments(input.attachments);
11880
+ const answerable = STATUS_KINDS[kind].answerable;
11881
+ if (answerable && input.interaction === void 0) invalid(`a ${kind} needs an interaction`);
11882
+ if (!answerable && input.interaction !== void 0) invalid(`a ${kind} cannot have an interaction`);
11883
+ if (input.supersedes !== void 0 && (kind !== "question" || typeof input.supersedes !== "string" || !STATUS_ID2.test(input.supersedes)))
11884
+ invalid("only a question can supersede, and supersedes must be a status ID");
11885
+ if (input.request_key !== void 0 && (typeof input.request_key !== "string" || !REQUEST_KEY.test(input.request_key)))
11886
+ invalid('request_key must be 1-128 letters, digits, ".", "_", ":" or "-"');
11887
+ return {
11888
+ kind,
11889
+ title,
11890
+ body: input.body,
11891
+ attachments,
11892
+ ...input.interaction === void 0 ? {} : { interaction: validInteraction(input.interaction) },
11893
+ ...input.supersedes === void 0 ? {} : { supersedes: input.supersedes },
11894
+ ...input.request_key === void 0 ? {} : { request_key: input.request_key }
11895
+ };
11896
+ }
11897
+ function statusPush(status) {
11898
+ const agent = status.author.display_name?.trim() || `${status.author.identity_cid.slice(0, 8)}\u2026`;
11899
+ const template = STATUS_KINDS[status.kind]?.push ?? "<Agent>: <title>";
11900
+ const title = clip(template.replace("<Agent>", agent).replace("<title>", status.title), PUSH_TITLE_MAX);
11901
+ const first = status.body.split("\n").map((text2) => text2.replace(/^\s*(?:#{1,6}\s|>\s?|[-*+]\s|\d+\.\s)*/, "").trim()).find(Boolean);
11902
+ return { title, body: clip(first ?? "Open the feed", PUSH_BODY_MAX) };
11903
+ }
11904
+ var statusEventId = (status) => `status:${status.status_id}:${status.revision}`;
11905
+ var sendEvent = (status) => ({ op: "send", eventId: statusEventId(status), delivery: status.kind === "question" ? "until-resolved" : "inbox", ...statusPush(status) });
11906
+ var resolveEvents = (status) => status.kind === "question" && status.state === "active" && !status.answer ? [{ op: "resolve", eventId: statusEventId(status) }] : [];
11907
+ var seenResolves = (status, revision) => status.kind === "question" ? [] : Array.from({ length: Math.max(0, revision - (status.seen_notified ?? 0)) }, (_, index) => ({ op: "resolve", eventId: statusEventId({ status_id: status.status_id, revision: (status.seen_notified ?? 0) + index + 1 }) }));
11908
+ var withEvents = (status, events) => events.length ? { ...status, notification_events: [...status.notification_events ?? [], ...events] } : status;
11909
+ var content = (r) => JSON.stringify([r.kind, r.title, r.body, r.attachments, r.interaction ?? null, r.supersedes ?? null]);
11910
+ var AlreadyAnsweredError = class extends StatusError {
11911
+ constructor(status) {
11912
+ super("conflict", "already_answered: this question already has an accepted answer");
11913
+ this.status = status;
11914
+ }
11915
+ };
11916
+ function writeDurably(path2, text2) {
11917
+ const temp = `${path2}.${process.pid}.tmp`;
11918
+ const fd = openSync2(temp, "w", 384);
11919
+ try {
11920
+ writeFileSync2(fd, text2);
11921
+ fsyncSync2(fd);
11922
+ } finally {
11923
+ closeSync2(fd);
11924
+ }
11925
+ renameSync2(temp, path2);
11926
+ const dir = openSync2(join(path2, ".."), "r");
11927
+ try {
11928
+ fsyncSync2(dir);
11929
+ } finally {
11930
+ closeSync2(dir);
11931
+ }
11932
+ }
11933
+ var statusesDirFor = (stateDir, ownerCid) => resolve(stateDir, `statuses-${createHash("sha256").update(ownerCid.toUpperCase()).digest("hex").slice(0, 24)}`);
11934
+ var storeObservers = /* @__PURE__ */ new Map();
11935
+ function subscribeStatuses(stateDir, ownerCid, onCommitted, signal) {
11936
+ if (signal.aborted) return () => {
11937
+ };
11938
+ const key = statusesDirFor(stateDir, ownerCid), observers = storeObservers.get(key) ?? /* @__PURE__ */ new Set();
11939
+ storeObservers.set(key, observers);
11940
+ observers.add(onCommitted);
11941
+ const dispose = () => {
11942
+ observers.delete(onCommitted);
11943
+ if (!observers.size) storeObservers.delete(key);
11944
+ signal.removeEventListener("abort", dispose);
11945
+ };
11946
+ signal.addEventListener("abort", dispose, { once: true });
11947
+ return dispose;
11948
+ }
11949
+ var MessengerStatusStore = class {
11950
+ dir;
11951
+ ingestDir;
11952
+ listeners = /* @__PURE__ */ new Set();
11953
+ constructor(stateDir, ownerCid) {
11954
+ this.dir = statusesDirFor(stateDir, ownerCid);
11955
+ this.ingestDir = join(this.dir, ".ingest");
11956
+ mkdirSync2(this.ingestDir, { recursive: true, mode: 448 });
11957
+ }
11958
+ /** Called after every committed change (live resource views, notification flush). */
11959
+ onChange(listener) {
11960
+ this.listeners.add(listener);
11961
+ return () => this.listeners.delete(listener);
11962
+ }
11963
+ changed() {
11964
+ for (const listener of [...this.listeners, ...storeObservers.get(this.dir) ?? []]) {
11965
+ try {
11966
+ listener();
11967
+ } catch {
11968
+ }
11969
+ }
11970
+ }
11971
+ path(id) {
11972
+ return join(this.dir, `${id}.json`);
11973
+ }
11974
+ write(record) {
11975
+ writeDurably(this.path(record.status_id), JSON.stringify(record, null, 2) + "\n");
11976
+ }
11977
+ get(id) {
11978
+ if (!STATUS_ID2.test(id)) return void 0;
11979
+ try {
11980
+ const record = JSON.parse(readFileSync2(this.path(id), "utf8"));
11981
+ if (record?.version !== 1 || record.status_id !== id || record.source !== "messenger") throw new Error(`unsupported status record ${id}`);
11982
+ return record;
11983
+ } catch (error) {
11984
+ if (error.code === "ENOENT") return void 0;
11985
+ throw error;
11986
+ }
11987
+ }
11988
+ require(id) {
11989
+ const record = this.get(id);
11990
+ if (!record) throw new StatusError("not_found", "status not found");
11991
+ return record;
11992
+ }
11993
+ list() {
11994
+ return readdirSync(this.dir).filter((name) => name.endsWith(".json") && STATUS_ID2.test(name.slice(0, -5))).map((name) => this.get(name.slice(0, -5))).filter((record) => !!record);
11995
+ }
11996
+ ingestPath(wireId) {
11997
+ return join(this.ingestDir, `${createHash("sha256").update(wireId).digest("hex")}.json`);
11998
+ }
11999
+ /** The recorded outcome of an already ingested command message, so a re-delivered message is never applied twice. */
12000
+ ingested(wireId) {
12001
+ try {
12002
+ return JSON.parse(readFileSync2(this.ingestPath(wireId), "utf8"));
12003
+ } catch (error) {
12004
+ if (error.code === "ENOENT") return void 0;
12005
+ throw error;
12006
+ }
12007
+ }
12008
+ recordIngest(record) {
12009
+ writeDurably(this.ingestPath(record.wire_id), JSON.stringify(record) + "\n");
12010
+ }
12011
+ /**
12012
+ * Ingest one `ours.status.publish` command, idempotently by its wire ID: the status and the ingest record are both
12013
+ * durable before the result is returned (and so before any command_result is sent).
12014
+ */
12015
+ ingestPublish(author, args, wireId, now = /* @__PURE__ */ new Date(), refusal) {
12016
+ const done = this.ingested(wireId);
12017
+ if (done) return done.outcome;
12018
+ let outcome;
12019
+ try {
12020
+ if (refusal) throw refusal;
12021
+ outcome = { ok: true, status_id: this.publish(author, args, wireId, now).status.status_id };
12022
+ } catch (error) {
12023
+ if (!(error instanceof StatusError)) throw error;
12024
+ outcome = { ok: false, code: error.code, message: error.message };
12025
+ }
12026
+ this.recordIngest({ version: 1, wire_id: wireId, author_cid: canonicalCid(author.cid), command: "ours.status.publish", outcome });
12027
+ return outcome;
12028
+ }
12029
+ /** Ingest one `ours.status.close` command, idempotently by its wire ID. Only the author can close its status. */
12030
+ ingestClose(author, args, wireId, now = /* @__PURE__ */ new Date()) {
12031
+ const done = this.ingested(wireId);
12032
+ if (done) return done.outcome;
12033
+ let outcome;
12034
+ try {
12035
+ const input = closedObject(args, ["status_id", "reason"], "close arguments");
12036
+ if (typeof input.status_id !== "string") invalid("status_id is required");
12037
+ outcome = { ok: true, status_id: this.close(author.cid, input.status_id, input.reason, now).status_id };
12038
+ } catch (error) {
12039
+ if (!(error instanceof StatusError)) throw error;
12040
+ outcome = { ok: false, code: error.code, message: error.message };
12041
+ }
12042
+ this.recordIngest({ version: 1, wire_id: wireId, author_cid: canonicalCid(author.cid), command: "ours.status.close", outcome });
12043
+ return outcome;
12044
+ }
12045
+ publish(author, raw, requestWireId, now = /* @__PURE__ */ new Date()) {
12046
+ const input = validatePublish(raw);
12047
+ const cid = canonicalCid(author.cid);
12048
+ const at2 = now.toISOString();
12049
+ const id = input.request_key ? `st_m${createHash("sha256").update(`${cid}\0${input.request_key}`).digest("hex").slice(0, 32)}` : `st_w${createHash("sha256").update(`${cid}\0${requestWireId}`).digest("hex").slice(0, 32)}`;
12050
+ const name = author.name?.trim() ? author.name.trim().slice(0, 120) : void 0;
12051
+ const record = {
12052
+ version: 1,
12053
+ status_id: id,
12054
+ source: "messenger",
12055
+ kind: input.kind,
12056
+ author: { identity_cid: cid, ...name ? { display_name: name } : {} },
12057
+ revision: 1,
12058
+ title: input.title,
12059
+ body: input.body,
12060
+ attachments: input.attachments,
12061
+ ...input.interaction ? { interaction: input.interaction } : {},
12062
+ state: "active",
12063
+ ...input.supersedes ? { supersedes: input.supersedes } : {},
12064
+ ...input.request_key ? { request_key: input.request_key } : {},
12065
+ request_wire_id: requestWireId,
12066
+ created_at: at2,
12067
+ updated_at: at2
12068
+ };
12069
+ const existing = this.get(id);
12070
+ if (existing) {
12071
+ if (existing.author.identity_cid !== cid || content(existing) !== content(record))
12072
+ throw new StatusError("idempotency_conflict", "request_key was already used for a different status");
12073
+ const superseded2 = this.closeSuperseded(existing, at2);
12074
+ if (superseded2) this.changed();
12075
+ return { status: existing, replayed: true, ...superseded2 ? { superseded: superseded2 } : {} };
12076
+ }
12077
+ if (input.supersedes) {
12078
+ const older = this.get(input.supersedes);
12079
+ if (!older || older.author.identity_cid !== cid) throw new StatusError("not_found", "the superseded status does not exist for this author");
12080
+ if (older.kind !== "question") invalid("only a question can be superseded");
12081
+ }
12082
+ const published = withEvents(record, [sendEvent(record)]);
12083
+ this.write(published);
12084
+ const superseded = this.closeSuperseded(published, at2);
12085
+ this.changed();
12086
+ return { status: published, replayed: false, ...superseded ? { superseded } : {} };
12087
+ }
12088
+ /** Close the author's older question this one supersedes, if it is still open. Idempotent. */
12089
+ closeSuperseded(status, at2) {
12090
+ if (!status.supersedes) return void 0;
12091
+ const older = this.get(status.supersedes);
12092
+ if (!older || older.author.identity_cid !== status.author.identity_cid || older.kind !== "question" || older.state !== "active") return void 0;
12093
+ const superseded = withEvents({ ...older, state: "closed", closed: { reason: "superseded", at: at2, superseded_by: status.status_id }, updated_at: at2 }, resolveEvents(older));
12094
+ this.write(superseded);
12095
+ return superseded;
12096
+ }
12097
+ /** The author closes its own status; an unanswered open question's notification is resolved. Idempotent. */
12098
+ close(authorCid, statusId, reasonRaw, now = /* @__PURE__ */ new Date()) {
12099
+ const cid = canonicalCid(authorCid);
12100
+ const current = this.get(statusId);
12101
+ if (!current || current.author.identity_cid !== cid) throw new StatusError("not_found", "status not found for this author");
12102
+ const reason = reasonRaw === void 0 ? "closed by its agent" : line(reasonRaw, "reason", STATUS_CLOSE_REASON_MAX);
12103
+ if (current.state === "closed") return current;
12104
+ const at2 = now.toISOString();
12105
+ const closed2 = withEvents({ ...current, state: "closed", closed: { reason, at: at2 }, updated_at: at2 }, resolveEvents(current));
12106
+ this.write(closed2);
12107
+ this.changed();
12108
+ return closed2;
12109
+ }
12110
+ /**
12111
+ * The Owner's one accepted answer to an open question (first answer wins), committed with its pending delivery and
12112
+ * the resolve of its notification. A repeat of the same submission returns the stored answer unchanged.
12113
+ */
12114
+ answer(statusId, input, now = /* @__PURE__ */ new Date()) {
12115
+ if (!SUBMISSION_ID.test(String(input.submissionId ?? ""))) invalid('submissionId must be 8-128 letters, digits, "_" or "-"');
12116
+ const current = this.require(statusId);
12117
+ if (current.answer) {
12118
+ if (current.answer.submission_id === input.submissionId) return { status: current, replayed: true };
12119
+ throw new AlreadyAnsweredError(current);
12120
+ }
12121
+ if (current.kind !== "question" || !current.interaction) invalid("only a question can be answered");
12122
+ if (current.state !== "active") throw new StatusError("conflict", "this question is closed");
12123
+ if (input.expectedRevision !== current.revision) throw new StatusError("conflict", "stale_state: the question changed; reload it");
12124
+ const interaction = current.interaction;
12125
+ const text2 = input.text === void 0 ? void 0 : String(input.text);
12126
+ if (text2 !== void 0 && (!text2.trim() || codePoints(text2) > STATUS_ANSWER_TEXT_MAX)) invalid(`answer text must be 1-${STATUS_ANSWER_TEXT_MAX} characters`);
12127
+ let selection;
12128
+ if (interaction.mode === "text") {
12129
+ if (input.selection !== void 0) invalid("a text question takes text only");
12130
+ if (text2 === void 0) invalid("answer text is required");
12131
+ } else {
12132
+ selection = input.selection ?? [];
12133
+ if (!Array.isArray(selection) || new Set(selection).size !== selection.length) invalid("selection must be a list of distinct option IDs");
12134
+ const ids = new Set(interaction.options.map((option2) => option2.id));
12135
+ if (selection.some((id) => !ids.has(id))) invalid("selection contains an unknown option");
12136
+ if (interaction.mode === "single" && selection.length + (text2 === void 0 ? 0 : 1) !== 1) invalid("a single-choice question takes exactly one answer");
12137
+ if (interaction.mode === "multi" && selection.length === 0 && text2 === void 0) invalid("choose at least one option");
12138
+ if (text2 !== void 0 && !interaction.allowOther) invalid("this question does not accept other text");
12139
+ }
12140
+ const at2 = now.toISOString();
12141
+ const answered = withEvents({ ...current, updated_at: at2, answer: {
12142
+ submission_id: input.submissionId,
12143
+ ...selection?.length ? { selection } : {},
12144
+ ...text2 === void 0 ? {} : { text: text2 },
12145
+ answered_at: at2,
12146
+ surface: input.surface === "session" ? "session" : "feed",
12147
+ delivery: { state: "pending", command_id: `ans_${randomBytes(12).toString("hex")}`, at: at2 }
12148
+ } }, resolveEvents(current));
12149
+ this.write(answered);
12150
+ this.changed();
12151
+ return { status: answered, replayed: false };
12152
+ }
12153
+ /** Record the receipt-checked outcome of one delivery attempt, only for the attempt that is still pending. */
12154
+ settleDelivery(statusId, commandId, outcome) {
12155
+ const current = this.require(statusId);
12156
+ const delivery = current.answer?.delivery;
12157
+ if (!delivery || delivery.state !== "pending" || delivery.command_id !== commandId) return current;
12158
+ const settled = { ...current, updated_at: outcome.at, answer: { ...current.answer, delivery: outcome } };
12159
+ this.write(settled);
12160
+ this.changed();
12161
+ return settled;
12162
+ }
12163
+ /** The Owner's manual Try again after `not_delivered`: a new pending attempt. Never automatic. */
12164
+ retryDelivery(statusId, now = /* @__PURE__ */ new Date()) {
12165
+ const current = this.require(statusId);
12166
+ if (current.answer?.delivery.state !== "not_delivered") throw new StatusError("conflict", "only an undelivered answer can be sent again");
12167
+ const at2 = now.toISOString();
12168
+ const retried = {
12169
+ ...current,
12170
+ updated_at: at2,
12171
+ answer: { ...current.answer, delivery: { state: "pending", command_id: `ans_${randomBytes(12).toString("hex")}`, at: at2 } }
12172
+ };
12173
+ this.write(retried);
12174
+ this.changed();
12175
+ return retried;
12176
+ }
12177
+ /** The Owner has seen this revision (informational statuses and ended questions; an open question stays unseen). */
12178
+ markSeen(statusId, revision) {
12179
+ const current = this.require(statusId);
12180
+ const awaiting = current.kind === "question" && current.state === "active" && !current.answer;
12181
+ if (awaiting || revision !== current.revision || (current.seen_revision ?? 0) >= revision) return current;
12182
+ const seen = withEvents({ ...current, seen_revision: revision, seen_notified: revision }, seenResolves(current, revision));
12183
+ this.write(seen);
12184
+ this.changed();
12185
+ return seen;
12186
+ }
12187
+ /**
12188
+ * Statuses seen before seeing read their notification keep an unread row: resolve each once by its own event ID.
12189
+ * Idempotent; returns how many statuses it linked.
12190
+ */
12191
+ resolveSeenNotifications() {
12192
+ let linked = 0;
12193
+ for (const current of this.list()) {
12194
+ const seen = current.seen_revision ?? 0;
12195
+ if (current.kind === "question" || seen <= (current.seen_notified ?? 0)) continue;
12196
+ this.write(withEvents({ ...current, seen_notified: seen }, seenResolves(current, seen)));
12197
+ linked++;
12198
+ }
12199
+ if (linked) this.changed();
12200
+ return linked;
12201
+ }
12202
+ /** Remove handed-off notification events (after the outbox durably accepted them). */
12203
+ clearEvents(statusId, eventKeys) {
12204
+ const current = this.get(statusId);
12205
+ if (!current?.notification_events?.length) return;
12206
+ const remaining = current.notification_events.filter((event) => !eventKeys.has(`${event.op}:${event.eventId}`));
12207
+ if (remaining.length === current.notification_events.length) return;
12208
+ const next = { ...current };
12209
+ if (remaining.length) next.notification_events = remaining;
12210
+ else delete next.notification_events;
12211
+ this.write(next);
12212
+ }
12213
+ };
12214
+ var statusAwaitsOwner = (status) => status.kind === "question" && status.state === "active" && !status.answer;
12215
+ var statusSeen = (status) => !statusAwaitsOwner(status) && (status.seen_revision ?? 0) >= status.revision;
12216
+ var FEED_PAGE_MAX = 200;
12217
+ function feedScope(query) {
12218
+ const scope = query.scope ?? (query.agent === void 0 ? "global" : "agent");
12219
+ if (scope === "global" && query.agent === void 0) return { kind: "global" };
12220
+ if (scope === "agent" && typeof query.agent === "string") return { kind: "agent", identityCid: canonicalCid(query.agent) };
12221
+ throw new StatusError("invalid_request", "scope must be global, or agent with an agent CID");
12222
+ }
12223
+ function feedItem(status) {
12224
+ const delivery = status.answer?.delivery;
12225
+ return {
12226
+ source: "messenger",
12227
+ status_id: status.status_id,
12228
+ kind: status.kind,
12229
+ title: status.title,
12230
+ author: status.author,
12231
+ revision: status.revision,
12232
+ state: status.state,
12233
+ answered: !!status.answer,
12234
+ ...delivery ? { answer_delivery: { state: delivery.state, at: delivery.at, ...delivery.state === "not_delivered" ? { reason: delivery.reason } : {} } } : {},
12235
+ awaits_owner: statusAwaitsOwner(status),
12236
+ seen: statusSeen(status),
12237
+ request_wire_id: status.request_wire_id,
12238
+ created_at: status.created_at,
12239
+ updated_at: status.updated_at
12240
+ };
12241
+ }
12242
+ function publicStatus(status) {
12243
+ const { version: _version, request_key: _key, seen_revision: _seen, seen_notified: _notified, notification_events: _events, ...visible } = status;
12244
+ return { ...visible, seen: statusSeen(status), awaits_owner: statusAwaitsOwner(status) };
12245
+ }
12246
+ function listFeed(store, scope, options = {}) {
12247
+ const limit = options.limit ?? 100;
12248
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > FEED_PAGE_MAX) throw new StatusError("invalid_request", `limit must be 1-${FEED_PAGE_MAX}`);
12249
+ const scoped = store.list().filter((status) => scope.kind === "global" || status.author.identity_cid === scope.identityCid).map(feedItem).sort((a, b2) => a.created_at.localeCompare(b2.created_at) || a.status_id.localeCompare(b2.status_id));
12250
+ let from = 0;
12251
+ if (options.after !== void 0) {
12252
+ from = scoped.findIndex((item) => item.status_id === options.after) + 1;
12253
+ if (!from) throw new StatusError("invalid_request", "after must be a status ID in this scope");
12254
+ }
12255
+ const listed = scoped.map((item, position) => ({ item, position })).filter(({ item }) => !options.eligible || !item.seen);
12256
+ const all = listed.map(({ item }) => item);
12257
+ const start2 = listed.findIndex(({ position }) => position >= from);
12258
+ const page = start2 < 0 ? [] : all.slice(start2, start2 + limit);
12259
+ const unseen = all.filter((item) => !item.seen);
12260
+ return {
12261
+ items: page,
12262
+ next_after: start2 >= 0 && start2 + page.length < all.length ? page.at(-1).status_id : null,
12263
+ total: all.length,
12264
+ unseen: unseen.length,
12265
+ open_questions: all.filter((item) => item.awaits_owner).map((item) => item.status_id),
12266
+ opens_at: unseen[0]?.status_id ?? all.at(-1)?.status_id ?? null,
12267
+ caught_up: unseen.length === 0,
12268
+ scope_version: createHash("sha256").update(JSON.stringify(all)).digest("hex").slice(0, 32),
12269
+ ...options.eligible ? { eligible: true } : {}
12270
+ };
12271
+ }
12272
+
12273
+ // src/status-service.ts
12274
+ var ATTACHMENT_KEYS = ["id", "name", "media_type", "size", "sha256"];
12275
+ var PUBLISH_COMMAND = "ours.status.publish";
12276
+ var CLOSE_COMMAND = "ours.status.close";
12277
+ var ANSWER_COMMAND = "ours.status.answer";
12278
+ var OWN_COMMANDS = /* @__PURE__ */ new Set([PUBLISH_COMMAND, CLOSE_COMMAND]);
12279
+ var option = { type: "object", additionalProperties: false, required: ["id", "label"], properties: {
12280
+ id: { type: "string" },
12281
+ label: { type: "string" },
12282
+ description: { type: "string" },
12283
+ recommended: { type: "boolean" }
12284
+ } };
12285
+ var STATUS_COMMAND_DEFINITIONS = Object.freeze([
12286
+ {
12287
+ name: PUBLISH_COMMAND,
12288
+ description: "Publish a status (update, question or alert) to the Owner's feed. The author is you, the sender. The result is {status_id} or {error:{code,message}}. A question needs an interaction; request_key makes a retried publish return the first result.",
12289
+ input_schema: { type: "object", additionalProperties: false, required: ["kind", "title", "body"], properties: {
12290
+ kind: { type: "string", enum: ["update", "question", "alert"] },
12291
+ title: { type: "string" },
12292
+ body: { type: "string" },
12293
+ attachments: { type: "array", maxItems: STATUS_ATTACHMENTS_MAX, items: { type: "object", additionalProperties: false, required: ["id"], properties: {
12294
+ id: { type: "string", description: "The wire_id of a file you already sent to this Owner" },
12295
+ name: { type: "string" },
12296
+ media_type: { type: "string" },
12297
+ size: { type: "integer" },
12298
+ sha256: { type: "string" }
12299
+ } } },
12300
+ interaction: { type: "object", additionalProperties: false, required: ["mode"], properties: {
12301
+ mode: { type: "string", enum: ["text", "single", "multi"] },
12302
+ options: { type: "array", items: option },
12303
+ allowOther: { type: "boolean" },
12304
+ placeholder: { type: "string" }
12305
+ } },
12306
+ supersedes: { type: "string" },
12307
+ request_key: { type: "string" }
12308
+ } }
12309
+ },
12310
+ {
12311
+ name: CLOSE_COMMAND,
12312
+ description: "Close one of your own statuses (a question you no longer need answered). Result {status_id} or {error}.",
12313
+ input_schema: { type: "object", additionalProperties: false, required: ["status_id"], properties: {
12314
+ status_id: { type: "string" },
12315
+ reason: { type: "string" }
12316
+ } }
12317
+ }
12318
+ ]);
12319
+ var outcomeJson = (outcome) => outcome.ok ? { status_id: outcome.status_id } : { error: { code: outcome.code, message: outcome.message } };
12320
+ var wireIdOf = (value) => {
12321
+ const id = value && typeof value === "object" ? value.wireId ?? value.wire_id : void 0;
12322
+ return typeof id === "string" && id ? id : void 0;
12323
+ };
12324
+ var unsupportedPeer = (error) => /unsupported_peer/.test(String(error?.message ?? error));
12325
+ function isStatusCommandMessage(message) {
12326
+ if (message?.message_kind !== "command" || typeof message.body !== "string") return false;
12327
+ try {
12328
+ return OWN_COMMANDS.has(JSON.parse(message.body).command ?? "");
12329
+ } catch {
12330
+ return false;
12331
+ }
12332
+ }
12333
+ function answerText(status) {
12334
+ const answer = status.answer;
12335
+ const labels = (answer.selection ?? []).map((id) => status.interaction?.options?.find((option2) => option2.id === id)?.label ?? id);
12336
+ const parts = [...labels, ...answer.text === void 0 ? [] : [answer.text]];
12337
+ return `Answer to your question "${status.title}" (${status.status_id}):
12338
+ ${parts.join("\n")}`;
12339
+ }
12340
+ var StatusService = class {
12341
+ constructor(store, client, outbox, warn = () => {
12342
+ }) {
12343
+ this.store = store;
12344
+ this.client = client;
12345
+ this.outbox = outbox;
12346
+ this.warn = warn;
12347
+ store.onChange(() => this.flushNotifications());
12348
+ }
12349
+ ingesting;
12350
+ again = false;
12351
+ delivering = /* @__PURE__ */ new Map();
12352
+ /**
12353
+ * Advertise the status commands, settle attempts a restart interrupted, flush pending push work and ingest.
12354
+ * An attempt left pending by a crash may or may not have reached the agent: it becomes `not_delivered` with that
12355
+ * reason, and only the Owner's Try again sends it again.
12356
+ */
12357
+ async start(now = /* @__PURE__ */ new Date()) {
12358
+ await this.advertise();
12359
+ for (const status of this.store.list()) {
12360
+ const delivery = status.answer?.delivery;
12361
+ if (delivery?.state === "pending")
12362
+ this.store.settleDelivery(status.status_id, delivery.command_id, {
12363
+ state: "not_delivered",
12364
+ command_id: delivery.command_id,
12365
+ at: now.toISOString(),
12366
+ reason: "the server restarted before the delivery result was known; use Try again if the agent did not receive it"
12367
+ });
12368
+ }
12369
+ try {
12370
+ this.store.resolveSeenNotifications();
12371
+ } catch (error) {
12372
+ this.warn(`Seen status notifications not linked yet: ${error.message}`);
12373
+ }
12374
+ this.flushNotifications();
12375
+ await this.ingest();
12376
+ }
12377
+ /** Merge the status commands into the identity's advertised catalog. */
12378
+ async advertise() {
12379
+ const current = await this.client.listSelfCommands();
12380
+ const foreign = current.filter((command) => !OWN_COMMANDS.has(command.name));
12381
+ const refuse = () => {
12382
+ throw new Error("handled by another process");
12383
+ };
12384
+ const commands = [
12385
+ ...foreign.map((command) => ({ ...command, handler: refuse })),
12386
+ { ...STATUS_COMMAND_DEFINITIONS[0], handler: async (args, ctx) => outcomeJson(await this.ingestPublish({ cid: ctx.sender_cid, name: ctx.sender_name }, args, ctx.request_wire_id)) },
12387
+ { ...STATUS_COMMAND_DEFINITIONS[1], handler: (args, ctx) => outcomeJson(this.store.ingestClose({ cid: ctx.sender_cid }, args, ctx.request_wire_id)) }
12388
+ ];
12389
+ await this.client.registerCommands(commands);
12390
+ }
12391
+ /**
12392
+ * A publish whose attachments name files by wire ID. Each must be a file this Messenger RECEIVED from the same
12393
+ * author; its metadata comes from the file history, and any metadata the agent supplied must match it. A status can
12394
+ * therefore never present another contact's file, or the Owner's own, as the author's. An already ingested command
12395
+ * keeps its recorded outcome: a refused publish stays refused, and the agent sends a new command after the file.
12396
+ */
12397
+ async ingestPublish(author, args, wireId) {
12398
+ if (this.store.ingested(wireId)) return this.store.ingestPublish(author, args, wireId);
12399
+ let resolved = args, refusal;
12400
+ try {
12401
+ resolved = await this.canonicalAttachments(author.cid, args);
12402
+ } catch (error) {
12403
+ if (!(error instanceof StatusError)) throw error;
12404
+ refusal = error;
12405
+ }
12406
+ return this.store.ingestPublish(author, resolved, wireId, /* @__PURE__ */ new Date(), refusal);
12407
+ }
12408
+ async canonicalAttachments(authorCid, args) {
12409
+ if (!args || typeof args !== "object" || Array.isArray(args)) return args;
12410
+ const raw = args.attachments;
12411
+ if (!Array.isArray(raw) || raw.length === 0 || raw.length > STATUS_ATTACHMENTS_MAX) return args;
12412
+ const attachments = [];
12413
+ for (const [index, item] of raw.entries()) {
12414
+ const given = item && typeof item === "object" && !Array.isArray(item) ? item : void 0;
12415
+ if (typeof given?.id !== "string") return args;
12416
+ const unknown = Object.keys(given).find((key) => !ATTACHMENT_KEYS.includes(key));
12417
+ if (unknown !== void 0)
12418
+ throw new StatusError("attachment_invalid", `attachments[${index}].${unknown} is not a known attachment field`);
12419
+ const file = this.client.getFileInfo ? await this.client.getFileInfo({ wire_id: given.id }) : null;
12420
+ if (!file)
12421
+ throw new StatusError("attachment_not_received", `attachments[${index}] is not a file received from you; send the file first, then publish`);
12422
+ if (file.direction !== "in" || canonicalCid(file.from.id) !== canonicalCid(authorCid))
12423
+ throw new StatusError("attachment_invalid", `attachments[${index}] was not sent by you`);
12424
+ const canonical3 = { id: file.wire_id, name: file.filename, media_type: file.mime, size: file.size, sha256: file.sha256 };
12425
+ for (const key of ["name", "media_type", "size", "sha256"])
12426
+ if (given[key] !== void 0 && given[key] !== canonical3[key])
12427
+ throw new StatusError("attachment_invalid", `attachments[${index}].${key} does not match the file you sent`);
12428
+ attachments.push(canonical3);
12429
+ }
12430
+ return { ...args, attachments };
12431
+ }
12432
+ /** Ingest unread status commands; overlapping requests coalesce into one follow-up pass. */
12433
+ ingest() {
12434
+ if (this.ingesting) {
12435
+ this.again = true;
12436
+ return this.ingesting;
12437
+ }
12438
+ return this.ingesting = this.ingestOnce().finally(() => {
12439
+ this.ingesting = void 0;
12440
+ if (this.again) {
12441
+ this.again = false;
12442
+ void this.ingest();
12443
+ }
12444
+ });
12445
+ }
12446
+ async ingestOnce() {
12447
+ const rows = await this.client.listIncomingMessages();
12448
+ const ours = [];
12449
+ for (const row of rows) {
12450
+ if (row.message_kind !== "command") continue;
12451
+ const message = await this.client.getHistoryItem({ wire_id: row.wire_id });
12452
+ if (!message || message.direction !== "in" || !isStatusCommandMessage(message)) continue;
12453
+ const { command, arguments: args } = JSON.parse(message.body);
12454
+ const author = { cid: message.from.id, name: message.from.name };
12455
+ if (command === PUBLISH_COMMAND) await this.ingestPublish(author, args, message.wire_id);
12456
+ else this.store.ingestClose(author, args, message.wire_id);
12457
+ ours.push(message.wire_id);
12458
+ }
12459
+ if (ours.length) await this.client.getMessages({ wire_ids: ours });
12460
+ }
12461
+ /**
12462
+ * Hand committed push work to the durable outbox, then clear it from the status (replay-safe by event ID). Oldest
12463
+ * status first; a status's events stay in order (a resolve never overtakes its send). Work that is refused (outbox
12464
+ * full) or fails (storage) stays on the status and is handed off by the next call — every change, and the server's
12465
+ * existing periodic recovery tick (`recover`), so it progresses without unrelated status traffic or a restart.
12466
+ */
12467
+ flushNotifications() {
12468
+ if (!this.outbox) return;
12469
+ let statuses;
12470
+ try {
12471
+ statuses = this.store.list().sort((a, b2) => a.created_at.localeCompare(b2.created_at) || a.status_id.localeCompare(b2.status_id));
12472
+ } catch (error) {
12473
+ this.warn(`Status notifications pending: ${error.message}`);
12474
+ return;
12475
+ }
12476
+ let full = false;
12477
+ for (const status of statuses) {
12478
+ const events = status.notification_events ?? [];
12479
+ if (!events.length) continue;
12480
+ const handed = /* @__PURE__ */ new Set();
12481
+ try {
12482
+ for (const event of events) {
12483
+ if (event.op === "send") {
12484
+ const accepted = this.outbox.enqueueEvent({
12485
+ eventId: event.eventId,
12486
+ title: event.title,
12487
+ body: event.body,
12488
+ target: { kind: "status", authorCid: status.author.identity_cid, statusId: status.status_id },
12489
+ delivery: event.delivery
12490
+ });
12491
+ if (!accepted) {
12492
+ full = true;
12493
+ break;
12494
+ }
12495
+ } else this.outbox.enqueueResolve(event.eventId);
12496
+ handed.add(`${event.op}:${event.eventId}`);
12497
+ }
12498
+ this.store.clearEvents(status.status_id, handed);
12499
+ } catch (error) {
12500
+ this.warn(`Status notifications pending for ${status.status_id}: ${error.message}`);
12501
+ }
12502
+ if (full) {
12503
+ this.warn("Notification outbox is full; status pushes stay pending");
12504
+ break;
12505
+ }
12506
+ }
12507
+ this.outbox.prompt();
12508
+ }
12509
+ /** The periodic recovery tick: hand off retained push work, then ingest any status command a prompt missed. */
12510
+ recover() {
12511
+ this.flushNotifications();
12512
+ return this.ingest();
12513
+ }
12514
+ /** The Owner answers (feed or chat): first answer wins; delivery is attempted once, receipt-checked. */
12515
+ async answer(statusId, input) {
12516
+ const result = this.store.answer(statusId, input);
12517
+ if (result.replayed) return result;
12518
+ return { status: await this.deliver(statusId), replayed: false };
12519
+ }
12520
+ /** The Owner's manual Try again after `not_delivered`. */
12521
+ async retry(statusId) {
12522
+ this.store.retryDelivery(statusId);
12523
+ return this.deliver(statusId);
12524
+ }
12525
+ /** One delivery attempt for the pending answer: the typed command, or the readable text when unsupported. */
12526
+ deliver(statusId) {
12527
+ const running = this.delivering.get(statusId);
12528
+ if (running) return running;
12529
+ const attempt = this.deliverOnce(statusId).finally(() => this.delivering.delete(statusId));
12530
+ this.delivering.set(statusId, attempt);
12531
+ return attempt;
12532
+ }
12533
+ async deliverOnce(statusId) {
12534
+ const status = this.store.get(statusId);
12535
+ const delivery = status?.answer?.delivery;
12536
+ if (!status || delivery?.state !== "pending") return status;
12537
+ const { command_id: commandId } = delivery;
12538
+ const at2 = () => (/* @__PURE__ */ new Date()).toISOString();
12539
+ const answer = status.answer;
12540
+ try {
12541
+ const sent = await this.client.sendCommand({ contact: status.author.identity_cid, command: ANSWER_COMMAND, arguments: {
12542
+ status_id: status.status_id,
12543
+ submission_id: answer.submission_id,
12544
+ question: status.title,
12545
+ ...answer.selection ? { selection: answer.selection } : {},
12546
+ ...answer.text === void 0 ? {} : { text: answer.text }
12547
+ } });
12548
+ const wireId = wireIdOf(sent);
12549
+ return this.store.settleDelivery(statusId, commandId, wireId ? { state: "delivered", command_id: commandId, at: at2(), wire_id: wireId } : { state: "not_delivered", command_id: commandId, at: at2(), reason: "the answer command was not accepted" });
12550
+ } catch (error) {
12551
+ if (!unsupportedPeer(error)) {
12552
+ return this.store.settleDelivery(statusId, commandId, {
12553
+ state: "not_delivered",
12554
+ command_id: commandId,
12555
+ at: at2(),
12556
+ reason: `the answer could not be sent: ${String(error?.message ?? error).slice(0, 300)}`
12557
+ });
12558
+ }
12559
+ }
12560
+ try {
12561
+ const sent = await this.client.sendMessage({
12562
+ contact: status.author.identity_cid,
12563
+ text: answerText(status),
12564
+ reply_to_wire_id: status.request_wire_id
12565
+ });
12566
+ const wireId = wireIdOf(sent);
12567
+ return this.store.settleDelivery(statusId, commandId, wireId ? { state: "delivered_as_text", command_id: commandId, at: at2(), wire_id: wireId } : { state: "not_delivered", command_id: commandId, at: at2(), reason: "the text reply was not accepted" });
12568
+ } catch (error) {
12569
+ return this.store.settleDelivery(statusId, commandId, {
12570
+ state: "not_delivered",
12571
+ command_id: commandId,
12572
+ at: at2(),
12573
+ reason: `the text reply could not be sent: ${String(error?.message ?? error).slice(0, 300)}`
12574
+ });
12575
+ }
12576
+ }
12577
+ };
12578
+
11728
12579
  // src/notification-producer.ts
11729
12580
  var MessengerNotificationProducer = class {
11730
12581
  constructor(stateDir, config, identityCid, client, warn) {
@@ -11735,9 +12586,10 @@ var MessengerNotificationProducer = class {
11735
12586
  if (!Array.isArray(view.contacts) || !Array.isArray(view.pending) || [...view.contacts, ...view.pending].some((contact) => typeof contact?.container_id !== "string")) throw Error("Contact inventory unavailable");
11736
12587
  return [...view.contacts, ...view.pending].some((contact) => contactIdentity(contact.container_id) === contactIdentity(cid));
11737
12588
  };
11738
- this.outbox = new NotificationOutbox(join(stateDir, "notification-outbox.json"), config, async (value, eventId) => {
12589
+ this.outbox = new NotificationOutbox(join2(stateDir, "notification-outbox.json"), config, async (value, eventId) => {
11739
12590
  const record = value;
11740
12591
  if (await knownContact(record.sender_id) === false) return;
12592
+ if (record.event === "message_received" && client.getHistoryItem && isStatusCommandMessage(await client.getHistoryItem({ wire_id: record.wire_id }))) return;
11741
12593
  const event = await projectPushEvent(client, {
11742
12594
  contactId: record.sender_id,
11743
12595
  wireId: record.wire_id,
@@ -11778,7 +12630,7 @@ var MessengerNotificationProducer = class {
11778
12630
  const record = value;
11779
12631
  if (typeof record?.sender_id === "string" && contactIdentity(record.sender_id) === contactIdentity(cid)) return true;
11780
12632
  if (!payload) return false;
11781
- return contactIdentity(payload.target.contactId) === contactIdentity(cid);
12633
+ return payload.target.kind === "contact" && contactIdentity(payload.target.contactId) === contactIdentity(cid);
11782
12634
  });
11783
12635
  void this.outbox.drain();
11784
12636
  }
@@ -11791,7 +12643,7 @@ var MessengerNotificationProducer = class {
11791
12643
  import { existsSync as existsSync3 } from "node:fs";
11792
12644
  import { readFile, realpath, stat } from "node:fs/promises";
11793
12645
  import { createServer } from "node:http";
11794
- import { dirname as dirname5, extname, isAbsolute as isAbsolute2, relative, resolve as resolve3, sep } from "node:path";
12646
+ import { dirname as dirname5, extname, isAbsolute as isAbsolute2, relative, resolve as resolve4, sep } from "node:path";
11795
12647
  import { fileURLToPath } from "node:url";
11796
12648
  import { Worker } from "node:worker_threads";
11797
12649
 
@@ -11804,12 +12656,12 @@ import { randomUUID as randomUUID2 } from "node:crypto";
11804
12656
 
11805
12657
  // src/workspace-profile.ts
11806
12658
  init_define_MESSENGER_BUILD_INFO();
11807
- import { existsSync as existsSync2, lstatSync, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
11808
- import { join as join2, resolve } from "node:path";
12659
+ import { existsSync as existsSync2, lstatSync, mkdirSync as mkdirSync3, readFileSync as readFileSync3, renameSync as renameSync3, writeFileSync as writeFileSync3 } from "node:fs";
12660
+ import { join as join3, resolve as resolve2 } from "node:path";
11809
12661
  import { randomUUID } from "node:crypto";
11810
12662
  var profileObservers = /* @__PURE__ */ new Map();
11811
12663
  function profileKey(dir, cid) {
11812
- return resolve(path(dir, cid));
12664
+ return resolve2(path(dir, cid));
11813
12665
  }
11814
12666
  function subscribeHumanProfile(dir, cid, onCommitted, signal) {
11815
12667
  if (signal.aborted) return () => {
@@ -11843,7 +12695,7 @@ function profileName(value) {
11843
12695
  }
11844
12696
  function path(dir, cid) {
11845
12697
  if (!/^[a-f0-9]{64}$/i.test(cid)) throw Error("Invalid identity");
11846
- return join2(dir, "human-" + cid.toLowerCase() + ".json");
12698
+ return join3(dir, "human-" + cid.toLowerCase() + ".json");
11847
12699
  }
11848
12700
  function readHumanProfile(dir, cid) {
11849
12701
  if (!/^[a-f0-9]{64}$/i.test(cid)) return;
@@ -11851,12 +12703,12 @@ function readHumanProfile(dir, cid) {
11851
12703
  if (!existsSync2(file)) return;
11852
12704
  const stat2 = lstatSync(file);
11853
12705
  if (!stat2.isFile() || stat2.isSymbolicLink() || stat2.nlink !== 1 || stat2.uid !== process.getuid?.() || (stat2.mode & 63) !== 0) throw Error("Private profile path required");
11854
- const row = JSON.parse(readFileSync2(file, "utf8"));
12706
+ const row = JSON.parse(readFileSync3(file, "utf8"));
11855
12707
  return workspaceProfile(row);
11856
12708
  }
11857
12709
  function writeHumanProfile(dir, cid, value) {
11858
12710
  const row = workspaceProfile(value);
11859
- mkdirSync2(dir, { recursive: true, mode: 448 });
12711
+ mkdirSync3(dir, { recursive: true, mode: 448 });
11860
12712
  const directory = lstatSync(dir);
11861
12713
  if (!directory.isDirectory() || directory.isSymbolicLink() || directory.uid !== process.getuid?.() || (directory.mode & 63) !== 0) throw Error("Private profile directory required");
11862
12714
  const file = path(dir, cid);
@@ -11865,15 +12717,15 @@ function writeHumanProfile(dir, cid, value) {
11865
12717
  if (!stat2.isFile() || stat2.isSymbolicLink() || stat2.nlink !== 1 || stat2.uid !== process.getuid?.() || (stat2.mode & 63) !== 0) throw Error("Private profile path required");
11866
12718
  }
11867
12719
  const temporary = file + "." + randomUUID();
11868
- writeFileSync2(temporary, JSON.stringify(row) + "\n", { mode: 384, flag: "wx" });
11869
- renameSync2(temporary, file);
12720
+ writeFileSync3(temporary, JSON.stringify(row) + "\n", { mode: 384, flag: "wx" });
12721
+ renameSync3(temporary, file);
11870
12722
  publishHumanProfile(dir, cid);
11871
12723
  return row;
11872
12724
  }
11873
12725
 
11874
12726
  // src/watch.ts
11875
12727
  init_define_MESSENGER_BUILD_INFO();
11876
- import { createHash } from "node:crypto";
12728
+ import { createHash as createHash2 } from "node:crypto";
11877
12729
 
11878
12730
  // src/events.ts
11879
12731
  init_define_MESSENGER_BUILD_INFO();
@@ -11937,8 +12789,8 @@ var MessengerEventBus = class {
11937
12789
  }
11938
12790
  if (sub.closed) return Promise.resolve(null);
11939
12791
  if (sub.waiting) throw new Error("only one pending next() is allowed per event subscriber");
11940
- return new Promise((resolve4) => {
11941
- sub.waiting = resolve4;
12792
+ return new Promise((resolve5) => {
12793
+ sub.waiting = resolve5;
11942
12794
  });
11943
12795
  },
11944
12796
  close: () => this.#close(sub)
@@ -11948,9 +12800,9 @@ var MessengerEventBus = class {
11948
12800
  for (const sub of this.#subscribers) {
11949
12801
  if (sub.closed) continue;
11950
12802
  if (sub.waiting) {
11951
- const resolve4 = sub.waiting;
12803
+ const resolve5 = sub.waiting;
11952
12804
  sub.waiting = null;
11953
- resolve4(event);
12805
+ resolve5(event);
11954
12806
  continue;
11955
12807
  }
11956
12808
  if (sub.overflowed) continue;
@@ -11970,9 +12822,9 @@ var MessengerEventBus = class {
11970
12822
  sub.closed = true;
11971
12823
  sub.queue.length = 0;
11972
12824
  this.#subscribers.delete(sub);
11973
- const resolve4 = sub.waiting;
12825
+ const resolve5 = sub.waiting;
11974
12826
  sub.waiting = null;
11975
- resolve4?.(null);
12827
+ resolve5?.(null);
11976
12828
  }
11977
12829
  };
11978
12830
  function toSse(event, identity) {
@@ -11988,7 +12840,7 @@ function toSse(event, identity) {
11988
12840
 
11989
12841
  // src/watch.ts
11990
12842
  function pageDigest(events) {
11991
- return createHash("sha256").update(JSON.stringify(events)).digest("base64url");
12843
+ return createHash2("sha256").update(JSON.stringify(events)).digest("base64url");
11992
12844
  }
11993
12845
  function applyNotificationPage(page, push, delivery, events, stats, log2) {
11994
12846
  if (!Number.isSafeInteger(page.cursor) || page.cursor < 0 || !Array.isArray(page.events)) {
@@ -12034,12 +12886,12 @@ function applyNotificationPage(page, push, delivery, events, stats, log2) {
12034
12886
  }
12035
12887
  function abortableWait(ms, signal) {
12036
12888
  if (signal.aborted) return Promise.resolve();
12037
- return new Promise((resolve4) => {
12889
+ return new Promise((resolve5) => {
12038
12890
  const timer = setTimeout(done, ms);
12039
12891
  function done() {
12040
12892
  clearTimeout(timer);
12041
12893
  signal.removeEventListener("abort", done);
12042
- resolve4();
12894
+ resolve5();
12043
12895
  }
12044
12896
  signal.addEventListener("abort", done, { once: true });
12045
12897
  });
@@ -12098,8 +12950,8 @@ function startResourceObserver(client, identity, callbacks) {
12098
12950
  let readyResolve;
12099
12951
  let readyReject;
12100
12952
  let readySettled = false;
12101
- const ready = new Promise((resolve4, reject) => {
12102
- readyResolve = resolve4;
12953
+ const ready = new Promise((resolve5, reject) => {
12954
+ readyResolve = resolve5;
12103
12955
  readyReject = reject;
12104
12956
  });
12105
12957
  void ready.catch(() => {
@@ -12171,7 +13023,7 @@ init_define_MESSENGER_BUILD_INFO();
12171
13023
 
12172
13024
  // src/typed-commands.ts
12173
13025
  init_define_MESSENGER_BUILD_INFO();
12174
- import { createHash as createHash2 } from "node:crypto";
13026
+ import { createHash as createHash3 } from "node:crypto";
12175
13027
  var MAX_COMMANDS = 64;
12176
13028
  var MAX_COMMAND_NAME_LENGTH = 128;
12177
13029
  var MAX_COMMAND_DESCRIPTION_LENGTH = 2048;
@@ -12231,7 +13083,7 @@ function projectCatalog(recipientCid, commands) {
12231
13083
  input_schema: command.input_schema
12232
13084
  };
12233
13085
  });
12234
- const fingerprint2 = createHash2("sha256").update(canonical({
13086
+ const fingerprint2 = createHash3("sha256").update(canonical({
12235
13087
  recipient_cid: recipientCid,
12236
13088
  commands: projected
12237
13089
  })).digest("base64url");
@@ -12375,23 +13227,23 @@ data: ${bytes.toString("utf8")}
12375
13227
  yield { event: "resource-chunk", data: { ...binding, type: "commit", totalBytes: bytes.length } };
12376
13228
  }
12377
13229
  function canonicalResourceDescriptor(value) {
12378
- const invalid = () => {
13230
+ const invalid2 = () => {
12379
13231
  throw new Error("invalid resource descriptor");
12380
13232
  };
12381
- if (!value || typeof value !== "object" || Array.isArray(value)) return invalid();
13233
+ if (!value || typeof value !== "object" || Array.isArray(value)) return invalid2();
12382
13234
  const row = value;
12383
- if (Object.keys(row).some((key) => !["viewId", "resource", "entityId", "window", "addressing"].includes(key)) || typeof row.viewId !== "string" || !/^[A-Za-z0-9_-]{1,128}$/.test(row.viewId) || !["contacts", "identity", "messages", "files", "commands", "activity"].includes(String(row.resource))) return invalid();
13235
+ if (Object.keys(row).some((key) => !["viewId", "resource", "entityId", "window", "addressing"].includes(key)) || typeof row.viewId !== "string" || !/^[A-Za-z0-9_-]{1,128}$/.test(row.viewId) || !["contacts", "identity", "messages", "files", "commands", "activity", "statuses"].includes(String(row.resource))) return invalid2();
12384
13236
  const resource = row.resource;
12385
13237
  const scoped = ["messages", "files", "commands"].includes(resource);
12386
- if (scoped ? typeof row.entityId !== "string" || !row.entityId : row.entityId !== void 0) return invalid();
12387
- if (row.addressing !== void 0 && (row.addressing !== "cid" || !["messages", "files"].includes(resource) || !/^[a-f0-9]{64}$/i.test(String(row.entityId)))) return invalid();
12388
- if (resource !== "messages" && row.window !== void 0) return invalid();
13238
+ if (scoped ? typeof row.entityId !== "string" || !row.entityId : row.entityId !== void 0) return invalid2();
13239
+ if (row.addressing !== void 0 && (row.addressing !== "cid" || !["messages", "files"].includes(resource) || !/^[a-f0-9]{64}$/i.test(String(row.entityId)))) return invalid2();
13240
+ if (resource !== "messages" && row.window !== void 0) return invalid2();
12389
13241
  let window2;
12390
13242
  if (resource === "messages") {
12391
13243
  const raw = row.window ?? { limit: 50, retainedPages: 1 };
12392
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return invalid();
13244
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return invalid2();
12393
13245
  const w3 = raw;
12394
- if (Object.keys(w3).some((key) => !["limit", "retainedPages", "oldestSequence"].includes(key)) || !Number.isInteger(w3.limit) || w3.limit < 1 || w3.limit > 200 || !Number.isSafeInteger(w3.retainedPages) || w3.retainedPages < 1 || w3.oldestSequence !== void 0 && (!Number.isSafeInteger(w3.oldestSequence) || w3.oldestSequence < 1)) return invalid();
13246
+ if (Object.keys(w3).some((key) => !["limit", "retainedPages", "oldestSequence"].includes(key)) || !Number.isInteger(w3.limit) || w3.limit < 1 || w3.limit > 200 || !Number.isSafeInteger(w3.retainedPages) || w3.retainedPages < 1 || w3.oldestSequence !== void 0 && (!Number.isSafeInteger(w3.oldestSequence) || w3.oldestSequence < 1)) return invalid2();
12395
13247
  window2 = {
12396
13248
  limit: w3.limit,
12397
13249
  retainedPages: w3.retainedPages,
@@ -12496,8 +13348,8 @@ var ResourceOutput = class {
12496
13348
  return this.#fail(new Error("resource pending limit exceeded"));
12497
13349
  }
12498
13350
  admitted();
12499
- return new Promise((resolve4, reject) => {
12500
- const item = { envelope, bytes, resolve: resolve4, reject };
13351
+ return new Promise((resolve5, reject) => {
13352
+ const item = { envelope, bytes, resolve: resolve5, reject };
12501
13353
  if (!this.#active) {
12502
13354
  this.#active = item;
12503
13355
  void this.#pump();
@@ -12548,11 +13400,11 @@ data: ${JSON.stringify(frame.data)}
12548
13400
  }
12549
13401
  #drain() {
12550
13402
  if (this.#closed) return Promise.resolve();
12551
- return new Promise((resolve4) => {
13403
+ return new Promise((resolve5) => {
12552
13404
  const release = () => {
12553
13405
  this.response.removeListener("drain", release);
12554
13406
  this.#releaseDrain = void 0;
12555
- resolve4();
13407
+ resolve5();
12556
13408
  };
12557
13409
  this.#releaseDrain = release;
12558
13410
  this.response.once("drain", release);
@@ -12636,8 +13488,8 @@ var ResourceConnections = class {
12636
13488
  open(response) {
12637
13489
  const id = randomUUID2(), controller = new AbortController();
12638
13490
  let resolveClosed;
12639
- const closed2 = new Promise((resolve4) => {
12640
- resolveClosed = resolve4;
13491
+ const closed2 = new Promise((resolve5) => {
13492
+ resolveClosed = resolve5;
12641
13493
  });
12642
13494
  let connection;
12643
13495
  const close = () => {
@@ -12697,6 +13549,11 @@ data: ${JSON.stringify({
12697
13549
  connection.localRevision++;
12698
13550
  for (const view of connection.views.values()) if (view.descriptor.resource === "identity") this.#schedule(connection, view);
12699
13551
  }, controller.signal);
13552
+ subscribeStatuses(this.deps.stateDir, this.deps.identityCid, () => {
13553
+ if (!connection || controller.signal.aborted) return;
13554
+ connection.localRevision++;
13555
+ for (const view of connection.views.values()) if (view.descriptor.resource === "statuses") this.#schedule(connection, view);
13556
+ }, controller.signal);
12700
13557
  response.write(`event: resource-connection
12701
13558
  data: ${JSON.stringify({
12702
13559
  protocolVersion: 1,
@@ -12731,8 +13588,8 @@ data: ${JSON.stringify({
12731
13588
  if (!connection.epochs.has(viewId) && connection.epochs.size >= 256) throw new ResourceBindingError(503, "resource epoch capacity exceeded");
12732
13589
  if (current) this.#retire(current);
12733
13590
  let resolveInitial, rejectInitial;
12734
- const initial = new Promise((resolve4, reject) => {
12735
- resolveInitial = resolve4;
13591
+ const initial = new Promise((resolve5, reject) => {
13592
+ resolveInitial = resolve5;
12736
13593
  rejectInitial = reject;
12737
13594
  });
12738
13595
  void initial.catch(() => {
@@ -12838,7 +13695,7 @@ data: ${JSON.stringify({
12838
13695
  #coverage(connection, source) {
12839
13696
  const now = Date.now();
12840
13697
  if (now - (connection.coverageAt ?? -Infinity) < 15e3 || !connection.observer.healthy) return Promise.resolve();
12841
- const eligible = [...connection.views.values()].filter((view) => this.#current(connection, view) && !view.failed && !view.running && !view.dirty && view.payload !== void 0 && view.covered && view.covered.producerGeneration === source.producerGeneration && view.covered.position === source.position && (view.descriptor.resource !== "identity" || view.localRevision === connection.localRevision) && now - (view.qualifiedAt ?? 0) >= 15e3);
13698
+ const eligible = [...connection.views.values()].filter((view) => this.#current(connection, view) && !view.failed && !view.running && !view.dirty && view.payload !== void 0 && view.covered && view.covered.producerGeneration === source.producerGeneration && view.covered.position === source.position && (view.descriptor.resource !== "identity" && view.descriptor.resource !== "statuses" || view.localRevision === connection.localRevision) && now - (view.qualifiedAt ?? 0) >= 15e3);
12842
13699
  if (!eligible.length) return Promise.resolve();
12843
13700
  const views = eligible.map((view) => ({
12844
13701
  protocolVersion: 1,
@@ -12936,9 +13793,9 @@ function mediaResponsePolicy(mime2) {
12936
13793
 
12937
13794
  // src/command-invocations.ts
12938
13795
  init_define_MESSENGER_BUILD_INFO();
12939
- import { createHash as createHash3 } from "node:crypto";
12940
- import { chmodSync, mkdirSync as mkdirSync3, readFileSync as readFileSync3, renameSync as renameSync3, writeFileSync as writeFileSync3 } from "node:fs";
12941
- import { dirname as dirname2, join as join3 } from "node:path";
13796
+ import { createHash as createHash4 } from "node:crypto";
13797
+ import { chmodSync, mkdirSync as mkdirSync4, readFileSync as readFileSync4, renameSync as renameSync4, writeFileSync as writeFileSync4 } from "node:fs";
13798
+ import { dirname as dirname2, join as join4 } from "node:path";
12942
13799
  var MAX_INVOCATIONS = 4096;
12943
13800
  var InvocationConflictError = class extends Error {
12944
13801
  };
@@ -12950,7 +13807,7 @@ function canonical2(value) {
12950
13807
  return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical2(value[key])}`).join(",")}}`;
12951
13808
  }
12952
13809
  function invocationFingerprint(input) {
12953
- return createHash3("sha256").update(canonical2(input)).digest("base64url");
13810
+ return createHash4("sha256").update(canonical2(input)).digest("base64url");
12954
13811
  }
12955
13812
  function validRecord(value) {
12956
13813
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
@@ -12965,10 +13822,10 @@ var CommandInvocationStore = class _CommandInvocationStore {
12965
13822
  }
12966
13823
  static open(stateDir, identityCid, capacity = MAX_INVOCATIONS) {
12967
13824
  if (!Number.isInteger(capacity) || capacity < 1) throw new Error("invocation capacity must be a positive integer");
12968
- const file = join3(stateDir, `typed-commands-${createHash3("sha256").update(identityCid).digest("hex").slice(0, 24)}.json`);
13825
+ const file = join4(stateDir, `typed-commands-${createHash4("sha256").update(identityCid).digest("hex").slice(0, 24)}.json`);
12969
13826
  let state = { version: 1, records: {} };
12970
13827
  try {
12971
- const parsed = JSON.parse(readFileSync3(file, "utf8"));
13828
+ const parsed = JSON.parse(readFileSync4(file, "utf8"));
12972
13829
  if (!parsed || typeof parsed !== "object" || parsed.version !== 1 || !parsed.records || typeof parsed.records !== "object" || !Object.values(parsed.records).every(validRecord)) {
12973
13830
  throw new Error("invalid typed command invocation state");
12974
13831
  }
@@ -13016,11 +13873,11 @@ var CommandInvocationStore = class _CommandInvocationStore {
13016
13873
  return record;
13017
13874
  }
13018
13875
  save() {
13019
- mkdirSync3(dirname2(this.file), { recursive: true, mode: 448 });
13876
+ mkdirSync4(dirname2(this.file), { recursive: true, mode: 448 });
13020
13877
  const temp = `${this.file}.${process.pid}.tmp`;
13021
- writeFileSync3(temp, JSON.stringify(this.state), { mode: 384 });
13878
+ writeFileSync4(temp, JSON.stringify(this.state), { mode: 384 });
13022
13879
  chmodSync(temp, 384);
13023
- renameSync3(temp, this.file);
13880
+ renameSync4(temp, this.file);
13024
13881
  }
13025
13882
  };
13026
13883
  function statusFor(delivery, wireId) {
@@ -13230,13 +14087,13 @@ var Preprocessor = class {
13230
14087
  return this.droppedBufferSize + this.pos;
13231
14088
  }
13232
14089
  getError(code, cpOffset) {
13233
- const { line, col, offset } = this;
14090
+ const { line: line2, col, offset } = this;
13234
14091
  const startCol = col + cpOffset;
13235
14092
  const startOffset = offset + cpOffset;
13236
14093
  return {
13237
14094
  code,
13238
- startLine: line,
13239
- endLine: line,
14095
+ startLine: line2,
14096
+ endLine: line2,
13240
14097
  startCol,
13241
14098
  endCol: startCol,
13242
14099
  startOffset,
@@ -18381,12 +19238,12 @@ var Parser = class {
18381
19238
  /** @protected */
18382
19239
  _insertTemplate(token) {
18383
19240
  const tmpl = this.treeAdapter.createElement(token.tagName, NS.HTML, token.attrs);
18384
- const content = this.treeAdapter.createDocumentFragment();
18385
- this.treeAdapter.setTemplateContent(tmpl, content);
19241
+ const content2 = this.treeAdapter.createDocumentFragment();
19242
+ this.treeAdapter.setTemplateContent(tmpl, content2);
18386
19243
  this._attachElementToTree(tmpl, token.location);
18387
19244
  this.openElements.push(tmpl, token.tagID);
18388
19245
  if (this.options.sourceCodeLocationInfo)
18389
- this.treeAdapter.setNodeSourceCodeLocation(content, null);
19246
+ this.treeAdapter.setNodeSourceCodeLocation(content2, null);
18390
19247
  }
18391
19248
  /** @protected */
18392
19249
  _insertFakeRootElement() {
@@ -21265,10 +22122,10 @@ function serializeAttributes(node, { treeAdapter }) {
21265
22122
  }
21266
22123
  function serializeTextNode(node, options) {
21267
22124
  const { treeAdapter } = options;
21268
- const content = treeAdapter.getTextNodeContent(node);
22125
+ const content2 = treeAdapter.getTextNodeContent(node);
21269
22126
  const parent = treeAdapter.getParentNode(node);
21270
22127
  const parentTn = parent && treeAdapter.isElementNode(parent) && treeAdapter.getTagName(parent);
21271
- return parentTn && treeAdapter.getNamespaceURI(parent) === NS.HTML && hasUnescapedText(parentTn, options.scriptingEnabled) ? content : escapeText(content);
22128
+ return parentTn && treeAdapter.getNamespaceURI(parent) === NS.HTML && hasUnescapedText(parentTn, options.scriptingEnabled) ? content2 : escapeText(content2);
21272
22129
  }
21273
22130
  function serializeCommentNode(node, { treeAdapter }) {
21274
22131
  return `<!--${treeAdapter.getCommentNodeContent(node)}-->`;
@@ -21445,6 +22302,15 @@ var HttpError = class extends Error {
21445
22302
  }
21446
22303
  };
21447
22304
  var bad = (m2) => new HttpError(400, m2);
22305
+ function statusService(deps) {
22306
+ if (!deps.statuses) throw new HttpError(404, "Agent statuses are unavailable (typed commands are disabled)");
22307
+ return deps.statuses;
22308
+ }
22309
+ function statusHttpError(error) {
22310
+ if (!(error instanceof StatusError)) return error;
22311
+ const status = error.code === "not_found" ? 404 : error.code === "forbidden" ? 403 : error.code === "conflict" || error.code === "idempotency_conflict" ? 409 : error.code === "limit_exceeded" ? 413 : 400;
22312
+ return new HttpError(status, error.message);
22313
+ }
21448
22314
  function str(body, key) {
21449
22315
  const v2 = body[key];
21450
22316
  if (typeof v2 !== "string" || v2 === "") throw bad(`${key} must be a non-empty string`);
@@ -21787,8 +22653,8 @@ async function serveEvents(req, res, deps) {
21787
22653
  };
21788
22654
  const waitForDrain = () => {
21789
22655
  if (drainWait) return drainWait;
21790
- drainWait = new Promise((resolve4) => {
21791
- releaseDrain = resolve4;
22656
+ drainWait = new Promise((resolve5) => {
22657
+ releaseDrain = resolve5;
21792
22658
  });
21793
22659
  res.once("drain", onDrain);
21794
22660
  return drainWait;
@@ -21878,6 +22744,8 @@ async function projectResourceView(deps, input, signal, source) {
21878
22744
  return projectCommandResource(client, deps, { contact: descriptor.entityId });
21879
22745
  case "activity":
21880
22746
  return projectActivity(client, signal, source);
22747
+ case "statuses":
22748
+ return listFeed(statusService(deps).store, { kind: "global" }, { limit: FEED_PAGE_MAX });
21881
22749
  case "messages": {
21882
22750
  const pin = descriptor.addressing === "cid" ? canonicalPeer(descriptor.entityId) : void 0;
21883
22751
  const peer = pin ? { cid: pin.cid, announcedName: "" } : await resolveContact(client, descriptor.entityId);
@@ -21971,6 +22839,77 @@ var ROUTES = {
21971
22839
  return { wire_id: wireId, delivery: "tracked" };
21972
22840
  },
21973
22841
  "GET /api/contacts/:contact/commands": async ({ client, deps, params }) => projectCommandResource(client, deps, params),
22842
+ // ---- external agents' statuses (canonical here; Fleet agents' statuses stay in Fleet) -------------------------
22843
+ "GET /api/statuses": async ({ deps, query }) => {
22844
+ const extra = [...query.keys()].filter((key) => !["scope", "agent", "after", "limit", "filter"].includes(key) || query.getAll(key).length !== 1);
22845
+ if (extra.length) throw bad(`unexpected query ${extra[0]}`);
22846
+ const filter = query.get("filter");
22847
+ if (filter !== null && filter !== "eligible") throw bad("filter must be eligible");
22848
+ try {
22849
+ const after = query.get("after") ?? void 0, limit = query.get("limit");
22850
+ return listFeed(
22851
+ statusService(deps).store,
22852
+ feedScope({ scope: query.get("scope") ?? void 0, agent: query.get("agent") ?? void 0 }),
22853
+ { ...after === void 0 ? {} : { after }, ...limit === null ? {} : { limit: Number(limit) }, ...filter === "eligible" ? { eligible: true } : {} }
22854
+ );
22855
+ } catch (error) {
22856
+ throw statusHttpError(error);
22857
+ }
22858
+ },
22859
+ "GET /api/statuses/:statusId": async ({ deps, params }) => {
22860
+ const status = statusService(deps).store.get(params.statusId);
22861
+ if (!status) throw new HttpError(404, "status not found");
22862
+ return { status: publicStatus(status) };
22863
+ },
22864
+ /** The chat ("session") card: the status a `ours.status.publish` message created, read from the store, never the raw JSON. */
22865
+ "GET /api/statuses/by-wire/:wireId": async ({ deps, params }) => {
22866
+ const service = statusService(deps);
22867
+ const ingested = service.store.ingested(params.wireId);
22868
+ if (!ingested) throw new HttpError(404, "no status for this message");
22869
+ if (!ingested.outcome.ok) return { error: { code: ingested.outcome.code, message: ingested.outcome.message } };
22870
+ const status = service.store.get(ingested.outcome.status_id);
22871
+ if (!status) throw new HttpError(404, "status not found");
22872
+ return { status: publicStatus(status) };
22873
+ },
22874
+ "POST /api/statuses/:statusId/answer": async ({ deps, params, body }) => {
22875
+ const allowed = ["expectedRevision", "submissionId", "selection", "text", "surface"];
22876
+ const extra = Object.keys(body).filter((key) => !allowed.includes(key));
22877
+ if (extra.length) throw bad(`unexpected answer field ${extra[0]}`);
22878
+ if (body.surface !== void 0 && body.surface !== "feed" && body.surface !== "session") throw bad("surface must be feed or session");
22879
+ if (body.selection !== void 0 && (!Array.isArray(body.selection) || body.selection.some((id) => typeof id !== "string"))) throw bad("selection must be a list of option IDs");
22880
+ if (body.text !== void 0 && typeof body.text !== "string") throw bad("text must be a string");
22881
+ try {
22882
+ const { status } = await statusService(deps).answer(params.statusId, {
22883
+ expectedRevision: body.expectedRevision,
22884
+ submissionId: body.submissionId,
22885
+ ...body.selection === void 0 ? {} : { selection: body.selection },
22886
+ ...body.text === void 0 ? {} : { text: body.text },
22887
+ ...body.surface === void 0 ? {} : { surface: body.surface }
22888
+ });
22889
+ return { status: publicStatus(status) };
22890
+ } catch (error) {
22891
+ throw statusHttpError(error);
22892
+ }
22893
+ },
22894
+ /** The Owner's manual Try again after `not_delivered`. */
22895
+ "POST /api/statuses/:statusId/answer/deliver": async ({ deps, params }) => {
22896
+ try {
22897
+ return { status: publicStatus(await statusService(deps).retry(params.statusId)) };
22898
+ } catch (error) {
22899
+ throw statusHttpError(error);
22900
+ }
22901
+ },
22902
+ /** The Owner displayed this revision as the current feed card or its chat card came on screen. */
22903
+ "POST /api/statuses/:statusId/seen": async ({ deps, params, body }) => {
22904
+ if (Object.keys(body).some((key) => key !== "revision") || !Number.isSafeInteger(body.revision)) throw bad("expected { revision }");
22905
+ try {
22906
+ const store = statusService(deps).store;
22907
+ if (!store.get(params.statusId)) throw new HttpError(404, "status not found");
22908
+ return { status: publicStatus(store.markSeen(params.statusId, body.revision)) };
22909
+ } catch (error) {
22910
+ throw statusHttpError(error);
22911
+ }
22912
+ },
21974
22913
  "POST /api/commands/send": async ({ client, deps, body }) => {
21975
22914
  if (deps.config.typedCommands === false) throw new HttpError(404, "Typed commands are disabled");
21976
22915
  const peer = await resolveContact(client, str(body, "contact"));
@@ -22214,7 +23153,7 @@ var ROUTES = {
22214
23153
  const contactDeadline = Date.now() + 1e4;
22215
23154
  while (!(await client.listContacts()).contacts.some((contact) => contact.container_id.toUpperCase() === serverCid)) {
22216
23155
  if (Date.now() >= contactDeadline) throw bad("Enrollment contact is not ready; obtain a fresh setup payload before retrying");
22217
- await new Promise((resolve4) => setTimeout(resolve4, 100));
23156
+ await new Promise((resolve5) => setTimeout(resolve5, 100));
22218
23157
  }
22219
23158
  const argumentsValue = { type: "ours.app.bind-workspace.v1", accountId: String(challenge.accountId), workspaceId: String(challenge.workspaceId), nonce: String(challenge.nonce), hostWorkspaceId: String(body.hostWorkspaceId) };
22220
23159
  const outcome = await client.sendCommand({ contact: serverCid, command: "bind-workspace", arguments: argumentsValue });
@@ -22457,7 +23396,7 @@ async function serveApi(req, res, deps) {
22457
23396
  const [connectionId, viewId, epoch, baselineId] = resourceHeaders.map((values) => values[0]);
22458
23397
  const baseline = await resourceService(deps).bound(connectionId, viewId, Number(epoch), baselineId);
22459
23398
  const descriptor = baseline.descriptor;
22460
- const route = descriptor.addressing === "cid" ? descriptor.resource === "files" ? "GET /api/peers/:cid/files" : "GET /api/peers/:cid/page" : descriptor.resource === "contacts" ? "GET /api/contacts" : descriptor.resource === "activity" ? "GET /api/activity" : descriptor.resource === "identity" ? "GET /api/identity" : descriptor.resource === "commands" ? "GET /api/contacts/:contact/commands" : descriptor.resource === "files" ? "GET /api/conversations/:contact/files" : "GET /api/conversations/:contact/page";
23399
+ const route = descriptor.addressing === "cid" ? descriptor.resource === "files" ? "GET /api/peers/:cid/files" : "GET /api/peers/:cid/page" : descriptor.resource === "contacts" ? "GET /api/contacts" : descriptor.resource === "activity" ? "GET /api/activity" : descriptor.resource === "statuses" ? "GET /api/statuses" : descriptor.resource === "identity" ? "GET /api/identity" : descriptor.resource === "commands" ? "GET /api/contacts/:contact/commands" : descriptor.resource === "files" ? "GET /api/conversations/:contact/files" : "GET /api/conversations/:contact/page";
22461
23400
  const allowedQuery = descriptor.resource === "messages" && [...url.searchParams.keys()].every((key) => key === "limit") && (!url.searchParams.has("limit") || url.searchParams.getAll("limit").length === 1 && Number(url.searchParams.get("limit")) === descriptor.window.limit);
22462
23401
  if (hit.key !== route || descriptor.entityId !== void 0 && descriptor.entityId !== (hit.params.cid ?? hit.params.contact) || url.searchParams.size > 0 && !allowedQuery) throw new ResourceBindingError(409, "resource read descriptor mismatch");
22463
23402
  res.setHeader("X-Resource-Connection", connectionId);
@@ -22503,7 +23442,7 @@ function isOursError(error) {
22503
23442
 
22504
23443
  // src/daemon.ts
22505
23444
  init_define_MESSENGER_BUILD_INFO();
22506
- import { randomBytes as randomBytes2 } from "node:crypto";
23445
+ import { randomBytes as randomBytes3 } from "node:crypto";
22507
23446
 
22508
23447
  // node_modules/@ours.network/sdk/dist/index.js
22509
23448
  init_define_MESSENGER_BUILD_INFO();
@@ -23324,9 +24263,9 @@ async function Q(e2 = {}) {
23324
24263
 
23325
24264
  // src/owner-session.ts
23326
24265
  init_define_MESSENGER_BUILD_INFO();
23327
- import { randomBytes } from "node:crypto";
24266
+ import { randomBytes as randomBytes2 } from "node:crypto";
23328
24267
  import * as fs from "node:fs";
23329
- import { isAbsolute, join as join4, resolve as resolve2, dirname as dirname3 } from "node:path";
24268
+ import { isAbsolute, join as join5, resolve as resolve3, dirname as dirname3 } from "node:path";
23330
24269
  import { spawnSync } from "node:child_process";
23331
24270
  function stateExists(path2) {
23332
24271
  try {
@@ -23342,18 +24281,18 @@ var OwnerSession = class _OwnerSession {
23342
24281
  constructor(stateDir, selection) {
23343
24282
  this.stateDir = stateDir;
23344
24283
  this.selection = selection;
23345
- this.path = join4(stateDir, "owner-session.json");
24284
+ this.path = join5(stateDir, "owner-session.json");
23346
24285
  }
23347
24286
  record;
23348
24287
  path;
23349
24288
  lockFd;
23350
24289
  static async open(stateDir, selection, attach) {
23351
- const saved = stateDir && stateExists(join4(stateDir, "owner-session.json"));
24290
+ const saved = stateDir && stateExists(join5(stateDir, "owner-session.json"));
23352
24291
  if (!selection || process.platform !== "linux") {
23353
24292
  if (saved) throw new ConfigurationError("Saved messenger ownership requires its qualified V1 activation and original selection");
23354
24293
  return void 0;
23355
24294
  }
23356
- if (!stateDir || !isAbsolute(stateDir) || resolve2(stateDir) !== stateDir) {
24295
+ if (!stateDir || !isAbsolute(stateDir) || resolve3(stateDir) !== stateDir) {
23357
24296
  throw new ConfigurationError("Messenger ownership requires an absolute private state directory");
23358
24297
  }
23359
24298
  const capability = spawnSync("flock", ["--version"], { stdio: "ignore", timeout: 5e3 });
@@ -23380,7 +24319,7 @@ var OwnerSession = class _OwnerSession {
23380
24319
  }
23381
24320
  session.record = {
23382
24321
  version: 1,
23383
- ownerInstanceId: "messenger-" + randomBytes(24).toString("hex"),
24322
+ ownerInstanceId: "messenger-" + randomBytes2(24).toString("hex"),
23384
24323
  selection: { ...selection },
23385
24324
  phase: "active"
23386
24325
  };
@@ -23455,7 +24394,7 @@ var OwnerSession = class _OwnerSession {
23455
24394
  }
23456
24395
  fs.mkdirSync(this.stateDir, { recursive: true, mode: 448 });
23457
24396
  this.privateStat(this.stateDir, true);
23458
- const path2 = join4(this.stateDir, "owner-session.lock");
24397
+ const path2 = join5(this.stateDir, "owner-session.lock");
23459
24398
  this.lockFd = fs.openSync(path2, fs.constants.O_CREAT | fs.constants.O_RDWR | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK, 384);
23460
24399
  const st2 = this.privateStat(path2);
23461
24400
  const opened = fs.fstatSync(this.lockFd);
@@ -23493,7 +24432,7 @@ var OwnerSession = class _OwnerSession {
23493
24432
  }
23494
24433
  write() {
23495
24434
  if (stateExists(this.path)) this.privateStat(this.path);
23496
- const temporary = this.path + "." + randomBytes(12).toString("hex") + ".tmp";
24435
+ const temporary = this.path + "." + randomBytes2(12).toString("hex") + ".tmp";
23497
24436
  let fd;
23498
24437
  try {
23499
24438
  fd = fs.openSync(temporary, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY | fs.constants.O_NOFOLLOW, 384);
@@ -23552,7 +24491,7 @@ async function startRuntime(cfg, buildInfo, attach = Q) {
23552
24491
  throw new ConfigurationError("OURS_DAEMON_URL, OURS_DAEMON_ID and OURS_DAEMON_CREDENTIAL_PATH must be set together");
23553
24492
  }
23554
24493
  const owner = await OwnerSession.open(cfg.stateDir, selected ? { endpoint, expectedInstanceId, credentialPath, identity: cfg.identity } : void 0, attach);
23555
- const leaseToken = owner?.ownerInstanceId ?? `messenger-${randomBytes2(24).toString("hex")}`;
24494
+ const leaseToken = owner?.ownerInstanceId ?? `messenger-${randomBytes3(24).toString("hex")}`;
23556
24495
  let client;
23557
24496
  let info;
23558
24497
  try {
@@ -23620,9 +24559,9 @@ async function bindIdentity(runtime, cfg) {
23620
24559
  // src/push.ts
23621
24560
  init_define_MESSENGER_BUILD_INFO();
23622
24561
  var import_web_push = __toESM(require_src2(), 1);
23623
- import { createHash as createHash4, randomUUID as randomUUID3, timingSafeEqual } from "node:crypto";
23624
- import { chmodSync as chmodSync2, lstatSync as lstatSync4, mkdirSync as mkdirSync6, readFileSync as readFileSync5, renameSync as renameSync5, writeFileSync as writeFileSync6 } from "node:fs";
23625
- import { dirname as dirname4, join as join5 } from "node:path";
24562
+ import { createHash as createHash5, randomUUID as randomUUID3, timingSafeEqual } from "node:crypto";
24563
+ import { chmodSync as chmodSync2, lstatSync as lstatSync4, mkdirSync as mkdirSync7, readFileSync as readFileSync6, renameSync as renameSync6, writeFileSync as writeFileSync7 } from "node:fs";
24564
+ import { dirname as dirname4, join as join6 } from "node:path";
23626
24565
  var MAX_BINDINGS = 32;
23627
24566
  var MAX_ENDPOINT_LENGTH = 2048;
23628
24567
  var MAX_LABEL_LENGTH = 160;
@@ -23647,7 +24586,7 @@ function nonEmpty3(value, max = Number.MAX_SAFE_INTEGER) {
23647
24586
  return typeof value === "string" && value.length > 0 && value.length <= max;
23648
24587
  }
23649
24588
  function fingerprint(publicKey) {
23650
- return createHash4("sha256").update(publicKey).digest("base64url");
24589
+ return createHash5("sha256").update(publicKey).digest("base64url");
23651
24590
  }
23652
24591
  function base64urlBytes(value, length, field) {
23653
24592
  if (!nonEmpty3(value, 256) || !/^[A-Za-z0-9_-]+$/.test(value)) {
@@ -23818,15 +24757,15 @@ var PushStore = class _PushStore {
23818
24757
  const env = typeof identityCidOrEnv === "string" ? envOrDependencies : identityCidOrEnv;
23819
24758
  const deps = typeof identityCidOrEnv === "string" ? dependencies : envOrDependencies;
23820
24759
  if (!nonEmpty3(identityCid, 512)) throw new Error("push identity CID must be a non-empty bounded string");
23821
- const file = join5(stateDir, "push.json");
23822
- mkdirSync6(dirname4(file), { recursive: true, mode: 448 });
24760
+ const file = join6(stateDir, "push.json");
24761
+ mkdirSync7(dirname4(file), { recursive: true, mode: 448 });
23823
24762
  let parsed;
23824
24763
  try {
23825
24764
  const stat2 = lstatSync4(file);
23826
24765
  if (!stat2.isFile() || stat2.isSymbolicLink()) throw preservedStateError(file, "not a safe regular file");
23827
24766
  let value;
23828
24767
  try {
23829
- value = JSON.parse(readFileSync5(file, "utf8"));
24768
+ value = JSON.parse(readFileSync6(file, "utf8"));
23830
24769
  } catch (error) {
23831
24770
  throw preservedStateError(file, `corrupt or unreadable (${error instanceof Error ? error.message : String(error)})`);
23832
24771
  }
@@ -23925,9 +24864,9 @@ var PushStore = class _PushStore {
23925
24864
  }
23926
24865
  persist() {
23927
24866
  const tmp = `${this.file}.tmp`;
23928
- writeFileSync6(tmp, JSON.stringify(this.state, null, 2), { mode: 384 });
24867
+ writeFileSync7(tmp, JSON.stringify(this.state, null, 2), { mode: 384 });
23929
24868
  chmodSync2(tmp, 384);
23930
- renameSync5(tmp, this.file);
24869
+ renameSync6(tmp, this.file);
23931
24870
  chmodSync2(this.file, 384);
23932
24871
  }
23933
24872
  get publicKey() {
@@ -24456,7 +25395,7 @@ function attachPresenceServer(server, registry, options) {
24456
25395
  clearInterval(pinger);
24457
25396
  server.removeListener("upgrade", upgrade);
24458
25397
  for (const socket of wss.clients) socket.terminate();
24459
- await new Promise((resolve4) => wss.close(() => resolve4()));
25398
+ await new Promise((resolve5) => wss.close(() => resolve5()));
24460
25399
  }
24461
25400
  };
24462
25401
  }
@@ -24503,7 +25442,7 @@ async function redirectStaleEntryAsset(req, res, appDir, pathname, basePath = "/
24503
25442
  const staleEntry = /^\/assets\/index-[A-Za-z0-9_-]+\.(js|css)$/.exec(pathname);
24504
25443
  if (!staleEntry) return false;
24505
25444
  try {
24506
- const index = (await readContainedFile(appDir, resolve3(appDir, "index.html"))).toString("utf8");
25445
+ const index = (await readContainedFile(appDir, resolve4(appDir, "index.html"))).toString("utf8");
24507
25446
  const extension2 = staleEntry[1];
24508
25447
  const currentEntry = new RegExp(
24509
25448
  `(?:src|href)=["'](\\.?\\/assets\\/index-[A-Za-z0-9_-]+\\.${extension2})["']`
@@ -24546,8 +25485,8 @@ async function serveApp(req, res, appDir, basePath = "/") {
24546
25485
  let assetRoot = appDir;
24547
25486
  let cacheControl = "no-cache";
24548
25487
  if (pathname.startsWith("/assets/")) {
24549
- assetRoot = resolve3(appDir, "assets");
24550
- const candidate = resolve3(appDir, `.${decodedPathname}`);
25488
+ assetRoot = resolve4(appDir, "assets");
25489
+ const candidate = resolve4(appDir, `.${decodedPathname}`);
24551
25490
  if (candidate !== assetRoot && !candidate.startsWith(`${assetRoot}${sep}`)) {
24552
25491
  appNotFound(res);
24553
25492
  return;
@@ -24555,25 +25494,25 @@ async function serveApp(req, res, appDir, basePath = "/") {
24555
25494
  asset = candidate;
24556
25495
  cacheControl = "public, max-age=31536000, immutable";
24557
25496
  } else if (pathname.startsWith("/icons/")) {
24558
- assetRoot = resolve3(appDir, "icons");
24559
- const candidate = resolve3(appDir, `.${decodedPathname}`);
25497
+ assetRoot = resolve4(appDir, "icons");
25498
+ const candidate = resolve4(appDir, `.${decodedPathname}`);
24560
25499
  if (candidate === assetRoot || !candidate.startsWith(`${assetRoot}${sep}`)) {
24561
25500
  appNotFound(res);
24562
25501
  return;
24563
25502
  }
24564
25503
  asset = candidate;
24565
25504
  } else if (pathname === "/manifest.webmanifest" || pathname === "/version.json" || pathname === "/sw.js" || pathname === "/icon.svg" || pathname === "/maskable-icon.svg") {
24566
- asset = resolve3(appDir, pathname.slice(1));
25505
+ asset = resolve4(appDir, pathname.slice(1));
24567
25506
  } else if (/\.[a-z0-9]+$/i.test(pathname)) {
24568
25507
  appNotFound(res);
24569
25508
  return;
24570
25509
  } else {
24571
- asset = resolve3(appDir, "index.html");
25510
+ asset = resolve4(appDir, "index.html");
24572
25511
  }
24573
25512
  try {
24574
25513
  let body = await readContainedFile(assetRoot, asset);
24575
25514
  const base = normalizeBasePath(basePath);
24576
- if (asset === resolve3(appDir, "index.html")) body = Buffer.from(prefixDocument(body.toString("utf8"), base));
25515
+ if (asset === resolve4(appDir, "index.html")) body = Buffer.from(prefixDocument(body.toString("utf8"), base));
24577
25516
  if (pathname === "/manifest.webmanifest" && base !== "/") {
24578
25517
  const manifest = JSON.parse(body.toString("utf8"));
24579
25518
  for (const key of ["id", "start_url", "scope"]) if (typeof manifest[key] === "string") manifest[key] = base + manifest[key].replace(/^\//, "");
@@ -24584,7 +25523,7 @@ async function serveApp(req, res, appDir, basePath = "/") {
24584
25523
  res.writeHead(200, appHeaders(type, cacheControl, body.length));
24585
25524
  res.end(req.method === "HEAD" ? void 0 : body);
24586
25525
  } catch (error) {
24587
- if (asset !== resolve3(appDir, "index.html")) {
25526
+ if (asset !== resolve4(appDir, "index.html")) {
24588
25527
  if (await redirectStaleEntryAsset(req, res, appDir, decodedPathname, basePath)) return;
24589
25528
  appNotFound(res);
24590
25529
  return;
@@ -24738,6 +25677,8 @@ async function start(cfg, buildInfo, dependencies = DEFAULT_START_DEPENDENCIES)
24738
25677
  let watcher;
24739
25678
  let delivery;
24740
25679
  let notificationOutbox;
25680
+ let statusTimer;
25681
+ let notificationDeliveryWithStatuses;
24741
25682
  let events;
24742
25683
  let http;
24743
25684
  let startupProbe;
@@ -24754,6 +25695,7 @@ async function start(cfg, buildInfo, dependencies = DEFAULT_START_DEPENDENCIES)
24754
25695
  startupProbe = void 0;
24755
25696
  await watcher?.stop().catch((error) => reportFailure(log.warn, "watcher stop", error));
24756
25697
  watcher = void 0;
25698
+ clearInterval(statusTimer);
24757
25699
  await notificationOutbox?.close();
24758
25700
  await delivery?.stop().catch((error) => reportFailure(log.warn, "push delivery stop", error));
24759
25701
  delivery = void 0;
@@ -24790,8 +25732,25 @@ async function start(cfg, buildInfo, dependencies = DEFAULT_START_DEPENDENCIES)
24790
25732
  const notificationConfig = producerConfig();
24791
25733
  if (notificationConfig) notificationOutbox = new MessengerNotificationProducer(cfg.stateDir, notificationConfig, bound.cid, runtime.client, log.warn);
24792
25734
  const notificationDelivery = notificationOutbox ?? delivery;
25735
+ let statuses;
25736
+ if (cfg.typedCommands !== false) {
25737
+ statuses = new StatusService(new MessengerStatusStore(cfg.stateDir, bound.cid), runtime.client, notificationOutbox?.outbox, log.warn);
25738
+ await statuses.start().catch((error) => reportFailure(log.warn, "status service start", error));
25739
+ const ingest = () => {
25740
+ void statuses.ingest().catch((error) => reportFailure(log.warn, "status ingest", error));
25741
+ };
25742
+ statusTimer = setInterval(() => {
25743
+ void statuses.recover().catch((error) => reportFailure(log.warn, "status recovery", error));
25744
+ }, 3e4);
25745
+ statusTimer.unref();
25746
+ const base = notificationDelivery;
25747
+ notificationDeliveryWithStatuses = { admit: (record, ...rest) => {
25748
+ if (record.event === "message_received") ingest();
25749
+ return base.admit(record, ...rest);
25750
+ } };
25751
+ }
24793
25752
  watcher = startWatcher(runtime.client, cfg.identity, push, log, events, {
24794
- delivery: notificationDelivery,
25753
+ delivery: notificationDeliveryWithStatuses ?? notificationDelivery,
24795
25754
  readPage: runtime.readNotificationPage
24796
25755
  });
24797
25756
  const readyDeps = {
@@ -24807,15 +25766,16 @@ async function start(cfg, buildInfo, dependencies = DEFAULT_START_DEPENDENCIES)
24807
25766
  }),
24808
25767
  events,
24809
25768
  identityCid: bound.cid,
24810
- retireContactNotifications: notificationOutbox ? (cid) => notificationOutbox.retireContact(cid) : void 0
25769
+ retireContactNotifications: notificationOutbox ? (cid) => notificationOutbox.retireContact(cid) : void 0,
25770
+ ...statuses ? { statuses } : {}
24811
25771
  };
24812
25772
  const moduleDir = dirname5(fileURLToPath(import.meta.url));
24813
25773
  const appCandidates = [
24814
- resolve3(moduleDir, "../web"),
24815
- resolve3(moduleDir, "../dist/web"),
24816
- resolve3(moduleDir, "web")
25774
+ resolve4(moduleDir, "../web"),
25775
+ resolve4(moduleDir, "../dist/web"),
25776
+ resolve4(moduleDir, "web")
24817
25777
  ];
24818
- const appDir = process.env.OURS_MESSENGER_WEB_DIR ?? appCandidates.find((candidate) => existsSync3(resolve3(candidate, "index.html")) && existsSync3(resolve3(candidate, "assets"))) ?? resolve3(moduleDir, "__messenger_web_not_built__");
25778
+ const appDir = process.env.OURS_MESSENGER_WEB_DIR ?? appCandidates.find((candidate) => existsSync3(resolve4(candidate, "index.html")) && existsSync3(resolve4(candidate, "assets"))) ?? resolve4(moduleDir, "__messenger_web_not_built__");
24819
25779
  http = createServer((req, res) => {
24820
25780
  const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
24821
25781
  let serving;