queued-message-wrapper.ts 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. /**
  2. * `<queued-user-message>` — out-of-band user input that arrived mid-turn.
  3. *
  4. * When a user types into Web (or any inbound source) while an agent's turn
  5. * is still running, the daemon parks the message on `SessionInboundQueue`.
  6. * Path A (local legacy local runtime) and Path B (cloud pi) both drain those queued
  7. * items at a turn-loop boundary and inject them back to the model as a
  8. * fresh `role:"user"` message. To keep the model honest about provenance,
  9. * the injected text is wrapped in `<queued-user-message>...</queued-user-message>`
  10. * — the model can see the inner content but knows it was inserted out of
  11. * band, not as the original prompt of the current turn.
  12. *
  13. * Anti-spoofing: user text might itself contain literal `<queued-user-message>`
  14. * tags (legitimately discussing the feature, or maliciously trying to fake
  15. * an out-of-band insertion to elevate priority / override prior instructions).
  16. * Before wrapping, the helper escapes any embedded opening / closing tags so
  17. * the only real wrapper boundary is the one this helper generates. The
  18. * regex is case-insensitive and attribute-tolerant to match the wrapping
  19. * shape produced by `wrapQueuedMessageText`.
  20. *
  21. * This module is framework-agnostic (no daemon / legacy local-runtime plugin /
  22. * cloud-runtime imports) so both injection paths can reuse it without
  23. * duplicating regex.
  24. */
  25. /** Tag name — keep in one place; changing it requires updating both injection paths. */
  26. export const QUEUED_USER_MESSAGE_TAG = 'queued-user-message';
  27. /**
  28. * Match any literal `<queued-user-message ...>` or `</queued-user-message>`
  29. * sequence the user might have typed verbatim. Case-insensitive, attribute-
  30. * tolerant, and matches both open and close forms in one pass so the
  31. * sanitizer is a single-replace.
  32. */
  33. const QUEUED_USER_MESSAGE_TAG_RE = /<\/?queued-user-message\b[^>]*>/giu;
  34. /**
  35. * Replace any literal opening / closing `<queued-user-message>` tag in `text`
  36. * with an escaped form (`&lt;queued-user-message&gt;` / `&lt;/queued-user-message&gt;`)
  37. * so the only real wrapper boundary is the one `wrapQueuedMessageText`
  38. * inserts. Idempotent on already-escaped input (`&lt;...&gt;` does not
  39. * contain `<`).
  40. */
  41. export function escapeQueuedUserMessageTags(text: string): string {
  42. if (!text) return '';
  43. return text.replace(QUEUED_USER_MESSAGE_TAG_RE, (match) => {
  44. // Replace `<` and `>` only — preserve everything in between verbatim.
  45. return match.replace(/</gu, '&lt;').replace(/>/gu, '&gt;');
  46. });
  47. }
  48. /** Metadata stamped onto a wrapped queued user message. Optional fields are
  49. * emitted as attributes only when non-empty so the wrapped form stays
  50. * compact for the common case (text-only Web message). */
  51. export interface QueuedMessageMetadata {
  52. /** Inbound source — `'api'` for Web, `'channel:feishu'` for IM, etc. */
  53. source?: string;
  54. /** Queue item id from `SessionInboundQueue`. Useful for debugging /
  55. * correlating logs across daemon → plugin → model output. */
  56. itemId?: string;
  57. /** Original enqueue timestamp (Unix ms). Lets the model see how stale
  58. * the message is by the time injection happens. */
  59. enqueuedAtMs?: number;
  60. }
  61. /** Escape a value so it is safe to embed inside an XML attribute. Replaces
  62. * the four characters that break attribute parsing. Conservative — keeps
  63. * Unicode and whitespace as-is. */
  64. function escapeAttributeValue(value: string): string {
  65. return value
  66. .replace(/&/gu, '&amp;')
  67. .replace(/"/gu, '&quot;')
  68. .replace(/</gu, '&lt;')
  69. .replace(/>/gu, '&gt;');
  70. }
  71. /**
  72. * Wrap a single drained user message in `<queued-user-message>` with metadata
  73. * attributes. Input text is sanitized first so embedded tags cannot fake an
  74. * outer boundary. Returns a single line of XML-ish text suitable for
  75. * appending directly to an assistant transcript as `role:"user"` content.
  76. *
  77. * Empty / whitespace-only input returns an empty string — caller should
  78. * skip injection entirely instead of emitting an empty wrapper.
  79. */
  80. export function wrapQueuedMessageText(text: string, metadata: QueuedMessageMetadata = {}): string {
  81. if (!text || !text.trim()) return '';
  82. const safeBody = escapeQueuedUserMessageTags(text);
  83. const attrs: string[] = [];
  84. if (metadata.source) attrs.push(`source="${escapeAttributeValue(metadata.source)}"`);
  85. if (metadata.itemId) attrs.push(`item-id="${escapeAttributeValue(metadata.itemId)}"`);
  86. if (metadata.enqueuedAtMs && Number.isFinite(metadata.enqueuedAtMs)) {
  87. attrs.push(`enqueued-at-ms="${metadata.enqueuedAtMs}"`);
  88. }
  89. const attrSuffix = attrs.length > 0 ? ` ${attrs.join(' ')}` : '';
  90. return `<${QUEUED_USER_MESSAGE_TAG}${attrSuffix}>\n${safeBody}\n</${QUEUED_USER_MESSAGE_TAG}>`;
  91. }
  92. /** Concatenate multiple wrapped queued messages with a blank line between
  93. * them so the model sees each one as a distinct out-of-band insertion.
  94. * Drops empty entries silently. */
  95. export function wrapQueuedMessageBatch(
  96. items: Array<{ text: string; metadata?: QueuedMessageMetadata }>,
  97. ): string {
  98. const wrapped = items
  99. .map((item) => wrapQueuedMessageText(item.text, item.metadata))
  100. .filter((text) => text.length > 0);
  101. return wrapped.join('\n\n');
  102. }