@agentdeploymentco/bishop 0.10.0 → 0.11.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/README.md +2 -0
- package/dist/agent-env.js +1 -0
- package/dist/cli.js +25 -22
- package/dist/commands/run.js +5 -3
- package/dist/config.js +4 -4
- package/dist/db.js +62 -12
- package/dist/decision/model.js +1 -0
- package/dist/decision/providers.js +1 -0
- package/dist/env.js +6 -7
- package/dist/gmail/authorize.js +1 -1
- package/dist/gmail/create.js +1 -1
- package/dist/gmail/destination.js +1 -1
- package/dist/gmail/history.js +1 -1
- package/dist/gmail/interface.js +2 -2
- package/dist/gmail/route.js +1 -1
- package/dist/gmail/setup.js +8 -8
- package/dist/harness/claude-options.js +1 -1
- package/dist/harness/claude-processes.js +1 -1
- package/dist/harness/claude.js +7 -7
- package/dist/harness/codex.js +4 -4
- package/dist/harness/create.js +1 -1
- package/dist/harness/layers.js +1 -1
- package/dist/harness/principal.js +16 -13
- package/dist/interface/authorize.js +1 -1
- package/dist/interface/etiquette.js +1 -1
- package/dist/interface/phrases.js +1 -1
- package/dist/interface/reply-gate.js +2 -0
- package/dist/interface/search.js +1 -0
- package/dist/outgoing.js +2 -2
- package/dist/permissions/cli.js +12 -0
- package/dist/permissions/entry.js +1 -0
- package/dist/permissions/instructions.js +2 -0
- package/dist/permissions/levels.js +1 -0
- package/dist/permissions/offline.js +1 -0
- package/dist/permissions/permissions.js +1 -0
- package/dist/permissions/refusal.js +1 -0
- package/dist/permissions/store.js +30 -0
- package/dist/permissions/subjects.js +1 -0
- package/dist/principals.js +3 -3
- package/dist/sandbox.js +11 -11
- package/dist/schedule/cli.js +10 -10
- package/dist/schedule/runner.js +4 -4
- package/dist/sessions/store.js +7 -6
- package/dist/setup.js +34 -26
- package/dist/slack/agent-session.js +1 -1
- package/dist/slack/app.js +2 -2
- package/dist/slack/bots.js +1 -1
- package/dist/slack/destination.js +1 -1
- package/dist/slack/groups.js +1 -0
- package/dist/slack/handlers.js +1 -1
- package/dist/slack/history.js +1 -1
- package/dist/slack/interface.js +2 -2
- package/dist/slack/presence.js +3 -3
- package/dist/slack/read.js +1 -1
- package/dist/slack/search.js +1 -0
- package/dist/slack/sockets.js +1 -0
- package/dist/slack/subjects.js +1 -0
- package/dist/slack/users.js +1 -1
- package/dist/slack/working.js +1 -0
- package/dist/teams/create.js +2 -2
- package/dist/teams/destination.js +1 -1
- package/dist/teams/history.js +1 -1
- package/dist/teams/interface.js +4 -3
- package/dist/teams/mentions.js +1 -1
- package/dist/teams/permissions.js +1 -0
- package/dist/teams/setup.js +81 -81
- package/dist/tools/conversations.js +2 -0
- package/dist/tools/found.js +3 -0
- package/dist/tools/history.js +2 -0
- package/dist/tools/messages.js +2 -2
- package/dist/tools/schedules.js +6 -6
- package/dist/tools/server.js +1 -1
- package/dist/transcript.js +26 -3
- package/dist/turn.js +2 -2
- package/package.json +4 -3
- package/dist/slack/authorize.js +0 -2
- package/dist/slack/authorizer.js +0 -3
- package/dist/slack/directory.js +0 -1
- package/dist/teams/authorize.js +0 -1
package/dist/slack/interface.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{runCommand as
|
|
2
|
-
`)},
|
|
1
|
+
import{runCommand as Q}from"../commands/run.js";import{commandLine as V}from"../commands/syntax.js";import{etiquetteNote as Y,threadParticipants as $}from"../interface/etiquette.js";import{showsProgress as z,threadVerbosity as J}from"../interface/verbosity.js";import{log as g}from"../log.js";import{atLeast as X}from"../permissions/levels.js";import{principalLabel as Z}from"../principals.js";import{statusQueue as ee}from"./agent-session.js";import{createSlackApp as te}from"./app.js";import{botTurnCap as ae}from"./bots.js";import{slackObserver as ne}from"./context.js";import{deliverToSlack as se,describeSlackHandle as oe,parseSlackHandle as x,resolveSlackDestination as re,slackHandle as ie}from"./destination.js";import{describeSlackFile as ce,parseSlackFile as le,slackAttachment as C,slackFilePayload as me}from"./files.js";import{userGroups as de}from"./groups.js";import{registerHandlers as he}from"./handlers.js";import{landedMidThread as pe,namedSlackFiles as fe,threadHistory as we}from"./history.js";import{linkMentions as E,mentionableName as ue,renderMentions as N}from"./mentions.js";import{createPresence as ge}from"./presence.js";import{slackSighting as ye}from"./principal.js";import{slackMessageReader as ke}from"./read.js";import{say as F}from"./say.js";import{slackMessageSearch as be}from"./search.js";import{resolveSlackSubject as ve,slackLocation as Ie,slackMembership as H}from"./subjects.js";import{threadKeyString as Se}from"./thread.js";import{userDirectory as Te}from"./users.js";import{workingSessions as Me}from"./working.js";const xe={name:"slack",guidance:["This conversation is a Slack thread. Each thing you write is posted as its own message while","you work, and the tools you call show as a card between them, so someone is watching the","whole turn. Say what you are doing as you go, and keep it to a line or two. Your last message","is the answer to what was asked. Slack renders standard markdown, tables included, so write","normally and keep it short.","People and other agents are named to you as @name. Write @name to mention one and Bishop","makes it a real Slack mention; a name it cannot match to one account stays plain text, so","use the name you were given. @here, @channel, and @everyone are never mentions, whoever","writes them.","A thread can hold a conversation between other people that has nothing to do with you.",'Bishop marks a message you may leave alone with a <thread> tag carrying reply="optional":',"other people are talking here and this one did not name you, so answer it only if you have","something worth adding. To stay out of it, say <no-output> and nothing else, and Bishop","posts nothing at all. Every message without that tag is yours to answer."].join(`
|
|
2
|
+
`)},Ne=3e3;async function Pe(t,i,o=Ne){const r=await Ae(t.botUserId,i,o),m=ue(r)??t.username;if(!m)return;const u=[t.appName,r.realName].filter(h=>!!h?.trim()&&h?.toLowerCase()!==m.toLowerCase());return{address:`@${m}`,...u.length>0?{aka:[...new Set(u)]}:{}}}async function Ae(t,i,o){const r={userId:t};let m;const u=new Promise(h=>{m=setTimeout(()=>h(r),o)});try{return await Promise.race([i.lookup(t).catch(()=>r),u])}finally{clearTimeout(m)}}async function at(t){const{app:i,identity:o}=await te(t.credentials),r=Te(i.client,{self:o.botUserId}),m=de(i.client);await m.ready();const u=ae(t.maxBotTurns),h=$(),P=ne({client:i.client,users:r,home:o,self:o.botUserId}),v=J(t.meta,"slack",t.verbosity),j={verbosity:v,model:t.model,configured:t.configuredModel??{},...t.configuredModelAt?{configuredAt:t.configuredModelAt}:{},stop:t.stop,permissions:t.permissions,nameOf:e=>Z(e,t.principals)},l=await Pe(o,r),p={...xe,...l?{self:l}:{}};l?g.info({address:l.address,aka:l.aka},"the agent's name in Slack"):g.warn("could not read the bot's own name; the agent will not know what it is called");const I=new Map,A=ee(i.client),b=Me(A),K=async({key:e,keyString:a,thread:n,text:c,userId:d,isBot:k,sender:s,level:f,location:w},T)=>{const U=V(c);if(!U)return!1;const G=await y(d,k),q=await Q(U,{thread:n,interface:p.name,sender:{id:G.id,level:s},level:f,location:w,resolve:M=>D(M)},j);try{await F(T.client,{channel:e.channelId,threadTs:e.threadTs},q),I.get(a)?.interrupted()}catch(M){g.warn({thread:a,err:M},"couldn't answer a command")}return!0};async function S(e){const a=await r.lookup(e),n=t.principals.lookup("slack",e);return t.permissions.of(H(n?.id,a,m))}const D=e=>ve(e,{client:i.client,users:r,groups:m,home:o});async function y(e,a,n){const c=await r.lookup(e),d=ye(c,a,o);return t.principals.see(p.name,n?{...d,self:n}:d)}y(o.botUserId,!0,!0).catch(e=>{g.warn({err:e},"could not record the bot's own account")});function _(e,a){const n=ce(a);if(!n.unavailable)return t.attachments.remember(e,p.name,{id:n.id,name:n.name,payload:me(a)})}async function R(e,a){return a.files.length===0?[]:Promise.all(a.files.map(async n=>{const c=_(e.id,n),d=await t.files.save(e.dirKey,C(n,t.credentials.botToken));return c?{...d,ref:c}:d}))}const B=t.gate,L=B?({thread:e,keyString:a,inbound:n})=>B.admit({thread:e,...l?{agent:l.address}:{},participants:h.count(a),mentioned:n.mentionsAgent,message:async()=>{const c=fe(n.files,{remember:d=>t.attachments.remember(e.id,p.name,d)});return{principal:await y(n.userId,n.isBot),externalId:n.ts,text:await N(n.text,r),...c.length?{files:c}:{}}}}):void 0;function W(e,a){const n={channelId:e.channelId,threadTs:e.threadTs},c=N(e.messages[0]?.text??"",r),d=pe(e),k=Y({participants:e.participants,mentioned:e.messages.some(s=>s.mentionsAgent)});return{thread:e.thread,isNewThread:e.isNewThread,level:e.level,origin:p,...k?{note:k}:{},...d?{history:()=>we({client:a.client,key:e.key,before:d,admits:async s=>X((await S(s)).level,e.level),answersBots:u.answersBots,self:{botUserId:o.botUserId,...o.botId?{botId:o.botId}:{},...l?{botName:l.address}:{}},users:r,principal:y,remember:s=>t.attachments.remember(e.thread.id,p.name,s),saw:(s,f)=>h.saw(e.keyString,s,f)})}:{},observe:()=>P.observe({channelId:e.channelId,direct:e.isDirectMessage,speaker:e.messages.at(-1)?.userId??""}),async messages(){return Promise.all(e.messages.map(async(s,f)=>{const w=await R(e.thread,s);return{principal:await y(s.userId,s.isBot),externalId:s.ts,text:f===0?await c:await N(s.text,r),...w.length>0?{files:w}:{}}}))},showsProgress:()=>z(v.of(e.thread.id).level),working:s=>b.set(n,e.keyString,s),presence:()=>{b.open(n,e.keyString);let s=!1;const f=()=>(s=!0,b.release(n,e.keyString)),w=ge(e,a,{release:f,setStatus:A,outgoing:T=>E(T,r),title:()=>c,verbosity:()=>v.of(e.thread.id).level,...k?{mayDecline:!0}:{},...t.taskIntervalMs===void 0?{}:{taskIntervalMs:t.taskIntervalMs}});return I.set(e.keyString,w),{...w,finish:async()=>{try{await w.finish()}finally{I.delete(e.keyString),s||await f()}}}},async notify(s){await F(a.client,{channel:e.channelId,threadTs:e.threadTs},s)},async destination(){const s=ie({channel:e.channelId,threadTs:e.threadTs});return{interface:"slack",handle:s,label:await oe(i.client,s)}}}}const O={client:i.client,users:r,principal:y,self:{botUserId:o.botUserId,...o.botId?{botId:o.botId}:{},...l?{botName:l.address}:{}},remember:(e,a)=>t.attachments.remember(e,p.name,a)};return he(i,{identity:o,...l?{botName:l.address}:{},threads:t.threads,events:t.events,run:(e,a)=>t.run(W(e,a)),stop:t.stop,permissions:t.permissions,levelOf:S,bots:u,participants:h,command:K,changed:e=>P.changed(e),...L?{screen:L}:{}}),{name:"slack",async start(){await i.start(),o.scopes.includes("files:read")||g.warn("this Slack app has no files:read scope, so it cannot open files people share; reinstall it to grant one"),o.scopes.includes("files:write")||g.warn("this Slack app has no files:write scope, so it cannot send files back; reinstall it to grant one"),r.prime(),g.info("listening on Slack via Socket Mode")},async stop(){m.stop(),await b.close(),await i.stop()},membership:e=>H(e.id,{userId:e.externalId,...e.email?{email:e.email}:{}},m),resolveSubject:e=>D(e),reach:async e=>{const{channel:a}=x(e);return{locations:a.startsWith("D")?[]:[Ie(o.teamId,a)]}},resolveDestination:(e,a)=>re(i.client,e,{...a?.optedInOnly?{optedIn:async n=>(await S(n)).level!=="deny"}:{},seen:n=>t.principals.named(p.name,n).map(c=>c.externalId)}),sameConversation:(e,a)=>x(e).channel===x(a).channel,deliver:async e=>{const a=await se(i.client,{...e,text:await E(e.text,r)});return a?{threadKey:Se({teamId:o.teamId,channelId:a.channel,threadTs:a.threadTs})}:{}},readMessage:ke(O),searchMessages:be(O),attachment:e=>{const a=le(e);return a?C(a,t.credentials.botToken):void 0}}}export{xe as SLACK_ORIGIN,at as createSlackInterface,Pe as slackIdentity};
|
package/dist/slack/presence.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{DEFAULT_VERBOSITY as
|
|
1
|
+
import{DEFAULT_VERBOSITY as N}from"../config.js";import{saysNoOutput as I}from"../harness/principal.js";import{retitlePhrase as U,toolPhrase as V,turnTally as Y}from"../interface/phrases.js";import{showsProgress as q,showsTasks as b}from"../interface/verbosity.js";import{log as S}from"../log.js";import{fileShelf as z}from"../outgoing.js";import{renameSession as G,setSessionStatus as J}from"./agent-session.js";import{splitForSlack as K}from"./format.js";import{say as L}from"./say.js";import{taskMessage as Q}from"./tasks.js";import{attachToSlack as W}from"./upload.js";function X(r){const l=[];for(const a of r){if(typeof a=="string"){l.push({text:a.trim(),files:[]});continue}const o=l.at(-1);o?o.files.push(a):l.push({text:"",files:[a]})}return l}const Z=3e4;function ft(r,l,a={}){const o=l.client,d={channel:r.channelId,threadTs:r.threadTs},R=Date.now(),C=()=>a.verbosity?.()??N;let c,x,B="",i=!1,w="",$=!1,h,A=!1;const g=z();async function y(t,e){try{return await e()}catch(n){S.debug({thread:r.keyString,what:t,err:n},"presence call failed");return}}const D=a.setStatus??((t,e,n)=>J(o,t,e,n));let f=H();function E(t){return f=f.then(()=>D(r,t)),f}function M(){const t=a.release;return t?(f=f.then(t),f):E("active")}async function H(){const t=r.messages[0];if(await D(r,"processing",t?.userId),!(!a.title||t?.ts!==r.threadTs))try{await G(o,r,await a.title())}catch(e){S.debug({thread:r.keyString,err:e},"could not read the session title")}}async function k(){const t=c;t&&(c=void 0,await y("task.close",()=>t.close()))}async function T(t){const e=await y("say",()=>L(o,d,t));return e?(x=e,i=!0,!0):(i=!1,!1)}async function P(t,e){const n=t?K(t):[],s=n.pop()??"";let u=!0;for(const p of n)await T(p)||(u=!1);const m=e.map(p=>p.name).join(", ");let _,j=!1;try{_=await W(o,d,e,s)}catch(p){j=!0,S.error({thread:r.keyString,files:m,err:p},"could not upload a file")}return _?(x=_,i=!!s,u):(s&&!await T(s)&&(u=!1),j&&await y("say",()=>L(o,d,`_Could not upload ${m}._`)),i=!1,u)}async function F(t){await k();const e=g.place(t);let n=!0;for(const s of X(e.parts))(s.files.length?await P(s.text,s.files):await T(s.text))||(n=!1);n&&(B=e.text)}const O=setInterval(()=>{E("processing")},a.heartbeatMs??Z);return O.unref(),{interrupted(){i=!1},share:t=>g.offer(t),async handle(t){const e=C();switch(b(e)||await k(),t.type){case"text":{if(I(t.text)||!t.text.trim()||!q(e))return;await F(a.outgoing?await a.outgoing(t.text):t.text);return}case"tool":if(!b(e))return;c||(c=Q(o,d,a.taskIntervalMs),i=!1),c.note(V(t));return;case"tool_summary":if(!b(e))return;c?.retitle(U(t));return;case"done":$=!0,w=I(t.text)?"":t.text,A=!!a.mayDecline&&I(t.text);return;case"error":h=t.message;return;default:return}},async finish(){if(clearInterval(O),await k(),A&&!h){S.info({thread:r.keyString},"the agent left this message alone"),await M();return}const t=Y(Date.now()-R,$||!!h),e=w.trim()&&a.outgoing?await a.outgoing(w):w,n=h?`Something went wrong: ${h}`:g.strip(e)===B.trim()?"":e.trim(),s=x;!n&&s&&i&&await y("coda",()=>o.chat.update({channel:d.channel,ts:s.ts,markdown_text:`${s.text}
|
|
2
2
|
|
|
3
|
-
_${t}_`}))||await
|
|
3
|
+
_${t}_`}))||await F([n,`_${t}_`].filter(Boolean).join(`
|
|
4
4
|
|
|
5
|
-
`));const m=
|
|
5
|
+
`));const m=g.unplaced();m.length>0&&await P("",m),await M()}}}export{Z as HEARTBEAT_MS,ft as createPresence};
|
package/dist/slack/read.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{describedFile as b}from"../files.js";import{clampText as w,MAX_CHARS as
|
|
1
|
+
import{describedFile as b}from"../files.js";import{clampText as w,MAX_CHARS as x,withinFileBudget as I}from"../interface/history.js";import{MAX_CONTEXT as v}from"../interface/messages.js";import{log as _}from"../log.js";import{describeSlackFile as T,slackFilePayload as M}from"./files.js";import{renderMentions as A}from"./mentions.js";import{FILE_SHARE as C}from"./route.js";import{nameBotMentions as R,parseThreadKey as S}from"./thread.js";const B=/slack\.com\/archives\/([A-Z0-9]+)\/p(\d+)(\d{6})(?!\d)/i,E=/^\d+\.\d+$/;function P(n){const t=n.trim(),e=B.exec(t);return e?.[1]&&e[2]&&e[3]?{channelId:e[1].toUpperCase(),ts:`${e[2]}.${e[3]}`}:E.test(t)?{ts:t}:void 0}function F(n,t){if(!(!n.channelId||n.channelId===t))return"That message is in another conversation, and I only read the one I am asked in. Ask me again there and I can read it."}function N(n){const t=n;if(t?.ts)return{ts:t.ts,...t.user?{userId:t.user}:{},...t.bot_id?{botId:t.bot_id}:{},...t.subtype?{subtype:t.subtype}:{},...t.thread_ts?{threadTs:t.thread_ts}:{},replyCount:t.reply_count??0,text:t.text??"",shared:t.files??[]}}function m(n){return[...n].sort((t,e)=>t.ts<e.ts?-1:t.ts>e.ts?1:0)}function O(n,t){return t||!n.subtype||n.subtype===C}function nt(n){return async(t,e)=>{const r=S(t.threadKey);if(!r)return{kind:"refused",reason:"Bishop could not tell which conversation this is."};const s=P(e.message);if(!s)return{kind:"refused",reason:"That is not a Slack message link or timestamp. Paste the link from Slack's own Copy link, or give a timestamp like 1789419098.478749."};const i=F(s,r.channelId);if(i)return{kind:"refused",reason:i};const o=Math.min(Math.max(e.context,0),v),d={incomplete:!1},c=await X(n,r.channelId,s.ts,o,d);if(!c)return{kind:"refused",reason:"There is no such message in this conversation. It may have been deleted, or the link may point somewhere I cannot read from here."};const{kept:l,cut:u}=z(s.ts,c.find(f=>f.ts===s.ts)?.threadTs,c),a=[...u?["trimmed"]:[],...d.incomplete?["unavailable"]:[]];return G(n,t.id,I(l),s.ts,a)}}const U=new Set(["thread_not_found","message_not_found"]);function H(n){const t=n?.data?.error;return typeof t=="string"?t:void 0}function K(n){const t=H(n);return t!==void 0&&U.has(t)}async function h(n){try{const t=await n;return m((t.messages??[]).flatMap(e=>N(e)??[]))}catch(t){if(K(t))return;throw t}}async function p(n,t,e){try{return await h(n)??[]}catch(r){return e.incomplete=!0,_.warn({channel:t,err:r},"could not read the messages around one"),[]}}async function X(n,t,e,r,s){const o=(await h(n.client.conversations.replies({channel:t,ts:e,limit:1})))?.find(d=>d.ts===e);if(o)return o.threadTs||o.replyCount>0?$(n,t,o,r,s):L(n,t,o,r,s)}async function $(n,t,e,r,s){const i=e.threadTs??e.ts;if(r===0&&i===e.ts)return[e];const o=l=>p(n.client.conversations.replies({channel:t,ts:i,[l]:e.ts,inclusive:!1,limit:r+1}),t,s),[d,c]=await Promise.all([o("latest"),o("oldest")]);return y(n,e,[...d,...c],r,i)}async function L(n,t,e,r,s){if(r===0)return[e];const i=c=>p(n.client.conversations.history({channel:t,[c]:e.ts,inclusive:!1,limit:r}),t,s),[o,d]=await Promise.all([i("latest"),i("oldest")]);return y(n,e,[...o,...d],r)}function y(n,t,e,r,s){const i=new Map;for(const u of[...e,t])i.set(u.ts,u);const o=m([...i.values()]).filter(u=>u.ts===t.ts||O(u,k(u,n.self))),d=o.findIndex(u=>u.ts===t.ts),c=o.slice(Math.max(0,d-r),d+r+1);if(!s||c.some(u=>u.ts===s))return c;const l=o.find(u=>u.ts===s);return l?[l,...c]:c}function z(n,t,e){const r=a=>a.ts===n||a.ts===t,s=a=>a.ts===n?a:{...a,text:w(a.text)},i=e.map(s);let o=x-i.filter(r).reduce((a,f)=>a+f.text.length,0),d=!1;const c=[],l=i.findIndex(a=>a.ts===n),u=i.map((a,f)=>({message:a,distance:Math.abs(f-l)})).sort((a,f)=>a.distance-f.distance);for(const{message:a}of u){if(!r(a)){if(a.text.length>o){d=!0;continue}o-=a.text.length}c.push(a)}return{kept:m(c),cut:d}}function k(n,t){return n.userId&&n.userId===t.botUserId?!0:!!t.botId&&n.botId===t.botId}function D(n,t,e){return e.map(r=>{const s=T(r),i=b(s);if(s.unavailable)return i;const o=n.remember(t,{id:s.id,name:s.name,payload:M(r)});return o?{...i,ref:o}:{...i,unavailable:"Bishop could not record a reference for it"}})}function Z(n,t,e){const r=e?n.self.botUserId:t.userId??t.botId??"";return r?n.principal(r,!!t.botId,e):Promise.resolve(j)}const j={id:"",externalId:"",handle:"unknown",name:"unknown",kind:"unknown",affiliation:"unknown"};async function G(n,t,e,r,s){return{kind:"messages",entries:await Promise.all(e.map(async o=>{const d=k(o,n.self),c=D(n,t,o.shared);return{principal:await Z(n,o,d),text:await A(R(o.text,n.self.botUserId,n.self.botName),n.users),...c.length>0?{files:c}:{},...o.ts===r?{asked:!0}:{}}})),...s.length>0?{omitted:s}:{}}}export{X as around,h as ask,k as isSelf,F as mayRead,m as ordered,P as parseTarget,Z as principalOf,O as said,H as slackCode,nt as slackMessageReader,N as toRead};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{SCAN_DEADLINE_MS as nt}from"../interface/search.js";import{log as U}from"../log.js";import{renderMentions as st}from"./mentions.js";import{around as rt,isSelf as H,mayRead as ot,ordered as v,parseTarget as at,principalOf as it,slackCode as ct,toRead as j}from"./read.js";import{FILE_SHARE as ft}from"./route.js";import{nameBotMentions as dt,parseThreadKey as lt,spokenAt as z}from"./thread.js";const J=200,ut=new Set([ft,"bot_message","me_message"]);function ht(r,h){return r.subtype?r.subtype==="thread_broadcast"?h:ut.has(r.subtype):!0}const B=Symbol("timeout");async function Q(r,h){r.catch(()=>{});let g;const I=new Promise(T=>{g=setTimeout(()=>T(B),Math.max(0,h))});try{return await Promise.race([r,I])}finally{clearTimeout(g)}}function V(r){return(r/1e3).toFixed(6)}function W(r){return v(r).reverse()}function X(r){const h=r.response_metadata?.next_cursor;return r.has_more!==!1&&h?h:void 0}function Mt(r,h={}){const g=h.now??Date.now,I=h.deadlineMs??nt;function T(e,t){return{...e,at:z(e.ts),thread:t,spoken:H(e,r.self)||ht(e,t!==e.ts)}}async function O(e){return e.shown??=await st(dt(e.text,r.self.botUserId,r.self.botName),r.users),e.shown}async function D(e,t,c){return{ref:e.ts,thread:e.thread,at:e.at,principal:await it(r,e,H(e,r.self)),text:await O(e),...t?{match:!0}:{},...c===void 0?{}:{matchedAt:c}}}async function Y(e,t){const c=e.channelId,x=g()+I,p=()=>x-g(),b=n=>(t.after===void 0||n.at>=t.after)&&(t.before===void 0||n.at<t.before);let y=0,w,C=!1,i,S;const E=[],L=new Map,k=[];async function N(n,f){if(y>=t.scanLimit)return"scan_limit";if(p()<=0)return"time";const s=T(n,f);if(y+=1,w=w===void 0?s.at:Math.min(w,s.at),s.spoken&&b(s))if(!t.match)k.push({seen:s});else{const o=t.match(await O(s));o!==void 0&&k.push({seen:s,at:o})}return s}async function $(n){const f=[];L.set(n.ts,f);let s;do{if(p()<=0)return"time";let o;try{o=await Q(r.client.conversations.replies({channel:c,ts:n.ts,limit:J,...s?{cursor:s}:{}}),p())}catch(l){C=!0,U.warn({channel:c,thread:n.ts,err:l},"could not read a thread to search it");return}if(o===B)return"time";s=X(o);const u=v((o.messages??[]).flatMap(l=>j(l)??[]));for(const[l,a]of u.entries()){if(a.ts===n.ts)continue;const d=await N(a,n.ts);if(typeof d=="string")return d;if(f.push(d),k.length>=t.limit)return l===u.length-1&&!s?void 0:"limit"}}while(s)}let M,R=!0;t:do{if(p()<=0){i="time";break}let n;try{n=await Q(r.client.conversations.history({channel:c,limit:J,inclusive:!0,...t.before===void 0?{}:{latest:V(t.before)},...t.after===void 0?{}:{oldest:V(t.after)},...M?{cursor:M}:{}}),p())}catch(s){if(R){if(ct(s)==="missing_scope")return{kind:"refused",reason:"Slack won't let Bishop read this conversation's history. Group DMs need a permission Bishop does not ask for yet."};throw s}U.warn({channel:c,err:s},"could not read further back to search"),i="unavailable";break}if(n===B){i="time";break}R=!1,M=X(n);const f=W((n.messages??[]).flatMap(s=>j(s)??[]));for(const[s,o]of f.entries()){if(o.ts===e.threadTs||t.before!==void 0&&z(o.ts)>=t.before)continue;const u=await N(o,o.ts);if(typeof u=="string"){i=u;break t}E.push(u);const l=s===f.length-1&&!M;if(k.length>=t.limit&&(!l||o.replyCount>0)){i="limit",o.replyCount>0&&(S=o.ts);break t}if(o.replyCount>0){const a=await $(o);if(a){i=a,S=o.ts;break t}}if(k.length>=t.limit){l||(i="limit");break t}}}while(M);const A=W(k.map(({seen:n,at:f})=>({...n,matchedAt:f})));t.match||A.reverse();const q=t.context>0?tt(A,t.context):A.map(n=>({seen:n,match:!0}));return{kind:"messages",messages:await Promise.all(q.map(({seen:n,match:f})=>D(n,f,f?n.matchedAt:void 0))),read:y,...i?{stopped:{by:i,...w===void 0?{}:{oldest:w},...S?{partway:S}:{}}}:{},...C?{incomplete:!0}:{}};function tt(n,f){const s=new Set(n.map(a=>a.ts)),o=v(E.filter(a=>a.spoken)),u=new Map;for(const a of n){const d=a.ts!==a.thread,F=d?v((L.get(a.thread)??[]).filter(m=>m.spoken)):o,P=F.findIndex(m=>m.ts===a.ts),et=P<0?[]:F.slice(Math.max(0,P-f),P+f+1),K=d?a.thread:"",_=u.get(K)??new Map;u.set(K,_);const G=d?E.find(m=>m.ts===a.thread):void 0;for(const m of[...G?[G]:[],...et])_.has(m.ts)||_.set(m.ts,m);_.set(a.ts,a)}const l=new Set;return[...u.values()].flatMap(a=>v([...a.values()]).filter(d=>!l.has(d.ts)&&!!l.add(d.ts)).map(d=>({seen:d,match:s.has(d.ts)})))}}async function Z(e,t){const c=at(t.message);if(!c)return{kind:"refused",reason:"message takes the id of a message a search returned, like 1789419098.478749, or a link from Slack's Copy link."};const x=ot(c,e.channelId);if(x)return{kind:"refused",reason:x};const p={incomplete:!1},b=await rt(r,e.channelId,c.ts,t.context,p),y=b?.find(i=>i.ts===c.ts);if(!b||!y)return{kind:"refused",reason:"There is no such message in this conversation. It may have been deleted."};if((y.threadTs??y.ts)===e.threadTs)return{kind:"refused",reason:"That message is in this conversation, which you already have."};const w=b.filter(i=>i.ts!==e.threadTs);return{kind:"messages",messages:await Promise.all(w.map(async i=>D(T(i,i.threadTs??i.ts),i.ts===c.ts))),read:w.length,...p.incomplete?{incomplete:!0}:{}}}return async(e,t)=>{const c=lt(e.threadKey);return c?t.kind==="around"?Z(c,t):Y(c,t):{kind:"refused",reason:"Bishop could not tell which conversation this is."}}}export{Mt as slackMessageSearch};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{defaultProcessEventErrorHandler as I,LogLevel as E}from"@slack/bolt";import{SocketModeClient as j}from"@slack/socket-mode";import{log as s}from"../log.js";const N=14400*1e3,h=60*1e3;function R(r=s,l={}){const c=Object.keys(l).length?r.child(l):r;return{debug:(...i)=>c.debug({slack:i}),info:(...i)=>c.info({slack:i}),warn:(...i)=>c.warn({slack:i}),error:(...i)=>c.error({slack:i}),setLevel:()=>{},getLevel:()=>E.WARN,setName:()=>{}}}const B=/"type"\s*:\s*"(hello|disconnect)"/;function W(r){const l=typeof r=="string"?r:r instanceof Uint8Array?new TextDecoder().decode(r):"";if(B.test(l))try{const c=JSON.parse(l);if(c.type==="hello"||c.type==="disconnect")return{type:c.type,body:c}}catch{}}function K(r){const l=r.setTimer??((e,t)=>setTimeout(e,t).unref()),c=r.clearTimer??(e=>clearTimeout(e)),i=r.now??Date.now,O=r.makeClient??((e,t)=>new j({appToken:r.appToken,logger:t,logLevel:E.WARN}));let v,u=!1,k,T=!1;const C=R(),_=e=>({index:e,client:O(e,R(s,{slackSocket:e})),open:!1,restarting:!1}),f=[_(0),_(1)],m=e=>e===f[0]?f[1]:f[0];for(const e of f)P(e);function p(e,t,n){y(e),e.timer=l(()=>{e.timer=void 0,t()},n)}function y(e){e.timer!==void 0&&c(e.timer),e.timer=void 0}function P(e){const{client:t,index:n}=e;t.on("slack_event",async a=>{const{body:o,retry_num:d,retry_reason:x}=a;d&&s.info({slackSocket:n,retryNum:d,retryReason:x,type:o?.event?.type??o?.type,sentAt:typeof o?.event_time=="number"?new Date(o.event_time*1e3).toISOString():void 0},"Slack delivered an event again");let w=!1;const g={body:o,retryNum:d,retryReason:x,ack:async S=>{if(!w){w=!0;try{await a.ack(S)}catch(F){throw w=!1,F}}}};try{await v?.processEvent(g)}catch(S){await I({error:S,logger:C,event:g})&&await g.ack()}}),t.on("ws_message",a=>{const o=W(a);if(!o)return;if(o.type==="disconnect"){s.info({slackSocket:n,reason:o.body.reason},"Slack asked a socket to reconnect");return}const d=o.body.debug_info?.approximate_connection_time;s.debug({slackSocket:n,connections:o.body.num_connections,lifetimeS:d},"Slack socket said hello"),d&&(k=d*1e3),e.helloAt=i(),D(e)}),t.on("close",()=>{const a=e.open;e.open=!1,!(u||e.restarting||!a)&&(e.closedAt=i(),m(e).open?s.info({slackSocket:n},"a Slack socket closed and is reconnecting"):s.warn({slackSocket:n},"every Slack socket is closed, so new messages wait until one reconnects"))}),t.on("connected",()=>{e.open=!0,e.closedAt!==void 0&&(s.info({slackSocket:n,downMs:i()-e.closedAt},"a Slack socket reconnected"),e.closedAt=void 0)})}function A(e,t){const n=k??N,o=(((e.helloAt??0)-(t.helloAt??0))%n+n)%n;return{phase:o,lifetime:n,close:Math.min(o,n-o)<n/4}}function D(e){const t=m(e);if(y(e),t.helloAt===void 0||!t.open)return;k===void 0&&!T&&(T=!0,s.info({lifetimeMs:N},"Slack didn't say how long a socket lasts, so Bishop assumes a default to keep the two apart"));const{phase:n,lifetime:a,close:o}=A(e,t);o&&p(e,()=>{b(e)},(a/2-n+a)%a)}async function b(e){if(!u){if(!m(e).open||!e.open){p(e,()=>{b(e)},h);return}if(A(e,m(e)).close){s.info({slackSocket:e.index},"restarting a Slack socket so the two refresh at different times"),e.restarting=!0;try{await e.client.disconnect()}finally{e.restarting=!1}await L(e)}}}async function L(e){if(!u)try{await e.client.start(),u&&await e.client.disconnect()}catch(t){s.warn({slackSocket:e.index,err:t,retryMs:h},"couldn't reopen a Slack socket, and will try again"),p(e,()=>{L(e)},h)}}async function M(){u=!0;for(const e of f)y(e);await Promise.all(f.map(e=>e.client.disconnect()))}return{init(e){v=e},async start(){u=!1;const t=(await Promise.allSettled(f.map(n=>n.client.start()))).find(n=>n.status==="rejected");if(t)throw await M(),t.reason},stop:M}}export{R as boltLogger,K as socketPool};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{AmbiguousEntry as A,CHANNELS_ONLY as N,EntryError as s}from"../permissions/entry.js";import{findChannel as E}from"./destination.js";import{toUser as U}from"./members.js";import{mentionableName as C}from"./mentions.js";import{slackSighting as L}from"./principal.js";const u="slack";function P(e,n,t){return{interface:u,...e?{principalId:e}:{},groups:t.of(n.userId),addresses:n.email?[n.email]:[]}}function v(e,n){return`${e}:${n}`}const D=/^[UW][A-Z0-9]+$/,j=/^S[A-Z0-9]+$/,_=/^[CG][A-Z0-9]+$/,G=/^D[A-Z0-9]+$/;function h(e){return e?.trim().toLowerCase()||void 0}function x(e){const n=C(e)??e.handle;return n?`@${n}`:e.userId}function w(e,n){return{kind:"principal",interface:u,label:x(e),sighting:L(e,!1,n.home)}}function $(e){return{kind:"group",interface:u,label:e.handle?`@${e.handle} (group)`:`${e.id} (group)`,group:"usergroup",externalId:e.id,...e.handle?{name:e.handle}:{}}}function S(e,n,t){return{kind:"location",interface:u,label:t?`#${t}`:e,externalId:v(n.home.teamId,e),locationKind:"channel",...t?{name:t}:{}}}function f(e,n,t){if(e.kind&&!n.includes(e.kind))throw new s(`${e.text}: names a ${t}, not a ${e.kind}`)}async function Y(e,n){if(e.interface!==u)throw new s(`${e.text}: is not a Slack entry`);const{value:t}=e;switch(t.form){case"domain":return f(e,["group"],"domain"),{kind:"group",interface:u,label:`*@${t.domain}`,group:"domain",externalId:t.domain};case"email":{f(e,["user"],"person");const a=await Z(t.email,n);if(!a)throw new s(`${e.text}: no Slack user has that address`);return w(a,n)}case"id":return B(e,t.id,n);case"name":return M(e,t.name,t.sigil,n)}}async function Z(e,n){try{const t=await n.client.users.lookupByEmail({email:e});if(t.user?.id)return U(t.user)}catch{}}async function B(e,n,t){if(G.test(n))throw new s(`${e.text}: ${N}`);if(D.test(n)){f(e,["user"],"person");const a=await t.users.lookup(n);return w(a,t)}if(j.test(n)){f(e,["group"],"user group"),await t.groups.ready();const a=t.groups.list().find(i=>i.id===n);return $(a??{id:n})}if(_.test(n)){f(e,["channel"],"channel");let a;try{a=(await t.client.conversations.info({channel:n})).channel?.name}catch{}return S(n,t,a)}throw new s(`${e.text}: <${n}> is not a Slack id Bishop knows. A user id starts with U or W, a user group with S, and a channel with C or G.`)}async function M(e,n,t,a){if(t==="#"||e.kind==="channel"){f(e,["channel"],"channel");const o=await E(a.client,n);if(!o?.id)throw new s(`${e.text}: no Slack channel named #${n} that this app can see. A private channel has to have the app in it.`);return S(o.id,a,o.name??n)}const i=h(n);if(!i)throw new s(`${e.text}: names nothing`);const p=e.kind!=="user",m=e.kind!=="group";let c=[];if(m){const o=await a.users.roster({wait:!0});if(!o)throw new s(`${e.text}: Bishop could not read the workspace's member list to look the name up. Name the person by email or by <U\u2026> id instead.`);const d=new Map(o.map(r=>[r.userId,r]));for(const r of a.users.seen())d.has(r.userId)||d.set(r.userId,r);c=[...d.values()].filter(r=>h(r.handle)===i||h(r.displayName)===i||h(r.realName)===i)}let l=[];p&&(await a.groups.ready(),l=a.groups.list().filter(o=>h(o.handle)===i||h(o.name)===i));const[g]=c,[k]=l;if(c.length+l.length===1){if(g)return w(g,a);if(k)return $(k)}if(c.length+l.length===0)throw new s(`${e.text}: matches no Slack ${m&&p?"user or user group":m?"user":"user group"} by handle or name.`);const b=[...c.map(o=>`${x(o)} (slack:<${o.userId}>)`),...l.map(o=>`${$(o).label} (slack:<${o.id}>)`)],I=c.length>0&&l.length>0?`Write slack:user:${n} or slack:group:${n} to say which, or use the id.`:"Use the id, or an email for a person, to say which.";throw new A(`${e.text}: matches ${b.length}: ${b.join(", ")}. ${I}`)}export{Y as resolveSlackSubject,v as slackLocation,P as slackMembership};
|
package/dist/slack/users.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{log as
|
|
1
|
+
import{log as u}from"../log.js";import{isMentionable as D,listMembers as M,toUser as b}from"./members.js";const _=3600*1e3,L=2e3,N=60*1e3;function c(i){return i?.trim().toLowerCase()||void 0}function x(i,a){return c(i.handle)===a||c(i.displayName)===a||c(i.realName)===a}function E(i,a={}){const{ttlMs:d=_,deadlineMs:p=L,self:w}=a,o=new Map;let s,m;const f=new Map;async function y(e){let t={userId:e};try{const r=(await i.users.info({user:e})).user;if(r){const l=r.real_name?.trim();t={...b(r),userId:e,...!r.profile?.real_name?.trim()&&l?{realName:l}:{}}}}catch(n){u.debug({userId:e,err:n},"could not resolve the Slack user")}return o.set(e,{user:t,expires:Date.now()+d}),t}function h(){return m??=M(i,e=>D(e)&&e.id!==w).then(e=>{s={users:e,expires:Date.now()+d}}).catch(e=>{s={users:[],expires:Date.now()+N},u.debug({err:e},"could not list the workspace members")}).finally(()=>{m=void 0}),m}async function g(e=!1){if(s&&s.expires>Date.now())return s.users;const t=h();if(e)return await t,s?.users??[];let n;const r=new Promise(l=>{n=setTimeout(l,p)});return await Promise.race([t,r]),clearTimeout(n),s?s.users:(u.debug("the member list is still loading; leaving this name unlinked"),[])}return{get size(){return o.size},prime(){h()},async roster(e){const t=await g(e?.wait);return t.length>0?t:void 0},seen(){return[...o.values()].map(e=>e.user).filter(e=>e.userId!==a.self&&e.userId!=="USLACKBOT")},async lookup(e){if(!e)return{userId:e};const t=o.get(e);if(t&&t.expires>Date.now())return t.user;const n=f.get(e);if(n)return n;const r=y(e).finally(()=>f.delete(e));return f.set(e,r),r},async findByName(e){const t=c(e.replace(/^@+/,""));if(!t)return;const n=(await g()).filter(r=>x(r,t));if(n.length===1)return n[0];n.length>1&&u.debug({name:t,hits:n.length},"a written name matched more than one user")}}}export{E as userDirectory};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{HEARTBEAT_MS as c}from"./presence.js";function p(a,u={}){const n=new Map;let i=!1;function s(t,e){let r=n.get(e);return r||(r={ref:t,working:!1,turn:!1},n.set(e,r)),r.ref=t,r}function o(t){return t.heartbeat?(clearInterval(t.heartbeat),t.heartbeat=void 0,!0):!1}async function l(t,e,r){if(e.working){if(e.heartbeat)return;e.heartbeat=setInterval(()=>{a(e.ref,"processing")},u.heartbeatMs??c),e.heartbeat.unref(),await a(e.ref,"processing");return}n.delete(t),(o(e)||r)&&await a(e.ref,"active")}return{set(t,e,r){if(i)return;const f=s(t,e);f.working=r,f.turn||l(e,f,!1)},open(t,e){const r=s(t,e);r.turn=!0,o(r)},async release(t,e){const r=n.get(e);r?.turn&&(r.ref=t,r.turn=!1,i&&(r.working=!1),await l(e,r,!0))},async close(){i=!0;const t=[...n].filter(([,e])=>!e.turn&&o(e));for(const[e]of t)n.delete(e);await Promise.all(t.map(([,e])=>a(e.ref,"active")))}}}export{p as workingSessions};
|
package/dist/teams/create.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{randomUUID as
|
|
2
|
-
`)):
|
|
1
|
+
import{randomUUID as M}from"node:crypto";import{readFile as b}from"node:fs/promises";import{App as O}from"@microsoft/teams.apps";import{BishopError as x}from"../errors.js";import{log as h}from"../log.js";import{retry as p}from"../retry.js";import{teamsRetryable as u}from"./api.js";import{DOWNLOAD_TIMEOUT_MS as I,teamsFilesOf as $}from"./files.js";import{teamsGraph as S}from"./graph.js";import{createTeamsInterface as v}from"./interface.js";import{teamsLogger as C}from"./logger.js";import{createListener as F}from"./server.js";import{graphAddressOf as U}from"./thread.js";const k=3978,P="/healthz",D=500;async function R(e){const o=async(r,c)=>{try{return await b(r,"utf8")}catch(i){throw new x(`Couldn't read the TLS ${c} at ${r}: ${i.message}`,"ConfigError")}};return{cert:await o(e.cert,"certificate"),key:await o(e.key,"key")}}function w(e,o=[],r=[]){return{type:"message",text:e,...o.length>0?{attachments:o}:{},...r.length>0?{entities:r.map(c=>({type:"mention",mentioned:{id:c.id,name:c.name,role:"user"},text:c.text}))}:{}}}const _="application/vnd.microsoft.teams.card.file.consent",A="application/vnd.microsoft.teams.card.file.info";function E(e){if(!e||typeof e!="object")return;const o=e.ref;return typeof o=="string"?o:void 0}function B(e){const o={description:`Bishop wants to send ${e.name}.`,sizeInBytes:e.size,acceptContext:{ref:e.ref},declineContext:{ref:e.ref}};return{contentType:_,name:e.name,content:o}}function q(e){return{id:M(),contentType:A,contentUrl:e.webUrl,name:e.name,content:{uniqueId:e.uniqueId,fileType:e.fileType}}}async function j(e,o){const r=o.uploadInfo?.uploadUrl;if(!r)throw new Error("Teams returned no upload URL for the accepted file");const c=y(r),i=new Uint8Array(await b(e.path)),T=Math.max(0,i.byteLength-1),m=await fetch(c,{method:"PUT",headers:{"content-type":"application/octet-stream","content-length":String(i.byteLength),"content-range":`bytes 0-${T}/${i.byteLength}`},body:i});if(!m.ok)throw new Error(`Teams returned ${m.status} while receiving ${e.name}`)}async function se(e){const o=F({port:e.config?.port??k,healthPath:e.config?.healthPath??P,...e.config?.host?{host:e.config.host}:{},...e.config?.tls?{tls:await R(e.config.tls)}:{}}),r=new O({clientId:e.credentials.clientId,clientSecret:e.credentials.clientSecret,tenantId:e.credentials.tenantId,httpServerAdapter:o,logger:C()}),c=S(e.credentials),i=new Map,m=v({api:{async send(n,t,a){const s=a?.files??[];let d=t,g=[];a?.channel&&s.length>0?(g=(await Promise.all(s.map(l=>c.uploadChannelFile(a.channel,l)))).map(q),d=[t,...g.map(l=>`<attachment id="${l.id}"></attachment>`)].filter(Boolean).join(`
|
|
2
|
+
`)):s.length>0&&(g=s.map(f=>(i.set(f.ref,f),B(f))));try{const f=w(d,g,a?.mentions),l=await p(()=>r.send(n,f),{what:"teams send",retryable:u});return l?.id?{id:l.id}:void 0}catch(f){for(const l of s)i.delete(l.ref);throw f}},async update(n,t,a,s){await p(()=>r.api.conversations.updateActivity(n,t,w(a,[],s)),{what:"teams update",retryable:u})},async members(n){const t=await p(()=>r.api.conversations.getPagedMembers(n,D),{what:"teams roster page",retryable:u});return{members:t.members,complete:!t.continuationToken}},async channelInfo(n){return c.channel(n)},async channels(n){return c.channels(n)},async openChat(n){try{return(await p(()=>r.api.conversations.create({members:[{id:n,role:"user"}],tenantId:e.credentials.tenantId,channelData:{tenant:{id:e.credentials.tenantId}}}),{what:"teams open chat",retryable:u})).id}catch(t){if(t.response?.status===403)return;throw t}},async member(n,t){return await p(()=>r.api.conversations.getMemberById(n,t),{what:"teams roster",retryable:u})},async sharedFiles(n){const t=U(n);return t?c.files(t):[]},async history(n){const t=U(n);if(t)return c.conversation(t)},async fetchFile(n){const t=await fetch(y(n),{signal:AbortSignal.timeout(I)});if(!t.ok)throw new Error(`the download returned ${t.status}`);if(!t.body)throw new Error("the download sent no body");return t.body},async fetchAttachment(n){const t=y(n),a=new URL(r.api.serviceUrl);if(t.host!==a.host)throw h.warn({host:t.host,service:a.host},"refusing to send the app credential to a host that is not the Teams service"),new Error("the image is not hosted on the Teams service");const s=await r.api.http.get(t.toString(),{responseType:"arraybuffer",timeout:I});return N(s.data)},async fetchShared(n){return c.fetchShared(n)}},permissions:e.permissions,...e.config?.verbosity?{verbosity:e.config.verbosity}:{},listener:o,meta:e.meta,model:e.model,...e.configuredModel?{configuredModel:e.configuredModel}:{},...e.configuredModelAt?{configuredModelAt:e.configuredModelAt}:{},threads:e.threads,events:e.events,files:e.files,attachments:e.attachments,principals:e.principals,tenantId:e.credentials.tenantId,run:e.run,stop:e.stop,...e.gate?{gate:e.gate}:{}});r.on("message",async({activity:n})=>{await m.handle(G(n))}),r.on("conversationUpdate",async({activity:n})=>{const t=n.channelData?.channel?.id,a=n.channelData?.team?.aadGroupId;m.changed({conversationId:n.conversation.id,...typeof t=="string"?{channelId:t}:{},...typeof a=="string"?{teamId:a}:{}})}),r.on("file.consent.accept",async({activity:n,send:t})=>(await L(n.value,t),{status:200})),r.on("file.consent.decline",async({activity:n,send:t})=>{const a=E(n.value.context),s=a?i.get(a):void 0;return a&&i.delete(a),s?(await t(w(`${s.name} was not sent because the file-consent request was declined.`)),{status:200}):(h.warn("received a Teams file-consent decline for an unknown file"),{status:200})});async function L(n,t){const a=E(n.context),s=a?i.get(a):void 0;if(a&&i.delete(a),!s){h.warn("received a Teams file-consent acceptance for an unknown file");return}try{await j(s,n);const d=n.uploadInfo;if(!d?.contentUrl||!d.uniqueId)throw new Error("Teams returned incomplete file information after the upload");await t(w(`${s.name} was sent.`,[{contentType:A,contentUrl:d.contentUrl,name:d.name??s.name,content:{uniqueId:d.uniqueId,fileType:d.fileType??s.mimeType}}]))}catch(d){h.warn({err:d,file:s.name},"could not finish a Teams file upload"),await t(w(`Could not send ${s.name}: ${d.message}`))}}return await r.initialize(),h.info({endpoint:r.server.messagingEndpoint},"the Teams app is mounted"),m}function y(e){const o=new URL(e);if(o.protocol!=="https:")throw new Error("the download URL is not HTTPS");return o}function N(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);throw new Error("the download came back as something other than bytes")}function z(e){const o=e.recipient?.id,r=o?e.stripMentionsText?.({accountId:o}):e;return(r?.stripMentionsText?.({tagOnly:!0})??r)?.text??e.text??""}function G(e){const o=W(e.channelData);return{id:e.id,conversationId:e.conversation.id,conversationType:typeof e.conversation.conversationType=="string"?e.conversation.conversationType:"channel",text:z(e),...H(e.attachments),mentioned:e.isRecipientMentioned?.()===!0,from:{id:e.from.id,...e.from.aadObjectId?{aadObjectId:e.from.aadObjectId}:{},...e.from.name?{name:e.from.name}:{}},...e.recipient?.id?{recipientId:e.recipient.id}:{},...e.recipient?.name?{recipientName:e.recipient.name}:{},files:$(e.attachments),...o?{channel:o}:{}}}function H(e){const o=e?.find(r=>r.contentType?.toLowerCase()==="text/html"&&typeof r.content=="string")?.content;return typeof o=="string"?{html:o}:{}}function W(e){const o=e?.team?.aadGroupId,r=e?.channel?.id;if(!(typeof o!="string"||typeof r!="string"))return{teamId:o,channelId:r}}export{se as createTeams,G as inboundOf};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BishopError as
|
|
1
|
+
import{BishopError as a}from"../errors.js";import{log as d}from"../log.js";import{findPeople as p}from"./mentions.js";import{baseConversation as u,channelHandleOf as y,destinationOfHandle as w}from"./thread.js";const $=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function C(o,n,s={}){const t=n.trim();if($.test(t)){const i=o.nameOf(t);return i?f(o,t,`@${i}`,i):f(o,t,"a personal Teams chat","this person")}const e=s.from?.interface==="teams"?s.from.handle:void 0;if(t.startsWith("#"))return T(o,t.slice(1).trim(),e);if(t.startsWith("@"))return v(o,t.slice(1).trim(),e,s);throw new a(`can't tell where "${n}" is in Teams. Write #channel for a channel in this team, or @person for somebody in this conversation.`)}async function g(o,n,s){if(!n)throw new a("a Teams channel needs a name after the #");const t=s?w(s):void 0;if(t?.scope!=="channel")throw new a(`Bishop finds #${n} in the team it is asked from, and this conversation is not in a team. Ask in a channel of the team you mean.`);const e=t.channel?.teamId;if(!e)throw new a(`Teams did not say which team this channel belongs to, so Bishop cannot look for #${n}. Ask in the channel itself instead.`);let i;try{i=await o.channels(e)}catch(r){throw d.warn({err:r,team:e},"could not list the channels in a Teams team"),r.status===403?new a("This team has not given the app permission to list its channels. Reinstalling the app in the team grants it."):new a("Bishop could not list the channels in this team just now.")}const c=i.find(r=>r.name===n);if(!c){const r=i.find(m=>m.name.toLowerCase()===n.toLowerCase());throw new a(r?`No channel in this team is named exactly #${n}. Did you mean #${r.name}?`:`No channel in this team is named #${n}.`)}const h=t.channel?.channelId;return{teamId:e,channel:c,...h?{askedFrom:h}:{}}}async function T(o,n,s){const{teamId:t,channel:e,askedFrom:i}=await g(o.api,n,s);if(e.membershipType&&e.membershipType!=="standard"&&e.id!==i)throw new a(`#${e.name} is a ${e.membershipType} channel, and Bishop can't tell from here whether the app is in it. Ask for the report from inside that channel.`);return{interface:"teams",handle:y(e.id,{teamId:t,channelId:e.id}),label:`#${e.name}`}}async function v(o,n,s,t){if(!n)throw new a("a Teams person needs a name after the @");if(!s)throw new a(`Bishop finds @${n} among the people in the conversation it is asked from, and there is none here.`);const e=u(w(s).conversation),i=await o.roster.of(e);if(!i)throw new a("Bishop could not read who is in this conversation just now.");const c=p(i.people,n);if(c.length===0)throw new a(`Nobody in this conversation is called ${n}`+(i.complete?".":" among the people Bishop can see.")+" Ask from a conversation they are in.");if(c.length>1){const m=c.map(l=>l.email?`${l.name} (${l.email})`:l.name).join(", ");throw new a(`More than one person here could be ${n}: ${m}. Say which.`)}const[h]=c;let r;try{r=await o.api.member(e,h.id)}catch(m){if(d.warn({err:m,conversation:e},"could not read the Teams roster"),t.optedInOnly)throw new a(`Bishop could not check whether ${h.name} has access to this agent just now.`)}if(t.optedInOnly&&(!r||!o.allows(r)))throw new a(`${h.name} has no access to this agent, so Bishop won't start sending them messages they never asked for. An admin can give them a level with \`! permissions set\`, or the report can go to a channel they are in instead.`);return f(o,h.id,`@${h.name}`,h.name)}async function f(o,n,s,t=s){const e=await o.api.openChat(n).catch(i=>{throw d.warn({err:i},"could not open a Teams personal chat"),new a(`Teams could not open a chat with ${t} just now.`)});if(!e)throw new a(`Teams won't let the agent message ${t}: they have not added the app, and are not in a team that has it. They can add it in Teams, or the report can go to a channel they are in.`);return{interface:"teams",handle:`${e};scope=personal`,label:s}}export{$ as OBJECT_ID,g as findTeamChannel,C as resolveTeamsDestination};
|
package/dist/teams/history.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{describedFile as k}from"../files.js";import{declareUnread as b,trimHistory as v,withinFileBudget as y}from"../interface/history.js";import{log as p}from"../log.js";import{describeTeamsFile as I}from"./files.js";import{messageText as h}from"./html.js";import{threadIdOf as
|
|
1
|
+
import{describedFile as k}from"../files.js";import{declareUnread as b,trimHistory as v,withinFileBudget as y}from"../interface/history.js";import{log as p}from"../log.js";import{describeTeamsFile as I}from"./files.js";import{messageText as h}from"./html.js";import{threadIdOf as T}from"./thread.js";function W(n){if(n.conversationType==="personal")return!1;if(n.conversationType==="groupChat")return!0;const e=T(n.conversationId);return!!e&&e!==n.id}async function $(n){const{read:e}=n;if(!e)return p.warn("could not read the Teams conversation to catch the agent up"),[{kind:"omitted",reason:"unavailable"}];for(const t of e.messages)t.user&&t.at!==void 0&&n.saw?.(t.user.id,t.at);const i=new Map,o=new Map(e.messages.flatMap(t=>t.user?[[t.user.id,t.user]]:[]));await Promise.all([...o.values()].map(async t=>{try{i.set(t.id,await n.sender(t))}catch(u){p.warn({err:u,who:t.id},"could not check a Teams sender for history")}}));const s=x(e.messages,n,i),a=v(s.entries),f=a[1]?.kind==="omitted"&&a[1].reason==="trimmed",r=!e.complete&&!n.openedBy&&f?a.slice(1):a,l=y(r).map(t=>B(t,n));return e.complete?l:b(l,s.opensWithParent)}function x(n,e,i){const o=[];let s=!1,a=0;const f=()=>{a&&(o.push({kind:"omitted",reason:"unauthorized",count:a}),a=0)};for(const r of n){const d=r.id===e.openedBy,l=!!e.selfAppId&&r.app?.id===e.selfAppId,t=r.user?i.get(r.user.id):void 0;if(!l&&!t?.allowed){d&&(s=!0),a+=1;continue}const u=new Set(r.appMentions.filter(c=>c.appId===e.selfAppId).map(c=>c.id));if(!h(r.html,(c,m)=>u.has(c)?"":`@${m}`)&&r.files.length===0)continue;const w=h(r.html,(c,m)=>u.has(c)&&e.selfName?e.selfName:`@${m}`);d&&(s=!0),f();const g=l?e.self?.():t?.principal();o.push({kind:"message",principal:g??{id:"",externalId:e.selfAppId??"",handle:e.selfName?.replace(/^@/,"")||"unknown",name:e.selfName?.replace(/^@/,"")||"unknown",kind:"bot",affiliation:"unknown",self:!0},text:w,...r.files.length>0?{shared:r.files}:{}})}return f(),{entries:o,opensWithParent:s}}function B(n,e){if(n.kind!=="message")return n;const{shared:i,...o}=n;return i?.length?{...o,files:F(i,e)}:o}function F(n,e){return n.map(i=>{const o=k(I(i)),s=e.remember(i);return s?{...o,ref:s}:{...o,unavailable:"Bishop could not record a reference for it"}})}export{W as landedMidConversation,F as namedTeamsFiles,$ as teamsHistory};
|
package/dist/teams/interface.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import{runCommand as
|
|
2
|
-
`)}function
|
|
1
|
+
import{runCommand as Ie}from"../commands/run.js";import{BishopError as Te}from"../errors.js";import{etiquetteNote as ke,threadParticipants as Oe}from"../interface/etiquette.js";import{splitMessage as xe}from"../interface/format.js";import{showsProgress as Z,showsTasks as Se,threadVerbosity as Ae}from"../interface/verbosity.js";import{log as d}from"../log.js";import{atLeast as Me,lowest as ee}from"../permissions/levels.js";import{atDeny as Be,refusalText as ne}from"../permissions/refusal.js";import{principalLabel as Ke}from"../principals.js";import{teamsCommandLine as te}from"./command.js";import{teamsObserver as Ne}from"./context.js";import{resolveTeamsDestination as Ee}from"./destination.js";import{describeTeamsFile as _e,parseTeamsFile as je,teamsAttachment as oe,teamsFilePayload as Pe}from"./files.js";import{landedMidConversation as Ce,namedTeamsFiles as De,teamsHistory as $e}from"./history.js";import{findPeople as Fe,linkMentions as Re,teamsRoster as We}from"./mentions.js";import{handleReach as Le,resolveTeamsSubject as ae,teamsLocation as He,teamsMembership as M}from"./permissions.js";import{teamsPresence as Ge}from"./presence.js";import{teamsSighting as ie}from"./principal.js";import{addressesAgent as B,routeActivity as Ye}from"./route.js";import{baseConversation as ze,conversationOf as j,destinationHandleOf as Ue,destinationOfHandle as P,fileRouteOf as re,sameConversation as qe,scopeOf as se,threadIdOf as C,threadIn as D,threadKeyOf as Qe}from"./thread.js";function Ve(t){return[...Xe(t),...Je].join(`
|
|
2
|
+
`)}function Xe(t){return Z(t)?["This conversation is in Microsoft Teams. Each thing you write is posted as its own message","while you work, so somebody is watching the whole turn. Say what you are doing as you go,","and keep it to a line or two. Your last message is the answer to what was asked.","",Se(t)?"Your tool calls show as one message that is rewritten as you work, and replaced by a count of them once you speak again.":"Your tool calls are not shown, so a stretch of them is a silence unless you say what you are doing.","","Nothing more can reach this conversation once the turn ends, so never say you will follow up","separately: finish what you were asked before you stop.",""]:["This conversation is in Microsoft Teams. Only the last thing you write reaches it, and","anything you say on the way there is dropped, so put the whole answer in the message you","finish with. Never say you will follow up separately: nothing more can reach this","conversation until someone writes to you again.","","Nobody is watching while you work. None of your tool calls are visible and nothing you say","arrives until the turn is over, so a turn that takes minutes costs nothing, and there is no","typing indicator to say you are still going.",""]}const Je=["Teams renders a narrower markdown than Slack does. Bold, italics, links, inline code, fenced","code blocks and lists work. Tables do not, so write a list or plain prose where you would","otherwise reach for one.","","A file somebody attaches reaches you in a direct chat and in a channel, and so does an image","pasted into a message anywhere. One Bishop could not download arrives saying why instead of","going missing, so you can tell somebody what happened to it. A group chat is the one place a","file may not reach you at all: if somebody there asks about one you were given nothing for,","say it never arrived and ask them to send it in a direct chat.","","People are named to you by their Teams display name. Write @ and the name exactly as you were",'given it, spaces included, and Bishop makes it a real mention, as in "@Kim Lee, can you take','a look?". A name that does not match exactly one person stays plain text. You can always',"mention the person whose message you are answering. @here, @channel, @everyone and team","mentions are never created, whoever writes them.","",'Asked to mention somebody by part of their name, like "mention Kim", look them up with',"teams_find_person first. If one person matches, write @ and the full name it gives. If more","than one does, ask which one was meant rather than guessing.","","A conversation can hold people talking to each other and not to you. Bishop marks a message",'you may leave alone with a <thread> tag carrying reply="optional": other people are talking',"here and this one did not @mention you, so answer it only if you have something worth adding.","To stay out of it, say <no-output> and nothing else, and Bishop posts nothing at all. Every","message without that tag is yours to answer."],ce="There was no text in that message for me to act on. Say what you need in words, and @mention me so I see it.",Ze=ce+" If you attached a file, nothing about it reached me, so send it in a direct chat.",en=2e4,nn=3600*1e3;function xn(t){const T=new Set,k=new Map,$=new Map,F=new Set,x=Oe(),R=Ne({api:t.api,...t.tenantId?{tenantId:t.tenantId}:{}}),b=We(t.api),S=Ae(t.meta,"teams",t.verbosity),le={verbosity:S,model:t.model,configured:t.configuredModel??{},...t.configuredModelAt?{configuredAt:t.configuredModelAt}:{},stop:t.stop,permissions:t.permissions,nameOf:e=>Ke(e,t.principals)},K=new Map;let y,W=!1,L=!1;function N(e){return{name:"teams",guidance:Ve(S.of(e.id).level),...y?{self:y}:{}}}async function H(e,n,o){if(!n)return;const r=k.get(n);if(r)return r;if(($.get(n)??0)>Date.now())return;const a=ze(e);let s;try{s=await t.api.member(a,o),s&&k.set(n,s)}catch(i){d.warn({err:i,conversation:a},"could not read the Teams roster")}return!s&&t.permissions.fallback!=="deny"&&$.set(n,Date.now()+nn),s}async function I(e,n,o={}){const{files:r=[],opened:a}=o;let{channel:s}=o,i=e,c;const m=n?xe(n,en):[""];for(const[l,w]of m.entries()){const f=l===m.length-1,h=o.mentions?await Re(w,o.mentions):{text:w,mentions:[]},v=f&&(r.length>0||s)||h.mentions.length>0?{...f&&r.length>0?{files:r}:{},...f&&s?{channel:s}:{},...h.mentions.length>0?{mentions:h.mentions}:{}}:void 0,p=await t.api.send(i,h.text,v);a&&l===0&&p&&(a.root=p.id,i=D(e,p.id),s&&(s={...s,threadId:p.id})),c=p?{id:p.id,text:h.text,...h.mentions.length>0?{mentions:h.mentions}:{}}:void 0}return c}function G(e,n,o){const r=[n?.handle,n?.name].filter(a=>!!a);return{...r.length>0&&o?{sender:{id:o,names:r}}:{},roster:async()=>(await b.of(e))?.people}}function A(e,n){const o=t.principals.lookup("teams",e);return t.permissions.of(M(o?.id,e,n))}function Y(e){return e.conversationType==="channel"?t.permissions.location("teams",[He(e.conversationId)]):void 0}async function de(e,n){const o=await b.of(e);if(!o){const i=ee([n,t.permissions.fallback])??n;return d.warn({conversation:e,permission:i},"couldn't read a group chat's members; it runs no higher than the default level for now"),{level:i,denied:[]}}const a=o.members.filter(i=>!i.id.startsWith("28:")).map(i=>({found:i,level:A(i.aadObjectId??i.id,i).level})),s=a.filter(i=>i.level==="deny").map(({found:i})=>i.name??i.userPrincipalName??i.email??i.id);return{level:ee([n,...a.map(i=>i.level)])??n,denied:s}}function he(e){return{interface:"teams",handle:Ue(e),label:tn(e)}}const z={api:t.api,members:()=>k.values(),...t.tenantId?{tenantId:t.tenantId}:{}};function E(e,n){const o=Pe(n);if(!o)return;const r=_e(n);return t.attachments.remember(e,"teams",{id:r.id,name:r.name,payload:o})}async function me(e,n){return n.files.length===0?[]:Promise.all(n.files.map(async o=>{const r=E(e.id,o),a=await t.files.save(e.dirKey,oe(o,t.api));return r?{...a,ref:r}:a}))}function U(e,n,o){return t.principals.see(N(e).name,ie({id:n.from.aadObjectId??n.from.id,...n.from.name?{name:n.from.name}:{},bot:n.from.id.startsWith("28:")},o,t.tenantId))}function q(e,n){return t.principals.see("teams",{externalId:e,...n?{handle:n,name:n}:{},kind:"bot",affiliation:"unknown",self:!0})}async function fe(e,n,o){const r=N(e),a=j(n),s=C(a),i=n.recipientId?.replace(/^28:/,"");return $e({read:await t.api.history(n),...s?{openedBy:s}:{},...i?{selfAppId:i}:{},...y?{selfName:y.address}:{},...n.recipientId?{self:()=>q(n.recipientId,n.recipientName)}:{},sender:async c=>{const m=await H(a,c.id,c.id);return{allowed:Me(A(c.id,m).level,o),principal:()=>t.principals.see(r.name,ie({id:c.id,...c.name?{name:c.name}:{},bot:!1},m,t.tenantId))}},remember:c=>E(e.id,c),saw:(c,m)=>x.saw(e.threadKey,c,m)})}function ue(e,n,o,r,a,s){const i=j(n),c=C(i),m=n.channel?{teamId:n.channel.teamId,channelId:n.channel.channelId,...c?{threadId:c}:{}}:void 0,l=ke({participants:x.count(e.threadKey),mentioned:B(n)}),w=G(i,o,n.from.id);return{thread:e,isNewThread:r,level:a,get origin(){return N(e)},...l?{note:l}:{},...Ce(n)?{history:()=>fe(e,n,a)}:{},observe:()=>R.observe({conversationId:n.conversationId,scope:se(n),...n.channel?{channel:n.channel}:{},speaker:o.affiliation}),async messages(){const f=await me(e,n);return[{principal:o,externalId:n.id,text:n.text,...f.length>0?{files:f}:{}}]},showsProgress:()=>Z(S.of(e.id).level),presence:()=>{const f=Ge({send:(h,v)=>I(i,h,{...v?{files:v}:{},...m?{channel:m}:{},mentions:w}),post:h=>t.api.send(i,h),update:(h,v,p)=>t.api.update(i,h,v,p),threadKey:e.threadKey,verbosity:()=>S.of(e.id).level,...re(se(n),m)==="none"?{share:!1}:{},...l?{mayDecline:!0}:{}});return K.set(e.threadKey,f),{...f,finish:async()=>{try{await f.finish()}finally{K.delete(e.threadKey)}}}},async notify(f){await I(i,f)},async destination(){return s}}}async function pe(e){if(L)return;if(await t.events.seen(`teams:${e.id}`)){d.debug({activity:e.id},"already answered this Teams activity");return}!y&&e.recipientName&&(y={address:`@${e.recipientName}`},d.info({address:y.address},"the agent is known by this name in Teams")),!W&&e.recipientId&&(W=!0,q(e.recipientId,e.recipientName));const n=Qe(e),o=await t.threads.has(n),r=Ye(e,{threadKnown:o});if(r.action==="ignore"){d.debug({activity:e.id,thread:n,reason:r.reason},"leaving a Teams message alone");return}const a=e.from.aadObjectId;if(!a){d.warn({activity:e.id},"refusing a Teams message with no Entra object ID");return}x.saw(n,a,Date.now());const s=j(e),i=await H(s,a,e.from.id),c=A(a,i),m=e.conversationType==="groupChat"&&c.level!=="deny"?await de(s,c.level):void 0,l=await t.permissions.admit({sender:c.level,location:Y(e),...m?{audience:m.level}:{},remember:()=>t.threads.remember(n),known:o,command:te(e)!==void 0,follows:e.conversationType==="personal"});if(!l.ok){d.warn({activity:e.id,who:a,conversation:s,why:l.why},"refusing a Teams message");const u=e.from.id.startsWith("28:"),g=`${n}
|
|
3
|
+
${a}`,X=l.why==="below"||l.why==="locationBelow";if(!u&&(X?!F.has(g):B(e))){X&&F.add(g);const J=l.why==="audience"&&c.level==="admin"?m?.denied??[]:[],ge=J.length?`${ne(l)} ${Be(J)}`:ne(l);await I(s,ge).catch(be=>{d.debug({err:be},"could not tell somebody why the agent will not answer")})}return}const w=l.thread,f=he(e),h=te(e);if(h){const u=await Ie(h,{thread:w,interface:"teams",sender:{id:U(w,e,i).id,level:c},level:l.level,location:Y(e),resolve:g=>ae(z,g,f)},le);try{await I(s,u),K.get(n)?.interrupted()}catch(g){d.warn({thread:n,err:g},"couldn't answer a command")}d.info({thread:n,who:a},"ran a command");return}const v=new Set(e.files.map(u=>u.contentUrl)),p=(await t.api.sharedFiles(e)).filter(u=>!v.has(u.contentUrl)),O=p.length>0?{...e,files:[...e.files,...p]}:e;if(!O.text.trim()&&O.files.length===0){if(d.info({activity:e.id},"a Teams message had nothing to act on"),B(e)){const u=e.conversationType==="personal"?ce:Ze;await I(s,u).catch(g=>{d.debug({err:g},"could not answer a message with nothing in it")})}return}const _=U(w,O,i);t.permissions.of(M(_.id,a,i));const V=we(w,O,_).then(u=>{if(u)return d.info({thread:n,who:a,newThread:!o},"running a turn from Teams"),t.run(ue(w,O,_,!o,l.level,f))}).catch(u=>{d.error({thread:n,err:u},"a turn from Teams failed")}).finally(()=>{T.delete(V)});T.add(V)}async function we(e,n,o){return t.gate?t.gate.admit({thread:e,...y?{agent:y.address}:{},participants:x.count(e.threadKey),mentioned:B(n),message:async()=>{const r=De(n.files,{remember:a=>E(e.id,a)});return{principal:o,externalId:n.id,text:n.text,...r.length?{files:r}:{}}}}):!0}async function Q(){for(;T.size>0;)await Promise.allSettled([...T])}function ye(e){return e==="groupChat"?"Bishop cannot send files to Teams group chats yet.":e==="channel"?"Bishop has no Graph address for this Teams channel, so it cannot send files there.":"Bishop cannot send files to this older Teams destination. Ask for a new report in the conversation first."}async function ve(e){const n=P(e.handle),o=e.files??[],r=o.map(i=>i.name).join(", ");if(o.length>0&&re(n.scope,n.channel)==="none")throw new Te(ye(n.scope));const a=n.scope==="channel"&&!C(n.conversation)?{}:void 0,s=G(n.conversation);try{await I(n.conversation,e.text,{...n.channel?{channel:n.channel}:{},mentions:s,files:o,...a?{opened:a}:{}})}catch(i){if(!o.length)throw i;d.warn({handle:e.handle,files:r,err:i},"could not attach files to a Teams report");const c=a?.root;await I(c?D(n.conversation,c):n.conversation,`${e.text}
|
|
3
4
|
|
|
4
|
-
_Could not attach ${
|
|
5
|
+
_Could not attach ${r}; the report was sent without the file._`,{...n.channel?{channel:c?{...n.channel,threadId:c}:n.channel}:{},mentions:s,...a&&!c?{opened:a}:{}})}return a?.root?{threadKey:`teams:${D(n.conversation,a.root)}`}:{}}return{name:"teams",handle:pe,changed:e=>{R.changed(e),b.changed(e.conversationId),e.channelId&&b.changed(e.channelId)},settle:Q,deliver:ve,membership(e){return M(e.id,e.externalId,k.get(e.externalId),e.email)},resolveSubject:(e,n)=>ae(z,e,n),async reach(e){const n=Le(e);if(P(e).scope!=="groupChat")return n;const o=await b.of(P(e).conversation);if(!o)return{...n,recipients:[{interface:"teams",groups:[],addresses:[]}]};const r=o.members.filter(a=>!a.id.startsWith("28:"));return{...n,recipients:r.map(a=>{const s=a.aadObjectId??a.id;return M(t.principals.lookup("teams",s)?.id,s,a)})}},sameConversation:qe,async findPeople(e,n){const o=await b.of(e.threadKey.replace(/^teams:/,""));return o?{kind:"people",people:Fe(o.people,n).map(a=>({name:a.name,...a.email?{email:a.email}:{}})),complete:o.complete}:{kind:"refused",reason:"Bishop could not read who is in this conversation just now."}},resolveDestination:(e,n)=>Ee({api:t.api,roster:b,allows:o=>!!o.aadObjectId&&A(o.aadObjectId,o).level!=="deny",nameOf:o=>k.get(o)?.name},e,n),attachment:e=>{const n=je(e);return n?oe(n,t.api):void 0},async start(){await t.listener.start(),d.info({default:t.permissions.fallback},"listening for Teams activities")},async stop(){L=!0,await t.listener.stop(),T.size>0&&(d.info({turns:T.size},"waiting for Teams turns still running"),await Q())}}}function tn(t){return t.conversationType==="personal"?`a chat with ${t.from.name??"someone"}`:t.conversationType==="groupChat"?"a Teams group chat":"a Teams channel thread"}export{xn as createTeamsInterface,Ve as teamsGuidance};
|
package/dist/teams/mentions.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CODE as g}from"../interface/mentions.js";import{log as d}from"../log.js";import{baseConversation as m}from"./thread.js";const w=2e3,h=/(^|[^\p{L}\p{N}@/<])@(?=[\p{L}\p{N}])/gu,L=new Set(["here","channel","everyone","team"]),y=new RegExp("^\\s+\\p{Lu}","u");async function R(t,r,o=w){const
|
|
1
|
+
import{CODE as g}from"../interface/mentions.js";import{log as d}from"../log.js";import{baseConversation as m}from"./thread.js";const w=2e3,h=/(^|[^\p{L}\p{N}@/<])@(?=[\p{L}\p{N}])/gu,L=new Set(["here","channel","everyone","team"]),y=new RegExp("^\\s+\\p{Lu}","u");async function R(t,r,o=w){const a=t.split(g);if(!a.some((e,n)=>n%2===0&&new RegExp(h).test(e)))return{text:t,mentions:[]};try{const e=await b(r.roster?.(),o)??[],n=r.sender,s=n?n.names.map(l=>({id:n.id,name:l})):[],i=x([...e,...s]),c=[],u=a.map((l,f)=>f%2===1?l:S(l,i,n?.id,c)).join("");return c.length>0&&d.debug({mentions:c.length},"linked mentions in agent text"),{text:u,mentions:c}}catch(e){return d.debug({err:e},"could not link mentions; sending the text as written"),{text:t,mentions:[]}}}function x(t){return t.filter(r=>r.name.trim()).sort((r,o)=>o.name.trim().length-r.name.trim().length)}function S(t,r,o,a){let e="",n=0;for(const s of t.matchAll(h)){const i=(s.index??0)+(s[1]??"").length;if(i<n)continue;const c=t.slice(i+1),u=T(c,r,o);if(!u)continue;const l=c.slice(0,u.name.trim().length),f=`<at>${l}</at>`;a.push({id:u.id,name:u.name,text:f}),e+=t.slice(n,i)+f,n=i+1+l.length}return e+t.slice(n)}function T(t,r,o){let a=0;const e=new Map;for(const i of r){const c=i.name.trim();if(a>0&&c.length<a)break;k(t,c)&&(a=c.length,e.has(i.id)||e.set(i.id,i))}if(e.size===0)return;const n=t.slice(0,a);if(L.has(n.toLowerCase()))return;const s=o!==void 0&&e.has(o);if(!(!s&&!/\s/.test(n)&&y.test(t.slice(a)))){if(e.size===1)return[...e.values()][0];if(s)return e.get(o);d.debug({hits:e.size},"a written name matched more than one person")}}function k(t,r){return t.slice(0,r.length).toLowerCase()!==r.toLowerCase()?!1:!/^[\p{L}\p{N}]/u.test(t.slice(r.length))}async function b(t,r){if(!t)return;let o;const a=new Promise(e=>{o=setTimeout(()=>{d.debug("the Teams roster took too long; only the sender can be mentioned"),e(void 0)},r)});try{return await Promise.race([t.catch(()=>{}),a])}finally{clearTimeout(o)}}const C=10*6e4,_=6e4;function A(t,r=Date.now){const o=new Map;async function a(e,n){try{const{members:s,complete:i}=await t.members(e);return i||d.debug({conversation:e},"a roster bigger than one page; using the first page"),{people:s.flatMap(u=>{const l=u.name?.trim(),f=(u.email??u.userPrincipalName)?.trim();return l?[{id:u.id,name:l,...f?{email:f}:{}}]:[]}),members:s,complete:i}}catch(s){d.debug({conversation:e,err:s},"could not read a Teams roster for mentions"),n.expires=r()+_;return}}return{of(e){const n=m(e),s=o.get(n);if(s&&s.expires>r())return s.roster;for(const[c,u]of o)u.expires<=r()&&o.delete(c);const i={roster:Promise.resolve(void 0),expires:r()+C};return i.roster=a(n,i),o.set(n,i),i.roster},changed(e){o.delete(m(e))}}}function v(t,r){const o=r.trim().replace(/^@+/,"").toLowerCase();if(!o)return[];const a=t.filter(n=>n.name.toLowerCase()===o);if(a.length>0)return a;const e=p(o);return t.filter(n=>{const s=new Set(p(n.name.toLowerCase()));return e.length>0&&e.every(i=>s.has(i))?!0:n.email?.toLowerCase().split("@")[0]===o})}function p(t){return t.split(/[^\p{L}\p{N}]+/u).filter(Boolean)}export{v as findPeople,R as linkMentions,A as teamsRoster};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{BishopError as k}from"../errors.js";import{CHANNELS_ONLY as b,EntryError as w}from"../permissions/entry.js";import{findTeamChannel as v,OBJECT_ID as $}from"./destination.js";import{teamsSighting as E}from"./principal.js";import{baseConversation as I,destinationOfHandle as N}from"./thread.js";const s="teams";function m(a){const t=a.map(i=>i?.trim().toLowerCase()).filter(i=>!!i);return[...new Set(t)]}function C(a,t,i,n){const r=m([i?.userPrincipalName,i?.email,n]);return{interface:s,...a?{principalId:a}:{},groups:[],addresses:r,names:m([t,i?.aadObjectId,...r])}}function c(a){return I(a)}function S(a){const t=N(a);return{locations:t.scope==="channel"?[c(t.conversation)]:[]}}const u="Name a person in Teams by their user principal name, like dana@example.com, or by their Entra object ID in brackets, like <3f2c1d4e-\u2026>.";function h(a,t,i){const n=t?.userPrincipalName??t?.name??a;return{kind:"principal",interface:s,label:n,sighting:{...E({id:a,...t?.name?{name:t.name}:{},bot:!1},t,i.tenantId),kind:"unknown"}}}async function D(a,t,i){const{value:n,kind:r}=t,o=e=>{throw new w(`${t.text}: ${e}`)};r==="group"&&o("Teams has no user groups Bishop can see. Name a person, everyone at a domain with *@example.com, or a channel with #name.");const f=e=>[...a.members()].find(d=>m([d.aadObjectId,d.userPrincipalName,d.email]).includes(e));if(n.form==="domain")return r&&o(`*@${n.domain} is everyone at a domain, so it takes no ${r}: before it.`),{kind:"group",interface:s,label:`*@${n.domain}`,group:"domain",externalId:n.domain};const l=r==="channel"||"sigil"in n&&n.sigil==="#";if(n.form==="email"){l&&o(u);const e=f(n.email);return e?.aadObjectId?h(e.aadObjectId.toLowerCase(),e,a):{kind:"pending",interface:s,label:n.email,target:"principal",match:n.email}}if(n.form==="id"){if(n.id.startsWith("19:")){r==="user"&&o(`${n.id} is a conversation, not a person.`),/@thread\.v2$/i.test(c(n.id))&&o(b);const e=c(n.id);return p(e,`#<${e}>`)}if($.test(n.id)&&!l){const e=n.id.toLowerCase();return h(e,f(e),a)}return o("Bishop reads an ID in brackets as an Entra object ID for a person, or a conversation ID starting 19: for a channel or chat.")}if(!l)return o(`Bishop can't tell who "${n.name}" is. ${u}`);if(n.name.includes("/"))return o("Bishop can't look up a team by name yet. Write #channel from a channel in that team, or the channel by conversation ID, like #<19:\u2026@thread.tacv2>.");const g=i?.interface===s?i.handle:void 0;try{const e=await v(a.api,n.name,g);return p(c(e.channel.id),`#${e.channel.name}`,e.channel.name)}catch(e){throw e instanceof k&&o(e.message),e}}function p(a,t,i){return{kind:"location",interface:s,label:t,externalId:a,locationKind:"channel",...i?{name:i}:{}}}export{S as handleReach,D as resolveTeamsSubject,c as teamsLocation,C as teamsMembership};
|