@agentdeploymentco/bishop 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +128 -9
  2. package/dist/cli.js +17 -14
  3. package/dist/config.js +4 -4
  4. package/dist/env.js +4 -4
  5. package/dist/gmail/api.js +1 -1
  6. package/dist/gmail/etiquette.js +1 -0
  7. package/dist/gmail/fake.js +6 -4
  8. package/dist/gmail/history.js +1 -1
  9. package/dist/gmail/identity.js +1 -0
  10. package/dist/gmail/interface.js +2 -2
  11. package/dist/gmail/labels.js +1 -1
  12. package/dist/gmail/message.js +10 -12
  13. package/dist/gmail/presence.js +3 -3
  14. package/dist/gmail/route.js +1 -1
  15. package/dist/harness/claude.js +5 -5
  16. package/dist/harness/codex.js +4 -4
  17. package/dist/harness/principal.js +9 -8
  18. package/dist/interface/format.js +4 -0
  19. package/dist/interface/phrases.js +1 -0
  20. package/dist/interface/verbosity.js +1 -0
  21. package/dist/log.js +1 -1
  22. package/dist/outgoing.js +2 -0
  23. package/dist/schedule/presence.js +3 -3
  24. package/dist/schedule/runner.js +3 -3
  25. package/dist/slack/commands/run.js +3 -1
  26. package/dist/slack/destination.js +1 -1
  27. package/dist/slack/format.js +1 -4
  28. package/dist/slack/interface.js +2 -2
  29. package/dist/slack/manifest.js +1 -1
  30. package/dist/slack/presence.js +3 -3
  31. package/dist/slack/tasks.js +1 -1
  32. package/dist/slack/upload.js +1 -0
  33. package/dist/slack/verbosity.js +1 -1
  34. package/dist/teams/api.js +1 -0
  35. package/dist/teams/authorize.js +1 -0
  36. package/dist/teams/create.js +1 -0
  37. package/dist/teams/entra.js +3 -0
  38. package/dist/teams/fake.js +1 -0
  39. package/dist/teams/files.js +1 -0
  40. package/dist/teams/graph.js +1 -0
  41. package/dist/teams/interface.js +4 -0
  42. package/dist/teams/logger.js +1 -0
  43. package/dist/teams/presence.js +7 -0
  44. package/dist/teams/progress.js +1 -0
  45. package/dist/teams/provision.js +10 -0
  46. package/dist/teams/route.js +1 -0
  47. package/dist/teams/server.js +1 -0
  48. package/dist/teams/setup.js +190 -0
  49. package/dist/teams/thread.js +1 -0
  50. package/dist/teams/verify.js +2 -0
  51. package/dist/thread-model.js +1 -0
  52. package/dist/tools/files.js +2 -2
  53. package/dist/tools/server.js +1 -1
  54. package/dist/turn.js +1 -1
  55. package/package.json +8 -1
  56. package/dist/slack/phrases.js +0 -1
  57. /package/dist/{slack → interface}/etiquette.js +0 -0
  58. /package/dist/{slack → interface}/status.js +0 -0
@@ -0,0 +1,4 @@
1
+ import{DEFAULT_VERBOSITY as U}from"../config.js";import{BishopError as Y}from"../errors.js";import{etiquetteNote as $,threadParticipants as z}from"../interface/etiquette.js";import{splitMessage as G}from"../interface/format.js";import{showsProgress as R,showsTasks as H}from"../interface/verbosity.js";import{log as s}from"../log.js";import{describeTeamsFile as L,parseTeamsFile as W,teamsAttachment as N,teamsFilePayload as q}from"./files.js";import{teamsPresence as Q}from"./presence.js";import{addressesAgent as m,routeActivity as V}from"./route.js";import{baseConversation as X,conversationOf as O,sameConversation as J,threadKeyOf as Z}from"./thread.js";function tt(e){return[...nt(e),...et].join(`
2
+ `)}function nt(e){return R(e)?["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.","",H(e)?"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 et=["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.","","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."],ot="You are not on this agent\u2019s allow list, so it can\u2019t answer you.",A="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.",at=A+" If you attached a file, nothing about it reached me, so send it in a direct chat.",it=2e4;function pt(e){const h=new Set,w=new Map,p=z(),g=e.verbosity??U,S=tt(g);let u,v=!1;function I(){return{name:"teams",guidance:S,...u?{self:u}:{}}}async function _(t,n){const o=n.from.aadObjectId;if(!o)return;const i=w.get(o);if(i)return i;const a=X(t);try{const r=await e.api.member(a,n.from.id);return r&&w.set(o,r),r}catch(r){s.warn({err:r,conversation:a},"could not read the Teams roster");return}}async function d(t,n){let o;for(const i of G(n,it)){const a=await e.api.send(t,i);o=a?{id:a.id,text:i}:void 0}return o}function T(t,n){return[t,n?.userPrincipalName,n?.email].filter(o=>!!o).map(o=>o.trim().toLowerCase())}function x(t,n){const o=q(n);if(!o)return;const i=L(n);return e.attachments.remember(t,"teams",{id:i.id,name:i.name,payload:o})}async function B(t,n){return n.files.length===0?[]:Promise.all(n.files.map(async o=>{const i=x(t.id,o),a=await e.files.save(t.dirKey,N(o,e.api));return i?{...a,ref:i}:a}))}function F(t,n){return{id:t.from.aadObjectId??t.from.id,...t.from.name?{displayName:t.from.name}:{},...n?.name?{realName:n.name}:{},...n?.email?{email:n.email}:{}}}function j(t,n,o,i){const a=O(n),r=$({participants:p.count(t.threadKey),mentioned:m(n)});return{thread:t,isNewThread:i,origin:I(),...r?{note:r}:{},async messages(){const c=await B(t,n);return[{principal:o,text:n.text,...c.length>0?{files:c}:{}}]},presence:()=>Q({send:c=>d(a,c),post:c=>e.api.send(a,c),update:(c,y)=>e.api.update(a,c,y),threadKey:t.threadKey,verbosity:()=>g,...r?{mayDecline:!0}:{}}),async notify(c){await d(a,c)},async destination(){return{interface:"teams",handle:a,label:rt(n)}}}}async function K(t){if(v)return;if(await e.events.seen(`teams:${t.id}`)){s.debug({activity:t.id},"already answered this Teams activity");return}!u&&t.recipientName&&(u={address:`@${t.recipientName}`},s.info({address:u.address},"the agent is known by this name in Teams"));const n=Z(t),o=await e.threads.has(n),i=V(t,{threadKnown:o});if(i.action==="ignore"){s.debug({activity:t.id,thread:n,reason:i.reason},"leaving a Teams message alone");return}const a=t.from.aadObjectId;if(!a){s.warn({activity:t.id},"refusing a Teams message with no Entra object ID");return}p.saw(n,a,Date.now());const r=O(t),c=e.allow.open?void 0:await _(r,t);if(!e.allow.open&&!T(a,c).some(l=>e.allow.allows(l))){s.warn({activity:t.id,who:a,conversation:r},"refusing an unauthorized Teams message"),m(t)&&await d(r,ot).catch(l=>{s.debug({err:l},"could not tell somebody they are not on the allow list")});return}const y=new Set(t.files.map(l=>l.contentUrl)),k=(await e.api.sharedFiles(t)).filter(l=>!y.has(l.contentUrl)),f=k.length>0?{...t,files:[...t.files,...k]}:t;if(!f.text.trim()&&f.files.length===0){if(s.info({activity:t.id},"a Teams message had nothing to act on"),m(t)){const l=t.conversationType==="personal"?A:at;await d(r,l).catch(C=>{s.debug({err:C},"could not answer a message with nothing in it")})}return}const P=await e.threads.remember(n),D=F(f,c);s.info({thread:n,who:a,newThread:!o},"running a turn from Teams");const E=e.run(j(P,f,D,!o)).catch(l=>{s.error({thread:n,err:l},"a turn from Teams failed")}).finally(()=>{h.delete(E)});h.add(E)}async function b(){for(;h.size>0;)await Promise.allSettled([...h])}async function M(t){const n=(t.files??[]).map(o=>o.name).join(", ");return n&&s.warn({handle:t.handle,files:n},"a report carried files, which Teams cannot send"),await d(t.handle,n?`${t.text}
3
+
4
+ _Could not attach ${n}: Bishop cannot send files in Teams._`:t.text),{}}return{name:"teams",handle:K,settle:b,deliver:M,allows(t){return e.allow.open?!0:T(t,w.get(t)).some(n=>e.allow.allows(n))},sameConversation:J,async resolveDestination(){throw new Y("Bishop cannot yet name a Teams channel or chat from what you typed. Ask for a report in the conversation you want it in, which names itself.")},attachment:t=>{const n=W(t);return n?N(n,e.api):void 0},async start(){await e.listener.start(),s.info({allow:e.allow.open?"anyone in the tenant":"a list"},"listening for Teams activities")},async stop(){v=!0,await e.listener.stop(),h.size>0&&(s.info({turns:h.size},"waiting for Teams turns still running"),await b())}}}function rt(e){return e.conversationType==="personal"?`a chat with ${e.from.name??"someone"}`:e.conversationType==="groupChat"?"a Teams group chat":"a Teams channel thread"}export{pt as createTeamsInterface,tt as teamsGuidance};
@@ -0,0 +1 @@
1
+ import{log as c}from"../log.js";function i(o,e,n){const r=n.find(t=>t instanceof Error),f=n.filter(t=>!(t instanceof Error)).map(t=>typeof t=="string"?t:JSON.stringify(t)).join(" ");o[e]({...r?{err:r}:{}},f||"teams sdk")}function d(o="teams",e=c){const n=e.child({sdk:o});return{debug:(...r)=>i(n,"debug",r),info:(...r)=>i(n,"info",r),warn:(...r)=>i(n,"warn",r),error:(...r)=>i(n,"error",r),trace:(...r)=>i(n,"debug",r),log:(r,...f)=>i(n,r==="trace"?"debug":s(r),f),child:r=>d(`${o}.${r}`,e)}}function s(o){return o==="debug"||o==="info"||o==="warn"||o==="error"?o:"info"}export{d as teamsLogger};
@@ -0,0 +1,7 @@
1
+ import{DEFAULT_VERBOSITY as k}from"../config.js";import{saysNoOutput as f}from"../harness/principal.js";import{summaryPhrase as D,toolPhrase as P,turnTally as _}from"../interface/phrases.js";import{showsCost as A,showsProgress as B,showsTasks as d}from"../interface/verbosity.js";import{log as n}from"../log.js";import{teamsTask as I}from"./progress.js";const N="The agent finished without saying anything. Nothing went wrong that it reported, but there is no answer to send.";function F(e){const m=()=>e.verbosity?.()??k,K=Date.now();let a;const y=[];let c=0,i="",o,w="",g=!1,s,T=!1;async function l(){const t=a;t&&(a=void 0,await t.close())}async function p(t){await l();try{const r=await e.send(t);c+=1,i=t,o=r}catch(r){i="",o=void 0,n.debug({thread:e.threadKey,err:r},"could not post to Teams while working")}}return{async handle(t){const r=m();switch(d(r)||await l(),t.type){case"text":{if(f(t.text)||!t.text.trim()||(y.push(t.text),!B(r)))return;await p(t.text);return}case"tool":if(!d(r))return;a||(a=I({send:e.post,update:e.update,threadKey:e.threadKey},e.taskIntervalMs),i="",o=void 0),a.note(P(t));return;case"tool_summary":if(!d(r))return;a?.retitle(D(t.summary));return;case"done":g=!0,w=f(t.text)?"":t.text,T=!!e.mayDecline&&f(t.text);return;case"error":s=t.message;return;default:return}},async finish(){if(await l(),T&&!s){n.info({thread:e.threadKey},"the agent stayed out of a Teams conversation");return}const t=w.trim()||(c===0?y.join(`
2
+
3
+ `).trim():""),r=b(t),h=A(m())?`_${_(Date.now()-K,g||!!s)}_`:"";if(!r&&h&&o)try{await e.update(o.id,`${o.text}
4
+
5
+ ${h}`);return}catch(u){n.debug({thread:e.threadKey,err:u},"could not close a Teams turn in place")}const x=[r,h].filter(Boolean).join(`
6
+
7
+ `);if(x)try{await e.send(x),r&&n.info({thread:e.threadKey,chars:r.length},"answered in Teams")}catch(u){r?n.error({thread:e.threadKey,err:u},"could not post the answer to Teams"):n.debug({thread:e.threadKey,err:u},"could not say what a Teams turn cost")}}};function b(t){return s?`Something went wrong: ${s}`:t?t===i.trim()?"":t:c===0?N:""}}export{F as teamsPresence};
@@ -0,0 +1 @@
1
+ import{toolTally as u}from"../interface/phrases.js";import{statusLine as d}from"../interface/status.js";import{log as l}from"../log.js";const m=2e3,f="\u23F3";function w(e,c=m){let a,o=!1,n=0;const s=d(async t=>{if(o)return;const r=`${f} _${t}_`;if(a){await e.update(a,r);return}const i=await e.send(r);if(i){a=i.id;return}o=!0,l.debug({thread:e.threadKey},"Teams did not say what it made of the progress message")},c);return{note(t){n+=1,s.set(t)},retitle(t){s.set(t)},async close(){if(await s.close(),!a&&!o)return;const t=`_${u(n)}_`;try{if(a){await e.update(a,t);return}await e.send(t)}catch(r){l.debug({thread:e.threadKey,err:r},"could not close a Teams progress message")}}}}export{w as teamsTask};
@@ -0,0 +1,10 @@
1
+ import{spawn as g}from"node:child_process";import{BishopError as y}from"../errors.js";import{exec as c}from"../exec.js";import{log as i}from"../log.js";class o extends y{constructor(e){super(e,"TeamsCliError")}}const l="teams",u="npm install -g --allow-scripts=@azure/msal-node-extensions,keytar @microsoft/teams.cli",T=["Bishop needs the Teams Developer CLI to create the app, and it is not installed.","",` ${u}`,"","Or see https://microsoft.github.io/teams-sdk/"].join(`
2
+ `),k=["This usually means the CLI cannot store a login. It keeps its token in a","native module that npm refuses to build by default, and falls back to","holding it in memory, so every command starts logged out. Reinstall it with:","",` ${u}`].join(`
3
+ `);function f(){return{...process.env,TEAMS_NO_INTERACTIVE:"1"}}function I(n){const e=n.trim();if(!e)return;try{return JSON.parse(e)}catch{}const t=e.indexOf("{"),a=e.lastIndexOf("}");if(!(t<0||a<=t))try{return JSON.parse(e.slice(t,a+1))}catch{return}}function w(n){if(typeof n!="object"||n===null)return;const e=n;if(e.ok!==!1||!e.error)return;const t=typeof e.error.message=="string"?e.error.message:"unknown error",a=typeof e.error.suggestion=="string"?`
4
+ ${e.error.suggestion}`:"";return`${t}${a}`}function C(n){return n.replace(/("CLIENT_SECRET"\s*:\s*")[^"]*"/g,'$1<redacted>"')}async function r(n){const e=await c(l,["--disable-auto-update",...n,"--json"],{env:f()});if(e.code===null)throw new o(T);const t=I(e.stdout),a=w(t);if(a)throw new o(a);if(e.code!==0||t===void 0){const s=C(e.output);i.debug({args:n,code:e.code,output:s},"the teams cli failed");const p=s.trim().split(`
5
+ `).slice(-4).join(`
6
+ `);throw new o(`\`teams ${n.join(" ")}\` failed.${p?`
7
+ ${p}`:""}`.trim())}return t}async function N(){const n=await c(l,["--version"],{env:f()});if(n.code!==null)return n.output.trim().split(`
8
+ `)[0]}async function _(){const n=await r(["status"]),e=n.tdp?.sideloading,t=e?.tenant,a=e?.user,s=typeof t=="boolean"||typeof a=="boolean";return{loggedIn:n.loggedIn===!0,...n.username?{username:n.username}:{},...n.tenantId?{tenantId:n.tenantId}:{},...s?{sideloading:{...typeof t=="boolean"?{tenant:t}:{},...typeof a=="boolean"?{user:a}:{}}}:{}}}function A(n=process.env){return!!(n.SSH_CONNECTION||n.SSH_CLIENT)}async function b(){return new Promise(n=>{const e=g(l,["login"],{stdio:"inherit",env:process.env});e.on("error",()=>n(!1)),e.on("exit",t=>n(t===0))})}async function $(n){const e=["app","create","--teams-managed","--name",n.name];n.endpoint&&e.push("--endpoint",n.endpoint);const t=await r(e),a=t.credentials;if(!t.teamsAppId||!a?.CLIENT_ID||!a.TENANT_ID)throw new o("The Teams CLI created an app but reported no credentials for it.");if(!a.CLIENT_SECRET)throw new o(`The Teams CLI created app ${t.teamsAppId} without a client secret.
9
+ Create one with \`teams app auth secret create ${t.teamsAppId}\`, then run
10
+ \`bishop teams setup --manual\`.`);return{teamsAppId:t.teamsAppId,clientId:a.CLIENT_ID,clientSecret:a.CLIENT_SECRET,tenantId:a.TENANT_ID,...t.endpoint?{endpoint:t.endpoint}:{},...t.installLink?{installLink:t.installLink}:{},...t.portalLink?{portalLink:t.portalLink}:{}}}async function v(n){const e=await r(["app","get",n]);return{teamsAppId:e.teamsAppId??n,...e.appId?{clientId:e.appId}:{},...e.name?{name:e.name}:{},...e.endpoint?{endpoint:e.endpoint}:{},...e.installLink?{installLink:e.installLink}:{},...e.portalLink?{portalLink:e.portalLink}:{}}}async function O(n,e){return{needsReinstall:(await r(["app","update",n,"--endpoint",e])).needsReinstall===!0}}const D=["ChannelMessage.Read.Group","ChatMessage.Read.Chat"];async function M(n){const e=await r(["app","rsc","list",n]);if(!Array.isArray(e))throw new o(`\`teams app rsc list ${n}\` did not report a list.`);const t=e.map(a=>a?.name).filter(a=>typeof a=="string");if(e.length>0&&t.length===0)throw new o(`\`teams app rsc list ${n}\` reported no permission names.`);return t}async function P(n,e){try{return{applied:!0,needsReinstall:(await r(["app","rsc","add",n,e,"--type","Application"])).needsReinstall===!0}}catch(t){return i.warn({err:t,teamsAppId:n,permission:e},"could not add an RSC permission"),{applied:!1,needsReinstall:!1,reason:t instanceof Error?t.message:"the update failed"}}}const d="bots[0].supportsFiles";function E(n){const e=n.filter(t=>t.path===d);return e.length===0||e.every(t=>t.oldValue===!0)}async function j(n,e={}){try{const t=await r(["app","manifest","update",n,"--set-json",`${d}=true`,...e.check?["--dry-run"]:["--yes"]]),a=Array.isArray(t.changes)?t.changes:[],s=!E(a);return!e.check&&t.dryRun===!0?(i.warn({teamsAppId:n},"the teams cli previewed the manifest update instead of applying it"),{applied:!1,changed:!1,needsReinstall:!1,reason:"the Teams CLI previewed the change instead of uploading it"}):(t.unpreservedChanges??[]).some(h=>h.path===d)?(i.warn({teamsAppId:n},"the manifest did not keep the file support field"),{applied:!1,changed:!1,needsReinstall:!1,reason:"the manifest did not keep the change"}):{applied:!0,changed:s,needsReinstall:s&&(t.needsReinstall===!0||t.versionBumped===!0)}}catch(t){return i.warn({err:t,teamsAppId:n},"could not turn on Teams file support"),{applied:!1,changed:!1,needsReinstall:!1,reason:t instanceof Error?t.message:"the update failed"}}}const m=80;async function B(n,e){if(e.length>m)return{applied:!1,reason:`a description has to be ${m} characters or fewer, and this one is ${e.length}`};try{return await r(["app","update",n,"--short-description",e]),{applied:!0}}catch(t){return i.warn({err:t,teamsAppId:n},"could not set the app description"),{applied:!1,reason:t instanceof Error?t.message:"the update failed"}}}export{T as INSTALL_TEAMS_CLI,u as INSTALL_TEAMS_CLI_COMMAND,k as LOGIN_DID_NOT_PERSIST,m as MAX_DESCRIPTION,D as RSC_PERMISSIONS,o as TeamsCliError,P as addRscPermission,$ as createTeamsApp,B as describeTeamsApp,M as getRscPermissions,v as getTeamsApp,I as parseCliJson,C as redactSecrets,O as setTeamsEndpoint,j as setTeamsFiles,N as teamsCliVersion,b as teamsLogin,A as teamsLoginWouldUseDeviceCode,_ as teamsStatus};
@@ -0,0 +1 @@
1
+ const t="personal";function e(n){return n.conversationType===t||n.mentioned}function o(n){return!!n.recipientId&&n.from.id===n.recipientId}function i(n,r){return o(n)?{action:"ignore",reason:"from self"}:e(n)?{action:"run"}:r.threadKnown?{action:"run"}:{action:"ignore",reason:"nobody addressed the agent and no turn has run here"}}export{e as addressesAgent,o as isSelf,i as routeActivity};
@@ -0,0 +1 @@
1
+ import{createServer as E}from"node:http";import{createServer as T}from"node:https";import{BishopError as g}from"../errors.js";import{log as i}from"../log.js";const S=1024*1024,b=1e4,_=3e4;function B(n){try{return new URL(n??"/","http://localhost").pathname}catch{return}}async function O(n){let d=0;const c=[];for await(const s of n){if(d+=s.length,d>S)throw new Error(`body over ${S} bytes`);c.push(s)}return Buffer.concat(c).toString("utf8")}function l(n,d,c){if(c===void 0){n.writeHead(d),n.end();return}const s=JSON.stringify(c);n.writeHead(d,{"content-type":"application/json","content-length":Buffer.byteLength(s)}),n.end(s)}function N(n){const d=new Map,c=new Set;let s,m;const p=async(t,e)=>{const a=B(t.url),f=a!==void 0&&t.method==="POST"?d.get(a):void 0;if(!f){l(e,404);return}let u;try{const r=await O(t);u=r.length>0?JSON.parse(r):void 0}catch(r){i.debug({err:r,path:a},"rejected a malformed request body"),l(e,400);return}try{const r=await f({body:u,headers:t.headers});l(e,r.status,r.body)}catch(r){i.error({err:r,path:a},"the Teams endpoint failed to handle a request"),l(e,500)}},w=(t,e)=>{p(t,e).catch(a=>{i.error({err:a},"the Teams endpoint could not answer a request"),e.headersSent?e.destroy():l(e,500)})},o=n.tls?T({cert:n.tls.cert,key:n.tls.key},w):E(w);o.headersTimeout=b,o.requestTimeout=_,o.on("connection",t=>{c.add(t),t.on("close",()=>c.delete(t))});const y=n.host??"127.0.0.1";return{registerRoute(t,e,a){d.set(e,a),i.debug({method:t,path:e},"registered a route on the Teams endpoint")},start(t=n.port){const e=Number(t);return m=new Promise((a,f)=>{const u=r=>{const h=`${y}:${e}`;f(r.code==="EADDRINUSE"?new g(`Something is already listening on ${h}.`):r.code==="EACCES"?new g(`Not allowed to listen on ${h}.`):r)};o.once("error",u),o.listen(e,y,()=>{o.off("error",u),o.on("error",h=>{i.error({err:h},"the Teams endpoint failed")});const r=o.address();s=typeof r=="object"&&r?r.port:e,i.info({host:y,port:s,tls:!!n.tls},"the Teams endpoint is listening"),a()})}),m},async stop(){await m?.catch(()=>{}),await new Promise(t=>{if(!o.listening){t();return}o.close(()=>t());for(const e of c)e.destroy()})},get port(){return s??n.port}}}export{N as createListener};
@@ -0,0 +1,190 @@
1
+ import{loadConfig as y,writeConfig as F}from"../config.js";import{log as I}from"../log.js";import{ensureGitignore as he,resolveAppDetails as j,SetupError as m,withPrompt as G,writeEnv as de}from"../setup.js";import{AZ_LOGIN_COMMAND as z,azAccount as ce,FILES_READ_ALL as x,FILES_READ_ALL_ROLE as le,GRAPH_APP_ID as me,grantGraphFiles as ue,INSTALL_AZ_CLI as we}from"./entra.js";import{addRscPermission as fe,createTeamsApp as ge,describeTeamsApp as Te,getRscPermissions as Ie,getTeamsApp as Ae,INSTALL_TEAMS_CLI as U,INSTALL_TEAMS_CLI_COMMAND as _e,LOGIN_DID_NOT_PERSIST as Ee,RSC_PERMISSIONS as C,setTeamsEndpoint as Se,setTeamsFiles as N,teamsCliVersion as W,teamsLogin as be,teamsLoginWouldUseDeviceCode as $,teamsStatus as v}from"./provision.js";import{readGraphRoles as L,verifyTeamsCredentials as ye}from"./verify.js";const Y=["The Teams CLI cannot log in from this machine. With no local browser it falls","back to the device code flow, which Microsoft blocks by default in every","tenant."].join(`
2
+ `),K=[Y,"","So an app cannot be created over SSH. Two ways on from here:",""," Run `bishop teams setup` on a workstation and copy the three BISHOP_TEAMS_*"," lines it writes to .env over to this host.",""," Have somebody else create the app, then run `bishop teams setup --manual`"," here with what they send back. `bishop teams instructions` prints what to"," ask them for."].join(`
3
+ `),V=[Y,"","So the app has to be re-pointed from a machine that can log in:",""," bishop teams endpoint <url> --app-id <the app id>","","or by editing the bot endpoint in the Teams Developer Portal."].join(`
4
+ `);function Z(e){return new m($()?`${U}
5
+
6
+ ${e}`:U)}function R(e){return{...e.BISHOP_TEAMS_CLIENT_ID?.trim()?{clientId:e.BISHOP_TEAMS_CLIENT_ID.trim()}:{},...e.BISHOP_TEAMS_CLIENT_SECRET?.trim()?{clientSecret:e.BISHOP_TEAMS_CLIENT_SECRET.trim()}:{},...e.BISHOP_TEAMS_TENANT_ID?.trim()?{tenantId:e.BISHOP_TEAMS_TENANT_ID.trim()}:{}}}function O(e){const{clientId:n,clientSecret:t,tenantId:a}=R(e);if(n&&t&&a)return{clientId:n,clientSecret:t,tenantId:a}}function q(e,n){const t=e.teams?.app;if(t&&O(n))return{app:t}}async function J(e,n,t,a){let i;try{i=await de(e,{BISHOP_TEAMS_CLIENT_ID:a.clientId,BISHOP_TEAMS_CLIENT_SECRET:a.clientSecret,BISHOP_TEAMS_TENANT_ID:a.tenantId})}catch(r){throw new m(`The credentials could not be written to .env: ${r instanceof Error?r.message:String(r)}
7
+
8
+ The app was created, so save these somewhere before this scrolls away:
9
+
10
+ BISHOP_TEAMS_CLIENT_ID=${a.clientId}
11
+ BISHOP_TEAMS_CLIENT_SECRET=${a.clientSecret}
12
+ BISHOP_TEAMS_TENANT_ID=${a.tenantId}
13
+
14
+ Then run \`bishop teams setup --manual\` once .env is writable.`)}await F({...n,teams:{...n.teams,app:t}},e);const s=await he(e,[".env","bishop.db*"]);return` .bishop/config.json app configuration
15
+ ${i} credentials
16
+ `+(s.length?` .gitignore added ${s.join(", ")}
17
+ `:"")}async function k(e){if(e)try{return await Ae(e)}catch(n){I.debug({err:n,teamsAppId:e},"could not read the Teams app back");return}}function Q(e,n){return n.map(t=>` teams app rsc add ${e} ${t} --type Application
18
+ `).join("")}const S=`Without these the agent only hears a message that @mentions it, so a reply to
19
+ its own answer never reaches it.
20
+ `;async function Ce(e){const n=[],t=[];for(const a of C){const i=await fe(e,a);i.applied||(n.push(a),t.push(` ${a}: ${i.reason}
21
+ `))}return n.length===0?"":`
22
+ These permissions could not be added to the app:
23
+ `+t.join("")+`
24
+ ${S}Add them with:
25
+
26
+ `+Q(e,n)}async function X(e){if(e)try{const n=new Set(await Ie(e));return C.filter(t=>!n.has(t))}catch(n){I.debug({err:n,teamsAppId:e},"could not read the app\u2019s RSC permissions");return}}const Ne=`Then remove the app from every team and chat it is in, and add it again.
27
+ Teams asks for these permissions only when an app is installed. Updating an
28
+ app that is already installed does not ask, and it will keep hearing nothing
29
+ but mentions until it has been removed and installed again.
30
+ `,M=`Without it Teams shows no attach button in a chat with the agent, so nobody
31
+ can send it a file. An image pasted into a message arrives either way, and a
32
+ file attached in a channel never does.
33
+ `;function b(e){return` teams app manifest update ${e} --set-json 'bots[0].supportsFiles=true' --yes
34
+ `}function $e(e,n){return`
35
+ File support could not be turned on for this app: ${n??"the update failed"}
36
+
37
+ ${M}Turn it on with:
38
+
39
+ `+b(e)}function ve(e){return`
40
+ Bishop could not check whether this app has file support: the Teams CLI is
41
+ not installed here, or is not logged in. Run this again where it is, or turn
42
+ it on with:
43
+
44
+ `+b(e)}const Le=`This moved the app\u2019s manifest version, so update the app where it is already
45
+ installed. Until that reaches a chat, it will go on showing no attach button.
46
+ `;function ee(e){return`
47
+ This app does not have file support.
48
+
49
+ ${M}Turn it on with:
50
+
51
+ `+b(e)+`
52
+ ${Le}`}function P(e,n=" "){const t=e??"<client id>",a=`${n} `;return`${n}az ad app permission add --id ${t} \\
53
+ ${a}--api ${me} \\
54
+ ${a}--api-permissions ${le}=Role
55
+ ${n}az ad app permission admin-consent --id ${t}
56
+ `}const Re=`Without it the agent is still told what was attached and says it could not
57
+ read it. A file in a direct chat needs none of this.
58
+ `;function A(e,n){return`
59
+ ${n}
60
+
61
+ ${P(e)}
62
+ ${Re}`}const B=`A file attached in a channel is read through Microsoft Graph, which needs one
63
+ grant in Entra.`;function Oe(e,n=" "){return`${n}az ad app permission admin-consent --id ${e}
64
+ `}const ke=`
65
+ The Azure CLI accepted the grant for Files.Read.All, and the app cannot
66
+ read a file attached in a channel yet: its own token does not carry the
67
+ permission. Entra can take minutes to apply a consent on a registration
68
+ made seconds earlier. Re-run \`bishop teams setup\` to see whether it took,
69
+ and if it still reports the grant missing, run the consent again:
70
+
71
+ `,Me=`
72
+ The Azure CLI accepted the grant for Files.Read.All, and Bishop could not
73
+ reach Entra to check that it took. Re-run \`bishop teams setup\` to find out.
74
+ `,ne=`
75
+ The app can read a file attached in a channel: Files.Read.All is granted.
76
+ `,Pe=`Consenting an application permission takes an administrator, which is the
77
+ usual reason. An app registration made moments ago can also be too new for
78
+ Entra to have it everywhere yet, so this is worth running once by hand
79
+ before asking anybody. Re-run \`bishop teams setup\` to see whether it took.`;async function Be(e,n=L){const t=await ce();if(!t.installed)return A(e.clientId,`${B} Bishop makes it with the Azure CLI,
80
+ which is not installed here. ${we}
81
+ Then run:`);if(!t.loggedIn)return A(e.clientId,`${B} Bishop makes it with the Azure CLI,
82
+ which is not logged in here. Run \`${z}\`, which is
83
+ what a tenant with no Azure subscription needs, and then:`);if(t.tenantId&&t.tenantId.toLowerCase()!==e.tenantId.toLowerCase())return A(e.clientId,`${B} The Azure CLI is signed in to tenant
84
+ ${t.tenantId}, and this app is in ${e.tenantId}, so
85
+ Bishop left it alone. Sign in to the app\u2019s tenant and run:`);const a=await ue(e.clientId);if(!a.applied)return A(e.clientId,`Bishop could not grant Files.Read.All: ${a.reason}
86
+
87
+ ${Pe}
88
+ An administrator makes the grant with:`);const i=await n(e);return i?.includes(x)?ne:i?ke+Oe(e.clientId):Me}function te(e,n){return n?n.includes(x)?ne:A(e,`The app cannot read a file attached in a channel: Files.Read.All is not
89
+ granted on its app registration. An administrator grants it with:`):`
90
+ Bishop could not check whether the app can read a file attached in a
91
+ channel. That needs Files.Read.All on the app registration, which an
92
+ administrator grants with:
93
+
94
+ `+P(e)}function ae(e,n){return`
95
+ The app is missing ${n.length===1?"a permission":"permissions"}:
96
+ `+n.map(t=>` ${t}
97
+ `).join("")+`
98
+ ${S}Add them with:
99
+
100
+ `+Q(e,n)+`
101
+ ${Ne}`}const De=`
102
+ ${S}Bishop could not check whether this app has the permissions for that: the
103
+ Teams CLI is not installed here, or is not logged in. Run this again where it
104
+ is, or see \`bishop teams instructions\` for what they are.
105
+ `;function He(e,n){return n?n.length>0?ae(e,n):"":`
106
+ ${S}Bishop cannot check this app, so confirm with whoever created it that it has
107
+ the permissions \`bishop teams instructions\` asks for.
108
+ `}function Fe(e,n){return!e||!n?.applied?`
109
+ ${M}Bishop cannot check this app, so confirm with whoever created it that file
110
+ support is on.
111
+ `:n.changed?ee(e):""}async function ie(e,n,t){const a=await k(e.app.id),i=a?.endpoint,s=e.app.id?a?i??"not set":"unknown, the Teams CLI could not read the app":"unknown, no Teams app ID is recorded here";if(n(`This agent is already set up in Teams as "${e.app.displayName??e.app.name}".
112
+ `+(e.app.id?` App ID ${e.app.id}
113
+ `:"")+` Endpoint ${s}
114
+ Its credentials are in .env and its configuration in .bishop/config.json.
115
+ `),a&&!i&&n(`
116
+ Teams has nowhere to deliver to until the app is pointed at Bishop.
117
+ Run \`bishop teams endpoint <url>\` with the URL that reaches this host.
118
+ `),e.app.id){const p=await X(e.app.id);p?p.length>0&&n(ae(e.app.id,p)):n(De)}if(e.app.id){const p=await N(e.app.id,{check:!0});p.applied?p.changed&&n(ee(e.app.id)):n(ve(e.app.id))}const r=O(process.env);n(te(r?.clientId,r&&await t(r))),n(`
119
+ To change where Teams delivers, run \`bishop teams endpoint <url>\`.
120
+ To set this up again, remove teams.app from .bishop/config.json and the
121
+ BISHOP_TEAMS_* lines from .env first.
122
+ `)}function je(e,n){if(!e)return;const{tenant:t,user:a}=e;t!==!1&&a!==!1||n(`
123
+ Note: custom apps cannot be installed in Teams from here.
124
+ `+(t===!1?` The tenant-wide setting is off. An administrator turns it on in the Teams
125
+ Admin Center, under Org-wide app settings, Custom apps.
126
+ `:"")+(a===!1?` Your own app setup policy blocks it. An administrator changes it in the
127
+ Teams Admin Center, under Users, Policies, App setup policy.
128
+ `:"")+`Setup will still create the app, but somebody will have to install it.
129
+ `)}function Ge(e,n){const t=e.teams?.app,a=R(n),i=Object.keys(a).length>0;if(t&&!O(n)){const{clientId:s,clientSecret:r,tenantId:p}=a,h=[s?void 0:"BISHOP_TEAMS_CLIENT_ID",r?void 0:"BISHOP_TEAMS_CLIENT_SECRET",p?void 0:"BISHOP_TEAMS_TENANT_ID"].filter(Boolean);throw new m(`An app is already recorded here, but its credentials are not.
130
+
131
+ App ${t.displayName??t.name}${t.id?` (${t.id})`:""}
132
+ Missing ${h.join(`
133
+ `)}
134
+
135
+ Creating a new app would leave that one orphaned in your tenant. Either:
136
+ finish this one with \`bishop teams setup --manual\`, giving it a client
137
+ secret from \`teams app auth secret create ${t.id??"<app id>"}\`, or
138
+ remove teams.app from .bishop/config.json to start over.`)}if(i&&!t)throw new m(`Teams credentials are already in the environment, but no app is recorded
139
+ here: ${Object.keys(a).length} of 3 are set.
140
+
141
+ Creating a new app would overwrite them, and a client secret cannot be
142
+ read back once it is lost.
143
+
144
+ Run \`bishop teams setup --manual\` to record the app those credentials
145
+ belong to, or remove the BISHOP_TEAMS_* lines from .env to start over.`)}async function Ve(e,n=L){const t=e.cwd??process.cwd(),a=e.prompt&&process.stdin.isTTY===!0,i=o=>process.stdout.write(o),s=await y(t),r=q(s,process.env);if(r){await ie(r,i,n);return}Ge(s,process.env);const p=await W();if(!p)throw Z(K);I.debug({teamsCli:p},"found the teams cli");let h=await v();if(!h.loggedIn){if($())throw new m(K);if(!a)throw new m("The Teams CLI is not logged in to Microsoft 365.\nRun `teams login`, then run this again.");i("The Teams CLI is not logged in to Microsoft 365. Starting `teams login`.\n\n");const o=await be();if(h=o?await v():h,!h.loggedIn)throw new m(`The Teams CLI is still not logged in, so the app cannot be created.
146
+ `+(o?`
147
+ \`teams login\` reported success, but the login did not survive it.
148
+ ${Ee}`:"Run `teams login` on its own to see what went wrong."));i(`
149
+ Logged in.
150
+ `)}je(h.sideloading,i),await G(a,async o=>{const d=await j(e,t,o),u=e.endpoint?.trim()||await o("Messaging endpoint URL (leave blank to set later)","");i(`
151
+ Creating the Teams app for "${d.displayName}"${h.username?` in ${h.username}'s tenant`:""}...
152
+ `);const c=await ge({name:d.displayName,...u?{endpoint:u}:{}}),f=d.description?await Te(c.teamsAppId,d.description):{applied:!1,reason:void 0};d.description&&!f.applied&&i(`
153
+ The description was not applied: ${f.reason}
154
+ `);const w=await Ce(c.teamsAppId);w&&i(w);const l=await N(c.teamsAppId);l.applied||i($e(c.teamsAppId,l.reason));const g={id:c.teamsAppId,name:d.name,displayName:d.displayName,...f.applied&&d.description?{description:d.description}:{}},T=await J(t,s,g,c),_=await Be(c,n);I.info({teamsAppId:c.teamsAppId,endpoint:u||void 0},"teams app created"),i(`
155
+ Done.
156
+ ${T}`+_+(c.installLink?`
157
+ Install it in Teams:
158
+ ${c.installLink}
159
+ `:"")+(u?"":`
160
+ The app has no messaging endpoint yet, so Teams has nowhere to deliver to.
161
+ Run \`bishop teams endpoint <url>\` with the URL that reaches this host.
162
+ `)+"\nRun `bishop` to start the agent.\n")})}async function Ze(e,n=ye,t=L){const a=e.cwd??process.cwd(),i=e.prompt&&process.stdin.isTTY===!0,s=o=>process.stdout.write(o),r=await y(a),p=r.teams?.app,h=q(r,process.env);if(h){const o=e.appId?.trim();if(o&&!h.app.id){await F({...r,teams:{...r.teams,app:{...h.app,id:o}}},a),s(`Recorded Teams app ID ${o} for "${h.app.displayName??h.app.name}".
163
+ `);return}await ie(h,s,t);return}await G(i,async o=>{const d=R(process.env),u=d.clientId||await o("Client ID",""),c=d.clientSecret||await o("Client secret",""),f=d.tenantId||await o("Tenant ID","");if(!u||!c||!f)throw new m(`All three credentials are needed: a client ID, a client secret, and a
164
+ tenant ID. Set BISHOP_TEAMS_CLIENT_ID, BISHOP_TEAMS_CLIENT_SECRET and
165
+ BISHOP_TEAMS_TENANT_ID, or run this in a terminal so they can be typed in.
166
+
167
+ Run \`bishop teams instructions\` for what to send whoever creates the app.`);const w={clientId:u,clientSecret:c,tenantId:f},l=e.appId?.trim()||p?.id||await o("Teams app ID (optional)","");s(`
168
+ Checking the credentials...
169
+ `);const g=await n(w);if(!g.ok)throw new m(`Microsoft rejected these credentials.
170
+ ${g.detail}
171
+
172
+ This is the same request Bishop makes on every turn, so the agent would
173
+ not have been able to answer anything.`);g.detail?s(`${g.detail} Saving them anyway.
174
+ `):s(`Accepted.
175
+ `);const T=await k(l||void 0),_=e.name??p?.name??T?.name,D=e.displayName??p?.displayName??T?.name,H=e.description??p?.description,E=await j({...e,..._?{name:_}:{},...D?{displayName:D}:{},...H?{description:H}:{}},a,o),se={...l?{id:l}:{},name:E.name,displayName:E.displayName,...E.description?{description:E.description}:{}},oe=await J(a,r,se,w),re=await X(l||void 0),pe=l?await N(l,{check:!0}):void 0;I.info({teamsAppId:l||void 0},"teams app adopted"),s(`
176
+ Done.
177
+ ${oe}`+(T?.endpoint?`
178
+ The app is pointed at ${T.endpoint}
179
+ `:`
180
+ Bishop cannot tell where this app is pointed, so confirm with whoever
181
+ created it that its messaging endpoint reaches this host. Bishop serves it
182
+ at /api/messages.
183
+ `)+He(l,re)+Fe(l,pe)+te(w.clientId,await t(w))+"\nRun `bishop` to start the agent.\n")})}async function qe(e,n={}){const t=n.cwd??process.cwd(),a=o=>process.stdout.write(o),i=await y(t),s=n.appId?.trim()||i.teams?.app?.id;if(!s)throw new m("No Teams app is recorded here, so there is nothing to point.\nRun `bishop teams setup` first, or pass --app-id.");if(!await W())throw Z(V);if($()&&!(await v()).loggedIn)throw new m(V);const p=(await k(s))?.endpoint;if(p===e){a(`App ${s} already points at ${e}. Nothing to do.
184
+ `);return}const{needsReinstall:h}=await Se(s,e);I.info({teamsAppId:s,before:p,endpoint:e,needsReinstall:h},"teams messaging endpoint updated"),a(`App ${s} now points at ${e}
185
+ `),h&&a(`
186
+ The app's manifest changed, which usually means its valid domains did.
187
+ Reinstall it in Teams before expecting it to receive anything.
188
+ `)}function Je(e){const n=e?.trim()||"https://<the URL that reaches this host>/api/messages";return["Bishop needs a Microsoft Teams app. To create one for it:","","1. Create a Teams app with a bot. A Teams-managed bot is enough and needs no"," Azure subscription:","",` ${_e}`," teams login"," teams app create --teams-managed --name <app name> --endpoint <url>",""," The install flags are not optional: without them the CLI cannot store a"," login and every command starts logged out.","","2. Point the bot at this messaging endpoint:","",` ${n}`,""," Teams POSTs every activity here, so it has to be reachable over HTTPS.","","3. Give the app these resource-specific consent permissions:","",...C.map(t=>` teams app rsc add <app id> ${t} --type Application`),""," Without them Teams only delivers a message that @mentions the agent, so a"," reply to its own answer never reaches it. Whoever installs the app in a team"," or a chat is who consents, and Teams only asks at install time. An app that"," is already installed has to be removed from every team and chat it is in and"," added again: updating it in place never asks, so it goes on hearing nothing"," but mentions.","","4. Turn on file support, so the agent can be sent a file at all:","",` ${b("<app id>").trim()}`,""," Without it Teams shows no attach button in a chat with the agent, so there"," is nothing for anyone to send. An image pasted into a message arrives either"," way. `--yes` is not optional: the CLI refuses the write without it unless"," somebody is there to answer a prompt.","","5. Let the agent read a file attached in a channel. Those are on SharePoint"," rather than on the bot channel, so Bishop reads them through Microsoft"," Graph, which needs one application permission on the app registration:","",` ${z}`,...P("<client id>"," ").trimEnd().split(`
189
+ `),""," That is Files.Read.All, and it is tenant-wide, which is why it takes an"," administrator. `--allow-no-subscriptions` is what a tenant with no Azure"," subscription needs, which is the ordinary case for a Teams-managed bot."," Skipping this costs only channel files: the agent is still told one was"," attached, and says it could not read it.","","6. Allow the app to be installed. Custom app installation has to be on for the"," tenant (Teams Admin Center, Org-wide app settings, Custom apps) and for"," whoever installs it (Users, Policies, App setup policy).","","7. Send back three values, which are credentials and should travel like any"," other secret:",""," the app registration\u2019s client ID"," a client secret for it"," the tenant ID","","Then run `bishop teams setup --manual` here and give it those three.",""].join(`
190
+ `)}export{Je as administratorInstructions,Be as applyChannelFileGrant,q as existingTeamsSetup,qe as repointTeamsEndpoint,Ve as setupTeams,Ze as setupTeamsManually};
@@ -0,0 +1 @@
1
+ const i=new Set(["personal","groupChat"]),c=/^[1-9]\d*$/;function a(n){const t=n.conversationId;return i.has(n.conversationType)||t.includes(";messageid=")?t:c.test(n.id)?`${t};messageid=${n.id}`:t}function f(n){return`teams:${a(n)}`}function s(n){return n.split(";")[0]??n}function h(n,t){return o(n)===o(t)}function o(n){const[t="",...e]=n.split(";"),r=e.find(d=>d.startsWith("messageid="));return r?`${t};${r}`:t}function l(n){if(n.conversationType==="personal")return;if(i.has(n.conversationType))return{kind:"chat",chatId:s(n.conversationId),messageId:n.id};if(!n.channel)return;const t=u(n);return{kind:"channel",teamId:n.channel.teamId,channelId:n.channel.channelId,messageId:n.id,...t?{replyToId:t}:{}}}function u(n){const t=n.conversationId.split(";").find(e=>e.startsWith("messageid="))?.slice(10);return t&&t!==n.id?t:void 0}export{s as baseConversation,a as conversationOf,l as graphAddressOf,h as sameConversation,f as threadKeyOf};
@@ -0,0 +1,2 @@
1
+ import{log as a}from"../log.js";const d="https://login.microsoftonline.com",u="https://api.botframework.com/.default",l="https://graph.microsoft.com/.default",f=1e4;async function y(n,r=fetch){const t=new URLSearchParams({grant_type:"client_credentials",client_id:n.clientId,client_secret:n.clientSecret,scope:u});let e;try{e=await r(`${d}/${encodeURIComponent(n.tenantId)}/oauth2/v2.0/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:t})}catch(s){return a.warn({err:s},"could not reach Entra to check the Teams credentials"),{ok:!0,detail:"Could not reach Microsoft to check the credentials."}}if(e.ok)return{ok:!0};if(e.status>=500||e.status===429)return a.warn({status:e.status},"Entra could not answer the Teams credential check"),{ok:!0,detail:`Microsoft could not answer the check (HTTP ${e.status}).`};const o=await p(e);return o?{ok:!1,detail:o}:(a.warn({status:e.status},"a Teams credential check was answered by something else"),{ok:!0,detail:`Something other than Microsoft answered the check (HTTP ${e.status}).`})}async function p(n){let r;try{const t=await n.json();typeof t.error_description=="string"?r=t.error_description:typeof t.error=="string"&&(r=t.error)}catch{}return r?.split(`
2
+ `)[0]?.trim()||void 0}async function w(n,r=fetch){const t=new URLSearchParams({grant_type:"client_credentials",client_id:n.clientId,client_secret:n.clientSecret,scope:l});let e;try{e=await r(`${d}/${encodeURIComponent(n.tenantId)}/oauth2/v2.0/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:t,signal:AbortSignal.timeout(f)})}catch(i){a.debug({err:i},"could not reach Entra to read the app\u2019s Graph permissions");return}if(!e.ok){a.debug({status:e.status},"Entra would not issue a Graph token for the app");return}let o;try{o=(await e.json()).access_token}catch{return}if(typeof o!="string")return;const s=h(o);if(!s)return;const c=s.roles;if(c===void 0)return[];if(Array.isArray(c))return c.filter(i=>typeof i=="string")}function h(n){const r=n.split(".")[1];if(r)try{const t=JSON.parse(Buffer.from(r,"base64url").toString("utf8"));return typeof t=="object"&&t!==null?t:void 0}catch{return}}export{w as readGraphRoles,y as verifyTeamsCredentials};
@@ -0,0 +1 @@
1
+ const f={model:"agent.model",effort:"agent.effort"},c=/^[\w./:@-]+$/;function d(o){return c.test(o)}const s=["model","effort"];function i(o){return{of(t){const e={};for(const n of s){const r=o.get(t,f[n]);r&&(e[n]=r)}return e},set(t,e){for(const n of s){const r=e[n];r!==void 0&&o.set(t,f[n],r)}},clear(t,e){o.clear(t,f[e])}}}export{s as MODEL_SETTINGS,d as isHarnessName,i as threadModel};
@@ -1,2 +1,2 @@
1
- import{z as a}from"zod";import{FETCH_FILE_TOOL as h,fileTag as f}from"../harness/principal.js";import{defineTool as s,ToolRefusal as o}from"./types.js";function c(i){return[s({name:h,description:["Downloads a file somebody shared in this conversation and gives you the path to it.","","Takes the ref from an <attachment> tag. Ask for a file when you need to open it, rather","than for everything in the conversation. Asking for one already downloaded hands back","the same path without fetching it again, so ask rather than reusing a path from earlier","in the conversation. It fails, with the reason, when there is no file to be had."].join(`
2
- `),input:{ref:a.string().trim().min(1).describe("The ref attribute of the file tag naming the file you want")},async run(t,n){const e=await i.fetch(n.thread,t.ref);if(!e)throw new o(`No file with the ref ${t.ref} was shared in this conversation. Refs come from the file tags Bishop writes, and one only works in the conversation it was written in.`);if(!e.path){const r=e.unavailable??"the download produced no file";throw new o(`Bishop could not fetch the file with ref ${t.ref}: ${r}.`+(e.url?` The original is at ${e.url}`:""))}return f({...e,ref:t.ref})}})]}export{c as fileTools};
1
+ import{z as i}from"zod";import{FETCH_FILE_TOOL as s,fileTag as f}from"../harness/principal.js";import{SHARE_FILE_DESCRIPTION as l,SHARE_FILE_TOOL as c,ShareRefused as m}from"../outgoing.js";import{defineTool as a,ToolRefusal as r}from"./types.js";function y(t){return[d(t),w()]}function d(t){return a({name:s,description:["Downloads a file somebody shared in this conversation and gives you the path to it.","","Takes the ref from an <attachment> tag. Ask for a file when you need to open it, rather","than for everything in the conversation. Asking for one already downloaded hands back","the same path without fetching it again, so ask rather than reusing a path from earlier","in the conversation. It fails, with the reason, when there is no file to be had."].join(`
2
+ `),input:{ref:i.string().trim().min(1).describe("The ref attribute of the file tag naming the file you want")},async run(n,o){const e=await t.fetch(o.thread,n.ref);if(!e)throw new r(`No file with the ref ${n.ref} was shared in this conversation. Refs come from the file tags Bishop writes, and one only works in the conversation it was written in.`);if(!e.path){const h=e.unavailable??"the download produced no file";throw new r(`Bishop could not fetch the file with ref ${n.ref}: ${h}.`+(e.url?` The original is at ${e.url}`:""))}return f({...e,ref:n.ref})}})}function w(){return a({name:c,description:l,input:{path:i.string().trim().min(1).describe("Absolute path to the file to send"),name:i.string().trim().min(1).optional().describe("What the recipient sees it called. Defaults to the filename on disk.")},async run(t,n){const o=n.share;if(!o)throw new r("There is nowhere to put a file in this conversation, so nothing was sent.");try{const e=await o({path:t.path,...t.name?{name:t.name}:{}});return`Registered ${e.name}. Write <attachment ref="${e.ref}" /> in your reply where the file should appear.`}catch(e){throw e instanceof m?new r(e.message):e}}})}export{y as fileTools,w as shareTool};
@@ -1 +1 @@
1
- import{randomBytes as v,randomUUID as S}from"node:crypto";import{createServer as E}from"node:http";import{McpServer as T}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as b}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{isInitializeRequest as B}from"@modelcontextprotocol/sdk/types.js";import{log as p}from"../log.js";import{ToolRefusal as g}from"./types.js";const O="bishop",y="/mcp",_="BISHOP_TOOL_TOKEN",x=1048576;function k(i){const r=i.headers.authorization;return r&&/^Bearer\s+(.+)$/i.exec(r.trim())?.[1]?.trim()||void 0}function u(i,r,s){i.writeHead(r,{"content-type":"application/json"}),i.end(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32001,message:s}}))}async function R(i){const r=[];let s=0;for await(const n of i){if(s+=n.length,s>x)throw new Error("request body is too large");r.push(n)}if(r.length!==0)return JSON.parse(Buffer.concat(r).toString("utf8"))}const A="Bishop's tools answer to a person, and this message came from another bot. Ask someone in the conversation to do it.";function N(i,r){const s=new T({name:O,version:"1"});for(const n of i)s.registerTool(n.name,{description:n.description,inputSchema:n.input},async m=>{try{if(r.principal.isBot)throw new g(A);return{content:[{type:"text",text:await n.run(m,r)}]}}catch(a){const d=a instanceof Error?a.message:String(a);return a instanceof g?p.info({tool:n.name,thread:r.thread.threadKey,reason:d},"a tool refused"):p.error({tool:n.name,thread:r.thread.threadKey,err:a},"a tool failed"),{content:[{type:"text",text:d}],isError:!0}}});return s}async function L(i){const r=i.host??"127.0.0.1",s=new Map,n=new Map;async function m(e,t){const o=new b({sessionIdGenerator:()=>S(),onsessioninitialized:c=>{if(s.get(e)!==t){o.close().catch(()=>{});return}n.set(c,{token:e,transport:o}),t.sessions.add(c)}});return o.onclose=()=>{const c=o.sessionId;c&&(n.delete(c),t.sessions.delete(c))},await N(i.tools,t.context).connect(o),o}const a=E((e,t)=>{(async()=>{try{if(!e.url?.startsWith(y))return u(t,404,"no such endpoint");const o=k(e),c=o?s.get(o):void 0;if(!c||!o)return u(t,401,"this call carries no valid turn credential");const l=e.method==="POST"?await R(e):void 0,f=e.headers["mcp-session-id"],h=typeof f=="string"?n.get(f):void 0;if(h){if(h.token!==o)return u(t,404,"no such session");await h.transport.handleRequest(e,t,l);return}if(typeof f=="string")return u(t,404,"no such session");if(!B(l))return u(t,400,"the first call on a connection must be initialize");await(await m(o,c)).handleRequest(e,t,l)}catch(o){p.error({err:o},"a tool call could not be handled"),t.headersSent?t.end():u(t,400,"that request could not be handled")}})()});await new Promise((e,t)=>{a.once("error",t),a.listen(0,r,()=>{a.removeListener("error",t),e()})});const d=a.address();if(!d||typeof d=="string")throw new Error("the tool endpoint started without a port");const w=`http://${r}:${d.port}${y}`;return p.info({url:w,tools:i.tools.map(e=>e.name)},"serving the agent its own tools"),{url:w,toolNames:i.tools.map(e=>e.name),grant(e){const t=v(32).toString("base64url"),o={context:e,sessions:new Set};return s.set(t,o),{access:{url:w,tokenEnvVar:_,token:t},revoke:()=>{if(s.delete(t)){for(const l of o.sessions){const f=n.get(l);n.delete(l),f?.transport.close().catch(h=>{p.debug({err:h},"a tool connection did not close cleanly")})}o.sessions.clear()}}}},async stop(){for(const{transport:e}of n.values())await e.close().catch(()=>{});n.clear(),s.clear(),a.closeAllConnections(),await new Promise(e=>a.close(()=>e()))}}}export{y as PATH,O as SERVER_NAME,_ as TOKEN_ENV_VAR,L as startToolServer};
1
+ import{randomBytes as T,randomUUID as b}from"node:crypto";import{createServer as k}from"node:http";import{McpServer as B}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as O}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{isInitializeRequest as _}from"@modelcontextprotocol/sdk/types.js";import{log as h}from"../log.js";import{ToolRefusal as y}from"./types.js";const x="bishop",v="/mcp",R="BISHOP_TOOL_TOKEN",A=1048576;function N(i){const r=i.headers.authorization;return r&&/^Bearer\s+(.+)$/i.exec(r.trim())?.[1]?.trim()||void 0}function p(i,r,a){i.writeHead(r,{"content-type":"application/json"}),i.end(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32001,message:a}}))}async function I(i){const r=[];let a=0;for await(const n of i){if(a+=n.length,a>A)throw new Error("request body is too large");r.push(n)}if(r.length!==0)return JSON.parse(Buffer.concat(r).toString("utf8"))}const P="Bishop's tools answer to a person, and this message came from another bot. Ask someone in the conversation to do it.";function z(i,r){const a=new B({name:x,version:"1"});for(const n of i)a.registerTool(n.name,{description:n.description,inputSchema:n.input},async w=>{try{if(r.principal.isBot)throw new y(P);return{content:[{type:"text",text:await n.run(w,r)}]}}catch(c){const f=c instanceof Error?c.message:String(c);return c instanceof y?h.info({tool:n.name,thread:r.thread.threadKey,reason:f},"a tool refused"):h.error({tool:n.name,thread:r.thread.threadKey,err:c},"a tool failed"),{content:[{type:"text",text:f}],isError:!0}}});return a}async function D(i){const r=i.host??"127.0.0.1",a=new Map,n=new Map;async function w(e,t){const o=new O({sessionIdGenerator:()=>b(),onsessioninitialized:s=>{if(a.get(e)!==t){o.close().catch(()=>{});return}n.set(s,{token:e,transport:o}),t.sessions.add(s)}});return o.onclose=()=>{const s=o.sessionId;s&&(n.delete(s),t.sessions.delete(s))},await z(t.tools,t.context).connect(o),o}const c=k((e,t)=>{(async()=>{try{if(!e.url?.startsWith(v))return p(t,404,"no such endpoint");const o=N(e),s=o?a.get(o):void 0;if(!s||!o)return p(t,401,"this call carries no valid turn credential");const l=e.method==="POST"?await I(e):void 0,d=e.headers["mcp-session-id"],m=typeof d=="string"?n.get(d):void 0;if(m){if(m.token!==o)return p(t,404,"no such session");await m.transport.handleRequest(e,t,l);return}if(typeof d=="string")return p(t,404,"no such session");if(!_(l))return p(t,400,"the first call on a connection must be initialize");await(await w(o,s)).handleRequest(e,t,l)}catch(o){h.error({err:o},"a tool call could not be handled"),t.headersSent?t.end():p(t,400,"that request could not be handled")}})()});await new Promise((e,t)=>{c.once("error",t),c.listen(0,r,()=>{c.removeListener("error",t),e()})});const f=c.address();if(!f||typeof f=="string")throw new Error("the tool endpoint started without a port");const g=`http://${r}:${f.port}${v}`;return h.info({url:g,tools:i.tools.map(e=>e.name)},"serving the agent its own tools"),{url:g,toolNames:i.tools.map(e=>e.name),grant(e,t){const o=T(32).toString("base64url"),s=t?.only,l=s?i.tools.filter(u=>s.includes(u.name)):i.tools;s&&l.length!==s.length&&h.error({asked:[...s],serving:l.map(u=>u.name)},"a turn asked for tools this endpoint does not serve");const d={context:e,tools:l,sessions:new Set};return a.set(o,d),{access:{url:g,tokenEnvVar:R,token:o},revoke:()=>{if(a.delete(o)){for(const u of d.sessions){const S=n.get(u);n.delete(u),S?.transport.close().catch(E=>{h.debug({err:E},"a tool connection did not close cleanly")})}d.sessions.clear()}}}},async stop(){for(const{transport:e}of n.values())await e.close().catch(()=>{});n.clear(),a.clear(),c.closeAllConnections(),await new Promise(e=>c.close(()=>e()))}}}export{v as PATH,x as SERVER_NAME,R as TOKEN_ENV_VAR,D as startToolServer};
package/dist/turn.js CHANGED
@@ -1 +1 @@
1
- import{log as o}from"./log.js";import{worktreeName as b}from"./worktrees.js";function v(i){const s=new Map,l=new Set;async function y(e){const r=i.sharedDirNotice;if(!(!r||l.has(e.thread.threadKey))){l.add(e.thread.threadKey);try{await e.notify(r)}catch(n){o.debug({thread:e.thread.threadKey,err:n},"could not deliver the shared-directory notice")}}}function w(e,r){if(!(!i.tools||e.tools===!1))return i.tools.grant({thread:e.thread,principal:r,origin:e.origin,destination:()=>e.destination()})}async function m(e){await y(e);const r=new AbortController,n=e.presence();let d;try{s.set(e.thread.threadKey,r);const a=e.freshSession?void 0:await i.sessions.get(e.thread.id),h=await i.cwd(e.thread),[p,f]=await Promise.all([e.messages(),a?void 0:e.history?.().catch(t=>{o.warn({thread:e.thread.threadKey,err:t},"could not read the history")})]),[c,...g]=p;if(!c)throw new Error("a turn with no messages");const K=g.at(-1)?.principal??c.principal;if(r.signal.aborted){o.info({thread:e.thread.threadKey},"turn stopped before the agent started");return}d=w(e,K);for await(const t of i.harness.runTurn({messages:[c,...g],cwd:h,threadKey:e.thread.threadKey,worktree:b(e.thread.dirKey),...a?{sessionId:a}:{},...e.note?{note:e.note}:{},...f?.length?{history:f}:{},origin:e.origin,...d?{tools:d.access}:{},signal:r.signal}))t.type==="session"&&t.sessionId!==a&&await i.sessions.set(e.thread.id,t.sessionId),t.type==="text"&&o.debug({thread:e.thread.threadKey,chars:t.text.length},"agent said something"),t.type==="tool"&&o.debug({thread:e.thread.threadKey,tool:t.name,detail:t.summary??t.detail},"tool activity"),t.type==="done"&&o.info({thread:e.thread.threadKey,...t.usage},"turn complete"),t.type==="error"&&o.error({thread:e.thread.threadKey,kind:t.kind,err:t.message},"turn errored"),await n.handle(t)}catch(a){const h=a instanceof Error?a.message:String(a);throw o.error({thread:e.thread.threadKey,err:a},"turn failed before the agent answered"),await n.handle({type:"error",kind:"turn_failed",message:h}),a}finally{d?.revoke(),s.get(e.thread.threadKey)===r&&s.delete(e.thread.threadKey),await n.finish()}}return{run:m,stop(e){const r=s.get(e);return r?(r.abort(),!0):!1}}}export{v as makeTurnRunner};
1
+ import{log as d}from"./log.js";import{worktreeName as u}from"./worktrees.js";function A(n){const h=new Map,y=new Set;async function w(e){const a=n.sharedDirNotice;if(!(!a||y.has(e.thread.threadKey))){y.add(e.thread.threadKey);try{await e.notify(a)}catch(o){d.debug({thread:e.thread.threadKey,err:o},"could not deliver the shared-directory notice")}}}function K(e,a,o){if(!n.tools||e.tools===!1)return;const i=Array.isArray(e.tools)?e.tools:void 0;if(i&&i.length===0)return;const r=o.share?.bind(o);return n.tools.grant({thread:e.thread,principal:a,origin:e.origin,destination:()=>e.destination(),...r?{share:r}:{}},...i?[{only:i}]:[])}async function p(e){await w(e);const a=new AbortController,o=e.presence();let i;try{h.set(e.thread.threadKey,a);const r=e.freshSession?void 0:await n.sessions.get(e.thread.id),c=await n.cwd(e.thread),[b,g]=await Promise.all([e.messages(),r?void 0:e.history?.().catch(t=>{d.warn({thread:e.thread.threadKey,err:t},"could not read the history")})]),[f,...m]=b;if(!f)throw new Error("a turn with no messages");const k=m.at(-1)?.principal??f.principal;if(a.signal.aborted){d.info({thread:e.thread.threadKey},"turn stopped before the agent started");return}i=K(e,k,o);const l=n.model?.of(e.thread.id)??{};let s;for await(const t of n.harness.runTurn({messages:[f,...m],cwd:c,threadKey:e.thread.threadKey,worktree:u(e.thread.dirKey),...r?{sessionId:r}:{},...l.model?{model:l.model}:{},...l.effort?{effort:l.effort}:{},...e.note?{note:e.note}:{},...g?.length?{history:g}:{},origin:e.origin,...i?{tools:i.access}:{},signal:a.signal}))t.type==="session"&&(t.model&&(s=t.model),t.sessionId!==r&&await n.sessions.set(e.thread.id,t.sessionId)),t.type==="text"&&d.debug({thread:e.thread.threadKey,chars:t.text.length},"agent said something"),t.type==="tool"&&d.debug({thread:e.thread.threadKey,tool:t.name,detail:t.summary??t.detail},"tool activity"),t.type==="done"&&d.info({thread:e.thread.threadKey,...s?{model:s}:{},...t.usage},"turn complete"),t.type==="error"&&d.error({thread:e.thread.threadKey,...s?{model:s}:{},kind:t.kind,err:t.message},"turn errored"),await o.handle(t)}catch(r){const c=r instanceof Error?r.message:String(r);throw d.error({thread:e.thread.threadKey,err:r},"turn failed before the agent answered"),await o.handle({type:"error",kind:"turn_failed",message:c}),r}finally{i?.revoke(),h.get(e.thread.threadKey)===a&&h.delete(e.thread.threadKey),await o.finish()}}return{run:p,stop(e){const a=h.get(e);return a?(a.abort(),!0):!1}}}export{A as makeTurnRunner};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentdeploymentco/bishop",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "An agent gateway. Connects an agent to Slack and email.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
@@ -22,15 +22,22 @@
22
22
  "build:release": "rm -rf dist && tsc -p tsconfig.release.json && node scripts/minify.mjs && chmod +x dist/cli.js",
23
23
  "prepublishOnly": "npm run build:release && node scripts/check-package.mjs",
24
24
  "dev": "tsx src/cli.ts",
25
+ "dev:slack": "./scripts/dev.sh start",
26
+ "dev:slack:stop": "./scripts/dev.sh stop",
27
+ "dev:slack:restart": "./scripts/dev.sh restart",
28
+ "dev:slack:status": "./scripts/dev.sh status",
29
+ "dev:slack:logs": "./scripts/dev.sh logs",
25
30
  "typecheck": "tsc --noEmit",
26
31
  "test": "vitest run",
27
32
  "test:watch": "vitest",
33
+ "eval:etiquette": "tsx test/etiquette-eval.ts",
28
34
  "lint": "biome check src test",
29
35
  "format": "biome check --write src test",
30
36
  "check": "npm run lint && npm run typecheck && npm test"
31
37
  },
32
38
  "dependencies": {
33
39
  "@anthropic-ai/claude-agent-sdk": "^0.3",
40
+ "@microsoft/teams.apps": "^2.0.16",
34
41
  "@modelcontextprotocol/sdk": "^1.30.0",
35
42
  "@openai/codex-sdk": "^0.149.1",
36
43
  "@slack/bolt": "^5.0.0",
@@ -1 +0,0 @@
1
- import{FETCH_FILE_TOOL as r}from"../harness/principal.js";const a={Read:e=>e?`Reading ${e}`:"Reading a file",Write:e=>e?`Writing ${e}`:"Writing a file",Edit:e=>e?`Editing ${e}`:"Editing a file",NotebookEdit:e=>e?`Editing ${e}`:"Editing a notebook",Bash:e=>e??"Running a command",BashOutput:()=>"Checking on a command",Glob:e=>e?`Looking for ${e}`:"Looking through files",Grep:e=>e?`Searching for ${e}`:"Searching the code",WebFetch:e=>e?`Reading ${e}`:"Fetching a page",WebSearch:e=>e?`Searching for ${e}`:"Searching the web",Task:e=>e?`Working on ${e}`:"Delegating a subtask",TodoWrite:()=>"Planning",ExitPlanMode:()=>"Finishing up a plan",AskUserQuestion:()=>"Considering options"},s={schedule_create:"Setting up a schedule",schedule_list:"Checking what is scheduled",schedule_delete:"Removing a schedule",[r]:"Fetching a file from this conversation"};function c(e){if(!e.startsWith("mcp__"))return;const[,n,...t]=e.split("__");return n==="bishop"?s[t.join("__")]??"Sorting something out":n?`Calling ${n}`:"Calling a tool"}function l(e){const n=e.replaceAll(/[_-]+/g," ").replaceAll(/([a-z\d])([A-Z])/g,"$1 $2").trim();if(!n)return"Working";const t=n.toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}const i=100;function g(e){const n=e.trim();return n.length>i?`${n.slice(0,i-3)}...`:n}function h(e){const n=e.summary?.trim();if(n)return g(n);const t=a[e.name];if(t)return t(e.detail);const o=c(e.name);return o||l(e.name)}function m(e){const n=Math.max(0,Math.round(e/1e3)),t=Math.floor(n/60),o=n%60;return t?`${t}m ${o}s`:`${o}s`}export{m as elapsed,l as humanizeToolName,g as summaryPhrase,h as toolPhrase};
File without changes
File without changes