@rei-standard/amsg-server 2.5.0 → 2.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -54,7 +54,9 @@ const rei = await createReiServer({
54
54
 
55
55
  ## 关于 `messageType: 'instant'`
56
56
 
57
- > **Note**:新代码的 instant 消息请用 [@rei-standard/amsg-instant](https://github.com/Tosd0/ReiStandard/blob/main/packages/rei-standard-amsg/instant/README.md),跳过本端点的"建任务 → 处理 → 删任务" DB 来回。本端点的 `instant` 分支为兼容保留,行为不变、不会有运行时警告。
57
+ > **两条 instant 路径,按各自特点选一条(都是正式支持路径):**
58
+ > - **本端点的 `messageType: 'instant'`**(create task → process by UUID → delete task):任务先写进数据库再处理,投递不绑在请求连接上——客户端断开也没关系,任务行还在,能继续跑、能重试,想跑多久跑多久。适合**有数据库、需要长时间生成或保证消息零丢失**的场景。
59
+ > - **[@rei-standard/amsg-instant](https://github.com/Tosd0/ReiStandard/blob/main/packages/rei-standard-amsg/instant/README.md)**:纯 SSE 流 + Web Push backup,不需要数据库,适合无状态边缘运行时(如 Cloudflare Workers)。它的处理挂在响应连接上,客户端一断开就只剩平台给的那点宽限期把活干完(Deno Deploy 实测 ≈20-30s),所以适合**能快速跑完的短即时消息**。
58
60
 
59
61
  ## AI 接口 `apiUrl` 约束
60
62
 
package/dist/index.cjs CHANGED
@@ -525,7 +525,7 @@ function readReasoningContent(llmResponse) {
525
525
  }
526
526
  const content = _optionalChain([message, 'optionalAccess', _5 => _5.content]);
527
527
  if (typeof content === "string") {
528
- const match = content.match(/<(think|thinking|thought)>([\s\S]*?)<\/\1>/i);
528
+ const match = content.match(REASONING_TAG_RE);
529
529
  if (match) {
530
530
  const trimmed = match[2].trim();
531
531
  if (trimmed.length > 0) return trimmed;
@@ -533,6 +533,12 @@ function readReasoningContent(llmResponse) {
533
533
  }
534
534
  return null;
535
535
  }
536
+ var REASONING_TAG_RE = /<(think|thinking|thought)>([\s\S]*?)<\/\1>/i;
537
+ var REASONING_TAG_RE_G = /<(think|thinking|thought)>[\s\S]*?<\/\1>/gi;
538
+ function stripReasoningTags(content) {
539
+ if (typeof content !== "string" || !content.includes("<")) return content;
540
+ return content.replace(REASONING_TAG_RE_G, "").trim();
541
+ }
536
542
  async function processSingleMessage(task, ctx, providedMasterKey) {
537
543
  try {
538
544
  const masterKey = providedMasterKey || ctx.masterKey;
@@ -563,6 +569,10 @@ async function processSingleMessage(task, ctx, providedMasterKey) {
563
569
  } else {
564
570
  throw new Error("Invalid message configuration: no content source available");
565
571
  }
572
+ const reasoning = readReasoningContent(llmResponse);
573
+ if (reasoning) {
574
+ messageContent = stripReasoningTags(messageContent);
575
+ }
566
576
  const messages = splitMessageIntoSentences(messageContent, _nullishCoalesce(decryptedPayload.splitPattern, () => ( null)));
567
577
  if (!ctx.vapid.email || !ctx.vapid.publicKey || !ctx.vapid.privateKey) {
568
578
  throw new Error("VAPID configuration missing - push notifications cannot be sent");
@@ -574,7 +584,6 @@ async function processSingleMessage(task, ctx, providedMasterKey) {
574
584
  const avatarUrl = decryptedPayload.avatarUrl || null;
575
585
  const metadata = decryptedPayload.metadata || {};
576
586
  const messageIdBase = task.id != null ? `msg_task_${task.id}` : `msg_${_crypto.randomUUID.call(void 0, )}_instant`;
577
- const reasoning = readReasoningContent(llmResponse);
578
587
  if (reasoning) {
579
588
  const reasoningPush = _amsgshared.buildReasoningPush.call(void 0, {
580
589
  messageType: decryptedPayload.messageType,
package/dist/index.d.cts CHANGED
@@ -801,13 +801,13 @@ function isUniqueViolation(error) {
801
801
  * ReiStandard amsg-server v2.4.0
802
802
  *
803
803
  * Handles single message content generation and Web Push delivery for
804
- * scheduled tasks (`fixed` / `prompted` / `auto`) and the legacy
805
- * via-server instant path (`messageType: 'instant'`).
804
+ * scheduled tasks (`fixed` / `prompted` / `auto`) and the
805
+ * in-server instant path (`messageType: 'instant'`).
806
806
  *
807
807
  * Push wire shape comes from `@rei-standard/amsg-shared`'s
808
808
  * discriminated union (`AmsgPush`). The SW (`@rei-standard/amsg-sw`)
809
809
  * routes on `messageKind`. Server-driven pushes always carry
810
- * `source: 'instant'` (for the legacy in-server instant) or
810
+ * `source: 'instant'` (for the in-server instant path) or
811
811
  * `source: 'scheduled'` (for everything else).
812
812
  *
813
813
  * v2.4.0: when the LLM response carries non-empty
@@ -880,7 +880,7 @@ function readReasoningContent(llmResponse) {
880
880
  const choices = /** @type {{ choices?: unknown }} */ (llmResponse).choices;
881
881
  if (!Array.isArray(choices) || choices.length === 0) return null;
882
882
  const message = /** @type {{ message?: { reasoning_content?: unknown, content?: unknown } }} */ (choices[0])?.message;
883
-
883
+
884
884
  const raw = message?.reasoning_content;
885
885
  if (typeof raw === 'string') {
886
886
  const trimmed = raw.trim();
@@ -889,7 +889,7 @@ function readReasoningContent(llmResponse) {
889
889
 
890
890
  const content = message?.content;
891
891
  if (typeof content === 'string') {
892
- const match = content.match(/<(think|thinking|thought)>([\s\S]*?)<\/\1>/i);
892
+ const match = content.match(REASONING_TAG_RE);
893
893
  if (match) {
894
894
  const trimmed = match[2].trim();
895
895
  if (trimmed.length > 0) return trimmed;
@@ -899,6 +899,22 @@ function readReasoningContent(llmResponse) {
899
899
  return null;
900
900
  }
901
901
 
902
+ const REASONING_TAG_RE = /<(think|thinking|thought)>([\s\S]*?)<\/\1>/i;
903
+ const REASONING_TAG_RE_G = /<(think|thinking|thought)>[\s\S]*?<\/\1>/gi;
904
+
905
+ /**
906
+ * Mirrors `amsg-instant/src/message-processor.js#stripReasoningTags`.
907
+ * Removes any private chain-of-thought markup leaking through
908
+ * `message.content` so it does not also ship inside ContentPush.
909
+ *
910
+ * @param {string} content
911
+ * @returns {string}
912
+ */
913
+ function stripReasoningTags(content) {
914
+ if (typeof content !== 'string' || !content.includes('<')) return content;
915
+ return content.replace(REASONING_TAG_RE_G, '').trim();
916
+ }
917
+
902
918
  /**
903
919
  * @typedef {Object} ProcessorContext
904
920
  * @property {Object} webpush - The web-push module instance (already VAPID-configured).
@@ -952,6 +968,15 @@ async function processSingleMessage(task, ctx, providedMasterKey) {
952
968
  throw new Error('Invalid message configuration: no content source available');
953
969
  }
954
970
 
971
+ // Auto-extract reasoning BEFORE the sentence split: when reasoning
972
+ // came from the `<think>` fallback inside message.content, the same
973
+ // span is still embedded in messageContent and would otherwise leak
974
+ // as raw markup into ContentPush.
975
+ const reasoning = readReasoningContent(llmResponse);
976
+ if (reasoning) {
977
+ messageContent = stripReasoningTags(messageContent);
978
+ }
979
+
955
980
  // Sentence splitting (mirrors @rei-standard/amsg-instant
956
981
  // splitMessageIntoSentences — keep in lockstep; do not drift). Caller may
957
982
  // override the default regex via decryptedPayload.splitPattern (string
@@ -979,7 +1004,7 @@ async function processSingleMessage(task, ctx, providedMasterKey) {
979
1004
  // `messageId` format — deterministic when we have a task.id so a
980
1005
  // retry produces the same id for the same (task, sentence) pair
981
1006
  // (downstream dedupers can key on it). Falls back to a UUID for
982
- // the legacy in-server instant path that has no row id.
1007
+ // the in-server instant path that has no row id.
983
1008
  const messageIdBase = task.id != null
984
1009
  ? `msg_task_${task.id}`
985
1010
  : `msg_${randomUUID()}_instant`;
@@ -988,7 +1013,6 @@ async function processSingleMessage(task, ctx, providedMasterKey) {
988
1013
  // LLM response carried non-empty reasoning_content. `fixed` and
989
1014
  // explicit-userMessage paths produce no LLM response, so this
990
1015
  // block is naturally skipped for them (llmResponse stays null).
991
- const reasoning = readReasoningContent(llmResponse);
992
1016
  if (reasoning) {
993
1017
  const reasoningPush = buildReasoningPush({
994
1018
  messageType: decryptedPayload.messageType,
@@ -1374,12 +1398,20 @@ function createScheduleMessageHandler(ctx) {
1374
1398
  const encryptedPayload = encryptForStorage(JSON.stringify(fullTaskData), userKey);
1375
1399
 
1376
1400
  /**
1377
- * @deprecated Soft-deprecated. For new code, use @rei-standard/amsg-instant.
1378
- * This branch is kept for backward compatibility and the existing behavior
1379
- * (create task → process → delete) is unchanged. The dedicated amsg-instant
1380
- * package is stateless (no DB roundtrip), deployable to Cloudflare Workers,
1381
- * and locks the encryption + push-payload contract behind a single version.
1382
- * See packages/rei-standard-amsg/instant/README.md.
1401
+ * In-server instant path. Delivers an instant message through this
1402
+ * server's own task queue (create task → process by UUID → delete task).
1403
+ * The task is written to the database before processing, so delivery is
1404
+ * not tied to the request connection: even if the client disconnects, the
1405
+ * row stays and the generation keeps running (and can be retried) for as
1406
+ * long as it needs. Use this when you have a database and want long or
1407
+ * guaranteed-complete generations with no dropped messages.
1408
+ *
1409
+ * The stateless alternative is `@rei-standard/amsg-instant`: it streams
1410
+ * over SSE with a Web Push backup and needs no database, which makes it a
1411
+ * good fit for edge runtimes (e.g. Cloudflare Workers). Its work rides the
1412
+ * response connection, so after the client disconnects it only has the
1413
+ * platform's brief grace window to finish (≈20-30s observed on Deno
1414
+ * Deploy) — ideal for short instant messages that complete quickly.
1383
1415
  */
1384
1416
  // Instant type: check VAPID before creating the task to avoid orphaned rows
1385
1417
  if (payload.messageType === 'instant') {
@@ -1435,11 +1467,20 @@ function createScheduleMessageHandler(ctx) {
1435
1467
  }
1436
1468
 
1437
1469
  /**
1438
- * @deprecated Soft-deprecated. For new code, use @rei-standard/amsg-instant.
1439
- * The "create-task → process-by-uuid → delete-task" sequence below is
1440
- * preserved verbatim so existing clients keep working. New integrations
1441
- * should call the dedicated amsg-instant endpoint instead — it skips this
1442
- * DB round-trip entirely. See packages/rei-standard-amsg/instant/README.md.
1470
+ * In-server instant path. Delivers an instant message through this
1471
+ * server's own task queue (create task → process by UUID → delete task).
1472
+ * The task is written to the database before processing, so delivery is
1473
+ * not tied to the request connection: even if the client disconnects, the
1474
+ * row stays and the generation keeps running (and can be retried) for as
1475
+ * long as it needs. Use this when you have a database and want long or
1476
+ * guaranteed-complete generations with no dropped messages.
1477
+ *
1478
+ * The stateless alternative is `@rei-standard/amsg-instant`: it streams
1479
+ * over SSE with a Web Push backup and needs no database, which makes it a
1480
+ * good fit for edge runtimes (e.g. Cloudflare Workers). Its work rides the
1481
+ * response connection, so after the client disconnects it only has the
1482
+ * platform's brief grace window to finish (≈20-30s observed on Deno
1483
+ * Deploy) — ideal for short instant messages that complete quickly.
1443
1484
  */
1444
1485
  // Instant type: send immediately
1445
1486
  if (payload.messageType === 'instant') {
package/dist/index.d.ts CHANGED
@@ -801,13 +801,13 @@ function isUniqueViolation(error) {
801
801
  * ReiStandard amsg-server v2.4.0
802
802
  *
803
803
  * Handles single message content generation and Web Push delivery for
804
- * scheduled tasks (`fixed` / `prompted` / `auto`) and the legacy
805
- * via-server instant path (`messageType: 'instant'`).
804
+ * scheduled tasks (`fixed` / `prompted` / `auto`) and the
805
+ * in-server instant path (`messageType: 'instant'`).
806
806
  *
807
807
  * Push wire shape comes from `@rei-standard/amsg-shared`'s
808
808
  * discriminated union (`AmsgPush`). The SW (`@rei-standard/amsg-sw`)
809
809
  * routes on `messageKind`. Server-driven pushes always carry
810
- * `source: 'instant'` (for the legacy in-server instant) or
810
+ * `source: 'instant'` (for the in-server instant path) or
811
811
  * `source: 'scheduled'` (for everything else).
812
812
  *
813
813
  * v2.4.0: when the LLM response carries non-empty
@@ -880,7 +880,7 @@ function readReasoningContent(llmResponse) {
880
880
  const choices = /** @type {{ choices?: unknown }} */ (llmResponse).choices;
881
881
  if (!Array.isArray(choices) || choices.length === 0) return null;
882
882
  const message = /** @type {{ message?: { reasoning_content?: unknown, content?: unknown } }} */ (choices[0])?.message;
883
-
883
+
884
884
  const raw = message?.reasoning_content;
885
885
  if (typeof raw === 'string') {
886
886
  const trimmed = raw.trim();
@@ -889,7 +889,7 @@ function readReasoningContent(llmResponse) {
889
889
 
890
890
  const content = message?.content;
891
891
  if (typeof content === 'string') {
892
- const match = content.match(/<(think|thinking|thought)>([\s\S]*?)<\/\1>/i);
892
+ const match = content.match(REASONING_TAG_RE);
893
893
  if (match) {
894
894
  const trimmed = match[2].trim();
895
895
  if (trimmed.length > 0) return trimmed;
@@ -899,6 +899,22 @@ function readReasoningContent(llmResponse) {
899
899
  return null;
900
900
  }
901
901
 
902
+ const REASONING_TAG_RE = /<(think|thinking|thought)>([\s\S]*?)<\/\1>/i;
903
+ const REASONING_TAG_RE_G = /<(think|thinking|thought)>[\s\S]*?<\/\1>/gi;
904
+
905
+ /**
906
+ * Mirrors `amsg-instant/src/message-processor.js#stripReasoningTags`.
907
+ * Removes any private chain-of-thought markup leaking through
908
+ * `message.content` so it does not also ship inside ContentPush.
909
+ *
910
+ * @param {string} content
911
+ * @returns {string}
912
+ */
913
+ function stripReasoningTags(content) {
914
+ if (typeof content !== 'string' || !content.includes('<')) return content;
915
+ return content.replace(REASONING_TAG_RE_G, '').trim();
916
+ }
917
+
902
918
  /**
903
919
  * @typedef {Object} ProcessorContext
904
920
  * @property {Object} webpush - The web-push module instance (already VAPID-configured).
@@ -952,6 +968,15 @@ async function processSingleMessage(task, ctx, providedMasterKey) {
952
968
  throw new Error('Invalid message configuration: no content source available');
953
969
  }
954
970
 
971
+ // Auto-extract reasoning BEFORE the sentence split: when reasoning
972
+ // came from the `<think>` fallback inside message.content, the same
973
+ // span is still embedded in messageContent and would otherwise leak
974
+ // as raw markup into ContentPush.
975
+ const reasoning = readReasoningContent(llmResponse);
976
+ if (reasoning) {
977
+ messageContent = stripReasoningTags(messageContent);
978
+ }
979
+
955
980
  // Sentence splitting (mirrors @rei-standard/amsg-instant
956
981
  // splitMessageIntoSentences — keep in lockstep; do not drift). Caller may
957
982
  // override the default regex via decryptedPayload.splitPattern (string
@@ -979,7 +1004,7 @@ async function processSingleMessage(task, ctx, providedMasterKey) {
979
1004
  // `messageId` format — deterministic when we have a task.id so a
980
1005
  // retry produces the same id for the same (task, sentence) pair
981
1006
  // (downstream dedupers can key on it). Falls back to a UUID for
982
- // the legacy in-server instant path that has no row id.
1007
+ // the in-server instant path that has no row id.
983
1008
  const messageIdBase = task.id != null
984
1009
  ? `msg_task_${task.id}`
985
1010
  : `msg_${randomUUID()}_instant`;
@@ -988,7 +1013,6 @@ async function processSingleMessage(task, ctx, providedMasterKey) {
988
1013
  // LLM response carried non-empty reasoning_content. `fixed` and
989
1014
  // explicit-userMessage paths produce no LLM response, so this
990
1015
  // block is naturally skipped for them (llmResponse stays null).
991
- const reasoning = readReasoningContent(llmResponse);
992
1016
  if (reasoning) {
993
1017
  const reasoningPush = buildReasoningPush({
994
1018
  messageType: decryptedPayload.messageType,
@@ -1374,12 +1398,20 @@ function createScheduleMessageHandler(ctx) {
1374
1398
  const encryptedPayload = encryptForStorage(JSON.stringify(fullTaskData), userKey);
1375
1399
 
1376
1400
  /**
1377
- * @deprecated Soft-deprecated. For new code, use @rei-standard/amsg-instant.
1378
- * This branch is kept for backward compatibility and the existing behavior
1379
- * (create task → process → delete) is unchanged. The dedicated amsg-instant
1380
- * package is stateless (no DB roundtrip), deployable to Cloudflare Workers,
1381
- * and locks the encryption + push-payload contract behind a single version.
1382
- * See packages/rei-standard-amsg/instant/README.md.
1401
+ * In-server instant path. Delivers an instant message through this
1402
+ * server's own task queue (create task → process by UUID → delete task).
1403
+ * The task is written to the database before processing, so delivery is
1404
+ * not tied to the request connection: even if the client disconnects, the
1405
+ * row stays and the generation keeps running (and can be retried) for as
1406
+ * long as it needs. Use this when you have a database and want long or
1407
+ * guaranteed-complete generations with no dropped messages.
1408
+ *
1409
+ * The stateless alternative is `@rei-standard/amsg-instant`: it streams
1410
+ * over SSE with a Web Push backup and needs no database, which makes it a
1411
+ * good fit for edge runtimes (e.g. Cloudflare Workers). Its work rides the
1412
+ * response connection, so after the client disconnects it only has the
1413
+ * platform's brief grace window to finish (≈20-30s observed on Deno
1414
+ * Deploy) — ideal for short instant messages that complete quickly.
1383
1415
  */
1384
1416
  // Instant type: check VAPID before creating the task to avoid orphaned rows
1385
1417
  if (payload.messageType === 'instant') {
@@ -1435,11 +1467,20 @@ function createScheduleMessageHandler(ctx) {
1435
1467
  }
1436
1468
 
1437
1469
  /**
1438
- * @deprecated Soft-deprecated. For new code, use @rei-standard/amsg-instant.
1439
- * The "create-task → process-by-uuid → delete-task" sequence below is
1440
- * preserved verbatim so existing clients keep working. New integrations
1441
- * should call the dedicated amsg-instant endpoint instead — it skips this
1442
- * DB round-trip entirely. See packages/rei-standard-amsg/instant/README.md.
1470
+ * In-server instant path. Delivers an instant message through this
1471
+ * server's own task queue (create task → process by UUID → delete task).
1472
+ * The task is written to the database before processing, so delivery is
1473
+ * not tied to the request connection: even if the client disconnects, the
1474
+ * row stays and the generation keeps running (and can be retried) for as
1475
+ * long as it needs. Use this when you have a database and want long or
1476
+ * guaranteed-complete generations with no dropped messages.
1477
+ *
1478
+ * The stateless alternative is `@rei-standard/amsg-instant`: it streams
1479
+ * over SSE with a Web Push backup and needs no database, which makes it a
1480
+ * good fit for edge runtimes (e.g. Cloudflare Workers). Its work rides the
1481
+ * response connection, so after the client disconnects it only has the
1482
+ * platform's brief grace window to finish (≈20-30s observed on Deno
1483
+ * Deploy) — ideal for short instant messages that complete quickly.
1443
1484
  */
1444
1485
  // Instant type: send immediately
1445
1486
  if (payload.messageType === 'instant') {
package/dist/index.mjs CHANGED
@@ -525,7 +525,7 @@ function readReasoningContent(llmResponse) {
525
525
  }
526
526
  const content = message?.content;
527
527
  if (typeof content === "string") {
528
- const match = content.match(/<(think|thinking|thought)>([\s\S]*?)<\/\1>/i);
528
+ const match = content.match(REASONING_TAG_RE);
529
529
  if (match) {
530
530
  const trimmed = match[2].trim();
531
531
  if (trimmed.length > 0) return trimmed;
@@ -533,6 +533,12 @@ function readReasoningContent(llmResponse) {
533
533
  }
534
534
  return null;
535
535
  }
536
+ var REASONING_TAG_RE = /<(think|thinking|thought)>([\s\S]*?)<\/\1>/i;
537
+ var REASONING_TAG_RE_G = /<(think|thinking|thought)>[\s\S]*?<\/\1>/gi;
538
+ function stripReasoningTags(content) {
539
+ if (typeof content !== "string" || !content.includes("<")) return content;
540
+ return content.replace(REASONING_TAG_RE_G, "").trim();
541
+ }
536
542
  async function processSingleMessage(task, ctx, providedMasterKey) {
537
543
  try {
538
544
  const masterKey = providedMasterKey || ctx.masterKey;
@@ -563,6 +569,10 @@ async function processSingleMessage(task, ctx, providedMasterKey) {
563
569
  } else {
564
570
  throw new Error("Invalid message configuration: no content source available");
565
571
  }
572
+ const reasoning = readReasoningContent(llmResponse);
573
+ if (reasoning) {
574
+ messageContent = stripReasoningTags(messageContent);
575
+ }
566
576
  const messages = splitMessageIntoSentences(messageContent, decryptedPayload.splitPattern ?? null);
567
577
  if (!ctx.vapid.email || !ctx.vapid.publicKey || !ctx.vapid.privateKey) {
568
578
  throw new Error("VAPID configuration missing - push notifications cannot be sent");
@@ -574,7 +584,6 @@ async function processSingleMessage(task, ctx, providedMasterKey) {
574
584
  const avatarUrl = decryptedPayload.avatarUrl || null;
575
585
  const metadata = decryptedPayload.metadata || {};
576
586
  const messageIdBase = task.id != null ? `msg_task_${task.id}` : `msg_${randomUUID()}_instant`;
577
- const reasoning = readReasoningContent(llmResponse);
578
587
  if (reasoning) {
579
588
  const reasoningPush = buildReasoningPush({
580
589
  messageType: decryptedPayload.messageType,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rei-standard/amsg-server",
3
- "version": "2.5.0",
3
+ "version": "2.5.2",
4
4
  "description": "ReiStandard Active Messaging server SDK with pluggable database adapters. Three-axis push schema (messageKind / messageType / messageSubtype) from @rei-standard/amsg-shared. Auto-emits ReasoningPush when the LLM response carries reasoning_content.",
5
5
  "repository": {
6
6
  "type": "git",