@primusclaw/personal-agent-teams 0.11.0 → 0.12.0

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/dist/index.js CHANGED
@@ -667,8 +667,8 @@ function streamActivity(kind, text4, replyTo, sequence, streamId = "") {
667
667
  return { type: "typing", text: text4, replyToId: replyTo, entities: [info] };
668
668
  }
669
669
  function streamFinal(activity, replyTo, streamId) {
670
- const own13 = Array.isArray(activity["entities"]) ? activity["entities"] : [];
671
- const entities = own13.filter((e) => !(isObject(e) && e["type"] === STREAM_ENTITY_TYPE));
670
+ const own14 = Array.isArray(activity["entities"]) ? activity["entities"] : [];
671
+ const entities = own14.filter((e) => !(isObject(e) && e["type"] === STREAM_ENTITY_TYPE));
672
672
  const final = { type: STREAM_ENTITY_TYPE, streamType: "final", streamId };
673
673
  return { ...activity, type: "message", replyToId: replyTo, entities: [final, ...entities] };
674
674
  }
@@ -3841,6 +3841,7 @@ function voteOf(activity) {
3841
3841
  import { z as z3 } from "zod";
3842
3842
  import { cpHead, pyStr as pyStr5 } from "@primusclaw/personal-agent";
3843
3843
  var FILE_DOWNLOAD_INFO = "application/vnd.microsoft.teams.file.download.info";
3844
+ var NOT_FILES = /* @__PURE__ */ new Set(["text/html", "forwardedmessagereference"]);
3844
3845
  var teamsFileHandle = z3.object({
3845
3846
  kind: z3.enum(["pasted", "download"]),
3846
3847
  url: z3.string(),
@@ -3881,7 +3882,7 @@ function inboundFiles(activity) {
3881
3882
  files.push(teamsFile(name, "", { kind: "pasted", url: contentUrl, index }));
3882
3883
  } else if (kind === FILE_DOWNLOAD_INFO && typeof downloadUrl === "string") {
3883
3884
  files.push(teamsFile(name, sentFileType(content["fileType"]), { kind: "download", url: downloadUrl, index }));
3884
- } else if (name && kind !== "text/html" && !kind.startsWith("application/vnd.microsoft.card.")) {
3885
+ } else if (name && !NOT_FILES.has(kind) && !kind.startsWith("application/vnd.microsoft.card.")) {
3885
3886
  unreadable.push(name);
3886
3887
  }
3887
3888
  }
@@ -3892,7 +3893,7 @@ function inboundFiles(activity) {
3892
3893
  import {
3893
3894
  err as err3,
3894
3895
  ok as ok3,
3895
- pyStr as pyStr13,
3896
+ pyStr as pyStr14,
3896
3897
  silentLogger as silentLogger5
3897
3898
  } from "@primusclaw/personal-agent";
3898
3899
 
@@ -3948,50 +3949,200 @@ function cardVerb(activity) {
3948
3949
  return cpHead2(pyStr6(verb) || "unknown", 40);
3949
3950
  }
3950
3951
 
3951
- // packages/teams/src/activity/inbound/identity.ts
3952
- import { cpHead as cpHead3, pyStr as pyStr7, pyStrip as pyStrip5 } from "@primusclaw/personal-agent";
3953
- function senderOf(activity) {
3954
- const who = partOf(activity, "from");
3955
- const aadId = who["aadObjectId"];
3956
- if (typeof aadId !== "string" || !aadId) return void 0;
3957
- const email = pyStrip5(pyStr7(who["userPrincipalName"]) || pyStr7(who["email"]));
3958
- return { aadId, name: pyStr7(who["name"]), email: email.includes("@") ? email : "" };
3952
+ // packages/teams/src/activity/inbound/forwards.ts
3953
+ import {
3954
+ isPySpace as isPySpace2,
3955
+ own as own10,
3956
+ pySplit as pySplit2,
3957
+ pyStr as pyStr10,
3958
+ squashSpaces as squashSpaces5
3959
+ } from "@primusclaw/personal-agent";
3960
+
3961
+ // packages/teams/src/activity/inbound/markup.ts
3962
+ import { cpLength as cpLength6, pyStr as pyStr7, pyStrip as pyStrip5 } from "@primusclaw/personal-agent";
3963
+
3964
+ // packages/teams/src/activity/inbound/patterns.ts
3965
+ import { own as own8 } from "@primusclaw/personal-agent";
3966
+ var SPACE_CHARS = "\\t\\n\\v\\f\\r\\x1c-\\x20\\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
3967
+ var SPACE = `[${SPACE_CHARS}]`;
3968
+ var WORD = "[\\p{L}\\p{N}_]";
3969
+ var NOT_WORD_NEXT = `(?!${WORD})`;
3970
+ var FOLDS = { i: "\\u0130\\u0131", k: "\\u212a", s: "\\u017f" };
3971
+ var SYNTAX = /[\\^$.*+?()[\]{}|/]/;
3972
+ function literalChar(ch) {
3973
+ return SYNTAX.test(ch) ? `\\${ch}` : ch;
3959
3974
  }
3960
- function conversationType(activity) {
3961
- return partOf(activity, "conversation")["conversationType"];
3975
+ function caseless(literal) {
3976
+ let source = "";
3977
+ for (const ch of literal) {
3978
+ const lower = ch.toLowerCase();
3979
+ const upper = ch.toUpperCase();
3980
+ if (lower === upper || Array.from(lower).length > 1 || Array.from(upper).length > 1) {
3981
+ source += literalChar(ch);
3982
+ continue;
3983
+ }
3984
+ source += `[${lower}${upper}${own8(FOLDS, lower) ?? ""}]`;
3985
+ }
3986
+ return source;
3962
3987
  }
3963
- function isPersonal(activity) {
3964
- return conversationType(activity) === "personal";
3988
+
3989
+ // packages/teams/src/activity/inbound/markup.ts
3990
+ var AT_TAG = /<\/?[Aa][Tt]>/g;
3991
+ var LINK_CHARS = 2e3;
3992
+ var WEB_URL = new RegExp(`^${caseless("http")}${caseless("s")}?://[^${SPACE_CHARS}<>"']+$`, "u");
3993
+ function webUrl(raw) {
3994
+ const url = typeof raw === "string" ? pyStrip5(raw) : "";
3995
+ return cpLength6(url) <= LINK_CHARS && WEB_URL.test(url) ? url : "";
3965
3996
  }
3966
- function isGroup(activity) {
3967
- return conversationType(activity) === "groupChat";
3997
+ function findTags(text4, names, closing) {
3998
+ const head = new RegExp(`${closing ? "(/?)" : "()"}(?:${names.map(caseless).join("|")})${NOT_WORD_NEXT}`, "uy");
3999
+ const found = [];
4000
+ let gt = -1;
4001
+ let at = text4.indexOf("<");
4002
+ while (at >= 0) {
4003
+ head.lastIndex = at + 1;
4004
+ const match = head.exec(text4);
4005
+ if (match) {
4006
+ const nameEnd = head.lastIndex;
4007
+ if (gt < nameEnd) gt = text4.indexOf(">", nameEnd);
4008
+ if (gt < 0) break;
4009
+ found.push({ start: at, end: gt + 1, closing: match[1] === "/", attrs: text4.slice(nameEnd, gt) });
4010
+ at = text4.indexOf("<", gt + 1);
4011
+ } else {
4012
+ at = text4.indexOf("<", at + 1);
4013
+ }
4014
+ }
4015
+ return found;
3968
4016
  }
3969
- function conversationKind(activity) {
3970
- if (isPersonal(activity)) return "personal";
3971
- return isGroup(activity) ? "group" : "channel";
4017
+ function replaceTags(text4, tags, by) {
4018
+ let out = "";
4019
+ let resume = 0;
4020
+ for (const tag of tags) {
4021
+ out += text4.slice(resume, tag.start) + by;
4022
+ resume = tag.end;
4023
+ }
4024
+ return out + text4.slice(resume);
3972
4025
  }
3973
- function conversationId(activity) {
3974
- return pyStr7(partOf(activity, "conversation")["id"]);
4026
+ var REPLY_ITEMTYPE = new RegExp(caseless("schema.skype.com/Reply"), "u");
4027
+ var FORWARD_ITEMTYPE = new RegExp(caseless("schema.skype.com/Forward"), "u");
4028
+ function cutReplies(markup) {
4029
+ return cutBlockquotes(markup, REPLY_ITEMTYPE);
3975
4030
  }
3976
- function tenantOf(activity) {
3977
- const channelData = activity.channelData;
3978
- const tenant = isFields(channelData) ? channelData["tenant"] : void 0;
3979
- const fromChannel = isFields(tenant) ? tenant["id"] : void 0;
3980
- return pyStr7(partOf(activity, "conversation")["tenantId"]) || pyStr7(fromChannel);
4031
+ function cutForwards(markup) {
4032
+ return cutBlockquotes(markup, FORWARD_ITEMTYPE);
3981
4033
  }
3982
- var ALNUM2 = /[\p{L}\p{N}]/u;
3983
- function clientPlatform(activity) {
3984
- const info = entitiesOf2(activity).find((entity) => entity["type"] === "clientInfo");
3985
- const platform = info?.["platform"];
3986
- if (typeof platform !== "string") return "";
3987
- return cpHead3(
3988
- Array.from(platform).filter((ch) => ALNUM2.test(ch)).join(""),
3989
- 16
3990
- );
4034
+ function cutBlockquotes(markup, itemtype) {
4035
+ const kept = [];
4036
+ const cut = [];
4037
+ let depth = 0;
4038
+ let attrs = "";
4039
+ let start = 0;
4040
+ let resume = 0;
4041
+ for (const tag of findTags(markup, ["blockquote"], true)) {
4042
+ if (depth === 0) {
4043
+ if (!tag.closing && itemtype.test(tag.attrs)) {
4044
+ kept.push(markup.slice(resume, tag.start));
4045
+ [depth, attrs, start] = [1, tag.attrs, tag.end];
4046
+ }
4047
+ continue;
4048
+ }
4049
+ depth += tag.closing ? -1 : 1;
4050
+ if (depth === 0) {
4051
+ cut.push([attrs, markup.slice(start, tag.start)]);
4052
+ resume = tag.end;
4053
+ }
4054
+ }
4055
+ if (depth) {
4056
+ cut.push([attrs, markup.slice(start)]);
4057
+ resume = markup.length;
4058
+ }
4059
+ kept.push(markup.slice(resume));
4060
+ return { kept: kept.join(""), cut };
4061
+ }
4062
+ function written(activity) {
4063
+ let text4 = pyStr7(activity.text);
4064
+ const reply = REPLY_ITEMTYPE.test(text4);
4065
+ const forward = FORWARD_ITEMTYPE.test(text4);
4066
+ if (reply || forward) {
4067
+ let kept = forward ? cutForwards(text4).kept : text4;
4068
+ kept = reply ? cutReplies(kept).kept : kept;
4069
+ text4 = replaceTags(kept, findTags(kept, ["p", "div", "br", "span"], true), " ");
4070
+ }
4071
+ text4 = replaceTags(text4, findTags(text4, ["attachment"], true), "");
4072
+ return replaceTags(text4, findTags(text4, ["quoted"], true), "");
4073
+ }
4074
+ var MESSAGE_ID = new RegExp(caseless("messageId"), "gu");
4075
+ var SPACE_ONE = new RegExp(`^${SPACE}$`, "u");
4076
+ function idHeadEnd(text4, at) {
4077
+ let i = at;
4078
+ while (i < text4.length && SPACE_ONE.test(text4.charAt(i))) i += 1;
4079
+ if (text4.charAt(i) !== "=") return void 0;
4080
+ i += 1;
4081
+ while (i < text4.length && SPACE_ONE.test(text4.charAt(i))) i += 1;
4082
+ return text4.charAt(i) === '"' || text4.charAt(i) === "'" ? i + 1 : i;
4083
+ }
4084
+ var VALUE_STOP = new RegExp(`["'/>${SPACE_CHARS}]`, "u");
4085
+ var WORD_CHAR = new RegExp(`^${WORD}$`, "u");
4086
+ function valueEnds(text4) {
4087
+ let runStart = 0;
4088
+ let runEnd = -1;
4089
+ return (at) => {
4090
+ if (at >= runStart && at < runEnd) return runEnd;
4091
+ let end = at;
4092
+ while (end < text4.length && !VALUE_STOP.test(text4[end] ?? "")) end++;
4093
+ [runStart, runEnd] = [at, end];
4094
+ return end;
4095
+ };
4096
+ }
4097
+ function codePointBefore(text4, at) {
4098
+ if (at <= 0) return void 0;
4099
+ const low = text4.charCodeAt(at - 1);
4100
+ const pair = low >= 56320 && low <= 57343 && at >= 2 ? text4.slice(at - 2, at) : text4.slice(at - 1, at);
4101
+ return Array.from(pair).at(-1);
4102
+ }
4103
+ function idCandidates(text4) {
4104
+ const end = valueEnds(text4);
4105
+ const found = [];
4106
+ for (const match of text4.matchAll(MESSAGE_ID)) {
4107
+ const before = codePointBefore(text4, match.index);
4108
+ if (before !== void 0 && WORD_CHAR.test(before)) continue;
4109
+ const valueStart = idHeadEnd(text4, match.index + match[0].length);
4110
+ if (valueStart === void 0) continue;
4111
+ const valueEnd = end(valueStart);
4112
+ if (valueEnd > valueStart) found.push({ start: match.index, valueStart, valueEnd });
4113
+ }
4114
+ return found;
4115
+ }
4116
+ function quotedIds(text4) {
4117
+ const candidates = idCandidates(text4);
4118
+ const ids = [];
4119
+ let next = 0;
4120
+ let resume = 0;
4121
+ let gt = -1;
4122
+ for (const tag of quotedStarts(text4)) {
4123
+ if (tag.start < resume) continue;
4124
+ if (gt < tag.nameEnd) gt = text4.indexOf(">", tag.nameEnd);
4125
+ const segmentEnd = gt < 0 ? text4.length : gt;
4126
+ while (next < candidates.length && (candidates[next]?.start ?? 0) < tag.nameEnd) next++;
4127
+ const found = candidates[next];
4128
+ if (found === void 0 || found.start >= segmentEnd) continue;
4129
+ ids.push(text4.slice(found.valueStart, found.valueEnd));
4130
+ resume = found.valueEnd;
4131
+ }
4132
+ return ids;
4133
+ }
4134
+ var QUOTED_HEAD = new RegExp(`${caseless("quoted")}${NOT_WORD_NEXT}`, "uy");
4135
+ function quotedStarts(text4) {
4136
+ const starts = [];
4137
+ for (let at = text4.indexOf("<"); at >= 0; at = text4.indexOf("<", at + 1)) {
4138
+ QUOTED_HEAD.lastIndex = at + 1;
4139
+ if (QUOTED_HEAD.test(text4)) starts.push({ start: at, nameEnd: QUOTED_HEAD.lastIndex });
4140
+ }
4141
+ return starts;
3991
4142
  }
3992
4143
 
3993
- // packages/teams/src/activity/inbound/links.ts
3994
- import { pyStr as pyStr9, squashSpaces as squashSpaces3 } from "@primusclaw/personal-agent";
4144
+ // packages/teams/src/activity/inbound/quotes-html.ts
4145
+ import { pyStr as pyStr8, squashSpaces as squashSpaces3 } from "@primusclaw/personal-agent";
3995
4146
 
3996
4147
  // packages/teams/src/html/html5-entities.ts
3997
4148
  var HTML5_ENTITIES = "AElig=C6|AElig;=C6|AMP=26|AMP;=26|Aacute=C1|Aacute;=C1|Abreve;=102|Acirc=C2|Acirc;=C2|Acy;=410|Afr;=1D504|Agrave=C0|Agrave;=C0|Alpha;=391|Amacr;=100|And;=2A53|Aogon;=104|Aopf;=1D538|ApplyFunction;=2061|Aring=C5|Aring;=C5|Ascr;=1D49C|Assign;=2254|Atilde=C3|Atilde;=C3|Auml=C4|Auml;=C4|Backslash;=2216|Barv;=2AE7|Barwed;=2306|Bcy;=411|Because;=2235|Bernoullis;=212C|Beta;=392|Bfr;=1D505|Bopf;=1D539|Breve;=2D8|Bscr;=212C|Bumpeq;=224E|CHcy;=427|COPY=A9|COPY;=A9|Cacute;=106|Cap;=22D2|CapitalDifferentialD;=2145|Cayleys;=212D|Ccaron;=10C|Ccedil=C7|Ccedil;=C7|Ccirc;=108|Cconint;=2230|Cdot;=10A|Cedilla;=B8|CenterDot;=B7|Cfr;=212D|Chi;=3A7|CircleDot;=2299|CircleMinus;=2296|CirclePlus;=2295|CircleTimes;=2297|ClockwiseContourIntegral;=2232|CloseCurlyDoubleQuote;=201D|CloseCurlyQuote;=2019|Colon;=2237|Colone;=2A74|Congruent;=2261|Conint;=222F|ContourIntegral;=222E|Copf;=2102|Coproduct;=2210|CounterClockwiseContourIntegral;=2233|Cross;=2A2F|Cscr;=1D49E|Cup;=22D3|CupCap;=224D|DD;=2145|DDotrahd;=2911|DJcy;=402|DScy;=405|DZcy;=40F|Dagger;=2021|Darr;=21A1|Dashv;=2AE4|Dcaron;=10E|Dcy;=414|Del;=2207|Delta;=394|Dfr;=1D507|DiacriticalAcute;=B4|DiacriticalDot;=2D9|DiacriticalDoubleAcute;=2DD|DiacriticalGrave;=60|DiacriticalTilde;=2DC|Diamond;=22C4|DifferentialD;=2146|Dopf;=1D53B|Dot;=A8|DotDot;=20DC|DotEqual;=2250|DoubleContourIntegral;=222F|DoubleDot;=A8|DoubleDownArrow;=21D3|DoubleLeftArrow;=21D0|DoubleLeftRightArrow;=21D4|DoubleLeftTee;=2AE4|DoubleLongLeftArrow;=27F8|DoubleLongLeftRightArrow;=27FA|DoubleLongRightArrow;=27F9|DoubleRightArrow;=21D2|DoubleRightTee;=22A8|DoubleUpArrow;=21D1|DoubleUpDownArrow;=21D5|DoubleVerticalBar;=2225|DownArrow;=2193|DownArrowBar;=2913|DownArrowUpArrow;=21F5|DownBreve;=311|DownLeftRightVector;=2950|DownLeftTeeVector;=295E|DownLeftVector;=21BD|DownLeftVectorBar;=2956|DownRightTeeVector;=295F|DownRightVector;=21C1|DownRightVectorBar;=2957|DownTee;=22A4|DownTeeArrow;=21A7|Downarrow;=21D3|Dscr;=1D49F|Dstrok;=110|ENG;=14A|ETH=D0|ETH;=D0|Eacute=C9|Eacute;=C9|Ecaron;=11A|Ecirc=CA|Ecirc;=CA|Ecy;=42D|Edot;=116|Efr;=1D508|Egrave=C8|Egrave;=C8|Element;=2208|Emacr;=112|EmptySmallSquare;=25FB|EmptyVerySmallSquare;=25AB|Eogon;=118|Eopf;=1D53C|Epsilon;=395|Equal;=2A75|EqualTilde;=2242|Equilibrium;=21CC|Escr;=2130|Esim;=2A73|Eta;=397|Euml=CB|Euml;=CB|Exists;=2203|ExponentialE;=2147|Fcy;=424|Ffr;=1D509|FilledSmallSquare;=25FC|FilledVerySmallSquare;=25AA|Fopf;=1D53D|ForAll;=2200|Fouriertrf;=2131|Fscr;=2131|GJcy;=403|GT=3E|GT;=3E|Gamma;=393|Gammad;=3DC|Gbreve;=11E|Gcedil;=122|Gcirc;=11C|Gcy;=413|Gdot;=120|Gfr;=1D50A|Gg;=22D9|Gopf;=1D53E|GreaterEqual;=2265|GreaterEqualLess;=22DB|GreaterFullEqual;=2267|GreaterGreater;=2AA2|GreaterLess;=2277|GreaterSlantEqual;=2A7E|GreaterTilde;=2273|Gscr;=1D4A2|Gt;=226B|HARDcy;=42A|Hacek;=2C7|Hat;=5E|Hcirc;=124|Hfr;=210C|HilbertSpace;=210B|Hopf;=210D|HorizontalLine;=2500|Hscr;=210B|Hstrok;=126|HumpDownHump;=224E|HumpEqual;=224F|IEcy;=415|IJlig;=132|IOcy;=401|Iacute=CD|Iacute;=CD|Icirc=CE|Icirc;=CE|Icy;=418|Idot;=130|Ifr;=2111|Igrave=CC|Igrave;=CC|Im;=2111|Imacr;=12A|ImaginaryI;=2148|Implies;=21D2|Int;=222C|Integral;=222B|Intersection;=22C2|InvisibleComma;=2063|InvisibleTimes;=2062|Iogon;=12E|Iopf;=1D540|Iota;=399|Iscr;=2110|Itilde;=128|Iukcy;=406|Iuml=CF|Iuml;=CF|Jcirc;=134|Jcy;=419|Jfr;=1D50D|Jopf;=1D541|Jscr;=1D4A5|Jsercy;=408|Jukcy;=404|KHcy;=425|KJcy;=40C|Kappa;=39A|Kcedil;=136|Kcy;=41A|Kfr;=1D50E|Kopf;=1D542|Kscr;=1D4A6|LJcy;=409|LT=3C|LT;=3C|Lacute;=139|Lambda;=39B|Lang;=27EA|Laplacetrf;=2112|Larr;=219E|Lcaron;=13D|Lcedil;=13B|Lcy;=41B|LeftAngleBracket;=27E8|LeftArrow;=2190|LeftArrowBar;=21E4|LeftArrowRightArrow;=21C6|LeftCeiling;=2308|LeftDoubleBracket;=27E6|LeftDownTeeVector;=2961|LeftDownVector;=21C3|LeftDownVectorBar;=2959|LeftFloor;=230A|LeftRightArrow;=2194|LeftRightVector;=294E|LeftTee;=22A3|LeftTeeArrow;=21A4|LeftTeeVector;=295A|LeftTriangle;=22B2|LeftTriangleBar;=29CF|LeftTriangleEqual;=22B4|LeftUpDownVector;=2951|LeftUpTeeVector;=2960|LeftUpVector;=21BF|LeftUpVectorBar;=2958|LeftVector;=21BC|LeftVectorBar;=2952|Leftarrow;=21D0|Leftrightarrow;=21D4|LessEqualGreater;=22DA|LessFullEqual;=2266|LessGreater;=2276|LessLess;=2AA1|LessSlantEqual;=2A7D|LessTilde;=2272|Lfr;=1D50F|Ll;=22D8|Lleftarrow;=21DA|Lmidot;=13F|LongLeftArrow;=27F5|LongLeftRightArrow;=27F7|LongRightArrow;=27F6|Longleftarrow;=27F8|Longleftrightarrow;=27FA|Longrightarrow;=27F9|Lopf;=1D543|LowerLeftArrow;=2199|LowerRightArrow;=2198|Lscr;=2112|Lsh;=21B0|Lstrok;=141|Lt;=226A|Map;=2905|Mcy;=41C|MediumSpace;=205F|Mellintrf;=2133|Mfr;=1D510|MinusPlus;=2213|Mopf;=1D544|Mscr;=2133|Mu;=39C|NJcy;=40A|Nacute;=143|Ncaron;=147|Ncedil;=145|Ncy;=41D|NegativeMediumSpace;=200B|NegativeThickSpace;=200B|NegativeThinSpace;=200B|NegativeVeryThinSpace;=200B|NestedGreaterGreater;=226B|NestedLessLess;=226A|NewLine;=A|Nfr;=1D511|NoBreak;=2060|NonBreakingSpace;=A0|Nopf;=2115|Not;=2AEC|NotCongruent;=2262|NotCupCap;=226D|NotDoubleVerticalBar;=2226|NotElement;=2209|NotEqual;=2260|NotEqualTilde;=2242,338|NotExists;=2204|NotGreater;=226F|NotGreaterEqual;=2271|NotGreaterFullEqual;=2267,338|NotGreaterGreater;=226B,338|NotGreaterLess;=2279|NotGreaterSlantEqual;=2A7E,338|NotGreaterTilde;=2275|NotHumpDownHump;=224E,338|NotHumpEqual;=224F,338|NotLeftTriangle;=22EA|NotLeftTriangleBar;=29CF,338|NotLeftTriangleEqual;=22EC|NotLess;=226E|NotLessEqual;=2270|NotLessGreater;=2278|NotLessLess;=226A,338|NotLessSlantEqual;=2A7D,338|NotLessTilde;=2274|NotNestedGreaterGreater;=2AA2,338|NotNestedLessLess;=2AA1,338|NotPrecedes;=2280|NotPrecedesEqual;=2AAF,338|NotPrecedesSlantEqual;=22E0|NotReverseElement;=220C|NotRightTriangle;=22EB|NotRightTriangleBar;=29D0,338|NotRightTriangleEqual;=22ED|NotSquareSubset;=228F,338|NotSquareSubsetEqual;=22E2|NotSquareSuperset;=2290,338|NotSquareSupersetEqual;=22E3|NotSubset;=2282,20D2|NotSubsetEqual;=2288|NotSucceeds;=2281|NotSucceedsEqual;=2AB0,338|NotSucceedsSlantEqual;=22E1|NotSucceedsTilde;=227F,338|NotSuperset;=2283,20D2|NotSupersetEqual;=2289|NotTilde;=2241|NotTildeEqual;=2244|NotTildeFullEqual;=2247|NotTildeTilde;=2249|NotVerticalBar;=2224|Nscr;=1D4A9|Ntilde=D1|Ntilde;=D1|Nu;=39D|OElig;=152|Oacute=D3|Oacute;=D3|Ocirc=D4|Ocirc;=D4|Ocy;=41E|Odblac;=150|Ofr;=1D512|Ograve=D2|Ograve;=D2|Omacr;=14C|Omega;=3A9|Omicron;=39F|Oopf;=1D546|OpenCurlyDoubleQuote;=201C|OpenCurlyQuote;=2018|Or;=2A54|Oscr;=1D4AA|Oslash=D8|Oslash;=D8|Otilde=D5|Otilde;=D5|Otimes;=2A37|Ouml=D6|Ouml;=D6|OverBar;=203E|OverBrace;=23DE|OverBracket;=23B4|OverParenthesis;=23DC|PartialD;=2202|Pcy;=41F|Pfr;=1D513|Phi;=3A6|Pi;=3A0|PlusMinus;=B1|Poincareplane;=210C|Popf;=2119|Pr;=2ABB|Precedes;=227A|PrecedesEqual;=2AAF|PrecedesSlantEqual;=227C|PrecedesTilde;=227E|Prime;=2033|Product;=220F|Proportion;=2237|Proportional;=221D|Pscr;=1D4AB|Psi;=3A8|QUOT=22|QUOT;=22|Qfr;=1D514|Qopf;=211A|Qscr;=1D4AC|RBarr;=2910|REG=AE|REG;=AE|Racute;=154|Rang;=27EB|Rarr;=21A0|Rarrtl;=2916|Rcaron;=158|Rcedil;=156|Rcy;=420|Re;=211C|ReverseElement;=220B|ReverseEquilibrium;=21CB|ReverseUpEquilibrium;=296F|Rfr;=211C|Rho;=3A1|RightAngleBracket;=27E9|RightArrow;=2192|RightArrowBar;=21E5|RightArrowLeftArrow;=21C4|RightCeiling;=2309|RightDoubleBracket;=27E7|RightDownTeeVector;=295D|RightDownVector;=21C2|RightDownVectorBar;=2955|RightFloor;=230B|RightTee;=22A2|RightTeeArrow;=21A6|RightTeeVector;=295B|RightTriangle;=22B3|RightTriangleBar;=29D0|RightTriangleEqual;=22B5|RightUpDownVector;=294F|RightUpTeeVector;=295C|RightUpVector;=21BE|RightUpVectorBar;=2954|RightVector;=21C0|RightVectorBar;=2953|Rightarrow;=21D2|Ropf;=211D|RoundImplies;=2970|Rrightarrow;=21DB|Rscr;=211B|Rsh;=21B1|RuleDelayed;=29F4|SHCHcy;=429|SHcy;=428|SOFTcy;=42C|Sacute;=15A|Sc;=2ABC|Scaron;=160|Scedil;=15E|Scirc;=15C|Scy;=421|Sfr;=1D516|ShortDownArrow;=2193|ShortLeftArrow;=2190|ShortRightArrow;=2192|ShortUpArrow;=2191|Sigma;=3A3|SmallCircle;=2218|Sopf;=1D54A|Sqrt;=221A|Square;=25A1|SquareIntersection;=2293|SquareSubset;=228F|SquareSubsetEqual;=2291|SquareSuperset;=2290|SquareSupersetEqual;=2292|SquareUnion;=2294|Sscr;=1D4AE|Star;=22C6|Sub;=22D0|Subset;=22D0|SubsetEqual;=2286|Succeeds;=227B|SucceedsEqual;=2AB0|SucceedsSlantEqual;=227D|SucceedsTilde;=227F|SuchThat;=220B|Sum;=2211|Sup;=22D1|Superset;=2283|SupersetEqual;=2287|Supset;=22D1|THORN=DE|THORN;=DE|TRADE;=2122|TSHcy;=40B|TScy;=426|Tab;=9|Tau;=3A4|Tcaron;=164|Tcedil;=162|Tcy;=422|Tfr;=1D517|Therefore;=2234|Theta;=398|ThickSpace;=205F,200A|ThinSpace;=2009|Tilde;=223C|TildeEqual;=2243|TildeFullEqual;=2245|TildeTilde;=2248|Topf;=1D54B|TripleDot;=20DB|Tscr;=1D4AF|Tstrok;=166|Uacute=DA|Uacute;=DA|Uarr;=219F|Uarrocir;=2949|Ubrcy;=40E|Ubreve;=16C|Ucirc=DB|Ucirc;=DB|Ucy;=423|Udblac;=170|Ufr;=1D518|Ugrave=D9|Ugrave;=D9|Umacr;=16A|UnderBar;=5F|UnderBrace;=23DF|UnderBracket;=23B5|UnderParenthesis;=23DD|Union;=22C3|UnionPlus;=228E|Uogon;=172|Uopf;=1D54C|UpArrow;=2191|UpArrowBar;=2912|UpArrowDownArrow;=21C5|UpDownArrow;=2195|UpEquilibrium;=296E|UpTee;=22A5|UpTeeArrow;=21A5|Uparrow;=21D1|Updownarrow;=21D5|UpperLeftArrow;=2196|UpperRightArrow;=2197|Upsi;=3D2|Upsilon;=3A5|Uring;=16E|Uscr;=1D4B0|Utilde;=168|Uuml=DC|Uuml;=DC|VDash;=22AB|Vbar;=2AEB|Vcy;=412|Vdash;=22A9|Vdashl;=2AE6|Vee;=22C1|Verbar;=2016|Vert;=2016|VerticalBar;=2223|VerticalLine;=7C|VerticalSeparator;=2758|VerticalTilde;=2240|VeryThinSpace;=200A|Vfr;=1D519|Vopf;=1D54D|Vscr;=1D4B1|Vvdash;=22AA|Wcirc;=174|Wedge;=22C0|Wfr;=1D51A|Wopf;=1D54E|Wscr;=1D4B2|Xfr;=1D51B|Xi;=39E|Xopf;=1D54F|Xscr;=1D4B3|YAcy;=42F|YIcy;=407|YUcy;=42E|Yacute=DD|Yacute;=DD|Ycirc;=176|Ycy;=42B|Yfr;=1D51C|Yopf;=1D550|Yscr;=1D4B4|Yuml;=178|ZHcy;=416|Zacute;=179|Zcaron;=17D|Zcy;=417|Zdot;=17B|ZeroWidthSpace;=200B|Zeta;=396|Zfr;=2128|Zopf;=2124|Zscr;=1D4B5|aacute=E1|aacute;=E1|abreve;=103|ac;=223E|acE;=223E,333|acd;=223F|acirc=E2|acirc;=E2|acute=B4|acute;=B4|acy;=430|aelig=E6|aelig;=E6|af;=2061|afr;=1D51E|agrave=E0|agrave;=E0|alefsym;=2135|aleph;=2135|alpha;=3B1|amacr;=101|amalg;=2A3F|amp=26|amp;=26|and;=2227|andand;=2A55|andd;=2A5C|andslope;=2A58|andv;=2A5A|ang;=2220|ange;=29A4|angle;=2220|angmsd;=2221|angmsdaa;=29A8|angmsdab;=29A9|angmsdac;=29AA|angmsdad;=29AB|angmsdae;=29AC|angmsdaf;=29AD|angmsdag;=29AE|angmsdah;=29AF|angrt;=221F|angrtvb;=22BE|angrtvbd;=299D|angsph;=2222|angst;=C5|angzarr;=237C|aogon;=105|aopf;=1D552|ap;=2248|apE;=2A70|apacir;=2A6F|ape;=224A|apid;=224B|apos;=27|approx;=2248|approxeq;=224A|aring=E5|aring;=E5|ascr;=1D4B6|ast;=2A|asymp;=2248|asympeq;=224D|atilde=E3|atilde;=E3|auml=E4|auml;=E4|awconint;=2233|awint;=2A11|bNot;=2AED|backcong;=224C|backepsilon;=3F6|backprime;=2035|backsim;=223D|backsimeq;=22CD|barvee;=22BD|barwed;=2305|barwedge;=2305|bbrk;=23B5|bbrktbrk;=23B6|bcong;=224C|bcy;=431|bdquo;=201E|becaus;=2235|because;=2235|bemptyv;=29B0|bepsi;=3F6|bernou;=212C|beta;=3B2|beth;=2136|between;=226C|bfr;=1D51F|bigcap;=22C2|bigcirc;=25EF|bigcup;=22C3|bigodot;=2A00|bigoplus;=2A01|bigotimes;=2A02|bigsqcup;=2A06|bigstar;=2605|bigtriangledown;=25BD|bigtriangleup;=25B3|biguplus;=2A04|bigvee;=22C1|bigwedge;=22C0|bkarow;=290D|blacklozenge;=29EB|blacksquare;=25AA|blacktriangle;=25B4|blacktriangledown;=25BE|blacktriangleleft;=25C2|blacktriangleright;=25B8|blank;=2423|blk12;=2592|blk14;=2591|blk34;=2593|block;=2588|bne;=3D,20E5|bnequiv;=2261,20E5|bnot;=2310|bopf;=1D553|bot;=22A5|bottom;=22A5|bowtie;=22C8|boxDL;=2557|boxDR;=2554|boxDl;=2556|boxDr;=2553|boxH;=2550|boxHD;=2566|boxHU;=2569|boxHd;=2564|boxHu;=2567|boxUL;=255D|boxUR;=255A|boxUl;=255C|boxUr;=2559|boxV;=2551|boxVH;=256C|boxVL;=2563|boxVR;=2560|boxVh;=256B|boxVl;=2562|boxVr;=255F|boxbox;=29C9|boxdL;=2555|boxdR;=2552|boxdl;=2510|boxdr;=250C|boxh;=2500|boxhD;=2565|boxhU;=2568|boxhd;=252C|boxhu;=2534|boxminus;=229F|boxplus;=229E|boxtimes;=22A0|boxuL;=255B|boxuR;=2558|boxul;=2518|boxur;=2514|boxv;=2502|boxvH;=256A|boxvL;=2561|boxvR;=255E|boxvh;=253C|boxvl;=2524|boxvr;=251C|bprime;=2035|breve;=2D8|brvbar=A6|brvbar;=A6|bscr;=1D4B7|bsemi;=204F|bsim;=223D|bsime;=22CD|bsol;=5C|bsolb;=29C5|bsolhsub;=27C8|bull;=2022|bullet;=2022|bump;=224E|bumpE;=2AAE|bumpe;=224F|bumpeq;=224F|cacute;=107|cap;=2229|capand;=2A44|capbrcup;=2A49|capcap;=2A4B|capcup;=2A47|capdot;=2A40|caps;=2229,FE00|caret;=2041|caron;=2C7|ccaps;=2A4D|ccaron;=10D|ccedil=E7|ccedil;=E7|ccirc;=109|ccups;=2A4C|ccupssm;=2A50|cdot;=10B|cedil=B8|cedil;=B8|cemptyv;=29B2|cent=A2|cent;=A2|centerdot;=B7|cfr;=1D520|chcy;=447|check;=2713|checkmark;=2713|chi;=3C7|cir;=25CB|cirE;=29C3|circ;=2C6|circeq;=2257|circlearrowleft;=21BA|circlearrowright;=21BB|circledR;=AE|circledS;=24C8|circledast;=229B|circledcirc;=229A|circleddash;=229D|cire;=2257|cirfnint;=2A10|cirmid;=2AEF|cirscir;=29C2|clubs;=2663|clubsuit;=2663|colon;=3A|colone;=2254|coloneq;=2254|comma;=2C|commat;=40|comp;=2201|compfn;=2218|complement;=2201|complexes;=2102|cong;=2245|congdot;=2A6D|conint;=222E|copf;=1D554|coprod;=2210|copy=A9|copy;=A9|copysr;=2117|crarr;=21B5|cross;=2717|cscr;=1D4B8|csub;=2ACF|csube;=2AD1|csup;=2AD0|csupe;=2AD2|ctdot;=22EF|cudarrl;=2938|cudarrr;=2935|cuepr;=22DE|cuesc;=22DF|cularr;=21B6|cularrp;=293D|cup;=222A|cupbrcap;=2A48|cupcap;=2A46|cupcup;=2A4A|cupdot;=228D|cupor;=2A45|cups;=222A,FE00|curarr;=21B7|curarrm;=293C|curlyeqprec;=22DE|curlyeqsucc;=22DF|curlyvee;=22CE|curlywedge;=22CF|curren=A4|curren;=A4|curvearrowleft;=21B6|curvearrowright;=21B7|cuvee;=22CE|cuwed;=22CF|cwconint;=2232|cwint;=2231|cylcty;=232D|dArr;=21D3|dHar;=2965|dagger;=2020|daleth;=2138|darr;=2193|dash;=2010|dashv;=22A3|dbkarow;=290F|dblac;=2DD|dcaron;=10F|dcy;=434|dd;=2146|ddagger;=2021|ddarr;=21CA|ddotseq;=2A77|deg=B0|deg;=B0|delta;=3B4|demptyv;=29B1|dfisht;=297F|dfr;=1D521|dharl;=21C3|dharr;=21C2|diam;=22C4|diamond;=22C4|diamondsuit;=2666|diams;=2666|die;=A8|digamma;=3DD|disin;=22F2|div;=F7|divide=F7|divide;=F7|divideontimes;=22C7|divonx;=22C7|djcy;=452|dlcorn;=231E|dlcrop;=230D|dollar;=24|dopf;=1D555|dot;=2D9|doteq;=2250|doteqdot;=2251|dotminus;=2238|dotplus;=2214|dotsquare;=22A1|doublebarwedge;=2306|downarrow;=2193|downdownarrows;=21CA|downharpoonleft;=21C3|downharpoonright;=21C2|drbkarow;=2910|drcorn;=231F|drcrop;=230C|dscr;=1D4B9|dscy;=455|dsol;=29F6|dstrok;=111|dtdot;=22F1|dtri;=25BF|dtrif;=25BE|duarr;=21F5|duhar;=296F|dwangle;=29A6|dzcy;=45F|dzigrarr;=27FF|eDDot;=2A77|eDot;=2251|eacute=E9|eacute;=E9|easter;=2A6E|ecaron;=11B|ecir;=2256|ecirc=EA|ecirc;=EA|ecolon;=2255|ecy;=44D|edot;=117|ee;=2147|efDot;=2252|efr;=1D522|eg;=2A9A|egrave=E8|egrave;=E8|egs;=2A96|egsdot;=2A98|el;=2A99|elinters;=23E7|ell;=2113|els;=2A95|elsdot;=2A97|emacr;=113|empty;=2205|emptyset;=2205|emptyv;=2205|emsp13;=2004|emsp14;=2005|emsp;=2003|eng;=14B|ensp;=2002|eogon;=119|eopf;=1D556|epar;=22D5|eparsl;=29E3|eplus;=2A71|epsi;=3B5|epsilon;=3B5|epsiv;=3F5|eqcirc;=2256|eqcolon;=2255|eqsim;=2242|eqslantgtr;=2A96|eqslantless;=2A95|equals;=3D|equest;=225F|equiv;=2261|equivDD;=2A78|eqvparsl;=29E5|erDot;=2253|erarr;=2971|escr;=212F|esdot;=2250|esim;=2242|eta;=3B7|eth=F0|eth;=F0|euml=EB|euml;=EB|euro;=20AC|excl;=21|exist;=2203|expectation;=2130|exponentiale;=2147|fallingdotseq;=2252|fcy;=444|female;=2640|ffilig;=FB03|fflig;=FB00|ffllig;=FB04|ffr;=1D523|filig;=FB01|fjlig;=66,6A|flat;=266D|fllig;=FB02|fltns;=25B1|fnof;=192|fopf;=1D557|forall;=2200|fork;=22D4|forkv;=2AD9|fpartint;=2A0D|frac12=BD|frac12;=BD|frac13;=2153|frac14=BC|frac14;=BC|frac15;=2155|frac16;=2159|frac18;=215B|frac23;=2154|frac25;=2156|frac34=BE|frac34;=BE|frac35;=2157|frac38;=215C|frac45;=2158|frac56;=215A|frac58;=215D|frac78;=215E|frasl;=2044|frown;=2322|fscr;=1D4BB|gE;=2267|gEl;=2A8C|gacute;=1F5|gamma;=3B3|gammad;=3DD|gap;=2A86|gbreve;=11F|gcirc;=11D|gcy;=433|gdot;=121|ge;=2265|gel;=22DB|geq;=2265|geqq;=2267|geqslant;=2A7E|ges;=2A7E|gescc;=2AA9|gesdot;=2A80|gesdoto;=2A82|gesdotol;=2A84|gesl;=22DB,FE00|gesles;=2A94|gfr;=1D524|gg;=226B|ggg;=22D9|gimel;=2137|gjcy;=453|gl;=2277|glE;=2A92|gla;=2AA5|glj;=2AA4|gnE;=2269|gnap;=2A8A|gnapprox;=2A8A|gne;=2A88|gneq;=2A88|gneqq;=2269|gnsim;=22E7|gopf;=1D558|grave;=60|gscr;=210A|gsim;=2273|gsime;=2A8E|gsiml;=2A90|gt=3E|gt;=3E|gtcc;=2AA7|gtcir;=2A7A|gtdot;=22D7|gtlPar;=2995|gtquest;=2A7C|gtrapprox;=2A86|gtrarr;=2978|gtrdot;=22D7|gtreqless;=22DB|gtreqqless;=2A8C|gtrless;=2277|gtrsim;=2273|gvertneqq;=2269,FE00|gvnE;=2269,FE00|hArr;=21D4|hairsp;=200A|half;=BD|hamilt;=210B|hardcy;=44A|harr;=2194|harrcir;=2948|harrw;=21AD|hbar;=210F|hcirc;=125|hearts;=2665|heartsuit;=2665|hellip;=2026|hercon;=22B9|hfr;=1D525|hksearow;=2925|hkswarow;=2926|hoarr;=21FF|homtht;=223B|hookleftarrow;=21A9|hookrightarrow;=21AA|hopf;=1D559|horbar;=2015|hscr;=1D4BD|hslash;=210F|hstrok;=127|hybull;=2043|hyphen;=2010|iacute=ED|iacute;=ED|ic;=2063|icirc=EE|icirc;=EE|icy;=438|iecy;=435|iexcl=A1|iexcl;=A1|iff;=21D4|ifr;=1D526|igrave=EC|igrave;=EC|ii;=2148|iiiint;=2A0C|iiint;=222D|iinfin;=29DC|iiota;=2129|ijlig;=133|imacr;=12B|image;=2111|imagline;=2110|imagpart;=2111|imath;=131|imof;=22B7|imped;=1B5|in;=2208|incare;=2105|infin;=221E|infintie;=29DD|inodot;=131|int;=222B|intcal;=22BA|integers;=2124|intercal;=22BA|intlarhk;=2A17|intprod;=2A3C|iocy;=451|iogon;=12F|iopf;=1D55A|iota;=3B9|iprod;=2A3C|iquest=BF|iquest;=BF|iscr;=1D4BE|isin;=2208|isinE;=22F9|isindot;=22F5|isins;=22F4|isinsv;=22F3|isinv;=2208|it;=2062|itilde;=129|iukcy;=456|iuml=EF|iuml;=EF|jcirc;=135|jcy;=439|jfr;=1D527|jmath;=237|jopf;=1D55B|jscr;=1D4BF|jsercy;=458|jukcy;=454|kappa;=3BA|kappav;=3F0|kcedil;=137|kcy;=43A|kfr;=1D528|kgreen;=138|khcy;=445|kjcy;=45C|kopf;=1D55C|kscr;=1D4C0|lAarr;=21DA|lArr;=21D0|lAtail;=291B|lBarr;=290E|lE;=2266|lEg;=2A8B|lHar;=2962|lacute;=13A|laemptyv;=29B4|lagran;=2112|lambda;=3BB|lang;=27E8|langd;=2991|langle;=27E8|lap;=2A85|laquo=AB|laquo;=AB|larr;=2190|larrb;=21E4|larrbfs;=291F|larrfs;=291D|larrhk;=21A9|larrlp;=21AB|larrpl;=2939|larrsim;=2973|larrtl;=21A2|lat;=2AAB|latail;=2919|late;=2AAD|lates;=2AAD,FE00|lbarr;=290C|lbbrk;=2772|lbrace;=7B|lbrack;=5B|lbrke;=298B|lbrksld;=298F|lbrkslu;=298D|lcaron;=13E|lcedil;=13C|lceil;=2308|lcub;=7B|lcy;=43B|ldca;=2936|ldquo;=201C|ldquor;=201E|ldrdhar;=2967|ldrushar;=294B|ldsh;=21B2|le;=2264|leftarrow;=2190|leftarrowtail;=21A2|leftharpoondown;=21BD|leftharpoonup;=21BC|leftleftarrows;=21C7|leftrightarrow;=2194|leftrightarrows;=21C6|leftrightharpoons;=21CB|leftrightsquigarrow;=21AD|leftthreetimes;=22CB|leg;=22DA|leq;=2264|leqq;=2266|leqslant;=2A7D|les;=2A7D|lescc;=2AA8|lesdot;=2A7F|lesdoto;=2A81|lesdotor;=2A83|lesg;=22DA,FE00|lesges;=2A93|lessapprox;=2A85|lessdot;=22D6|lesseqgtr;=22DA|lesseqqgtr;=2A8B|lessgtr;=2276|lesssim;=2272|lfisht;=297C|lfloor;=230A|lfr;=1D529|lg;=2276|lgE;=2A91|lhard;=21BD|lharu;=21BC|lharul;=296A|lhblk;=2584|ljcy;=459|ll;=226A|llarr;=21C7|llcorner;=231E|llhard;=296B|lltri;=25FA|lmidot;=140|lmoust;=23B0|lmoustache;=23B0|lnE;=2268|lnap;=2A89|lnapprox;=2A89|lne;=2A87|lneq;=2A87|lneqq;=2268|lnsim;=22E6|loang;=27EC|loarr;=21FD|lobrk;=27E6|longleftarrow;=27F5|longleftrightarrow;=27F7|longmapsto;=27FC|longrightarrow;=27F6|looparrowleft;=21AB|looparrowright;=21AC|lopar;=2985|lopf;=1D55D|loplus;=2A2D|lotimes;=2A34|lowast;=2217|lowbar;=5F|loz;=25CA|lozenge;=25CA|lozf;=29EB|lpar;=28|lparlt;=2993|lrarr;=21C6|lrcorner;=231F|lrhar;=21CB|lrhard;=296D|lrm;=200E|lrtri;=22BF|lsaquo;=2039|lscr;=1D4C1|lsh;=21B0|lsim;=2272|lsime;=2A8D|lsimg;=2A8F|lsqb;=5B|lsquo;=2018|lsquor;=201A|lstrok;=142|lt=3C|lt;=3C|ltcc;=2AA6|ltcir;=2A79|ltdot;=22D6|lthree;=22CB|ltimes;=22C9|ltlarr;=2976|ltquest;=2A7B|ltrPar;=2996|ltri;=25C3|ltrie;=22B4|ltrif;=25C2|lurdshar;=294A|luruhar;=2966|lvertneqq;=2268,FE00|lvnE;=2268,FE00|mDDot;=223A|macr=AF|macr;=AF|male;=2642|malt;=2720|maltese;=2720|map;=21A6|mapsto;=21A6|mapstodown;=21A7|mapstoleft;=21A4|mapstoup;=21A5|marker;=25AE|mcomma;=2A29|mcy;=43C|mdash;=2014|measuredangle;=2221|mfr;=1D52A|mho;=2127|micro=B5|micro;=B5|mid;=2223|midast;=2A|midcir;=2AF0|middot=B7|middot;=B7|minus;=2212|minusb;=229F|minusd;=2238|minusdu;=2A2A|mlcp;=2ADB|mldr;=2026|mnplus;=2213|models;=22A7|mopf;=1D55E|mp;=2213|mscr;=1D4C2|mstpos;=223E|mu;=3BC|multimap;=22B8|mumap;=22B8|nGg;=22D9,338|nGt;=226B,20D2|nGtv;=226B,338|nLeftarrow;=21CD|nLeftrightarrow;=21CE|nLl;=22D8,338|nLt;=226A,20D2|nLtv;=226A,338|nRightarrow;=21CF|nVDash;=22AF|nVdash;=22AE|nabla;=2207|nacute;=144|nang;=2220,20D2|nap;=2249|napE;=2A70,338|napid;=224B,338|napos;=149|napprox;=2249|natur;=266E|natural;=266E|naturals;=2115|nbsp=A0|nbsp;=A0|nbump;=224E,338|nbumpe;=224F,338|ncap;=2A43|ncaron;=148|ncedil;=146|ncong;=2247|ncongdot;=2A6D,338|ncup;=2A42|ncy;=43D|ndash;=2013|ne;=2260|neArr;=21D7|nearhk;=2924|nearr;=2197|nearrow;=2197|nedot;=2250,338|nequiv;=2262|nesear;=2928|nesim;=2242,338|nexist;=2204|nexists;=2204|nfr;=1D52B|ngE;=2267,338|nge;=2271|ngeq;=2271|ngeqq;=2267,338|ngeqslant;=2A7E,338|nges;=2A7E,338|ngsim;=2275|ngt;=226F|ngtr;=226F|nhArr;=21CE|nharr;=21AE|nhpar;=2AF2|ni;=220B|nis;=22FC|nisd;=22FA|niv;=220B|njcy;=45A|nlArr;=21CD|nlE;=2266,338|nlarr;=219A|nldr;=2025|nle;=2270|nleftarrow;=219A|nleftrightarrow;=21AE|nleq;=2270|nleqq;=2266,338|nleqslant;=2A7D,338|nles;=2A7D,338|nless;=226E|nlsim;=2274|nlt;=226E|nltri;=22EA|nltrie;=22EC|nmid;=2224|nopf;=1D55F|not=AC|not;=AC|notin;=2209|notinE;=22F9,338|notindot;=22F5,338|notinva;=2209|notinvb;=22F7|notinvc;=22F6|notni;=220C|notniva;=220C|notnivb;=22FE|notnivc;=22FD|npar;=2226|nparallel;=2226|nparsl;=2AFD,20E5|npart;=2202,338|npolint;=2A14|npr;=2280|nprcue;=22E0|npre;=2AAF,338|nprec;=2280|npreceq;=2AAF,338|nrArr;=21CF|nrarr;=219B|nrarrc;=2933,338|nrarrw;=219D,338|nrightarrow;=219B|nrtri;=22EB|nrtrie;=22ED|nsc;=2281|nsccue;=22E1|nsce;=2AB0,338|nscr;=1D4C3|nshortmid;=2224|nshortparallel;=2226|nsim;=2241|nsime;=2244|nsimeq;=2244|nsmid;=2224|nspar;=2226|nsqsube;=22E2|nsqsupe;=22E3|nsub;=2284|nsubE;=2AC5,338|nsube;=2288|nsubset;=2282,20D2|nsubseteq;=2288|nsubseteqq;=2AC5,338|nsucc;=2281|nsucceq;=2AB0,338|nsup;=2285|nsupE;=2AC6,338|nsupe;=2289|nsupset;=2283,20D2|nsupseteq;=2289|nsupseteqq;=2AC6,338|ntgl;=2279|ntilde=F1|ntilde;=F1|ntlg;=2278|ntriangleleft;=22EA|ntrianglelefteq;=22EC|ntriangleright;=22EB|ntrianglerighteq;=22ED|nu;=3BD|num;=23|numero;=2116|numsp;=2007|nvDash;=22AD|nvHarr;=2904|nvap;=224D,20D2|nvdash;=22AC|nvge;=2265,20D2|nvgt;=3E,20D2|nvinfin;=29DE|nvlArr;=2902|nvle;=2264,20D2|nvlt;=3C,20D2|nvltrie;=22B4,20D2|nvrArr;=2903|nvrtrie;=22B5,20D2|nvsim;=223C,20D2|nwArr;=21D6|nwarhk;=2923|nwarr;=2196|nwarrow;=2196|nwnear;=2927|oS;=24C8|oacute=F3|oacute;=F3|oast;=229B|ocir;=229A|ocirc=F4|ocirc;=F4|ocy;=43E|odash;=229D|odblac;=151|odiv;=2A38|odot;=2299|odsold;=29BC|oelig;=153|ofcir;=29BF|ofr;=1D52C|ogon;=2DB|ograve=F2|ograve;=F2|ogt;=29C1|ohbar;=29B5|ohm;=3A9|oint;=222E|olarr;=21BA|olcir;=29BE|olcross;=29BB|oline;=203E|olt;=29C0|omacr;=14D|omega;=3C9|omicron;=3BF|omid;=29B6|ominus;=2296|oopf;=1D560|opar;=29B7|operp;=29B9|oplus;=2295|or;=2228|orarr;=21BB|ord;=2A5D|order;=2134|orderof;=2134|ordf=AA|ordf;=AA|ordm=BA|ordm;=BA|origof;=22B6|oror;=2A56|orslope;=2A57|orv;=2A5B|oscr;=2134|oslash=F8|oslash;=F8|osol;=2298|otilde=F5|otilde;=F5|otimes;=2297|otimesas;=2A36|ouml=F6|ouml;=F6|ovbar;=233D|par;=2225|para=B6|para;=B6|parallel;=2225|parsim;=2AF3|parsl;=2AFD|part;=2202|pcy;=43F|percnt;=25|period;=2E|permil;=2030|perp;=22A5|pertenk;=2031|pfr;=1D52D|phi;=3C6|phiv;=3D5|phmmat;=2133|phone;=260E|pi;=3C0|pitchfork;=22D4|piv;=3D6|planck;=210F|planckh;=210E|plankv;=210F|plus;=2B|plusacir;=2A23|plusb;=229E|pluscir;=2A22|plusdo;=2214|plusdu;=2A25|pluse;=2A72|plusmn=B1|plusmn;=B1|plussim;=2A26|plustwo;=2A27|pm;=B1|pointint;=2A15|popf;=1D561|pound=A3|pound;=A3|pr;=227A|prE;=2AB3|prap;=2AB7|prcue;=227C|pre;=2AAF|prec;=227A|precapprox;=2AB7|preccurlyeq;=227C|preceq;=2AAF|precnapprox;=2AB9|precneqq;=2AB5|precnsim;=22E8|precsim;=227E|prime;=2032|primes;=2119|prnE;=2AB5|prnap;=2AB9|prnsim;=22E8|prod;=220F|profalar;=232E|profline;=2312|profsurf;=2313|prop;=221D|propto;=221D|prsim;=227E|prurel;=22B0|pscr;=1D4C5|psi;=3C8|puncsp;=2008|qfr;=1D52E|qint;=2A0C|qopf;=1D562|qprime;=2057|qscr;=1D4C6|quaternions;=210D|quatint;=2A16|quest;=3F|questeq;=225F|quot=22|quot;=22|rAarr;=21DB|rArr;=21D2|rAtail;=291C|rBarr;=290F|rHar;=2964|race;=223D,331|racute;=155|radic;=221A|raemptyv;=29B3|rang;=27E9|rangd;=2992|range;=29A5|rangle;=27E9|raquo=BB|raquo;=BB|rarr;=2192|rarrap;=2975|rarrb;=21E5|rarrbfs;=2920|rarrc;=2933|rarrfs;=291E|rarrhk;=21AA|rarrlp;=21AC|rarrpl;=2945|rarrsim;=2974|rarrtl;=21A3|rarrw;=219D|ratail;=291A|ratio;=2236|rationals;=211A|rbarr;=290D|rbbrk;=2773|rbrace;=7D|rbrack;=5D|rbrke;=298C|rbrksld;=298E|rbrkslu;=2990|rcaron;=159|rcedil;=157|rceil;=2309|rcub;=7D|rcy;=440|rdca;=2937|rdldhar;=2969|rdquo;=201D|rdquor;=201D|rdsh;=21B3|real;=211C|realine;=211B|realpart;=211C|reals;=211D|rect;=25AD|reg=AE|reg;=AE|rfisht;=297D|rfloor;=230B|rfr;=1D52F|rhard;=21C1|rharu;=21C0|rharul;=296C|rho;=3C1|rhov;=3F1|rightarrow;=2192|rightarrowtail;=21A3|rightharpoondown;=21C1|rightharpoonup;=21C0|rightleftarrows;=21C4|rightleftharpoons;=21CC|rightrightarrows;=21C9|rightsquigarrow;=219D|rightthreetimes;=22CC|ring;=2DA|risingdotseq;=2253|rlarr;=21C4|rlhar;=21CC|rlm;=200F|rmoust;=23B1|rmoustache;=23B1|rnmid;=2AEE|roang;=27ED|roarr;=21FE|robrk;=27E7|ropar;=2986|ropf;=1D563|roplus;=2A2E|rotimes;=2A35|rpar;=29|rpargt;=2994|rppolint;=2A12|rrarr;=21C9|rsaquo;=203A|rscr;=1D4C7|rsh;=21B1|rsqb;=5D|rsquo;=2019|rsquor;=2019|rthree;=22CC|rtimes;=22CA|rtri;=25B9|rtrie;=22B5|rtrif;=25B8|rtriltri;=29CE|ruluhar;=2968|rx;=211E|sacute;=15B|sbquo;=201A|sc;=227B|scE;=2AB4|scap;=2AB8|scaron;=161|sccue;=227D|sce;=2AB0|scedil;=15F|scirc;=15D|scnE;=2AB6|scnap;=2ABA|scnsim;=22E9|scpolint;=2A13|scsim;=227F|scy;=441|sdot;=22C5|sdotb;=22A1|sdote;=2A66|seArr;=21D8|searhk;=2925|searr;=2198|searrow;=2198|sect=A7|sect;=A7|semi;=3B|seswar;=2929|setminus;=2216|setmn;=2216|sext;=2736|sfr;=1D530|sfrown;=2322|sharp;=266F|shchcy;=449|shcy;=448|shortmid;=2223|shortparallel;=2225|shy=AD|shy;=AD|sigma;=3C3|sigmaf;=3C2|sigmav;=3C2|sim;=223C|simdot;=2A6A|sime;=2243|simeq;=2243|simg;=2A9E|simgE;=2AA0|siml;=2A9D|simlE;=2A9F|simne;=2246|simplus;=2A24|simrarr;=2972|slarr;=2190|smallsetminus;=2216|smashp;=2A33|smeparsl;=29E4|smid;=2223|smile;=2323|smt;=2AAA|smte;=2AAC|smtes;=2AAC,FE00|softcy;=44C|sol;=2F|solb;=29C4|solbar;=233F|sopf;=1D564|spades;=2660|spadesuit;=2660|spar;=2225|sqcap;=2293|sqcaps;=2293,FE00|sqcup;=2294|sqcups;=2294,FE00|sqsub;=228F|sqsube;=2291|sqsubset;=228F|sqsubseteq;=2291|sqsup;=2290|sqsupe;=2292|sqsupset;=2290|sqsupseteq;=2292|squ;=25A1|square;=25A1|squarf;=25AA|squf;=25AA|srarr;=2192|sscr;=1D4C8|ssetmn;=2216|ssmile;=2323|sstarf;=22C6|star;=2606|starf;=2605|straightepsilon;=3F5|straightphi;=3D5|strns;=AF|sub;=2282|subE;=2AC5|subdot;=2ABD|sube;=2286|subedot;=2AC3|submult;=2AC1|subnE;=2ACB|subne;=228A|subplus;=2ABF|subrarr;=2979|subset;=2282|subseteq;=2286|subseteqq;=2AC5|subsetneq;=228A|subsetneqq;=2ACB|subsim;=2AC7|subsub;=2AD5|subsup;=2AD3|succ;=227B|succapprox;=2AB8|succcurlyeq;=227D|succeq;=2AB0|succnapprox;=2ABA|succneqq;=2AB6|succnsim;=22E9|succsim;=227F|sum;=2211|sung;=266A|sup1=B9|sup1;=B9|sup2=B2|sup2;=B2|sup3=B3|sup3;=B3|sup;=2283|supE;=2AC6|supdot;=2ABE|supdsub;=2AD8|supe;=2287|supedot;=2AC4|suphsol;=27C9|suphsub;=2AD7|suplarr;=297B|supmult;=2AC2|supnE;=2ACC|supne;=228B|supplus;=2AC0|supset;=2283|supseteq;=2287|supseteqq;=2AC6|supsetneq;=228B|supsetneqq;=2ACC|supsim;=2AC8|supsub;=2AD4|supsup;=2AD6|swArr;=21D9|swarhk;=2926|swarr;=2199|swarrow;=2199|swnwar;=292A|szlig=DF|szlig;=DF|target;=2316|tau;=3C4|tbrk;=23B4|tcaron;=165|tcedil;=163|tcy;=442|tdot;=20DB|telrec;=2315|tfr;=1D531|there4;=2234|therefore;=2234|theta;=3B8|thetasym;=3D1|thetav;=3D1|thickapprox;=2248|thicksim;=223C|thinsp;=2009|thkap;=2248|thksim;=223C|thorn=FE|thorn;=FE|tilde;=2DC|times=D7|times;=D7|timesb;=22A0|timesbar;=2A31|timesd;=2A30|tint;=222D|toea;=2928|top;=22A4|topbot;=2336|topcir;=2AF1|topf;=1D565|topfork;=2ADA|tosa;=2929|tprime;=2034|trade;=2122|triangle;=25B5|triangledown;=25BF|triangleleft;=25C3|trianglelefteq;=22B4|triangleq;=225C|triangleright;=25B9|trianglerighteq;=22B5|tridot;=25EC|trie;=225C|triminus;=2A3A|triplus;=2A39|trisb;=29CD|tritime;=2A3B|trpezium;=23E2|tscr;=1D4C9|tscy;=446|tshcy;=45B|tstrok;=167|twixt;=226C|twoheadleftarrow;=219E|twoheadrightarrow;=21A0|uArr;=21D1|uHar;=2963|uacute=FA|uacute;=FA|uarr;=2191|ubrcy;=45E|ubreve;=16D|ucirc=FB|ucirc;=FB|ucy;=443|udarr;=21C5|udblac;=171|udhar;=296E|ufisht;=297E|ufr;=1D532|ugrave=F9|ugrave;=F9|uharl;=21BF|uharr;=21BE|uhblk;=2580|ulcorn;=231C|ulcorner;=231C|ulcrop;=230F|ultri;=25F8|umacr;=16B|uml=A8|uml;=A8|uogon;=173|uopf;=1D566|uparrow;=2191|updownarrow;=2195|upharpoonleft;=21BF|upharpoonright;=21BE|uplus;=228E|upsi;=3C5|upsih;=3D2|upsilon;=3C5|upuparrows;=21C8|urcorn;=231D|urcorner;=231D|urcrop;=230E|uring;=16F|urtri;=25F9|uscr;=1D4CA|utdot;=22F0|utilde;=169|utri;=25B5|utrif;=25B4|uuarr;=21C8|uuml=FC|uuml;=FC|uwangle;=29A7|vArr;=21D5|vBar;=2AE8|vBarv;=2AE9|vDash;=22A8|vangrt;=299C|varepsilon;=3F5|varkappa;=3F0|varnothing;=2205|varphi;=3D5|varpi;=3D6|varpropto;=221D|varr;=2195|varrho;=3F1|varsigma;=3C2|varsubsetneq;=228A,FE00|varsubsetneqq;=2ACB,FE00|varsupsetneq;=228B,FE00|varsupsetneqq;=2ACC,FE00|vartheta;=3D1|vartriangleleft;=22B2|vartriangleright;=22B3|vcy;=432|vdash;=22A2|vee;=2228|veebar;=22BB|veeeq;=225A|vellip;=22EE|verbar;=7C|vert;=7C|vfr;=1D533|vltri;=22B2|vnsub;=2282,20D2|vnsup;=2283,20D2|vopf;=1D567|vprop;=221D|vrtri;=22B3|vscr;=1D4CB|vsubnE;=2ACB,FE00|vsubne;=228A,FE00|vsupnE;=2ACC,FE00|vsupne;=228B,FE00|vzigzag;=299A|wcirc;=175|wedbar;=2A5F|wedge;=2227|wedgeq;=2259|weierp;=2118|wfr;=1D534|wopf;=1D568|wp;=2118|wr;=2240|wreath;=2240|wscr;=1D4CC|xcap;=22C2|xcirc;=25EF|xcup;=22C3|xdtri;=25BD|xfr;=1D535|xhArr;=27FA|xharr;=27F7|xi;=3BE|xlArr;=27F8|xlarr;=27F5|xmap;=27FC|xnis;=22FB|xodot;=2A00|xopf;=1D569|xoplus;=2A01|xotime;=2A02|xrArr;=27F9|xrarr;=27F6|xscr;=1D4CD|xsqcup;=2A06|xuplus;=2A04|xutri;=25B3|xvee;=22C1|xwedge;=22C0|yacute=FD|yacute;=FD|yacy;=44F|ycirc;=177|ycy;=44B|yen=A5|yen;=A5|yfr;=1D536|yicy;=457|yopf;=1D56A|yscr;=1D4CE|yucy;=44E|yuml=FF|yuml;=FF|zacute;=17A|zcaron;=17E|zcy;=437|zdot;=17C|zeetrf;=2128|zeta;=3B6|zfr;=1D537|zhcy;=436|zigrarr;=21DD|zopf;=1D56B|zscr;=1D4CF|zwj;=200D|zwnj;=200C";
@@ -4220,179 +4371,483 @@ function tokenize(markup) {
4220
4371
  return new Lexer(markup).run();
4221
4372
  }
4222
4373
 
4223
- // packages/teams/src/activity/inbound/markup.ts
4224
- import { cpLength as cpLength6, pyStr as pyStr8, pyStrip as pyStrip6 } from "@primusclaw/personal-agent";
4225
-
4226
- // packages/teams/src/activity/inbound/patterns.ts
4227
- import { own as own8 } from "@primusclaw/personal-agent";
4228
- var SPACE_CHARS = "\\t\\n\\v\\f\\r\\x1c-\\x20\\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
4229
- var SPACE = `[${SPACE_CHARS}]`;
4230
- var WORD = "[\\p{L}\\p{N}_]";
4231
- var NOT_WORD_NEXT = `(?!${WORD})`;
4232
- var FOLDS = { i: "\\u0130\\u0131", k: "\\u212a", s: "\\u017f" };
4233
- var SYNTAX = /[\\^$.*+?()[\]{}|/]/;
4234
- function literalChar(ch) {
4235
- return SYNTAX.test(ch) ? `\\${ch}` : ch;
4236
- }
4237
- function caseless(literal) {
4238
- let source = "";
4239
- for (const ch of literal) {
4240
- const lower = ch.toLowerCase();
4241
- const upper = ch.toUpperCase();
4242
- if (lower === upper || Array.from(lower).length > 1 || Array.from(upper).length > 1) {
4243
- source += literalChar(ch);
4244
- continue;
4374
+ // packages/teams/src/activity/inbound/quotes-html.ts
4375
+ var FIELDS = /* @__PURE__ */ new Map([
4376
+ ["mri", "sender"],
4377
+ ["time", "time"],
4378
+ ["preview", "text"],
4379
+ ["copy", "text"]
4380
+ ]);
4381
+ var BREAKS = /* @__PURE__ */ new Set(["br", "p", "div", "li", "tr"]);
4382
+ var VOID = /* @__PURE__ */ new Set(["br", "img", "hr", "wbr", "input", "meta", "link"]);
4383
+ var ITEMID = new RegExp(`(?<!${WORD})${caseless("itemid")}${SPACE}*=${SPACE}*["']?([^"'>${SPACE_CHARS}]+)`, "u");
4384
+ var MARK_OPEN = "\uE010";
4385
+ var MARK_CLOSE = "\uE011";
4386
+ var MARKS = /[\uE010\uE011]/gu;
4387
+ function imageMarker(index) {
4388
+ return `${MARK_OPEN}img${String(index)}${MARK_CLOSE}`;
4389
+ }
4390
+ var IMAGE_MARKER = /\uE010img([0-9]+)\uE011/gu;
4391
+ var EMOJI_ITEMTYPE = /^https?:\/\/schema\.skype\.com\/Emoji$/iu;
4392
+ var ReplyReader = class {
4393
+ senderId = "";
4394
+ time = "";
4395
+ parts = { sender: [], text: [] };
4396
+ everything = [];
4397
+ /** The images read, in order, when the reader reads them (`readImages`); else an `<img>` says nothing. */
4398
+ images;
4399
+ field = "";
4400
+ depth = 0;
4401
+ /**
4402
+ * How deep in a blockquote of its own the reader is, in a forwarded message (one read with images): a message
4403
+ * forwarded from a reply chain holds the reply's quote, whose author and preview are part of what was forwarded, not
4404
+ * the forwarded message's own.
4405
+ */
4406
+ nested = 0;
4407
+ /** The link being read, and the words shown for it so far. */
4408
+ href = "";
4409
+ words = "";
4410
+ constructor(readImages = false) {
4411
+ this.images = readImages ? [] : void 0;
4412
+ }
4413
+ read(tokens) {
4414
+ for (const token of tokens) {
4415
+ if (token.kind === "data") this.data(token.text);
4416
+ else if (token.kind === "end") this.end(token.tag);
4417
+ else if (token.selfClosing) this.breakAt(token.tag);
4418
+ else this.start(token.tag, token.attrs);
4245
4419
  }
4246
- source += `[${lower}${upper}${own8(FOLDS, lower) ?? ""}]`;
4420
+ return this;
4247
4421
  }
4248
- return source;
4249
- }
4250
-
4251
- // packages/teams/src/activity/inbound/markup.ts
4252
- var AT_TAG = /<\/?[Aa][Tt]>/g;
4253
- var LINK_CHARS = 2e3;
4254
- var WEB_URL = new RegExp(`^${caseless("http")}${caseless("s")}?://[^${SPACE_CHARS}<>"']+$`, "u");
4255
- function webUrl(raw) {
4256
- const url = typeof raw === "string" ? pyStrip6(raw) : "";
4257
- return cpLength6(url) <= LINK_CHARS && WEB_URL.test(url) ? url : "";
4258
- }
4259
- function findTags(text4, names, closing) {
4260
- const head = new RegExp(`${closing ? "(/?)" : "()"}(?:${names.map(caseless).join("|")})${NOT_WORD_NEXT}`, "uy");
4261
- const found = [];
4262
- let gt = -1;
4263
- let at = text4.indexOf("<");
4264
- while (at >= 0) {
4265
- head.lastIndex = at + 1;
4266
- const match = head.exec(text4);
4267
- if (match) {
4268
- const nameEnd = head.lastIndex;
4269
- if (gt < nameEnd) gt = text4.indexOf(">", nameEnd);
4270
- if (gt < 0) break;
4271
- found.push({ start: at, end: gt + 1, closing: match[1] === "/", attrs: text4.slice(nameEnd, gt) });
4272
- at = text4.indexOf("<", gt + 1);
4273
- } else {
4274
- at = text4.indexOf("<", at + 1);
4422
+ breakAt(tag) {
4423
+ if (BREAKS.has(tag)) this.say("\n");
4424
+ }
4425
+ start(tag, attrs) {
4426
+ this.breakAt(tag);
4427
+ if (tag === "img") this.image(attrs);
4428
+ if (VOID.has(tag)) return;
4429
+ if (tag === "blockquote" && this.images !== void 0) this.nested++;
4430
+ if (tag === "a") [this.href, this.words] = [webUrl(attrValue(attrs, "href")), ""];
4431
+ if (this.field) {
4432
+ this.depth++;
4433
+ return;
4434
+ }
4435
+ if (this.nested > 0) return;
4436
+ const field = FIELDS.get(pyStr8(attrValue(attrs, "itemprop")).toLowerCase());
4437
+ if (field === "time") {
4438
+ this.time ||= pyStr8(attrValue(attrs, "itemid"));
4439
+ } else if (field) {
4440
+ if (field === "sender") this.senderId ||= pyStr8(attrValue(attrs, "itemid"));
4441
+ [this.field, this.depth] = [field, 1];
4275
4442
  }
4276
4443
  }
4277
- return found;
4444
+ /** An emoji is its own character; any other image is a marker (when images are read). */
4445
+ image(attrs) {
4446
+ if (this.images === void 0) return;
4447
+ const alt = squashSpaces3(pyStr8(attrValue(attrs, "alt")).replace(MARKS, ""));
4448
+ if (EMOJI_ITEMTYPE.test(pyStr8(attrValue(attrs, "itemtype")).trim())) {
4449
+ this.say(alt);
4450
+ return;
4451
+ }
4452
+ this.images.push({ src: webUrl(attrValue(attrs, "src")), itemId: pyStr8(attrValue(attrs, "itemid")), alt });
4453
+ this.say(imageMarker(this.images.length - 1));
4454
+ }
4455
+ end(tag) {
4456
+ this.breakAt(tag);
4457
+ if (VOID.has(tag)) return;
4458
+ if (tag === "blockquote" && this.nested > 0) this.nested--;
4459
+ if (tag === "a") {
4460
+ if (this.href && !this.words.includes(this.href)) this.say(` <${this.href}>`);
4461
+ this.href = "";
4462
+ }
4463
+ if (this.field) {
4464
+ this.depth--;
4465
+ if (this.depth <= 0) this.field = "";
4466
+ }
4467
+ }
4468
+ data(text4) {
4469
+ const words = this.images === void 0 ? text4 : text4.replace(MARKS, "");
4470
+ this.words += words;
4471
+ this.say(words);
4472
+ }
4473
+ say(piece) {
4474
+ this.everything.push(piece);
4475
+ if (this.field) this.parts[this.field].push(piece);
4476
+ }
4477
+ };
4478
+ function htmlForward(attrs, inner) {
4479
+ const reader2 = new ReplyReader(true).read(tokenize(inner));
4480
+ const quote2 = quoteOf(attrs, reader2);
4481
+ return {
4482
+ messageId: quote2.messageId,
4483
+ senderId: quote2.senderId,
4484
+ sender: quote2.sender,
4485
+ time: quote2.time,
4486
+ text: quote2.text,
4487
+ images: reader2.images ?? []
4488
+ };
4278
4489
  }
4279
- function replaceTags(text4, tags, by) {
4280
- let out = "";
4281
- let resume = 0;
4282
- for (const tag of tags) {
4283
- out += text4.slice(resume, tag.start) + by;
4284
- resume = tag.end;
4490
+ function htmlQuote(attrs, inner) {
4491
+ return quoteOf(attrs, new ReplyReader().read(tokenize(inner)));
4492
+ }
4493
+ function quoteOf(attrs, reader2) {
4494
+ const sender = squashSpaces3(reader2.parts.sender.join(""));
4495
+ let text4 = reader2.parts.text.join("");
4496
+ if (!text4) {
4497
+ const everything = reader2.everything.join("");
4498
+ text4 = sender ? everything.replace(sender, () => "") : everything;
4285
4499
  }
4286
- return out + text4.slice(resume);
4500
+ return {
4501
+ messageId: ITEMID.exec(attrs)?.[1] ?? "",
4502
+ senderId: reader2.senderId,
4503
+ sender,
4504
+ time: reader2.time,
4505
+ text: text4,
4506
+ deleted: false,
4507
+ source: "html"
4508
+ };
4287
4509
  }
4288
- var REPLY_ITEMTYPE = new RegExp(caseless("schema.skype.com/Reply"), "u");
4289
- function cutReplies(markup) {
4290
- const kept = [];
4291
- const cut = [];
4292
- let depth = 0;
4293
- let attrs = "";
4294
- let start = 0;
4295
- let resume = 0;
4296
- for (const tag of findTags(markup, ["blockquote"], true)) {
4297
- if (depth === 0) {
4298
- if (!tag.closing && REPLY_ITEMTYPE.test(tag.attrs)) {
4299
- kept.push(markup.slice(resume, tag.start));
4300
- [depth, attrs, start] = [1, tag.attrs, tag.end];
4301
- }
4302
- continue;
4510
+ function htmlQuotes(activity) {
4511
+ const cut = [...cutReplies(cutForwards(pyStr8(activity.text)).kept).cut];
4512
+ for (const attachment of attachmentsOf(activity)) {
4513
+ const content = attachment["content"];
4514
+ if (pyStr8(attachment["contentType"]).toLowerCase() === "text/html" && typeof content === "string") {
4515
+ cut.push(...cutReplies(cutForwards(content).kept).cut);
4303
4516
  }
4304
- depth += tag.closing ? -1 : 1;
4305
- if (depth === 0) {
4306
- cut.push([attrs, markup.slice(start, tag.start)]);
4307
- resume = tag.end;
4517
+ }
4518
+ return cut.map(([attrs, inner]) => htmlQuote(attrs, inner));
4519
+ }
4520
+
4521
+ // packages/teams/src/activity/inbound/quotes.ts
4522
+ import { cpHead as cpHead3, pyStr as pyStr9, pyStrip as pyStrip6, squashSpaces as squashSpaces4, own as own9 } from "@primusclaw/personal-agent";
4523
+ function entityQuotes(activity) {
4524
+ const quotes = [];
4525
+ for (const entity of entitiesOf2(activity)) {
4526
+ const data = entity["type"] === "quotedReply" ? entity["quotedReply"] : void 0;
4527
+ if (!isFields(data)) continue;
4528
+ quotes.push({
4529
+ messageId: pyStr9(data["messageId"]),
4530
+ senderId: pyStr9(data["senderId"]),
4531
+ sender: squashSpaces4(pyStr9(data["senderName"])),
4532
+ time: pyStr9(data["time"]),
4533
+ text: pyStr9(data["preview"]),
4534
+ deleted: data["isReplyDeleted"] === true,
4535
+ source: "entity"
4536
+ });
4537
+ }
4538
+ return quotes;
4539
+ }
4540
+ function sameQuote(known, html) {
4541
+ if (known.messageId) return known.messageId === html.messageId;
4542
+ return known.sender === html.sender && known.text === html.text;
4543
+ }
4544
+ function quotesOf(activity) {
4545
+ const quotes = entityQuotes(activity);
4546
+ for (const html of htmlQuotes(activity)) {
4547
+ const same = quotes.findIndex((q) => sameQuote(q, html));
4548
+ const known = quotes[same];
4549
+ if (known === void 0) {
4550
+ quotes.push(html);
4551
+ continue;
4308
4552
  }
4553
+ quotes[same] = {
4554
+ ...known,
4555
+ senderId: known.senderId || html.senderId,
4556
+ sender: known.sender || html.sender,
4557
+ time: known.time || html.time,
4558
+ text: known.text || html.text
4559
+ };
4309
4560
  }
4310
- if (depth) {
4311
- cut.push([attrs, markup.slice(start)]);
4312
- resume = markup.length;
4561
+ for (const id of quotedIds(pyStr9(activity.text))) {
4562
+ if (!quotes.some((q) => q.messageId === id)) {
4563
+ quotes.push({
4564
+ messageId: id,
4565
+ senderId: "",
4566
+ sender: "",
4567
+ time: "",
4568
+ text: "",
4569
+ deleted: false,
4570
+ source: "placeholder"
4571
+ });
4572
+ }
4313
4573
  }
4314
- kept.push(markup.slice(resume));
4315
- return { kept: kept.join(""), cut };
4574
+ return quotes;
4316
4575
  }
4317
- function written(activity) {
4318
- let text4 = pyStr8(activity.text);
4319
- if (REPLY_ITEMTYPE.test(text4)) {
4320
- const { kept } = cutReplies(text4);
4321
- text4 = replaceTags(kept, findTags(kept, ["p", "div", "br", "span"], true), " ");
4576
+ function isBotQuote(quote2, bot) {
4577
+ const botId = pyStr9(bot["id"]).toLowerCase();
4578
+ const quoteId = quote2.senderId.toLowerCase();
4579
+ if (botId && quoteId) {
4580
+ const botTail = botId.slice(botId.lastIndexOf(":") + 1);
4581
+ const quoteTail = quoteId.slice(quoteId.lastIndexOf(":") + 1);
4582
+ return quoteId === botId || quoteTail !== "" && quoteTail === botTail;
4322
4583
  }
4323
- return replaceTags(text4, findTags(text4, ["quoted"], true), "");
4584
+ return !quoteId && Boolean(quote2.sender) && quote2.sender.toLowerCase() === pyStrip6(pyStr9(bot["name"])).toLowerCase();
4324
4585
  }
4325
- var MESSAGE_ID = new RegExp(caseless("messageId"), "gu");
4326
- var SPACE_ONE = new RegExp(`^${SPACE}$`, "u");
4327
- function idHeadEnd(text4, at) {
4328
- let i = at;
4329
- while (i < text4.length && SPACE_ONE.test(text4.charAt(i))) i += 1;
4330
- if (text4.charAt(i) !== "=") return void 0;
4331
- i += 1;
4332
- while (i < text4.length && SPACE_ONE.test(text4.charAt(i))) i += 1;
4333
- return text4.charAt(i) === '"' || text4.charAt(i) === "'" ? i + 1 : i;
4586
+ var KIND_CHAR = /^[\p{L}\p{N}/._-]$/u;
4587
+ function kindsOf(items, key) {
4588
+ if (!Array.isArray(items)) return [];
4589
+ return items.filter(isFields).slice(0, 10).map(
4590
+ (item3) => Array.from(cpHead3(pyStr9(own9(item3, key)), 40)).filter((ch) => KIND_CHAR.test(ch)).join("")
4591
+ );
4334
4592
  }
4335
- var VALUE_STOP = new RegExp(`["'/>${SPACE_CHARS}]`, "u");
4336
- var WORD_CHAR = new RegExp(`^${WORD}$`, "u");
4337
- function valueEnds(text4) {
4338
- let runStart = 0;
4339
- let runEnd = -1;
4340
- return (at) => {
4341
- if (at >= runStart && at < runEnd) return runEnd;
4342
- let end = at;
4343
- while (end < text4.length && !VALUE_STOP.test(text4[end] ?? "")) end++;
4344
- [runStart, runEnd] = [at, end];
4345
- return end;
4346
- };
4593
+ function logPlaceholderQuotes(activity, quotes, logger) {
4594
+ if (!quotes.some((q) => q.source === "placeholder")) return;
4595
+ logger.warn("a quoted placeholder came with no quote data", {
4596
+ entityTypes: kindsOf(activity.entities, "type").join(","),
4597
+ attachmentTypes: kindsOf(activity.attachments, "contentType").join(",")
4598
+ });
4347
4599
  }
4348
- function codePointBefore(text4, at) {
4349
- if (at <= 0) return void 0;
4350
- const low = text4.charCodeAt(at - 1);
4351
- const pair = low >= 56320 && low <= 57343 && at >= 2 ? text4.slice(at - 2, at) : text4.slice(at - 1, at);
4352
- return Array.from(pair).at(-1);
4600
+
4601
+ // packages/teams/src/activity/inbound/forwards.ts
4602
+ var FORWARD_REFERENCE = "forwardedmessagereference";
4603
+ var REFERENCE_CHARS = 1e6;
4604
+ function str(value) {
4605
+ return typeof value === "string" ? value : "";
4353
4606
  }
4354
- function idCandidates(text4) {
4355
- const end = valueEnds(text4);
4607
+ function htmlForwards(activity) {
4608
+ const markups = [pyStr10(activity.text)];
4609
+ for (const attachment of attachmentsOf(activity)) {
4610
+ const content = attachment["content"];
4611
+ if (pyStr10(attachment["contentType"]).toLowerCase() === "text/html" && typeof content === "string") {
4612
+ markups.push(content);
4613
+ }
4614
+ }
4356
4615
  const found = [];
4357
- for (const match of text4.matchAll(MESSAGE_ID)) {
4358
- const before = codePointBefore(text4, match.index);
4359
- if (before !== void 0 && WORD_CHAR.test(before)) continue;
4360
- const valueStart = idHeadEnd(text4, match.index + match[0].length);
4361
- if (valueStart === void 0) continue;
4362
- const valueEnd = end(valueStart);
4363
- if (valueEnd > valueStart) found.push({ start: match.index, valueStart, valueEnd });
4616
+ for (const markup of markups) {
4617
+ if (!FORWARD_ITEMTYPE.test(markup)) continue;
4618
+ found.push(cutForwards(markup).cut.map(([attrs, inner]) => ({ ...htmlForward(attrs, inner), source: "html" })));
4364
4619
  }
4365
4620
  return found;
4366
4621
  }
4367
- function quotedIds(text4) {
4368
- const candidates = idCandidates(text4);
4369
- const ids = [];
4370
- let next = 0;
4371
- let resume = 0;
4372
- let gt = -1;
4373
- for (const tag of quotedStarts(text4)) {
4374
- if (tag.start < resume) continue;
4375
- if (gt < tag.nameEnd) gt = text4.indexOf(">", tag.nameEnd);
4376
- const segmentEnd = gt < 0 ? text4.length : gt;
4377
- while (next < candidates.length && (candidates[next]?.start ?? 0) < tag.nameEnd) next++;
4378
- const found = candidates[next];
4379
- if (found === void 0 || found.start >= segmentEnd) continue;
4380
- ids.push(text4.slice(found.valueStart, found.valueEnd));
4381
- resume = found.valueEnd;
4622
+ function referenceContent(content) {
4623
+ if (isFields(content)) return content;
4624
+ if (typeof content !== "string" || content.length > REFERENCE_CHARS) return void 0;
4625
+ try {
4626
+ const parsed = JSON.parse(content);
4627
+ return isFields(parsed) ? parsed : void 0;
4628
+ } catch {
4629
+ return void 0;
4382
4630
  }
4383
- return ids;
4384
4631
  }
4385
- var QUOTED_HEAD = new RegExp(`${caseless("quoted")}${NOT_WORD_NEXT}`, "uy");
4386
- function quotedStarts(text4) {
4387
- const starts = [];
4388
- for (let at = text4.indexOf("<"); at >= 0; at = text4.indexOf("<", at + 1)) {
4389
- QUOTED_HEAD.lastIndex = at + 1;
4390
- if (QUOTED_HEAD.test(text4)) starts.push({ start: at, nameEnd: QUOTED_HEAD.lastIndex });
4632
+ function senderOf(content) {
4633
+ const sender = content["originalMessageSender"];
4634
+ if (!isFields(sender)) return { name: "", id: "" };
4635
+ for (const kind of ["user", "application", "device"]) {
4636
+ const who = own10(sender, kind);
4637
+ if (isFields(who) && (str(who["displayName"]) || str(who["id"]))) {
4638
+ return { name: squashSpaces5(str(who["displayName"])), id: str(who["id"]) };
4639
+ }
4391
4640
  }
4392
- return starts;
4641
+ return { name: "", id: "" };
4642
+ }
4643
+ function referenceForwards(activity) {
4644
+ const found = [];
4645
+ for (const attachment of attachmentsOf(activity)) {
4646
+ if (pyStr10(attachment["contentType"]).toLowerCase() !== FORWARD_REFERENCE) continue;
4647
+ const content = referenceContent(attachment["content"]) ?? {};
4648
+ const html = htmlForward("", str(content["originalMessageContent"]));
4649
+ const sender = senderOf(content);
4650
+ found.push({
4651
+ messageId: str(content["originalMessageId"]) || pyStr10(attachment["id"]),
4652
+ senderId: sender.id,
4653
+ sender: sender.name,
4654
+ time: str(content["originalSentDateTime"]),
4655
+ text: html.text,
4656
+ images: html.images,
4657
+ source: "reference"
4658
+ });
4659
+ }
4660
+ return found;
4661
+ }
4662
+ function plainText(read) {
4663
+ return squashSpaces5(read.text.replace(IMAGE_MARKER, ""));
4664
+ }
4665
+ function sameForward(known, other) {
4666
+ if (known.messageId && other.messageId) return known.messageId === other.messageId;
4667
+ return plainText(known) !== "" && plainText(known) === plainText(other);
4668
+ }
4669
+ function imageKey(image) {
4670
+ return objectIdOf(image) || image.src;
4671
+ }
4672
+ function withImagesOf(known, other) {
4673
+ const have = new Set(known.images.map(imageKey).filter(Boolean));
4674
+ const more = other.images.filter((image) => {
4675
+ const key = imageKey(image);
4676
+ if (key && have.has(key)) return false;
4677
+ if (key) have.add(key);
4678
+ return true;
4679
+ });
4680
+ if (more.length === 0) return { text: known.text, images: known.images };
4681
+ const images = [...known.images, ...more];
4682
+ const markers = more.map((_, at) => imageMarker(known.images.length + at)).join(" ");
4683
+ return { text: known.text ? `${known.text}
4684
+ ${markers}` : markers, images };
4685
+ }
4686
+ function forwardsRead(activity) {
4687
+ const found = referenceForwards(activity);
4688
+ for (const markup of htmlForwards(activity)) {
4689
+ const taken = /* @__PURE__ */ new Set();
4690
+ for (const html of markup) {
4691
+ const same = found.findIndex((known2, at) => !taken.has(at) && sameForward(known2, html));
4692
+ const known = found[same];
4693
+ if (known === void 0) {
4694
+ taken.add(found.length);
4695
+ found.push(html);
4696
+ continue;
4697
+ }
4698
+ taken.add(same);
4699
+ found[same] = {
4700
+ ...known,
4701
+ senderId: known.senderId || html.senderId,
4702
+ sender: known.sender || html.sender,
4703
+ time: known.time || html.time,
4704
+ ...plainText(known) || known.images.length ? withImagesOf(known, html) : { text: html.text, images: html.images }
4705
+ };
4706
+ }
4707
+ }
4708
+ return found;
4709
+ }
4710
+ var OBJECT_PATH = /\/objects\/([A-Za-z0-9._~-]{1,200})\/views\//u;
4711
+ var OBJECT_ID = /^[A-Za-z0-9._~-]{1,200}$/u;
4712
+ function objectIdOf(image) {
4713
+ if (OBJECT_ID.test(image.itemId) && image.itemId.includes("-")) return image.itemId;
4714
+ return OBJECT_PATH.exec(image.src)?.[1] ?? "";
4715
+ }
4716
+ function connectorImageUrl(serviceUrl, objectId) {
4717
+ if (!serviceUrl.startsWith("https://")) return "";
4718
+ const base2 = serviceUrl.endsWith("/") ? serviceUrl : `${serviceUrl}/`;
4719
+ return `${base2}v3/attachments/${encodeURIComponent(objectId)}/views/original`;
4720
+ }
4721
+ function decoded(text4) {
4722
+ try {
4723
+ return decodeURIComponent(text4);
4724
+ } catch {
4725
+ return text4;
4726
+ }
4727
+ }
4728
+ function tidy(text4) {
4729
+ return text4.split("\n").map((line2) => line2.trimEnd()).filter((line2) => line2.trim() !== "").join("\n").trim();
4730
+ }
4731
+ function forwardsOf(activity, files, logger) {
4732
+ const read = forwardsRead(activity);
4733
+ const all = [...files];
4734
+ if (read.length === 0) return { forwards: [], files: all };
4735
+ const serviceUrl = pyStr10(activity.serviceUrl);
4736
+ const placeOf = /* @__PURE__ */ new Map();
4737
+ for (const [at, file] of all.entries()) {
4738
+ const url = str(file.handle["url"]);
4739
+ const id = file.handle["kind"] === "pasted" ? /\/attachments\/([^/]+)\/views\//u.exec(url)?.[1] ?? "" : "";
4740
+ if (id) placeOf.set(decoded(id), at + 1);
4741
+ }
4742
+ const forwards = read.map((forward) => {
4743
+ const words = forward.images.map((image) => {
4744
+ const id = objectIdOf(image);
4745
+ const url = id ? connectorImageUrl(serviceUrl, id) : "";
4746
+ if (!url) return "[image not passed on]";
4747
+ let place = placeOf.get(id);
4748
+ if (place === void 0) {
4749
+ place = all.length + 1;
4750
+ const handle = { kind: "pasted", url, index: place };
4751
+ all.push({ name: "", type: "", handle: { ...handle } });
4752
+ placeOf.set(id, place);
4753
+ }
4754
+ return `[image-${String(place)}]`;
4755
+ });
4756
+ return {
4757
+ messageId: forward.messageId,
4758
+ author: forward.sender,
4759
+ text: tidy(forward.text.replace(IMAGE_MARKER, (_, at) => words[Number(at)] ?? "")),
4760
+ sentAt: forward.time,
4761
+ source: forward.source
4762
+ };
4763
+ });
4764
+ logger?.info("forwarded messages read", {
4765
+ count: forwards.length,
4766
+ sources: [...new Set(read.map((f) => f.source))].sort().join("+"),
4767
+ images: read.reduce((n, f) => n + f.images.length, 0),
4768
+ attachmentTypes: kindsOf(activity.attachments, "contentType").join(",")
4769
+ });
4770
+ return { forwards, files: all };
4771
+ }
4772
+ function forwardsInText(activity) {
4773
+ return FORWARD_ITEMTYPE.test(pyStr10(activity.text));
4774
+ }
4775
+ var LINK_ADDRESS = / <https?:\/\/[^\s<>]+>/gu;
4776
+ function ownWords(text4, forwards, keepSome = false) {
4777
+ const said = forwards.map((f) => squashSpaces5(f.text.replace(/\[image(?:-[0-9]+| not passed on)\]/gu, ""))).filter(Boolean);
4778
+ if (said.length === 0) return text4;
4779
+ let own14 = squashSpaces5(text4);
4780
+ for (const one of [...said].reverse()) {
4781
+ const shown = squashSpaces5(one.replace(LINK_ADDRESS, ""));
4782
+ const copy2 = [one, shown].find((words) => words !== "" && (own14 === words || own14.endsWith(` ${words}`)));
4783
+ if (copy2 === void 0) return text4;
4784
+ own14 = own14 === copy2 ? "" : own14.slice(0, own14.length - copy2.length - 1);
4785
+ }
4786
+ if (own14 === "" && keepSome) return text4;
4787
+ return firstWords(text4, pySplit2(own14).length);
4788
+ }
4789
+ function firstWords(text4, count2) {
4790
+ let at = 0;
4791
+ for (let words = 0; words < count2; words += 1) {
4792
+ while (at < text4.length && isPySpace2(text4.charAt(at))) at += 1;
4793
+ while (at < text4.length && !isPySpace2(text4.charAt(at))) at += 1;
4794
+ }
4795
+ return text4.slice(0, at);
4796
+ }
4797
+ var READ_KINDS = /^(?:text\/html|image\/.*|application\/vnd\.microsoft\.card\..*|application\/vnd\.microsoft\.teams\.file\.download\.info|forwardedmessagereference)$/u;
4798
+ function logUnreadKinds(activity, logger) {
4799
+ const kinds = kindsOf(activity.attachments, "contentType");
4800
+ if (!kinds.some((kind) => !READ_KINDS.test(kind.toLowerCase()))) return;
4801
+ logger.info("an attachment of a kind not read", {
4802
+ attachmentTypes: kinds.join(","),
4803
+ entityTypes: kindsOf(activity.entities, "type").join(",")
4804
+ });
4805
+ }
4806
+
4807
+ // packages/teams/src/activity/inbound/identity.ts
4808
+ import { cpHead as cpHead4, pyStr as pyStr11, pyStrip as pyStrip7 } from "@primusclaw/personal-agent";
4809
+ function senderOf2(activity) {
4810
+ const who = partOf(activity, "from");
4811
+ const aadId = who["aadObjectId"];
4812
+ if (typeof aadId !== "string" || !aadId) return void 0;
4813
+ const email = pyStrip7(pyStr11(who["userPrincipalName"]) || pyStr11(who["email"]));
4814
+ return { aadId, name: pyStr11(who["name"]), email: email.includes("@") ? email : "" };
4815
+ }
4816
+ function conversationType(activity) {
4817
+ return partOf(activity, "conversation")["conversationType"];
4818
+ }
4819
+ function isPersonal(activity) {
4820
+ return conversationType(activity) === "personal";
4821
+ }
4822
+ function isGroup(activity) {
4823
+ return conversationType(activity) === "groupChat";
4824
+ }
4825
+ function conversationKind(activity) {
4826
+ if (isPersonal(activity)) return "personal";
4827
+ return isGroup(activity) ? "group" : "channel";
4828
+ }
4829
+ function conversationId(activity) {
4830
+ return pyStr11(partOf(activity, "conversation")["id"]);
4831
+ }
4832
+ function tenantOf(activity) {
4833
+ const channelData = activity.channelData;
4834
+ const tenant = isFields(channelData) ? channelData["tenant"] : void 0;
4835
+ const fromChannel = isFields(tenant) ? tenant["id"] : void 0;
4836
+ return pyStr11(partOf(activity, "conversation")["tenantId"]) || pyStr11(fromChannel);
4837
+ }
4838
+ var ALNUM2 = /[\p{L}\p{N}]/u;
4839
+ function clientPlatform(activity) {
4840
+ const info = entitiesOf2(activity).find((entity) => entity["type"] === "clientInfo");
4841
+ const platform = info?.["platform"];
4842
+ if (typeof platform !== "string") return "";
4843
+ return cpHead4(
4844
+ Array.from(platform).filter((ch) => ALNUM2.test(ch)).join(""),
4845
+ 16
4846
+ );
4393
4847
  }
4394
4848
 
4395
4849
  // packages/teams/src/activity/inbound/links.ts
4850
+ import { pyStr as pyStr12, squashSpaces as squashSpaces6 } from "@primusclaw/personal-agent";
4396
4851
  var LINK_COUNT = 20;
4397
4852
  var CARD_TYPES = ["application/vnd.microsoft.card.", "application/vnd.microsoft.teams.card."];
4398
4853
  var PLAIN_ENTITIES = /* @__PURE__ */ new Set(["mention", "clientInfo", "quotedReply", "ProductInfo", "streamInfo"]);
@@ -4406,7 +4861,7 @@ function htmlLinks(markup) {
4406
4861
  let words = "";
4407
4862
  const end = () => {
4408
4863
  if (url) {
4409
- const label = squashSpaces3(words);
4864
+ const label = squashSpaces6(words);
4410
4865
  found.push({ url, label: label === url ? "" : label });
4411
4866
  }
4412
4867
  [url, words] = ["", ""];
@@ -4425,8 +4880,8 @@ function htmlLinks(markup) {
4425
4880
  }
4426
4881
  function objectLinks(node, title, depth) {
4427
4882
  const found = [];
4428
- const own13 = node["title"];
4429
- const label = typeof own13 === "string" ? squashSpaces3(own13) : title;
4883
+ const own14 = node["title"];
4884
+ const label = typeof own14 === "string" ? squashSpaces6(own14) : title;
4430
4885
  const action2 = node["type"] === "openUrl" || node["type"] === "Action.OpenUrl" ? webUrl(node["value"]) : "";
4431
4886
  if (action2) found.push({ url: action2, label });
4432
4887
  for (const [key, value] of Object.entries(node)) {
@@ -4448,12 +4903,12 @@ function cardLinks(node, title = "", depth = 0) {
4448
4903
  function attachmentLinks(activity) {
4449
4904
  const found = [];
4450
4905
  for (const attachment of attachmentsOf(activity)) {
4451
- const kind = pyStr9(attachment["contentType"]).toLowerCase();
4906
+ const kind = pyStr12(attachment["contentType"]).toLowerCase();
4452
4907
  const content = attachment["content"];
4453
4908
  if (kind === "text/html" && typeof content === "string") {
4454
- found.push(...htmlLinks(cutReplies(content).kept));
4909
+ found.push(...htmlLinks(cutForwards(cutReplies(content).kept).kept));
4455
4910
  } else if (CARD_TYPES.some((prefix) => kind.startsWith(prefix))) {
4456
- found.push(...cardLinks(content, pyStr9(attachment["name"])));
4911
+ found.push(...cardLinks(content, pyStr12(attachment["name"])));
4457
4912
  const url = "contentUrl" in attachment ? webUrl(attachment["contentUrl"]) : "";
4458
4913
  if (url) found.push({ url, label: "" });
4459
4914
  }
@@ -4475,7 +4930,7 @@ function inboundLinksOf(activity) {
4475
4930
  }
4476
4931
 
4477
4932
  // packages/teams/src/activity/inbound/mentions.ts
4478
- import { BOT_NAME, cpLength as cpLength7, pyLstrip as pyLstrip2, pyStr as pyStr10, pyStrip as pyStrip7 } from "@primusclaw/personal-agent";
4933
+ import { BOT_NAME, cpLength as cpLength7, pyLstrip as pyLstrip2, pyStr as pyStr13, pyStrip as pyStrip8 } from "@primusclaw/personal-agent";
4479
4934
  var DEFAULT_BOT_NAME = BOT_NAME;
4480
4935
  function isMention(entity) {
4481
4936
  return entity["type"] === "mention";
@@ -4512,10 +4967,10 @@ function messageText(activity) {
4512
4967
  const botId = botIdOf(activity);
4513
4968
  for (const entity of entitiesOf2(activity)) {
4514
4969
  if (isMention(entity) && (!botId || mentionsBot(entity, botId) || !truthy(entity["mentioned"]))) {
4515
- text4 = text4.replaceAll(pyStr10(entity["text"]), "");
4970
+ text4 = text4.replaceAll(pyStr13(entity["text"]), "");
4516
4971
  }
4517
4972
  }
4518
- return pyStrip7(text4.replace(AT_TAG, ""));
4973
+ return pyStrip8(text4.replace(AT_TAG, ""));
4519
4974
  }
4520
4975
  var HOLD_OPEN = String.fromCharCode(57344);
4521
4976
  var HOLD_CLOSE = String.fromCharCode(57345);
@@ -4524,7 +4979,7 @@ function holdMentions(activity, botId) {
4524
4979
  let text4 = written(activity);
4525
4980
  const others = [];
4526
4981
  for (const entity of entitiesOf2(activity).filter(isMention)) {
4527
- const raw = pyStr10(entity["text"]);
4982
+ const raw = pyStr13(entity["text"]);
4528
4983
  const mentioned2 = entity["mentioned"];
4529
4984
  if (!raw || !text4.includes(raw)) continue;
4530
4985
  if (mentionsBot(entity, botId)) {
@@ -4536,7 +4991,7 @@ function holdMentions(activity, botId) {
4536
4991
  }
4537
4992
  }
4538
4993
  for (const entity of entitiesOf2(activity).filter(isMention)) {
4539
- if (!truthy(entity["mentioned"])) text4 = text4.replaceAll(pyStr10(entity["text"]), "");
4994
+ if (!truthy(entity["mentioned"])) text4 = text4.replaceAll(pyStr13(entity["text"]), "");
4540
4995
  }
4541
4996
  return { held: text4.replace(AT_TAG, ""), others };
4542
4997
  }
@@ -4554,13 +5009,13 @@ function release(held, others) {
4554
5009
  text4 += held.slice(resume);
4555
5010
  const lead = cpLength7(text4) - cpLength7(pyLstrip2(text4));
4556
5011
  for (const [index, offset] of offsets) offsets.set(index, offset - lead);
4557
- return { text: pyStrip7(text4), offsets };
5012
+ return { text: pyStrip8(text4), offsets };
4558
5013
  }
4559
5014
  function inbound(other, offset) {
4560
5015
  return {
4561
- channelUserId: pyStr10(other.mentioned["id"]),
4562
- userId: pyStr10(other.mentioned["aadObjectId"]),
4563
- name: pyStr10(other.mentioned["name"]),
5016
+ channelUserId: pyStr13(other.mentioned["id"]),
5017
+ userId: pyStr13(other.mentioned["aadObjectId"]),
5018
+ name: pyStr13(other.mentioned["name"]),
4564
5019
  shown: other.shown,
4565
5020
  offset
4566
5021
  };
@@ -4584,187 +5039,6 @@ function cpIndexOf(text4, part) {
4584
5039
  return at < 0 ? -1 : cpLength7(text4.slice(0, at));
4585
5040
  }
4586
5041
 
4587
- // packages/teams/src/activity/inbound/quotes.ts
4588
- import { cpHead as cpHead4, pyStr as pyStr12, pyStrip as pyStrip8, squashSpaces as squashSpaces5, own as own9 } from "@primusclaw/personal-agent";
4589
-
4590
- // packages/teams/src/activity/inbound/quotes-html.ts
4591
- import { pyStr as pyStr11, squashSpaces as squashSpaces4 } from "@primusclaw/personal-agent";
4592
- var FIELDS = /* @__PURE__ */ new Map([
4593
- ["mri", "sender"],
4594
- ["time", "time"],
4595
- ["preview", "text"],
4596
- ["copy", "text"]
4597
- ]);
4598
- var BREAKS = /* @__PURE__ */ new Set(["br", "p", "div", "li", "tr"]);
4599
- var VOID = /* @__PURE__ */ new Set(["br", "img", "hr", "wbr", "input", "meta", "link"]);
4600
- var ITEMID = new RegExp(`(?<!${WORD})${caseless("itemid")}${SPACE}*=${SPACE}*["']?([^"'>${SPACE_CHARS}]+)`, "u");
4601
- var ReplyReader = class {
4602
- senderId = "";
4603
- time = "";
4604
- parts = { sender: [], text: [] };
4605
- everything = [];
4606
- field = "";
4607
- depth = 0;
4608
- /** The link being read, and the words shown for it so far. */
4609
- href = "";
4610
- words = "";
4611
- read(tokens) {
4612
- for (const token of tokens) {
4613
- if (token.kind === "data") this.data(token.text);
4614
- else if (token.kind === "end") this.end(token.tag);
4615
- else if (token.selfClosing) this.breakAt(token.tag);
4616
- else this.start(token.tag, token.attrs);
4617
- }
4618
- return this;
4619
- }
4620
- breakAt(tag) {
4621
- if (BREAKS.has(tag)) this.say("\n");
4622
- }
4623
- start(tag, attrs) {
4624
- this.breakAt(tag);
4625
- if (VOID.has(tag)) return;
4626
- if (tag === "a") [this.href, this.words] = [webUrl(attrValue(attrs, "href")), ""];
4627
- if (this.field) {
4628
- this.depth++;
4629
- return;
4630
- }
4631
- const field = FIELDS.get(pyStr11(attrValue(attrs, "itemprop")).toLowerCase());
4632
- if (field === "time") {
4633
- this.time ||= pyStr11(attrValue(attrs, "itemid"));
4634
- } else if (field) {
4635
- if (field === "sender") this.senderId ||= pyStr11(attrValue(attrs, "itemid"));
4636
- [this.field, this.depth] = [field, 1];
4637
- }
4638
- }
4639
- end(tag) {
4640
- this.breakAt(tag);
4641
- if (VOID.has(tag)) return;
4642
- if (tag === "a") {
4643
- if (this.href && !this.words.includes(this.href)) this.say(` <${this.href}>`);
4644
- this.href = "";
4645
- }
4646
- if (this.field) {
4647
- this.depth--;
4648
- if (this.depth <= 0) this.field = "";
4649
- }
4650
- }
4651
- data(text4) {
4652
- this.words += text4;
4653
- this.say(text4);
4654
- }
4655
- say(piece) {
4656
- this.everything.push(piece);
4657
- if (this.field) this.parts[this.field].push(piece);
4658
- }
4659
- };
4660
- function htmlQuote(attrs, inner) {
4661
- const reader2 = new ReplyReader().read(tokenize(inner));
4662
- const sender = squashSpaces4(reader2.parts.sender.join(""));
4663
- let text4 = reader2.parts.text.join("");
4664
- if (!text4) {
4665
- const everything = reader2.everything.join("");
4666
- text4 = sender ? everything.replace(sender, () => "") : everything;
4667
- }
4668
- return {
4669
- messageId: ITEMID.exec(attrs)?.[1] ?? "",
4670
- senderId: reader2.senderId,
4671
- sender,
4672
- time: reader2.time,
4673
- text: text4,
4674
- deleted: false,
4675
- source: "html"
4676
- };
4677
- }
4678
- function htmlQuotes(activity) {
4679
- const cut = [...cutReplies(pyStr11(activity.text)).cut];
4680
- for (const attachment of attachmentsOf(activity)) {
4681
- const content = attachment["content"];
4682
- if (pyStr11(attachment["contentType"]).toLowerCase() === "text/html" && typeof content === "string") {
4683
- cut.push(...cutReplies(content).cut);
4684
- }
4685
- }
4686
- return cut.map(([attrs, inner]) => htmlQuote(attrs, inner));
4687
- }
4688
-
4689
- // packages/teams/src/activity/inbound/quotes.ts
4690
- function entityQuotes(activity) {
4691
- const quotes = [];
4692
- for (const entity of entitiesOf2(activity)) {
4693
- const data = entity["type"] === "quotedReply" ? entity["quotedReply"] : void 0;
4694
- if (!isFields(data)) continue;
4695
- quotes.push({
4696
- messageId: pyStr12(data["messageId"]),
4697
- senderId: pyStr12(data["senderId"]),
4698
- sender: squashSpaces5(pyStr12(data["senderName"])),
4699
- time: pyStr12(data["time"]),
4700
- text: pyStr12(data["preview"]),
4701
- deleted: data["isReplyDeleted"] === true,
4702
- source: "entity"
4703
- });
4704
- }
4705
- return quotes;
4706
- }
4707
- function sameQuote(known, html) {
4708
- if (known.messageId) return known.messageId === html.messageId;
4709
- return known.sender === html.sender && known.text === html.text;
4710
- }
4711
- function quotesOf(activity) {
4712
- const quotes = entityQuotes(activity);
4713
- for (const html of htmlQuotes(activity)) {
4714
- const same = quotes.findIndex((q) => sameQuote(q, html));
4715
- const known = quotes[same];
4716
- if (known === void 0) {
4717
- quotes.push(html);
4718
- continue;
4719
- }
4720
- quotes[same] = {
4721
- ...known,
4722
- senderId: known.senderId || html.senderId,
4723
- sender: known.sender || html.sender,
4724
- time: known.time || html.time,
4725
- text: known.text || html.text
4726
- };
4727
- }
4728
- for (const id of quotedIds(pyStr12(activity.text))) {
4729
- if (!quotes.some((q) => q.messageId === id)) {
4730
- quotes.push({
4731
- messageId: id,
4732
- senderId: "",
4733
- sender: "",
4734
- time: "",
4735
- text: "",
4736
- deleted: false,
4737
- source: "placeholder"
4738
- });
4739
- }
4740
- }
4741
- return quotes;
4742
- }
4743
- function isBotQuote(quote2, bot) {
4744
- const botId = pyStr12(bot["id"]).toLowerCase();
4745
- const quoteId = quote2.senderId.toLowerCase();
4746
- if (botId && quoteId) {
4747
- const botTail = botId.slice(botId.lastIndexOf(":") + 1);
4748
- const quoteTail = quoteId.slice(quoteId.lastIndexOf(":") + 1);
4749
- return quoteId === botId || quoteTail !== "" && quoteTail === botTail;
4750
- }
4751
- return !quoteId && Boolean(quote2.sender) && quote2.sender.toLowerCase() === pyStrip8(pyStr12(bot["name"])).toLowerCase();
4752
- }
4753
- var KIND_CHAR = /^[\p{L}\p{N}/._-]$/u;
4754
- function kindsOf(items, key) {
4755
- if (!Array.isArray(items)) return [];
4756
- return items.filter(isFields).slice(0, 10).map(
4757
- (item3) => Array.from(cpHead4(pyStr12(own9(item3, key)), 40)).filter((ch) => KIND_CHAR.test(ch)).join("")
4758
- );
4759
- }
4760
- function logPlaceholderQuotes(activity, quotes, logger) {
4761
- if (!quotes.some((q) => q.source === "placeholder")) return;
4762
- logger.warn("a quoted placeholder came with no quote data", {
4763
- entityTypes: kindsOf(activity.entities, "type").join(","),
4764
- attachmentTypes: kindsOf(activity.attachments, "contentType").join(",")
4765
- });
4766
- }
4767
-
4768
5042
  // packages/teams/src/activity/inbound/to-event.ts
4769
5043
  function wireReferenceOf(activity) {
4770
5044
  const ref = {
@@ -4788,10 +5062,10 @@ function conversationRefOf(activity) {
4788
5062
  }
4789
5063
  function base(activity, sender) {
4790
5064
  return {
4791
- id: pyStr13(activity.id),
5065
+ id: pyStr14(activity.id),
4792
5066
  sender,
4793
5067
  conversation: conversationRefOf(activity),
4794
- locale: pyStr13(activity.locale),
5068
+ locale: pyStr14(activity.locale),
4795
5069
  clientPlatform: clientPlatform(activity)
4796
5070
  };
4797
5071
  }
@@ -4800,16 +5074,18 @@ function messageOf(activity, sender, options) {
4800
5074
  const personal = isPersonal(activity);
4801
5075
  const found = quotesOf(activity);
4802
5076
  const attached = inboundFiles(activity);
5077
+ const forwarded = forwardsOf(activity, attached.files, logger);
4803
5078
  logPlaceholderQuotes(activity, found, logger);
5079
+ logUnreadKinds(activity, logger);
4804
5080
  const bot = partOf(activity, "recipient");
4805
5081
  return {
4806
5082
  type: "message",
4807
5083
  ...base(activity, sender),
4808
- text: messageText(activity),
5084
+ text: forwarded.forwards.length && !forwardsInText(activity) ? ownWords(messageText(activity), forwarded.forwards, /<attachment\b/iu.test(pyStr14(activity.text))) : messageText(activity),
4809
5085
  mentioned: isMentioned(activity),
4810
5086
  targeted: isTargeted(activity),
4811
5087
  namesBotFirst: addressedToBot(activity, options.botName ?? DEFAULT_BOT_NAME),
4812
- conversationName: personal ? "" : pyStr13(partOf(activity, "conversation")["name"]),
5088
+ conversationName: personal ? "" : pyStr14(partOf(activity, "conversation")["name"]),
4813
5089
  mentions: mentionsOf(activity),
4814
5090
  links: inboundLinksOf(activity),
4815
5091
  quotes: found.map((q) => ({
@@ -4821,7 +5097,8 @@ function messageOf(activity, sender, options) {
4821
5097
  deleted: q.deleted,
4822
5098
  source: q.source
4823
5099
  })),
4824
- files: attached.files,
5100
+ ...forwarded.forwards.length ? { forwards: forwarded.forwards } : {},
5101
+ files: forwarded.files,
4825
5102
  unreadableFiles: attached.unreadable,
4826
5103
  provenance: "typed"
4827
5104
  };
@@ -4832,7 +5109,7 @@ function actionOf(activity, sender) {
4832
5109
  ...base(activity, sender),
4833
5110
  verb: cardKindOf(activity),
4834
5111
  data: cardDataOf(activity) ?? {},
4835
- cardMessageId: pyStr13(activity.replyToId),
5112
+ cardMessageId: pyStr14(activity.replyToId),
4836
5113
  invoke: isCardClick(activity),
4837
5114
  clickVerb: cardVerb(activity)
4838
5115
  };
@@ -4841,11 +5118,11 @@ function toInboundEvent(raw, options = {}) {
4841
5118
  const parsed = parseActivity(raw);
4842
5119
  if (!parsed.ok) return parsed;
4843
5120
  const activity = parsed.value;
4844
- const who = senderOf(activity);
5121
+ const who = senderOf2(activity);
4845
5122
  if (who === void 0) return err3({ kind: "no_sender" });
4846
5123
  const sender = {
4847
5124
  id: who.aadId,
4848
- channelUserId: pyStr13(partOf(activity, "from")["id"]),
5125
+ channelUserId: pyStr14(partOf(activity, "from")["id"]),
4849
5126
  name: who.name,
4850
5127
  email: who.email
4851
5128
  };
@@ -4928,11 +5205,11 @@ function teamsMasker(redact, note2) {
4928
5205
  }
4929
5206
 
4930
5207
  // packages/teams/src/config/env.ts
4931
- import { pyRstrip as pyRstrip5, pyStrip as pyStrip10, own as own11 } from "@primusclaw/personal-agent";
5208
+ import { pyRstrip as pyRstrip5, pyStrip as pyStrip10, own as own12 } from "@primusclaw/personal-agent";
4932
5209
 
4933
5210
  // packages/teams/src/azure/workload-identity.ts
4934
5211
  import { readFileSync } from "node:fs";
4935
- import { pyRstrip as pyRstrip4, silentLogger as silentLogger7, own as own10 } from "@primusclaw/personal-agent";
5212
+ import { pyRstrip as pyRstrip4, silentLogger as silentLogger7, own as own11 } from "@primusclaw/personal-agent";
4936
5213
 
4937
5214
  // packages/teams/src/connector/errors.ts
4938
5215
  var TokenError = class extends Error {
@@ -4967,16 +5244,16 @@ var DeadlineError = class extends Error {
4967
5244
 
4968
5245
  // packages/teams/src/connector/timer.ts
4969
5246
  function startTimer(clock, ms, reason, parent) {
4970
- const own13 = new AbortController();
5247
+ const own14 = new AbortController();
4971
5248
  const stop = new AbortController();
4972
5249
  clock.sleep(ms, stop.signal).then(
4973
5250
  () => {
4974
- own13.abort(new DeadlineError(reason));
5251
+ own14.abort(new DeadlineError(reason));
4975
5252
  },
4976
5253
  () => void 0
4977
5254
  // the timer was disposed: its sleep is cancelled, nothing is due
4978
5255
  );
4979
- const signal = parent === void 0 ? own13.signal : AbortSignal.any([parent, own13.signal]);
5256
+ const signal = parent === void 0 ? own14.signal : AbortSignal.any([parent, own14.signal]);
4980
5257
  return {
4981
5258
  signal,
4982
5259
  dispose: () => {
@@ -5057,7 +5334,7 @@ function signAssertion(signer, claims) {
5057
5334
 
5058
5335
  // packages/teams/src/connector/tokens/federated.ts
5059
5336
  import { z as z5 } from "zod";
5060
- import { cpHead as cpHead5, pyStr as pyStr14, silentLogger as silentLogger6 } from "@primusclaw/personal-agent";
5337
+ import { cpHead as cpHead5, pyStr as pyStr15, silentLogger as silentLogger6 } from "@primusclaw/personal-agent";
5061
5338
 
5062
5339
  // packages/teams/src/connector/py-parse.ts
5063
5340
  import { pyRstrip as pyRstrip3, pyStrip as pyStrip9 } from "@primusclaw/personal-agent";
@@ -5304,7 +5581,7 @@ function entraCodes(text4) {
5304
5581
  if (list === void 0) return "";
5305
5582
  const codes = list.map(pyInt);
5306
5583
  if (codes.some((code) => code === void 0)) return "";
5307
- const error = pyStr14(parsed.data.error);
5584
+ const error = pyStr15(parsed.data.error);
5308
5585
  const shown = codes.slice(0, 3).map((code) => `AADSTS${String(code)}`).join(",");
5309
5586
  if (!(codes.length || error)) return "";
5310
5587
  return ` (${cpHead5(error, 40)}${error && shown ? ": " : ""}${shown})`;
@@ -5325,7 +5602,7 @@ var SETTINGS = {
5325
5602
  keyFile: "BOT_ASSERTION_KEY_FILE"
5326
5603
  };
5327
5604
  function workerIdentityFromEnv(env, why) {
5328
- const get3 = (name) => (own10(env, name) ?? "").trim();
5605
+ const get3 = (name) => (own11(env, name) ?? "").trim();
5329
5606
  const missing = Object.values(SETTINGS).filter((name) => !get3(name));
5330
5607
  if (missing.length) throw new WorkerIdentityError(`${why} needs the worker identity: set ${missing.join(", ")}`);
5331
5608
  const issuer = get3(SETTINGS.issuer);
@@ -5424,7 +5701,7 @@ var TeamsConfigError = class extends Error {
5424
5701
  var ON = ["1", "true", "yes", "on"];
5425
5702
  var OFF = ["0", "false", "no", "off"];
5426
5703
  function get(env, name, fallback = "") {
5427
- return pyStrip10(own11(env, name) ?? fallback);
5704
+ return pyStrip10(own12(env, name) ?? fallback);
5428
5705
  }
5429
5706
  function required(env, name) {
5430
5707
  const value = get(env, name);
@@ -5625,7 +5902,7 @@ var Person = z6.object({
5625
5902
  function aadOf(request) {
5626
5903
  return (request.params["aad"] ?? "").toLowerCase();
5627
5904
  }
5628
- function str(value) {
5905
+ function str2(value) {
5629
5906
  return typeof value === "string" || typeof value === "number" ? String(value) : "";
5630
5907
  }
5631
5908
  async function personState(deps, aad, scope) {
@@ -5668,11 +5945,11 @@ function putPersonRoute(deps) {
5668
5945
  const parsed = Person.safeParse(bodyJson(request));
5669
5946
  if (!parsed.success) return Promise.resolve(json(400, { error: "name_and_key_required" }));
5670
5947
  const data = parsed.data;
5671
- const name = str(data.name);
5672
- const outcome = deps.links.redeemPending(aad, name, deps.links.stashPending(str(data.key)));
5948
+ const name = str2(data.name);
5949
+ const outcome = deps.links.redeemPending(aad, name, deps.links.stashPending(str2(data.key)));
5673
5950
  if (outcome !== "ok") return Promise.resolve(json(409, { error: "not_linked", outcome }));
5674
- if (str(data.claw_user_id)) deps.links.setClawUserId(aad, str(data.claw_user_id));
5675
- deps.members.rememberMember(str(data.teams_id) || `29:${aad}`, aad, name);
5951
+ if (str2(data.claw_user_id)) deps.links.setClawUserId(aad, str2(data.claw_user_id));
5952
+ deps.members.rememberMember(str2(data.teams_id) || `29:${aad}`, aad, name);
5676
5953
  if (data.subscribe === false) deps.notifySubs.claimNotifyAttempt(aad, NO_SUBSCRIPTION_SECONDS);
5677
5954
  return Promise.resolve(json(200, { status: "linked" }));
5678
5955
  }
@@ -6190,11 +6467,124 @@ function teamsVersion() {
6190
6467
  return packageVersion(new URL("../package.json", import.meta.url));
6191
6468
  }
6192
6469
 
6193
- // packages/teams/src/servicebus/consumer.ts
6470
+ // packages/teams/src/probe/probe.ts
6194
6471
  import { errorName as errorName5, silentLogger as silentLogger12 } from "@primusclaw/personal-agent";
6472
+ var PROBE = "primusclaw.probe";
6473
+ var PROBE_CONVERSATION = "primusclaw-probe";
6474
+ var PROBE_REPLY_TIMEOUT_MS = 12e4;
6475
+ var PROBE_ID = /^[A-Za-z0-9-]{1,64}$/;
6476
+ var ISO_UTC = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/;
6477
+ function sentAtMs(value) {
6478
+ if (typeof value !== "string" || !ISO_UTC.test(value)) return void 0;
6479
+ const ms = Date.parse(value);
6480
+ return Number.isFinite(ms) ? ms : void 0;
6481
+ }
6482
+ var DeliveryProbe = class {
6483
+ constructor(parts) {
6484
+ this.parts = parts;
6485
+ this.logger = parts.logger ?? silentLogger12;
6486
+ }
6487
+ parts;
6488
+ logger;
6489
+ stopping = new AbortController();
6490
+ waiting = /* @__PURE__ */ new Set();
6491
+ /** Whether `body` is a probe (the inbound handler hands it here instead of reading it as an activity). */
6492
+ static is(body) {
6493
+ return body["type"] === PROBE;
6494
+ }
6495
+ /**
6496
+ * Answer one probe: queue the answer, and wait for its ack in the background (the ack comes on the probe's own session,
6497
+ * which the consumer reads only after this returns). A probe that cannot be read is logged and dropped; one whose answer
6498
+ * cannot be queued is counted unanswered at once. Never throws: a redelivered probe would measure the redelivery.
6499
+ */
6500
+ async answer(body) {
6501
+ const id = body["id"];
6502
+ const sent = sentAtMs(body["sent_at"]);
6503
+ if (typeof id !== "string" || !PROBE_ID.test(id) || sent === void 0) {
6504
+ this.logger.warn("delivery probe not read", { why: "malformed" });
6505
+ return;
6506
+ }
6507
+ const outbox = this.parts.outbox;
6508
+ if (outbox === void 0 || this.stopping.signal.aborted) return;
6509
+ const ack = `probe-${id}`;
6510
+ const waiter = this.parts.acks.expect(ack);
6511
+ try {
6512
+ await outbox.publish(
6513
+ envelope("probe", { conversation: { id: PROBE_CONVERSATION } }, { type: "typing" }, { ack })
6514
+ );
6515
+ } catch (error) {
6516
+ this.parts.acks.forget(ack);
6517
+ const feedbackMs2 = this.since(sent);
6518
+ this.logger.warn("delivery probe", {
6519
+ id,
6520
+ outcome: "not_queued",
6521
+ feedback_ms: feedbackMs2,
6522
+ error: errorName5(error)
6523
+ });
6524
+ this.parts.stats?.probed(feedbackMs2, null);
6525
+ return;
6526
+ }
6527
+ const feedbackMs = this.since(sent);
6528
+ const waiting = this.awaitAck(id, ack, waiter.promise, sent, feedbackMs);
6529
+ this.waiting.add(waiting);
6530
+ void waiting.finally(() => this.waiting.delete(waiting));
6531
+ }
6532
+ /** Resolves once every probe answered so far has its ack or has timed out (a test waits for it). */
6533
+ settled() {
6534
+ return Promise.all([...this.waiting]).then(() => void 0);
6535
+ }
6536
+ /** Stop waiting for acks: the worker is stopping (the probes still out are neither answered nor counted). */
6537
+ close() {
6538
+ this.stopping.abort(new DOMException("the worker is stopping", "AbortError"));
6539
+ }
6540
+ since(sent) {
6541
+ return Math.max(Math.trunc(this.parts.clock.epochMs() - sent), 0);
6542
+ }
6543
+ async awaitAck(id, ack, acked, sent, feedbackMs) {
6544
+ const timer = new AbortController();
6545
+ const signal = AbortSignal.any([timer.signal, this.stopping.signal]);
6546
+ const timedOut = this.parts.clock.sleep(this.parts.timeoutMs ?? PROBE_REPLY_TIMEOUT_MS, signal).then(
6547
+ () => "timeout",
6548
+ () => "stopped"
6549
+ // (the ack came first, or the worker is stopping)
6550
+ );
6551
+ let outcome;
6552
+ try {
6553
+ outcome = await Promise.race([acked.then(() => "acked"), timedOut]);
6554
+ } finally {
6555
+ timer.abort();
6556
+ this.parts.acks.forget(ack);
6557
+ }
6558
+ if (outcome === "stopped") return;
6559
+ if (outcome === "timeout") {
6560
+ this.parts.acks.gaveUp(ack);
6561
+ this.logger.warn("delivery probe", { id, outcome: "unanswered", feedback_ms: feedbackMs });
6562
+ this.parts.stats?.probed(feedbackMs, null);
6563
+ return;
6564
+ }
6565
+ const replyMs = this.since(sent);
6566
+ this.logger.info("delivery probe", { id, outcome: "answered", feedback_ms: feedbackMs, reply_ms: replyMs });
6567
+ this.parts.stats?.probed(feedbackMs, replyMs);
6568
+ }
6569
+ };
6570
+
6571
+ // packages/teams/src/servicebus/consumer.ts
6572
+ import { errorName as errorName6, silentLogger as silentLogger13 } from "@primusclaw/personal-agent";
6195
6573
  var IDLE_MS = 2e4;
6196
6574
  var BACKOFF_MS = 3e3;
6197
6575
  var NO_SESSION_PAUSE_MS = 1e3;
6576
+ var ACCEPT_DEADLINE_MS = 12e4;
6577
+ var RECEIVE_DEADLINE_MS = IDLE_MS + 4e4;
6578
+ var SETTLE_DEADLINE_MS = 6e4;
6579
+ var SESSION_HOLD_MS = 4 * 6e4;
6580
+ var WedgedCall = class extends Error {
6581
+ constructor(call) {
6582
+ super(`${call} did not answer in time`);
6583
+ this.call = call;
6584
+ }
6585
+ call;
6586
+ name = "WedgedCall";
6587
+ };
6198
6588
  function isIdleTimeout(error) {
6199
6589
  const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
6200
6590
  return code === "ServiceTimeout" || code === "SessionCannotBeLocked";
@@ -6254,53 +6644,162 @@ function decode(body) {
6254
6644
  var InboundConsumer = class {
6255
6645
  constructor(parts) {
6256
6646
  this.parts = parts;
6257
- this.logger = parts.logger ?? silentLogger12;
6647
+ this.logger = parts.logger ?? silentLogger13;
6258
6648
  }
6259
6649
  parts;
6260
- stopped = false;
6650
+ stopping = new AbortController();
6261
6651
  logger;
6262
- /** Run the receivers until `stop`. */
6652
+ /** Which connection the receivers are on: a receiver re-opens it only if no other has since it took its session. */
6653
+ generation = 0;
6654
+ /** How many receivers are in a pass on each connection (by generation): a session taken there may be in hand. */
6655
+ holders = /* @__PURE__ */ new Map();
6656
+ /** The close of each connection given up on, run once its last holder lets go. */
6657
+ retiring = /* @__PURE__ */ new Map();
6658
+ /** (a method, not a getter: the stop comes between two reads, which a narrowed property would hide) */
6659
+ isStopped() {
6660
+ return this.stopping.signal.aborted;
6661
+ }
6662
+ /** Run the receivers until `stop`; resolves once each has settled what it took and closed its session. */
6263
6663
  async run() {
6264
6664
  await Promise.all(Array.from({ length: this.parts.receivers }, () => this.loop()));
6265
6665
  }
6666
+ /** Take nothing more: the waits end now, a message being handled is finished, and `run` resolves after the drain. */
6266
6667
  stop() {
6267
- this.stopped = true;
6668
+ if (this.isStopped()) return;
6669
+ this.logger.info("inbound consumer stopping: draining the sessions it holds");
6670
+ this.stopping.abort(new DOMException("the worker is stopping", "AbortError"));
6268
6671
  }
6269
- async loop() {
6270
- while (!this.stopped) {
6271
- let receiver;
6272
- try {
6273
- receiver = await this.parts.client.acceptNextSession(this.parts.queue);
6274
- } catch (error) {
6275
- await this.pause(error);
6276
- continue;
6672
+ /**
6673
+ * `call`, given up as wedged (WedgedCall) when it has not answered within `ms`; with `stoppable`, ended (rejected) by
6674
+ * the stop too. The deadline is this consumer's own timer, so an SDK call that ignores its abort signal still ends.
6675
+ */
6676
+ async within(call, ms, work, stoppable = false) {
6677
+ const timer = new AbortController();
6678
+ const signal = stoppable ? AbortSignal.any([timer.signal, this.stopping.signal]) : timer.signal;
6679
+ const deadline = this.parts.clock.sleep(ms, signal).then(
6680
+ () => {
6681
+ throw new WedgedCall(call);
6682
+ },
6683
+ (error) => {
6684
+ if (stoppable && this.isStopped()) throw error;
6685
+ return new Promise(() => void 0);
6277
6686
  }
6687
+ );
6688
+ work.catch(() => void 0);
6689
+ try {
6690
+ return await Promise.race([work, deadline]);
6691
+ } finally {
6692
+ timer.abort();
6693
+ }
6694
+ }
6695
+ async loop() {
6696
+ while (!this.isStopped()) {
6697
+ const generation = this.generation;
6698
+ this.hold(generation);
6699
+ let failed;
6278
6700
  try {
6279
- await this.drain(receiver);
6280
- } catch (error) {
6281
- await this.pause(error);
6701
+ failed = await this.pass(generation);
6282
6702
  } finally {
6283
- await receiver.close().catch((error) => {
6284
- this.logger.info("closing a session receiver failed", { error: errorName5(error) });
6285
- });
6703
+ this.letGo(generation);
6286
6704
  }
6705
+ if (failed !== void 0 && !this.isStopped()) await this.pause(failed.error, generation, failed.rearmed);
6706
+ }
6707
+ }
6708
+ /** Take a session on the current connection and handle it until it goes quiet; what failed, for the pause after. */
6709
+ async pass(generation) {
6710
+ let receiver;
6711
+ const accepting = this.parts.client.acceptNextSession(this.parts.queue, this.stopping.signal);
6712
+ try {
6713
+ receiver = await this.within("accept", ACCEPT_DEADLINE_MS, accepting, true);
6714
+ } catch (error) {
6715
+ accepting.then((late) => late.close()).catch(() => void 0);
6716
+ return { error, rearmed: false };
6717
+ }
6718
+ let failed;
6719
+ try {
6720
+ await this.drain(receiver);
6721
+ } catch (error) {
6722
+ failed = { error, rearmed: true };
6723
+ if (error instanceof WedgedCall && !this.isStopped()) this.rearm(error.call, generation);
6287
6724
  }
6725
+ await this.within("close", SETTLE_DEADLINE_MS, receiver.close()).catch((error) => {
6726
+ this.logger.info("closing a session receiver failed", { error: errorName6(error) });
6727
+ });
6728
+ return failed;
6729
+ }
6730
+ hold(generation) {
6731
+ this.holders.set(generation, (this.holders.get(generation) ?? 0) + 1);
6732
+ }
6733
+ letGo(generation) {
6734
+ const left = (this.holders.get(generation) ?? 1) - 1;
6735
+ if (left > 0) this.holders.set(generation, left);
6736
+ else {
6737
+ this.holders.delete(generation);
6738
+ this.retire(generation);
6739
+ }
6740
+ }
6741
+ /** Close a connection given up on, once no receiver holds a session taken on it (a wedged close is not waited for). */
6742
+ retire(generation) {
6743
+ const close = this.retiring.get(generation);
6744
+ if (close === void 0 || this.holders.has(generation)) return;
6745
+ this.retiring.delete(generation);
6746
+ void close().catch((error) => {
6747
+ this.logger.info("closing a re-opened inbound connection failed", { error: errorName6(error) });
6748
+ });
6288
6749
  }
6289
- async pause(error) {
6750
+ async pause(error, generation, rearmed = false) {
6290
6751
  if (isIdleTimeout(error)) {
6291
- await this.parts.clock.sleep(NO_SESSION_PAUSE_MS);
6752
+ await this.parts.clock.sleep(NO_SESSION_PAUSE_MS, this.stopping.signal).catch(() => void 0);
6292
6753
  return;
6293
6754
  }
6294
- this.logger.warn("inbound receiver error", { error: errorName5(error) });
6295
- await this.parts.clock.sleep(BACKOFF_MS);
6755
+ if (!(error instanceof WedgedCall)) this.logger.warn("inbound receiver error", { error: errorName6(error) });
6756
+ else if (!rearmed && !this.isStopped()) this.rearm(error.call, generation);
6757
+ await this.parts.clock.sleep(BACKOFF_MS, this.stopping.signal).catch(() => void 0);
6758
+ }
6759
+ /**
6760
+ * A call hung: a new connection is opened, once for all receivers that were on the old one, and the session taken
6761
+ * again. The old connection is closed when its last holder lets go (`retire`), not now: see the head of this file.
6762
+ */
6763
+ rearm(call, generation) {
6764
+ const reopen = this.parts.client.reopen?.bind(this.parts.client);
6765
+ const reopened = generation === this.generation && reopen !== void 0;
6766
+ if (reopened) {
6767
+ this.retiring.set(generation, reopen());
6768
+ this.generation += 1;
6769
+ this.retire(generation);
6770
+ }
6771
+ this.logger.warn("inbound receiver re-armed", { call, reopened });
6772
+ if (reopened || reopen === void 0) this.parts.stats?.rearmed?.();
6296
6773
  }
6297
6774
  async drain(receiver) {
6775
+ const taken = this.parts.clock.monotonicMs();
6298
6776
  for (; ; ) {
6299
- const messages = await receiver.receive(1, IDLE_MS);
6300
- if (messages.length === 0 || this.stopped) return;
6301
- for (const message2 of messages) await this.dispatch(receiver, message2);
6777
+ if (this.parts.clock.monotonicMs() - taken >= SESSION_HOLD_MS) return;
6778
+ let messages;
6779
+ try {
6780
+ messages = await this.within(
6781
+ "receive",
6782
+ RECEIVE_DEADLINE_MS,
6783
+ receiver.receive(1, IDLE_MS, this.stopping.signal),
6784
+ true
6785
+ );
6786
+ } catch (error) {
6787
+ if (this.isStopped()) return;
6788
+ throw error;
6789
+ }
6790
+ if (messages.length === 0) return;
6791
+ for (const message2 of messages) {
6792
+ if (this.isStopped()) await this.release(receiver, message2);
6793
+ else await this.dispatch(receiver, message2);
6794
+ }
6795
+ if (this.isStopped()) return;
6302
6796
  }
6303
6797
  }
6798
+ /** A message taken after the stop goes back to the queue at once, for the next worker. */
6799
+ async release(receiver, message2) {
6800
+ this.logLine(message2, "released", queueLagMs(message2, this.parts.clock.epochMs()), 0);
6801
+ await this.within("abandon", SETTLE_DEADLINE_MS, receiver.abandon(message2));
6802
+ }
6304
6803
  async dispatch(receiver, message2) {
6305
6804
  let body;
6306
6805
  try {
@@ -6308,7 +6807,11 @@ var InboundConsumer = class {
6308
6807
  } catch (error) {
6309
6808
  const why = error instanceof Error ? error.message : "undecodable";
6310
6809
  this.logLine(message2, "dead_lettered", queueLagMs(message2, this.parts.clock.epochMs()), 0);
6311
- await receiver.deadLetter(message2, "malformed", Array.from(why).slice(0, 200).join(""));
6810
+ await this.within(
6811
+ "dead-letter",
6812
+ SETTLE_DEADLINE_MS,
6813
+ receiver.deadLetter(message2, "malformed", Array.from(why).slice(0, 200).join(""))
6814
+ );
6312
6815
  return;
6313
6816
  }
6314
6817
  const timing = clientTiming(body);
@@ -6316,13 +6819,13 @@ var InboundConsumer = class {
6316
6819
  try {
6317
6820
  await this.parts.handle(body);
6318
6821
  } catch (error) {
6319
- this.logger.error("handler failed; abandoning for redelivery", { error: errorName5(error) });
6822
+ this.logger.error("handler failed; abandoning for redelivery", { error: errorName6(error) });
6320
6823
  this.record(message2, timing, started, false);
6321
- await receiver.abandon(message2);
6824
+ await this.within("abandon", SETTLE_DEADLINE_MS, receiver.abandon(message2));
6322
6825
  return;
6323
6826
  }
6324
6827
  this.record(message2, timing, started, true);
6325
- await receiver.complete(message2);
6828
+ await this.within("complete", SETTLE_DEADLINE_MS, receiver.complete(message2));
6326
6829
  }
6327
6830
  record(message2, timing, started, ok5) {
6328
6831
  const handleMs = Math.trunc(this.parts.clock.monotonicMs() - started);
@@ -6344,16 +6847,16 @@ var InboundConsumer = class {
6344
6847
  };
6345
6848
 
6346
6849
  // packages/teams/src/assembly/inbound.ts
6347
- import { silentLogger as silentLogger13 } from "@primusclaw/personal-agent";
6850
+ import { silentLogger as silentLogger14 } from "@primusclaw/personal-agent";
6348
6851
 
6349
6852
  // packages/teams/src/activity/inbound/group-changes.ts
6350
- import { pyStr as pyStr15 } from "@primusclaw/personal-agent";
6853
+ import { pyStr as pyStr16 } from "@primusclaw/personal-agent";
6351
6854
  function eventTypeOf(activity) {
6352
6855
  const data = activity.channelData;
6353
- return isFields(data) ? pyStr15(data["eventType"]) : "";
6856
+ return isFields(data) ? pyStr16(data["eventType"]) : "";
6354
6857
  }
6355
6858
  function botRemoved(activity) {
6356
- if (activity.type === "installationUpdate") return pyStr15(activity["action"]).startsWith("remove");
6859
+ if (activity.type === "installationUpdate") return pyStr16(activity["action"]).startsWith("remove");
6357
6860
  if (activity.type !== "conversationUpdate") return false;
6358
6861
  const bot = botIdOf(activity);
6359
6862
  const removed = activity["membersRemoved"];
@@ -6363,8 +6866,8 @@ function applyGroupChange(raw, context, textOf) {
6363
6866
  const parsed = parseActivity(raw);
6364
6867
  if (!parsed.ok || !isGroup(parsed.value)) return false;
6365
6868
  const activity = parsed.value;
6366
- const chatId = pyStr15(partOf(activity, "conversation")["id"]);
6367
- const messageId = pyStr15(activity.id);
6869
+ const chatId = pyStr16(partOf(activity, "conversation")["id"]);
6870
+ const messageId = pyStr16(activity.id);
6368
6871
  if (!chatId) return false;
6369
6872
  if (botRemoved(activity)) {
6370
6873
  context.forget(chatId);
@@ -6389,13 +6892,17 @@ function text3(value) {
6389
6892
  return typeof value === "number" && value !== 0 ? String(value) : "";
6390
6893
  }
6391
6894
  function inboundHandler(parts) {
6392
- const logger = parts.logger ?? silentLogger13;
6895
+ const logger = parts.logger ?? silentLogger14;
6393
6896
  return async (body) => {
6394
6897
  if (body["type"] === DELIVERED) {
6395
6898
  const activityId = text3(body["activity_id"]);
6396
6899
  parts.acks.resolve(text3(body["ack"]), activityId || void 0);
6397
6900
  return;
6398
6901
  }
6902
+ if (DeliveryProbe.is(body)) {
6903
+ await parts.probe?.answer(body);
6904
+ return;
6905
+ }
6399
6906
  if (body["type"] !== "message" && body["type"] !== "invoke") {
6400
6907
  if (parts.groupContext !== void 0) applyGroupChange(body, parts.groupContext, (a) => editedText(a, parts));
6401
6908
  return;
@@ -6415,11 +6922,11 @@ function editedText(activity, parts) {
6415
6922
 
6416
6923
  // packages/teams/src/assembly/outbound.ts
6417
6924
  import { readFileSync as readFileSync2 } from "node:fs";
6418
- import { silentLogger as silentLogger19 } from "@primusclaw/personal-agent";
6925
+ import { silentLogger as silentLogger20, turn as turn3 } from "@primusclaw/personal-agent";
6419
6926
  import { StartupError } from "@primusclaw/personal-agent-runtime/worker";
6420
6927
 
6421
6928
  // packages/teams/src/connector/outbox.ts
6422
- import { pyStr as pyStr18, silentLogger as silentLogger14 } from "@primusclaw/personal-agent";
6929
+ import { pyStr as pyStr19, silentLogger as silentLogger15 } from "@primusclaw/personal-agent";
6423
6930
 
6424
6931
  // packages/teams/src/connector/limits.ts
6425
6932
  var DEFAULT_LIMITS = {
@@ -6436,7 +6943,7 @@ var DEFAULT_LIMITS = {
6436
6943
  };
6437
6944
 
6438
6945
  // packages/teams/src/connector/request.ts
6439
- import { pyStr as pyStr16, pyStrip as pyStrip15 } from "@primusclaw/personal-agent";
6946
+ import { pyStr as pyStr17, pyStrip as pyStrip15 } from "@primusclaw/personal-agent";
6440
6947
  var CONVERSATION_SAFE = ":@;=";
6441
6948
  function quote(text4, safe) {
6442
6949
  try {
@@ -6449,17 +6956,17 @@ function conversationUrl(serviceUrl, conversationId2) {
6449
6956
  return `${rstripSlash(serviceUrl)}/v3/conversations/${quote(conversationId2, CONVERSATION_SAFE)}`;
6450
6957
  }
6451
6958
  function idText(value) {
6452
- return quote(pyStr16(value), "");
6959
+ return quote(pyStr17(value), "");
6453
6960
  }
6454
6961
  function address(envelope2, policy) {
6455
6962
  const { reference: reference2, activity } = envelope2;
6456
6963
  if (!isObject(reference2) || !isObject(activity)) {
6457
6964
  throw new UnaddressableError("an outbound envelope needs a reference and an activity");
6458
6965
  }
6459
- const serviceUrl = pyStrip15(pyStr16(reference2["serviceUrl"]));
6966
+ const serviceUrl = pyStrip15(pyStr17(reference2["serviceUrl"]));
6460
6967
  const raw = reference2["conversation"];
6461
6968
  const conversation = pyTruthy(raw) && raw !== void 0 ? raw : {};
6462
- const conversationId2 = isObject(conversation) ? pyStr16(conversation["id"]) : "";
6969
+ const conversationId2 = isObject(conversation) ? pyStr17(conversation["id"]) : "";
6463
6970
  if (!serviceUrl || !conversationId2 || !isObject(conversation)) {
6464
6971
  throw new UnaddressableError("the conversation reference has no serviceUrl or conversation id");
6465
6972
  }
@@ -6479,7 +6986,7 @@ function payloadOf(at, operation, activityId) {
6479
6986
  return payload;
6480
6987
  }
6481
6988
  function buildRequest(envelope2, policy = DEFAULT_CONNECTOR_HOSTS) {
6482
- const operation = (pyStr16(envelope2["operation"]) || "send").toLowerCase();
6989
+ const operation = (pyStr17(envelope2["operation"]) || "send").toLowerCase();
6483
6990
  const at = address(envelope2, policy);
6484
6991
  const activityId = envelope2["activity_id"];
6485
6992
  switch (operation) {
@@ -6521,7 +7028,7 @@ function buildListMembers(serviceUrl, conversationId2, policy = DEFAULT_CONNECTO
6521
7028
 
6522
7029
  // packages/teams/src/connector/response.ts
6523
7030
  import { z as z7 } from "zod";
6524
- import { cpHead as cpHead6, pyStr as pyStr17 } from "@primusclaw/personal-agent";
7031
+ import { cpHead as cpHead6, pyStr as pyStr18 } from "@primusclaw/personal-agent";
6525
7032
  function json2(text4) {
6526
7033
  try {
6527
7034
  return JSON.parse(text4);
@@ -6533,11 +7040,11 @@ var WithId = z7.object({ id: z7.unknown().optional() });
6533
7040
  var WithError = z7.object({ error: z7.object({ code: z7.unknown().optional() }) });
6534
7041
  function answerId(text4) {
6535
7042
  const parsed = WithId.safeParse(json2(text4));
6536
- return parsed.success ? pyStr17(parsed.data.id) || void 0 : void 0;
7043
+ return parsed.success ? pyStr18(parsed.data.id) || void 0 : void 0;
6537
7044
  }
6538
7045
  function errorCode(text4) {
6539
7046
  const parsed = WithError.safeParse(json2(text4));
6540
- return parsed.success ? cpHead6(pyStr17(parsed.data.error.code), 60) : "";
7047
+ return parsed.success ? cpHead6(pyStr18(parsed.data.error.code), 60) : "";
6541
7048
  }
6542
7049
  function retryAfterMs(header2) {
6543
7050
  const seconds = pyFloat(header2 ?? "");
@@ -6550,10 +7057,10 @@ function memberList(text4) {
6550
7057
  }
6551
7058
 
6552
7059
  // packages/teams/src/connector/retry.ts
6553
- import { errorName as errorName6 } from "@primusclaw/personal-agent";
7060
+ import { errorName as errorName7 } from "@primusclaw/personal-agent";
6554
7061
  function networkReason(error) {
6555
7062
  const cause = error instanceof Error && error.cause instanceof Error ? error.cause : error;
6556
- return `network: ${errorName6(cause)}`;
7063
+ return `network: ${errorName7(cause)}`;
6557
7064
  }
6558
7065
  var ConnectorClient = class {
6559
7066
  constructor(deps) {
@@ -6651,9 +7158,9 @@ function describe(envelope2) {
6651
7158
  const reference2 = isObject(envelope2["reference"]) ? envelope2["reference"] : {};
6652
7159
  const conversation = isObject(reference2["conversation"]) ? reference2["conversation"] : {};
6653
7160
  return {
6654
- operation: pyStr18(envelope2["operation"]) || "send",
6655
- kind: pyStr18(activity["type"]) || "message",
6656
- key: pyStr18(conversation["id"]),
7161
+ operation: pyStr19(envelope2["operation"]) || "send",
7162
+ kind: pyStr19(activity["type"]) || "message",
7163
+ key: pyStr19(conversation["id"]),
6657
7164
  ...outboundLogFields(envelope2)
6658
7165
  };
6659
7166
  }
@@ -6665,7 +7172,7 @@ var ConnectorOutbox = class {
6665
7172
  this.options = options;
6666
7173
  this.fallback = options.fallback;
6667
7174
  this.clock = options.clock;
6668
- this.logger = options.logger ?? silentLogger14;
7175
+ this.logger = options.logger ?? silentLogger15;
6669
7176
  this.policy = options.policy ?? DEFAULT_CONNECTOR_HOSTS;
6670
7177
  this.plain = options.plain ?? plainDecorations;
6671
7178
  this.limits = { ...DEFAULT_LIMITS, ...options.limits };
@@ -6973,7 +7480,7 @@ function buildRequestLazily(envelope2, policy) {
6973
7480
  }
6974
7481
 
6975
7482
  // packages/teams/src/connector/tokens/client-secret.ts
6976
- import { silentLogger as silentLogger15 } from "@primusclaw/personal-agent";
7483
+ import { silentLogger as silentLogger16 } from "@primusclaw/personal-agent";
6977
7484
  var ClientSecretTokenProvider = class extends CachedTokenProvider {
6978
7485
  source = "secret";
6979
7486
  scope;
@@ -6998,7 +7505,7 @@ var ClientSecretTokenProvider = class extends CachedTokenProvider {
6998
7505
  this.tenantId = options.tenantId;
6999
7506
  this.#secret = options.clientSecret;
7000
7507
  this.fetch = options.fetch ?? globalThis.fetch;
7001
- this.logger = options.logger ?? silentLogger15;
7508
+ this.logger = options.logger ?? silentLogger16;
7002
7509
  this.url = options.url || `${ENTRA_TOKEN_HOST}/${pyQuote(options.tenantId, "")}/oauth2/v2.0/token`;
7003
7510
  this.scope = options.scope ?? BOT_CONNECTOR_SCOPE;
7004
7511
  }
@@ -7037,7 +7544,7 @@ var ClientSecretTokenProvider = class extends CachedTokenProvider {
7037
7544
  };
7038
7545
 
7039
7546
  // packages/teams/src/connector/tokens/imds.ts
7040
- import { silentLogger as silentLogger16 } from "@primusclaw/personal-agent";
7547
+ import { silentLogger as silentLogger17 } from "@primusclaw/personal-agent";
7041
7548
  var BOT_CONNECTOR_RESOURCE = "https://api.botframework.com";
7042
7549
  var IMDS_TOKEN_URL = "http://169.254.169.254/metadata/identity/oauth2/token";
7043
7550
  var IMDS_API_VERSION = "2018-02-01";
@@ -7048,7 +7555,7 @@ var ImdsTokenProvider = class extends CachedTokenProvider {
7048
7555
  this.clientId = clientId;
7049
7556
  if (!clientId) throw new Error("the managed identity's client id is required");
7050
7557
  this.fetch = options.fetch ?? globalThis.fetch;
7051
- this.logger = options.logger ?? silentLogger16;
7558
+ this.logger = options.logger ?? silentLogger17;
7052
7559
  this.url = options.url ?? IMDS_TOKEN_URL;
7053
7560
  }
7054
7561
  clientId;
@@ -7082,9 +7589,9 @@ var ImdsTokenProvider = class extends CachedTokenProvider {
7082
7589
  };
7083
7590
 
7084
7591
  // packages/teams/src/gate/no-queue.ts
7085
- import { silentLogger as silentLogger17 } from "@primusclaw/personal-agent";
7592
+ import { silentLogger as silentLogger18 } from "@primusclaw/personal-agent";
7086
7593
  var NoQueue = class {
7087
- constructor(logger = silentLogger17) {
7594
+ constructor(logger = silentLogger18) {
7088
7595
  this.logger = logger;
7089
7596
  }
7090
7597
  logger;
@@ -7128,7 +7635,8 @@ function rawBody(message2) {
7128
7635
  return Buffer.from(typeof body === "string" ? body : JSON.stringify(body ?? null));
7129
7636
  }
7130
7637
  function azureBusClient(connection, lockRenewalMs) {
7131
- const client = typeof connection === "string" ? new ServiceBusClient(connection) : new ServiceBusClient(connection.namespace, connection.credential);
7638
+ const open = () => typeof connection === "string" ? new ServiceBusClient(connection) : new ServiceBusClient(connection.namespace, connection.credential);
7639
+ let client = open();
7132
7640
  return {
7133
7641
  sender(queue) {
7134
7642
  const sender = client.createSender(queue);
@@ -7137,10 +7645,11 @@ function azureBusClient(connection, lockRenewalMs) {
7137
7645
  close: () => sender.close()
7138
7646
  };
7139
7647
  },
7140
- async acceptNextSession(queue) {
7648
+ async acceptNextSession(queue, signal) {
7141
7649
  const receiver = await client.acceptNextSession(queue, {
7142
7650
  maxAutoLockRenewalDurationInMs: lockRenewalMs,
7143
- skipParsingBodyAsJson: true
7651
+ skipParsingBodyAsJson: true,
7652
+ ...signal ? { abortSignal: signal } : {}
7144
7653
  });
7145
7654
  const held = /* @__PURE__ */ new Map();
7146
7655
  const sdk = (message2) => {
@@ -7150,8 +7659,11 @@ function azureBusClient(connection, lockRenewalMs) {
7150
7659
  return found;
7151
7660
  };
7152
7661
  return {
7153
- async receive(count2, waitMs) {
7154
- const messages = await receiver.receiveMessages(count2, { maxWaitTimeInMs: waitMs });
7662
+ async receive(count2, waitMs, signal2) {
7663
+ const messages = await receiver.receiveMessages(count2, {
7664
+ maxWaitTimeInMs: waitMs,
7665
+ ...signal2 ? { abortSignal: signal2 } : {}
7666
+ });
7155
7667
  return messages.map((m) => {
7156
7668
  const received = {
7157
7669
  body: rawBody(m),
@@ -7172,12 +7684,17 @@ function azureBusClient(connection, lockRenewalMs) {
7172
7684
  close: () => receiver.close()
7173
7685
  };
7174
7686
  },
7687
+ reopen() {
7688
+ const old = client;
7689
+ client = open();
7690
+ return () => old.close();
7691
+ },
7175
7692
  close: () => client.close()
7176
7693
  };
7177
7694
  }
7178
7695
 
7179
7696
  // packages/teams/src/servicebus/outbox.ts
7180
- import { errorName as errorName7, pyJsonDumps, silentLogger as silentLogger18 } from "@primusclaw/personal-agent";
7697
+ import { errorName as errorName8, pyJsonDumps, silentLogger as silentLogger19 } from "@primusclaw/personal-agent";
7181
7698
  var IDLE_REOPEN_MS = 24e4;
7182
7699
  var ServiceBusOutbox = class {
7183
7700
  constructor(client, queue, clock, logger) {
@@ -7186,7 +7703,7 @@ var ServiceBusOutbox = class {
7186
7703
  this.clock = clock;
7187
7704
  this.sender = client.sender(queue);
7188
7705
  this.usedAt = clock.monotonicMs();
7189
- this.logger = logger ?? silentLogger18;
7706
+ this.logger = logger ?? silentLogger19;
7190
7707
  }
7191
7708
  client;
7192
7709
  queue;
@@ -7219,7 +7736,7 @@ var ServiceBusOutbox = class {
7219
7736
  try {
7220
7737
  await stale.close();
7221
7738
  } catch (error) {
7222
- this.logger.info("closing the idle outbound sender failed", { error: errorName7(error) });
7739
+ this.logger.info("closing the idle outbound sender failed", { error: errorName8(error) });
7223
7740
  }
7224
7741
  }
7225
7742
  async close() {
@@ -7229,10 +7746,11 @@ var ServiceBusOutbox = class {
7229
7746
  };
7230
7747
 
7231
7748
  // packages/teams/src/assembly/outbound.ts
7232
- var LOCK_RENEWAL_MS = 5 * 6e4;
7749
+ var HANDLER_MARGIN_MS = 10 * 6e4;
7750
+ var LOCK_RENEWAL_MS = SESSION_HOLD_MS + RECEIVE_DEADLINE_MS + turn3.TURN_DEADLINE_SECONDS * 1e3 + HANDLER_MARGIN_MS + SETTLE_DEADLINE_MS;
7233
7751
  function botTokenSource(settings, deps) {
7234
7752
  const { bot } = settings;
7235
- const logger = deps.logger ?? silentLogger19;
7753
+ const logger = deps.logger ?? silentLogger20;
7236
7754
  const base2 = { clock: deps.clock, logger, ...deps.fetch ? { fetch: deps.fetch } : {} };
7237
7755
  if (bot.clientSecretIgnored) {
7238
7756
  logger.warn("BOT_CLIENT_SECRET is set but not used: BOT_TOKEN_SOURCE names another source", {
@@ -7296,7 +7814,7 @@ function busConnections(settings, credential) {
7296
7814
  function gateOutbound(gate, deps) {
7297
7815
  const tokens = new GateToken(gate.runId);
7298
7816
  const policy = onlyConnector(gate.connectorUrl);
7299
- (deps.logger ?? silentLogger19).warn("release gate test entry: outbound to the recording connector only; no queue", {
7817
+ (deps.logger ?? silentLogger20).warn("release gate test entry: outbound to the recording connector only; no queue", {
7300
7818
  runId: gate.runId
7301
7819
  });
7302
7820
  const outbox = new ConnectorOutbox({
@@ -7312,9 +7830,9 @@ function gateOutbound(gate, deps) {
7312
7830
  function productionOutbound(settings, outbound, deps) {
7313
7831
  const queue = new ServiceBusOutbox(outbound, settings.bus.outboundQueue, deps.clock, deps.logger);
7314
7832
  if (settings.outboundMode !== "direct") {
7315
- return { outbox: queue, tokens: void 0, policy: DEFAULT_CONNECTOR_HOSTS, close: () => queue.close() };
7833
+ return { outbox: queue, queue, tokens: void 0, policy: DEFAULT_CONNECTOR_HOSTS, close: () => queue.close() };
7316
7834
  }
7317
- (deps.logger ?? silentLogger19).info("outbound mode: direct to the Bot Connector (the queue is the fallback)");
7835
+ (deps.logger ?? silentLogger20).info("outbound mode: direct to the Bot Connector (the queue is the fallback)");
7318
7836
  const tokens = botTokenSource(settings, deps);
7319
7837
  const outbox = new ConnectorOutbox({
7320
7838
  tokens,
@@ -7325,6 +7843,7 @@ function productionOutbound(settings, outbound, deps) {
7325
7843
  });
7326
7844
  return {
7327
7845
  outbox,
7846
+ queue,
7328
7847
  tokens,
7329
7848
  policy: DEFAULT_CONNECTOR_HOSTS,
7330
7849
  close: async () => {
@@ -7344,15 +7863,15 @@ import { EnvSecretSource, secretsSourceOf, wantedSecrets } from "@primusclaw/per
7344
7863
  import { z as z8 } from "zod";
7345
7864
  import {
7346
7865
  cpSlice as cpSlice2,
7347
- errorName as errorName8,
7348
- pyStr as pyStr19,
7866
+ errorName as errorName9,
7867
+ pyStr as pyStr20,
7349
7868
  pyStrip as pyStrip17,
7350
7869
  SecretsUnavailable as SecretsUnavailable2,
7351
- silentLogger as silentLogger20
7870
+ silentLogger as silentLogger21
7352
7871
  } from "@primusclaw/personal-agent";
7353
7872
 
7354
7873
  // packages/teams/src/azure/keyvault-config.ts
7355
- import { pyRstrip as pyRstrip6, SecretsUnavailable, pyStrip as pyStrip16, own as own12 } from "@primusclaw/personal-agent";
7874
+ import { pyRstrip as pyRstrip6, SecretsUnavailable, pyStrip as pyStrip16, own as own13 } from "@primusclaw/personal-agent";
7356
7875
  import { SETTING_ALIASES, settingValue } from "@primusclaw/personal-agent-runtime";
7357
7876
  var KEYVAULT_SCOPE = "https://vault.azure.net/.default";
7358
7877
  var KEYVAULT_API_VERSION = "7.4";
@@ -7372,7 +7891,7 @@ var ENV_NAMES = {
7372
7891
  FEEDBACK_GITHUB_APP_KEY: "FEEDBACK_GITHUB_KEY_FILE"
7373
7892
  };
7374
7893
  function get2(env, name) {
7375
- return pyStrip16(own12(env, name) ?? "");
7894
+ return pyStrip16(own13(env, name) ?? "");
7376
7895
  }
7377
7896
  function shadowedSettings(env, names) {
7378
7897
  return names.flatMap((name) => {
@@ -7432,7 +7951,7 @@ function vaultErrorCode(text4) {
7432
7951
  const error = body === void 0 ? void 0 : dictOf(body["error"]);
7433
7952
  const inner = error === void 0 ? void 0 : dictOf(error["innererror"]);
7434
7953
  if (error === void 0 || inner === void 0) return "";
7435
- const codes = [error["code"], inner["code"]].map((code) => cpSlice2(pyStr19(code), 0, 60)).filter(Boolean);
7954
+ const codes = [error["code"], inner["code"]].map((code) => cpSlice2(pyStr20(code), 0, 60)).filter(Boolean);
7436
7955
  return codes.length ? ` (${codes.join(": ")})` : "";
7437
7956
  }
7438
7957
  function secretValue(name, text4) {
@@ -7454,7 +7973,7 @@ var KeyVaultSecretSource = class {
7454
7973
  this.credential = credential;
7455
7974
  this.options = options;
7456
7975
  this.fetch = options.fetch ?? globalThis.fetch;
7457
- this.logger = options.logger ?? silentLogger20;
7976
+ this.logger = options.logger ?? silentLogger21;
7458
7977
  this.sleep = options.sleep ?? ((ms, signal) => options.clock.sleep(ms, signal));
7459
7978
  }
7460
7979
  url;
@@ -7562,7 +8081,7 @@ var KeyVaultSecretSource = class {
7562
8081
  status = response.status;
7563
8082
  text4 = await response.text();
7564
8083
  } catch (error) {
7565
- return { reason: `Key Vault unreachable (${errorName8(error)})`, transient: true, missing: false };
8084
+ return { reason: `Key Vault unreachable (${errorName9(error)})`, transient: true, missing: false };
7566
8085
  } finally {
7567
8086
  timer.dispose();
7568
8087
  }
@@ -7690,13 +8209,14 @@ function surfaceOf(teams, outbound, gate, deps) {
7690
8209
  return { acks, surface };
7691
8210
  }
7692
8211
  function connect(teams, parts, context) {
7693
- const { botName, acks, inbound: inbound2, gate } = parts;
8212
+ const { botName, acks, inbound: inbound2, gate, probe } = parts;
7694
8213
  const handle = inboundHandler({
7695
8214
  acks,
7696
8215
  route: context.route,
7697
8216
  botName,
7698
8217
  logger: context.logger,
7699
- groupContext: context.groupContext
8218
+ groupContext: context.groupContext,
8219
+ probe
7700
8220
  });
7701
8221
  const source = inbound2 === void 0 ? void 0 : new InboundConsumer({
7702
8222
  client: inbound2,
@@ -7708,6 +8228,9 @@ function connect(teams, parts, context) {
7708
8228
  stats: {
7709
8229
  processed: (lag, ms, ok5) => {
7710
8230
  context.metrics.processed(lag ?? null, ms, ok5);
8231
+ },
8232
+ rearmed: () => {
8233
+ context.metrics.inboundRearmed?.();
7711
8234
  }
7712
8235
  }
7713
8236
  });
@@ -7727,11 +8250,25 @@ function connect(teams, parts, context) {
7727
8250
  function opened(teams, botName, gate, deps) {
7728
8251
  const { outbound, inbound: inbound2 } = transport(teams, gate, deps);
7729
8252
  const { acks, surface } = surfaceOf(teams, outbound, gate, deps);
8253
+ let probe;
7730
8254
  return {
7731
8255
  surface,
7732
8256
  typedEvent: teamsTypedEvent(botName, deps.logger),
7733
- connect: (context) => connect(teams, { botName, acks, inbound: inbound2, gate }, context),
7734
- closes: [() => outbound.close(), () => inbound2?.close()]
8257
+ connect: (context) => {
8258
+ probe = new DeliveryProbe({
8259
+ outbox: outbound.queue,
8260
+ acks,
8261
+ clock: context.clock,
8262
+ logger: context.logger,
8263
+ stats: {
8264
+ probed: (feedbackMs, replyMs) => {
8265
+ context.metrics.probed?.(feedbackMs, replyMs);
8266
+ }
8267
+ }
8268
+ });
8269
+ return connect(teams, { botName, acks, inbound: inbound2, gate, probe }, context);
8270
+ },
8271
+ closes: [() => probe?.close(), () => outbound.close(), () => inbound2?.close()]
7735
8272
  };
7736
8273
  }
7737
8274
  function teamsSurface() {