@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
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{CHANNELS_ONLY as l,EntryError as o}from"./entry.js";const s=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function r(i,n){return new o(`${i.text} needs a lookup only a running Bishop can do. Use ${n}, or run \`! permissions set\` in a conversation with the agent.`)}function t(i,n){return{kind:"group",interface:i.interface,label:`*@${n}`,group:"domain",externalId:n}}function c(i){const{value:n}=i;if(n.form==="domain")return t(i,n.domain);if(n.form!=="id"||i.kind==="channel")throw r(i,"a person or group by ID, like slack:<U0123ABC> or slack:<S0123ABC>");const e=n.id.toUpperCase();if(/^[UW]/.test(e))return{kind:"principal",interface:"slack",label:`<@${e}>`,sighting:{externalId:e,kind:"unknown",affiliation:"unknown"}};if(e.startsWith("S"))return{kind:"group",interface:"slack",label:e,group:"usergroup",externalId:e};throw r(i,"a person or group by ID, like slack:<U0123ABC> or slack:<S0123ABC>")}function f(i){const{value:n}=i;if(n.form==="domain")return t(i,n.domain);if(n.form==="email"&&!i.kind)return{kind:"principal",interface:"gmail",label:n.email,sighting:{externalId:n.email,handle:n.email,email:n.email,kind:"unknown",affiliation:"unknown"}};throw new o(`${i.text}: Gmail names people by address, or everyone at a domain with *@domain`)}function d(i){const{value:n}=i;if(n.form==="domain")return t(i,n.domain);const e=n.form==="email"?n.email:n.form==="id"&&s.test(n.id)?n.id.toLowerCase():void 0;if(e)return{kind:"pending",interface:"teams",label:e,target:"principal",match:e};const a=n.form==="id"?n.id.split(";")[0]??n.id:"";if(n.form==="id"&&/@thread\.v2$/i.test(a))throw new o(`${i.text}: ${l}`);if(n.form==="id"&&a.startsWith("19:"))return{kind:"location",interface:"teams",label:a,externalId:a,locationKind:"channel"};throw r(i,"a principal name, an object ID, or teams:#<19:\u2026> for a channel")}function u(i){switch(i.interface){case"slack":return c(i);case"gmail":return f(i);case"teams":return d(i);default:throw new o(`${i.text}: Bishop has no interface called ${i.interface}`)}}export{u as offlineSubject};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{log as u}from"../log.js";import{atLeast as y,isRunning as m,lowest as h,parseLevel as A}from"./levels.js";import{domainsOf as _}from"./subjects.js";const v="level",B="level.told",N="config",x=t=>`${t.kind}:${t.id}`,w=(t,f,o)=>`${t} ${f} ${o}`;function M(t){return t.reduce((f,o)=>!f||o.grantedAt>f.grantedAt?o:f,void 0)}function $(t){return t.reduce((f,o)=>!f||!y(o.level,f.level)?o:f,void 0)}function C(t){const f=t.fallback??"deny",{store:o}=t;let c=new Map;function I(e,n,r){return{kind:r,id:n,interface:e.interface,label:e.label,level:"admin",grantedBy:N,grantedAt:0}}function k(e){return c.get(x(e))??o.get(e)}function K(e){switch(e.kind){case"principal":return{kind:"principal",id:t.principals.see(e.interface,e.sighting).id};case"group":return{kind:"group",id:o.ensureGroup(e.interface,e.group,e.externalId,e.name)};case"location":return{kind:"location",id:o.ensureLocation(e.interface,e.externalId,e.locationKind,e.name)};case"pending":return}}function E(e){switch(e.kind){case"principal":{const n=t.principals.lookup(e.interface,e.sighting.externalId);return n&&{kind:"principal",id:n.id}}case"group":{const[n]=o.findGroups(e.interface,e.group,[e.externalId]);return n?{kind:"group",id:n}:void 0}case"location":{const[n]=o.findLocations(e.interface,[e.externalId]);return n?{kind:"location",id:n}:void 0}case"pending":return}}function p(e){const n=t.meta.get(e,v),r=n?A(n):void 0;return r&&m(r)?r:void 0}function L(e,n){const r=p(e);return r||(t.meta.set(e,v,n),n)}function O(e,n,r,i){const l=r.map(g=>c.get(w(e,n,g))).find(g=>!!g);if(l)return[l];const s=o.pending(e,n,r),a=M(s),d=a&&i();if(!a||!d)return a?[a]:[];const R=o.attach(a.id,d);for(const g of s)g.id!==a.id&&o.removeNamed(e,n,g.match??"");const G={interface:e,[n]:d.id,permission:a.level,named:a.label};return R?u.info(G,"attached a permission level given by name to its row"):u.info(G,"dropped a permission level given by name: its row already held a newer one"),[]}return{fallback:f,of(e){const n=e.names??[],r=n.length?O(e.interface,"principal",n,()=>e.principalId?{kind:"principal",id:e.principalId}:void 0):[],i=r.find(d=>d.grantedBy===N);if(i)return{level:"admin",source:{from:"own",grant:i}};const l=$([...r,...e.principalId?[k({kind:"principal",id:e.principalId})]:[]].filter(d=>!!d));if(l)return{level:l.level,source:{from:"own",grant:l}};const s=[...o.findGroups(e.interface,"usergroup",e.groups),...o.findGroups(e.interface,"domain",_(e))].map(d=>k({kind:"group",id:d})).filter(d=>!!d),a=$(s);return a?{level:a.level,source:{from:"group",grant:a}}:{level:f,source:{from:"default"}}},location(e,n){const r=o.findLocations(e,n).map(i=>k({kind:"location",id:i}));return h(r.map(i=>i?.level))},thread:p,fix:L,told(e){const n=t.meta.get(e,B),r=n?A(n):void 0;return r&&m(r)?r:void 0},tell(e,n){t.meta.set(e,B,n)},async admit(e){if(e.sender==="deny")return{ok:!1,why:"deny",sender:e.sender};const n=h([e.sender,e.location]);if(e.known===!1&&(!n||!m(n)))return{ok:!1,why:"location",sender:e.sender};if(e.audience!==void 0){const l=h([e.audience,e.location]),s=await e.remember(),a=p(s.id);if(!l||!m(l))return e.command&&m(e.sender)?{ok:!0,thread:s,level:a??e.sender,sender:e.sender}:{ok:!1,why:"audience",sender:e.sender};const d=h([a,l]);return d!==a&&(t.meta.set(s.id,v,d),u.info({thread:s.threadKey,...a?{from:a}:{},to:d},"a group conversation's level followed the lowest level in it")),{ok:!0,thread:s,level:d,sender:e.sender}}const r=await e.remember(),i=p(r.id);if(!i){if(!n||!m(n))return{ok:!1,why:"location",sender:e.sender};const l=L(r.id,n);return u.info({thread:r.threadKey,permission:l},"fixed the thread's permission level"),{ok:!0,thread:r,level:l,sender:e.sender}}return e.follows&&n&&m(n)&&n!==i?(t.meta.set(r.id,v,n),u.info({thread:r.threadKey,from:i,to:n},"a one-to-one chat's level followed its person"),{ok:!0,thread:r,level:n,sender:e.sender}):y(e.sender,i)?!e.command&&e.location&&!y(e.location,i)?{ok:!1,why:"locationBelow",sender:e.sender,location:e.location,thread:i}:{ok:!0,thread:r,level:i,sender:e.sender}:{ok:!1,why:"below",sender:e.sender,thread:i}},grant(e){if(e.kind==="pending")return c.get(w(e.interface,e.target,e.match))??o.named(e.interface,e.target,[e.match])[0];const n=E(e);return n&&k(n)},grants(){const e=[...c.values()],n=new Set(c.keys()),r=o.all().filter(i=>i.kind==="pending"?!n.has(w(i.interface,i.target??"",i.match??"")):!n.has(x({kind:i.kind,id:i.id})));return[...e,...r]},set(e,n,r){if(e.kind==="pending"){if(n==="default"){o.removeNamed(e.interface,e.target,e.match);return}return o.setNamed(e.interface,e.target,e.match,e.label,n,r)}const i=K(e);if(n==="default"){o.remove(i);return}return o.set(i,n,r,e.label)},hasAdmin(){return c.size>0||o.all().some(e=>e.level==="admin")},bootstrap(e){c=new Map(e.map(n=>{if(n.kind==="pending"){const i=w(n.interface,n.target,n.match);return[i,I(n,i,"pending")]}const r=K(n);return[x(r),I(n,r.id,r.kind)]}))}}}export{N as CONFIG_GRANTOR,C as permissions};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const n="You don't have access to this agent, so it can't answer you.",a="This agent doesn't work here, so it can't answer you.";function o(t,e){return`This conversation runs at ${t} and you're at ${e}, so the agent won't act on what you write here. Start a new thread, or ask an admin to change your level.`}function r(t){return`At deny: ${t.join(", ")}.`}function s(t){switch(t.why){case"deny":return n;case"location":return a;case"below":return o(t.thread,t.sender);case"locationBelow":return`This conversation runs at ${t.thread}, and this channel is now at ${t.location}, so the agent won't act on what you write here. Start a new thread.`;case"audience":return"Somebody in this chat has no access to this agent, so it can't answer here. An admin can give them a level with `! permissions set`, or they can leave the chat."}}export{n as DENIED,a as LOCATION_DENIED,r as atDeny,o as belowThread,s as refusalText};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import{mint as s}from"../ids.js";import{parseLevel as S}from"./levels.js";const f={principal:"principal_id",location:"location_id",group:"group_id"};function A(r){if(!r.principal_id&&!r.location_id&&!r.group_id)return String(r.name_label??r.name);if(r.principal_id){const c=String(r.p_handle??r.principal_id),p=String(r.p_name??c);return p===c?c:`${p} (${c})`}if(r.location_id){const c=String(r.l_name??"");return c?`#${c}`:String(r.l_external_id??r.location_id)}return String(r.g_kind)==="domain"?`*@${String(r.g_external_id)}`:String(r.g_name||r.g_external_id||r.group_id)}function O(r){const c=`SELECT g.*, p.handle AS p_handle, p.name AS p_name, p.interface AS p_interface,
|
|
2
|
+
l.name AS l_name, l.kind AS l_kind, l.external_id AS l_external_id,
|
|
3
|
+
l.interface AS l_interface,
|
|
4
|
+
gr.name AS g_name, gr.kind AS g_kind, gr.external_id AS g_external_id,
|
|
5
|
+
gr.interface AS g_interface
|
|
6
|
+
FROM grants g
|
|
7
|
+
LEFT JOIN principals p ON p.id = g.principal_id
|
|
8
|
+
LEFT JOIN locations l ON l.id = g.location_id
|
|
9
|
+
LEFT JOIN groups gr ON gr.id = g.group_id`;function p(e){if(!e)return;const n=S(String(e.level));if(!n)return;const a={label:A(e),level:n,grantedBy:String(e.granted_by),grantedAt:Number(e.granted_at)},d=e.name?{target:"principal",match:String(e.name)}:{};if(!e.principal_id&&!e.location_id&&!e.group_id)return{...a,...d,kind:"pending",id:String(e.id),interface:String(e.name_interface)};const g=e.principal_id?"principal":e.location_id?"location":"group";return{...a,...d,kind:g,id:String(e[f[g]]),interface:String(e.p_interface??e.l_interface??e.g_interface??e.name_interface??"")}}const l=r.prepare(`INSERT INTO groups (id, interface, kind, external_id, name, created_at, updated_at)
|
|
10
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
11
|
+
ON CONFLICT (interface, kind, external_id) DO UPDATE SET
|
|
12
|
+
name = CASE WHEN excluded.name = '' THEN name ELSE excluded.name END,
|
|
13
|
+
updated_at = excluded.updated_at
|
|
14
|
+
RETURNING id`),_=r.prepare(`INSERT INTO locations (id, interface, external_id, kind, name, created_at, updated_at)
|
|
15
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
16
|
+
ON CONFLICT (interface, external_id) DO UPDATE SET
|
|
17
|
+
name = CASE WHEN name = '' THEN excluded.name ELSE name END
|
|
18
|
+
RETURNING id`),u=r.prepare(`${c} WHERE g.name_interface = ? AND g.name_target = ? AND g.name = ?`),m=r.prepare(`INSERT INTO grants (id, name_interface, name_target, name, name_label,
|
|
19
|
+
level, granted_by, granted_at)
|
|
20
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
21
|
+
ON CONFLICT (name_interface, name_target, name)
|
|
22
|
+
WHERE name IS NOT NULL
|
|
23
|
+
DO UPDATE SET name_label = excluded.name_label, level = excluded.level,
|
|
24
|
+
granted_by = excluded.granted_by, granted_at = excluded.granted_at`),E=r.prepare("DELETE FROM grants WHERE name_interface = ? AND name_target = ? AND name = ?"),t=e=>Array.from({length:e},()=>"?").join(", "),i={ensureGroup(e,n,a,d){const g=Date.now();return l.get(s("grp"),e,n,a,d??"",g,g).id},findGroups(e,n,a){return a.length===0?[]:r.prepare(`SELECT id FROM groups WHERE interface = ? AND kind = ?
|
|
25
|
+
AND external_id IN (${t(a.length)})`).all(e,n,...a).map(g=>g.id)},ensureLocation(e,n,a,d){const g=Date.now();return _.get(s("loc"),e,n,a,d??"",g,g).id},findLocations(e,n){return n.length===0?[]:r.prepare(`SELECT id FROM locations WHERE interface = ?
|
|
26
|
+
AND external_id IN (${t(n.length)})`).all(e,...n).map(d=>d.id)},get(e){return p(r.prepare(`${c} WHERE g.${f[e.kind]} = ?`).get(e.id))},set(e,n,a){const d=f[e.kind];return r.prepare(`INSERT INTO grants (id, ${d}, level, granted_by, granted_at) VALUES (?, ?, ?, ?, ?)
|
|
27
|
+
ON CONFLICT (${d}) DO UPDATE SET level = excluded.level,
|
|
28
|
+
granted_by = excluded.granted_by, granted_at = excluded.granted_at`).run(s("grt"),e.id,n,a,Date.now()),i.get(e)},remove(e){return r.prepare(`DELETE FROM grants WHERE ${f[e.kind]} = ?`).run(e.id).changes>0},named(e,n,a){return a.map(d=>p(u.get(e,n,d))).filter(d=>!!d)},pending(e,n,a){return a.length===0?[]:r.prepare(`${c} WHERE g.name_interface = ? AND g.name_target = ?
|
|
29
|
+
AND g.name IN (${t(a.length)})
|
|
30
|
+
AND g.principal_id IS NULL AND g.location_id IS NULL AND g.group_id IS NULL`).all(e,n,...a).map(p).filter(d=>!!d)},setNamed(e,n,a,d,g,o){return m.run(s("grt"),e,n,a,d,g,o,Date.now()),p(u.get(e,n,a))},removeNamed(e,n,a){return E.run(e,n,a).changes>0},attach(e,n){const a=f[n.kind],d=r.prepare(`SELECT id, granted_at FROM grants WHERE ${a} = ?`).get(n.id),g=r.prepare("SELECT granted_at FROM grants WHERE id = ?").get(e);if(!g||d?.id===e)return!1;const o=!d||d.granted_at<=g.granted_at;r.exec("BEGIN");try{o?(d&&r.prepare("DELETE FROM grants WHERE id = ?").run(d.id),r.prepare(`UPDATE grants SET ${a} = ? WHERE id = ?`).run(n.id,e)):r.prepare("DELETE FROM grants WHERE id = ?").run(e),r.exec("COMMIT")}catch(N){throw r.exec("ROLLBACK"),N}return o},all(){return r.prepare(`${c} ORDER BY g.granted_at`).all().map(p).filter(e=>!!e)}};return i}function D(){const r=new Map,c=new Map,p=new Map;let l=[];const _=(t,i)=>t?.kind===i.kind&&t.id===i.id,u=(t,i,e)=>n=>n.iface===t&&n.name?.target===i&&n.name.match===e,m=t=>({kind:t.target?t.target.kind:"pending",id:t.target?t.target.id:t.id,interface:t.iface,label:t.label,level:t.level,grantedBy:t.grantedBy,grantedAt:t.grantedAt,...t.name?{target:t.name.target,match:t.name.match}:{}}),E={ensureGroup(t,i,e){const n=`${t} ${i} ${e}`,a=r.get(n)??s("grp");return r.set(n,a),p.set(a,t),a},findGroups(t,i,e){return e.map(n=>r.get(`${t} ${i} ${n}`)).filter(n=>!!n)},ensureLocation(t,i){const e=`${t} ${i}`,n=c.get(e)??s("loc");return c.set(e,n),p.set(n,t),n},findLocations(t,i){return i.map(e=>c.get(`${t} ${e}`)).filter(e=>!!e)},get(t){const i=l.find(e=>_(e.target,t));return i&&m(i)},set(t,i,e,n){const a=l.find(g=>_(g.target,t)),d=Date.now();return a?Object.assign(a,{level:i,grantedBy:e,grantedAt:d}):l.push({id:s("grt"),iface:p.get(t.id)??"",target:t,label:n,level:i,grantedBy:e,grantedAt:d}),E.get(t)},remove(t){const i=l.length;return l=l.filter(e=>!_(e.target,t)),l.length<i},named(t,i,e){return e.flatMap(n=>l.filter(u(t,i,n)).map(m))},pending(t,i,e){return E.named(t,i,e).filter(n=>n.kind==="pending")},setNamed(t,i,e,n,a,d){const g=l.find(u(t,i,e)),o=Date.now();return g?Object.assign(g,{label:n,level:a,grantedBy:d,grantedAt:o}):l.push({id:s("grt"),iface:t,name:{target:i,match:e},label:n,level:a,grantedBy:d,grantedAt:o}),m(l.find(u(t,i,e)))},removeNamed(t,i,e){const n=l.length;return l=l.filter(a=>!u(t,i,e)(a)),l.length<n},attach(t,i){const e=l.find(a=>a.id===t&&!a.target);if(!e)return!1;const n=l.find(a=>_(a.target,i));return n&&n.grantedAt>e.grantedAt?(l=l.filter(a=>a!==e),!1):(n&&(l=l.filter(a=>a!==n)),e.target=i,!0)},all:()=>l.map(m)};return E}export{O as grantStore,D as memoryGrantStore};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function t(e){const n=e.lastIndexOf("@");if(!(n<=0||n===e.length-1))return e.slice(n+1).trim().toLowerCase()}function o(e){return[...new Set(e.addresses.map(t).filter(n=>!!n))]}export{t as domainOf,o as domainsOf};
|
package/dist/principals.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{mint as
|
|
2
|
-
ORDER BY created_at DESC, rowid DESC LIMIT 1`),
|
|
1
|
+
import{mint as I}from"./ids.js";import{log as k}from"./log.js";const x="system",m=Object.freeze({id:"p_0",externalId:"0",handle:"bishop",name:"Bishop",kind:"system",affiliation:"internal"});function S(e,n){return e.kind!=="person"||e.self?!1:[e.handle,e.name,e.email].some(t=>t?.trim().toLowerCase()===n)}function w(e){return e.trim().replace(/^@+/,"").toLowerCase()}function L(e,n){const t=n.find(e)?.principal;return t?t.name===t.handle?t.handle:`${t.name} (${t.handle})`:e}function R(e,n){const t=e.handle?.trim()||n?.handle||e.externalId,r=e.email?.trim()||n?.email,a=e.kind==="system"?"unknown":e.kind;return{...n?{id:n.id}:{},externalId:e.externalId,handle:t,name:e.name?.trim()||n?.name||t,...r?{email:r}:{},kind:a!=="unknown"?a:n?.kind??"unknown",affiliation:e.affiliation!=="unknown"?e.affiliation:n?.affiliation??"unknown",...e.self||n?.self?{self:!0}:{}}}function T(e,n){return e.handle===n.handle&&e.name===n.name&&e.email===n.email&&e.kind===n.kind&&e.affiliation===n.affiliation&&e.self===n.self}function u(e){return{id:e.id,externalId:e.external_id,handle:e.handle,name:e.name,...e.email?{email:e.email}:{},kind:e.kind,affiliation:e.affiliation,...e.self?{self:!0}:{}}}const E="id, interface, external_id, handle, name, email, kind, affiliation, self";function _(e){const n=e.prepare(`SELECT ${E} FROM principals WHERE interface = ? AND external_id = ?`),t=e.prepare(`SELECT ${E} FROM principals WHERE id = ?`),r=e.prepare(`SELECT ${E} FROM principals WHERE interface = ? AND self = 1
|
|
2
|
+
ORDER BY created_at DESC, rowid DESC LIMIT 1`),a=e.prepare(`SELECT ${E} FROM principals WHERE interface = ? AND kind = 'person' AND self = 0`),p=e.prepare(`INSERT INTO principals
|
|
3
3
|
(id, interface, external_id, handle, name, email, kind, affiliation, self, created_at, updated_at)
|
|
4
4
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),f=e.prepare(`UPDATE principals
|
|
5
5
|
SET handle = ?, name = ?, email = ?, kind = ?, affiliation = ?, self = ?, updated_at = ?
|
|
6
|
-
WHERE id = ?`);return{see(d
|
|
6
|
+
WHERE id = ?`);return{see(l,d){let o;try{const c=n.get(l,d.externalId);o=c?u(c):void 0}catch(c){k.warn({err:c,interface:l},"couldn't read a stored principal")}const s=R(d,o),i={...s,id:s.id??I("p")};if(o&&T(o,s))return i;try{const c=Date.now();o?(f.run(i.handle,i.name,i.email??null,i.kind,i.affiliation,i.self?1:0,c,i.id),k.debug({principal:i.id},"updated a principal the platform changed")):p.run(i.id,l,i.externalId,i.handle,i.name,i.email??null,i.kind,i.affiliation,i.self?1:0,c,c)}catch(c){k.warn({err:c,interface:l},"couldn't store a principal")}return i},find(l){const d=t.get(l);return d?{interface:d.interface,principal:u(d)}:void 0},lookup(l,d){const o=n.get(l,d);return o?u(o):void 0},agent(l){const d=r.get(l);return d?u(d):void 0},named(l,d){const o=w(d);return o?a.all(l).map(u).filter(s=>S(s,o)):[]}}}function y(){const e=new Map,n=(r,a)=>`${r}\0${a}`,t=new Map;return e.set(n(x,m.externalId),{interface:x,principal:m}),t.set(m.id,n(x,m.externalId)),{see(r,a){const p=n(r,a.externalId),f=R(a,e.get(p)?.principal),l={...f,id:f.id??I("p")};return e.set(p,{interface:r,principal:l}),t.set(l.id,p),l},find(r){const a=t.get(r);return a?e.get(a):void 0},lookup(r,a){return e.get(n(r,a))?.principal},agent(r){return[...e.values()].filter(a=>a.interface===r&&a.principal.self).at(-1)?.principal},named(r,a){const p=w(a);return p?[...e.values()].filter(f=>f.interface===r).map(f=>f.principal).filter(f=>S(f,p)):[]}}}export{x as SYSTEM_INTERFACE,m as SYSTEM_PRINCIPAL,y as memoryPrincipalStore,R as merge,L as principalLabel,_ as principalStore};
|
package/dist/sandbox.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import{randomBytes as
|
|
2
|
-
${n.output.trim()}`);if(
|
|
3
|
-
${r.output.trim()}`)}return o.stdout.trim()}function
|
|
4
|
-
# Written by Bishop at startup. Runs the command in ${
|
|
5
|
-
# argument per line, from ${
|
|
6
|
-
command=$${
|
|
7
|
-
dir=$${
|
|
8
|
-
unset ${
|
|
1
|
+
import{randomBytes as C}from"node:crypto";import{constants as _,createWriteStream as M,existsSync as R,realpathSync as T}from"node:fs";import{chmod as E,mkdir as m,open as H,realpath as I,rm as k,stat as L,writeFile as P}from"node:fs/promises";import{homedir as W,platform as K,tmpdir as U}from"node:os";import{basename as y,dirname as v,isAbsolute as A,join as l,resolve as d,sep as p}from"node:path";import{pipeline as z}from"node:stream/promises";import{CONFIG_DIR as S}from"./config.js";import{BishopError as f}from"./errors.js";import{exec as O}from"./exec.js";import{ensureThreadFilesDir as X}from"./files.js";import{MAX_SHARE_BYTES as j,ShareRefused as g}from"./outgoing.js";import{gitDirs as V,WORKTREE_DIR as Y}from"./worktrees.js";const x="nono",q=["linux","darwin"];async function fe(e,t=K()){if(!q.includes(t))throw new f(`agent.sandbox is on, but nono can't sandbox on ${t}. It runs on Linux and macOS.`);const o=await O(x,["--version"]);if(o.code!==0)throw new f("agent.sandbox is on, but nono is not installed or not on PATH. See https://nono.sh/docs/cli/getting_started/installation for how to install it.");const n=await O(x,["setup","--check-only"]);if(n.code!==0)throw new f(`agent.sandbox is on, but nono says this system can't enforce its sandbox:
|
|
2
|
+
${n.output.trim()}`);if(e.profile){const r=await O(x,["profile","show",e.profile]);if(r.code!==0)throw new f(`agent.sandbox.profile names "${e.profile}", which nono can't load:
|
|
3
|
+
${r.output.trim()}`)}return o.stdout.trim()}function G(e){return[d(e,S),d(e,".env")]}function u(e){const t=d(e);try{return T(t)}catch{const o=v(t);return o===t?t:l(u(o),y(t))}}function D(e,t){const o=u(e),n=u(t);return n===o||n.startsWith(o.endsWith(p)?o:o+p)}function ue(e){const t=d(e);return h([u(t),l(u(v(t)),y(t))])}function F(e,t){for(const o of e){const n=u(o),r=t.find(a=>{const i=(c,s)=>c.startsWith(s.endsWith(p)?s:s+p);return a===n||i(a,n)||i(n,a)});if(r)throw new f(`The sandbox would let the agent write ${o}, which contains ${r}. An agent that can change its message reviewer can approve itself: move the reviewer, and anything it reads, outside every directory the agent can write.`)}}function B(e,t){for(const o of e){const n=t.find(r=>D(o,r));if(n)throw new f(`The sandbox would have to grant ${o}, which contains ${n}. Bishop's own state can't sit inside the agent's directory with agent.sandbox on: run Bishop from a directory of its own and point --agent at the agent.`)}}async function we(e){const t=e.userHome??W(),o=d(e.cwd),n=await V(e.cwd),r=e.tmp??U(),a=[l(t,".config","git")].filter(R);let i;if(e.level==="read")i=[r],a.push(o,...n);else if(e.level==="write"&&e.isolated){const N=d(o,Y);await m(N,{recursive:!0}),i=[N,...n,r],a.push(o)}else i=[o,...n,r];e.dirKey&&a.push(await X(e.home,e.dirKey));const c=[l(t,".gitconfig")].filter(R),s=G(e.home);B([...i,...a,...c],s);const w=e.unwritable??[];return F(i,w),{allow:i,read:a,readFiles:c,...e.profile?{profile:e.profile}:{},protect:s,...w.length>0?{unwritable:w}:{}}}function he(e,t,o,n){const r=h([...e.allow,...t.allow??[]]),a=h([...e.read,...t.read??[]]),i=h(t.allowFiles??[]),c=h(e.readFiles);return B([...r,...a,...i,...c],e.protect),F([...r,...i],e.unwritable??[]),{command:x,args:["-s","wrap",...e.profile?["--profile",e.profile]:[],...r.flatMap(s=>["--allow",s]),...a.flatMap(s=>["--read",s]),...i.flatMap(s=>["--allow-file",s]),...c.flatMap(s=>["--read-file",s]),"--",o,...n]}}function h(e){return[...new Set(e)]}function J(e,t){return[...e.allow,...e.read].some(o=>D(o,t))}async function me(e){const t=d(e,S,"outgoing");return await k(t,{recursive:!0,force:!0}),await m(t,{recursive:!0,mode:448}),t}async function pe(e,t,o){if(!A(t))return t;const n=new g(`${t} is outside the directories you can work in, so nothing was sent. Copy it into your working directory first.`),r=await H(t,_.O_RDONLY|_.O_NONBLOCK).catch(()=>{throw new g(`There is no file at ${t}.`)});try{const a=await r.stat();if(!a.isFile())throw new g(`There is no file at ${t}.`);const i=await I(t).catch(()=>{}),c=i?await L(i).catch(()=>{}):void 0;if(!i||!c||c.ino!==a.ino||c.dev!==a.dev||!J(e,i))throw n;if(a.size>j)throw new g(`${t} is too large to send.`);const s=l(o,C(6).toString("hex"));await m(s,{recursive:!0,mode:448});const w=l(s,y(t));return await z(r.createReadStream({autoClose:!1}),M(w,{mode:384})),w}finally{await r.close()}}function ge(e){return A(e)?v(u(e)):void 0}const b="BISHOP_SANDBOX_COMMAND",$="BISHOP_SANDBOX_DIR",Q=`#!/bin/sh
|
|
4
|
+
# Written by Bishop at startup. Runs the command in ${b}, one
|
|
5
|
+
# argument per line, from ${$}, followed by this script's arguments.
|
|
6
|
+
command=$${b}
|
|
7
|
+
dir=$${$}
|
|
8
|
+
unset ${b} ${$}
|
|
9
9
|
if [ -z "$command" ] || [ -z "$dir" ]; then
|
|
10
10
|
echo "bishop: the sandbox launcher was started without a command" >&2
|
|
11
11
|
exit 1
|
|
@@ -15,6 +15,6 @@ set -f
|
|
|
15
15
|
IFS='
|
|
16
16
|
'
|
|
17
17
|
exec $command "$@"
|
|
18
|
-
`;async function
|
|
19
|
-
`));if(n!==void 0)throw new
|
|
20
|
-
`),[
|
|
18
|
+
`;async function xe(e){const t=d(e,S,"sandbox");await m(t,{recursive:!0,mode:448});const o=l(t,"launch");return await P(o,Q,{mode:448}),await E(o,448),o}function be(e,t){const o=[e.command,...e.args],n=[...o,t].find(r=>r===""||r.includes(`
|
|
19
|
+
`));if(n!==void 0)throw new f(`The sandbox can't pass ${JSON.stringify(n)} to its launcher, which takes one argument per line.`);return{[b]:o.join(`
|
|
20
|
+
`),[$]:t}}export{b as LAUNCH_COMMAND_ENV,$ as LAUNCH_DIR_ENV,x as NONO,fe as checkSandbox,me as clearedStaging,ge as executableDir,be as launchEnv,he as nonoCommand,G as protectedPaths,we as sandboxPolicy,J as sandboxReadable,pe as stageFile,ue as unwritablePaths,xe as writeLauncher};
|
package/dist/schedule/cli.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
import{userInfo as
|
|
2
|
-
runs ${
|
|
3
|
-
next ${
|
|
4
|
-
to ${
|
|
1
|
+
import{userInfo as R}from"node:os";import{WebClient as A}from"@slack/web-api";import{loadConfig as S}from"../config.js";import{dbPath as D,openDb as E}from"../db.js";import{describeMissing as B,loadEnv as C,readCredentials as T,whyNotStarted as v}from"../env.js";import{BishopError as a}from"../errors.js";import{gmailMembership as z}from"../gmail/authorize.js";import{resolveGmailDestination as F}from"../gmail/destination.js";import{interfaceFor as L,UnplaceableDestination as M}from"../interface/destination.js";import{permissions as N}from"../permissions/permissions.js";import{grantStore as j}from"../permissions/store.js";import{principalLabel as q,principalStore as $}from"../principals.js";import{threadMeta as G}from"../sessions/store.js";import{resolveSlackDestination as I}from"../slack/destination.js";import{describeTime as p,describeTiming as g,nextRun as x,parseAt as O,systemTimeZone as u,validateCron as Z,validateTimeZone as P}from"./cron.js";import{scheduleStore as U}from"./store.js";function W(e,t){const n=$(e),o=N({store:j(e),meta:G(e),principals:n,...t.permissions?.default?{fallback:t.permissions.default}:{}});return i=>o.of(z(n.lookup("gmail",i.trim().toLowerCase())?.id,i))}async function f(e){C(e);const t=await S(e),n=E(D(e));return{config:t,db:n,schedules:U(n)}}function b(e,t){const n=e?.trim();if(!n)throw new a(`${t} is required`);return n}function H(e){try{return e()}catch(t){throw t instanceof M?new a(`${t.message} Or say which with --interface.`):t}}async function J(e,t,n,o,i,r){if(t==="slack"){if(!n.slack)throw new a("Slack is not running here, so nothing sent to a Slack destination would arrive. "+(v(o,"slack")??"Run `bishop slack setup` first."));return I(new A(n.slack.botToken),e,{seen:s=>r.named("slack",s).map(c=>c.externalId)})}if(t==="gmail"){if(!n.gmail)throw new a("Gmail is not running here, so nothing sent to an address would arrive. "+(v(o,"gmail")??"Run `bishop gmail setup` first."));return F(e,{levelOf:i})}throw new a(`Bishop has no "${t}" interface`)}async function pt(e,t){const n=b(t.name,"--name"),o=t.cron?.trim()||void 0,i=t.at?.trim()||void 0;if(o===void 0==(i===void 0))throw new a("give exactly one of --cron, for a schedule that repeats, or --at");const r=b(t.prompt,"--prompt"),s=b(t.to,"--to"),c=t.tz?P(t.tz.trim()):u(),{config:y,db:d,schedules:k}=await f(e);try{let h;o?(Z(o,c),h=x(o,c,Date.now())):h=O(i??"",c);const m=T(y);if(!m.ok)throw new a(B(m));const w=await J(s,H(()=>L(s,t.interface)),m.credentials,m,W(d,y),$(d)),l=k.add({name:n,...o?{cron:o}:{},tz:c,prompt:r,destination:w,createdBy:`cli:${R().username}`,nextRunAt:h});process.stdout.write(`Added ${l.id} "${l.name}"
|
|
2
|
+
runs ${g(l)}
|
|
3
|
+
next ${p(l.nextRunAt,u())}
|
|
4
|
+
to ${w.label} via ${w.interface}
|
|
5
5
|
|
|
6
6
|
A running Bishop picks it up within a minute. Nothing fires while Bishop is stopped.
|
|
7
|
-
`)}finally{
|
|
8
|
-
`)}async function
|
|
9
|
-
`);return}const i=u(),r
|
|
7
|
+
`)}finally{d.close()}}function K(e,t,n){const o=[`${e.id} ${e.name}${e.enabled?"":" (disabled)"}`,` runs ${g(e)}`,` next ${e.enabled?p(e.nextRunAt,t):"never, while it is off"}`,` to ${e.destination.label} via ${e.destination.interface}`,` prompt ${e.prompt}`];return e.lastRunAt&&o.push(` last ${p(e.lastRunAt,t)}`),e.lastError&&o.push(` error ${e.lastError} (${e.consecutiveFailures} in a row)`),o.push(` by ${q(e.createdBy,n)}`),o.join(`
|
|
8
|
+
`)}async function ut(e){const{db:t,schedules:n}=await f(e);try{const o=n.all();if(o.length===0){process.stdout.write(`No schedules here.
|
|
9
|
+
`);return}const i=u(),r=$(t);process.stdout.write(`${o.map(s=>K(s,i,r)).join(`
|
|
10
10
|
|
|
11
11
|
`)}
|
|
12
12
|
`),process.stdout.write(`
|
|
13
13
|
Times shown in ${i}.
|
|
14
|
-
`)}finally{t.close()}}async function
|
|
15
|
-
`)}finally{n.close()}}async function
|
|
14
|
+
`)}finally{t.close()}}async function ft(e,t){const{db:n,schedules:o}=await f(e);try{const i=o.get(t);if(!i)throw new a(`no schedule ${t}. \`bishop schedules list\` has them.`);o.remove(t),process.stdout.write(`Removed ${t} "${i.name}"
|
|
15
|
+
`)}finally{n.close()}}async function dt(e,t,n){const{db:o,schedules:i}=await f(e);try{const r=i.get(t);if(!r)throw new a(`no schedule ${t}. \`bishop schedules list\` has them.`);const{cron:s}=r;if(n&&!s&&r.nextRunAt<=Date.now())throw new a(`${t} is a reminder whose time went by while it was off. Remove it, or add it again with a time in the future.`);const c=n&&s?x(s,r.tz,Date.now()):r.nextRunAt;i.setEnabled(t,n,c),n&&i.clearFailures(t),process.stdout.write(n?`Enabled ${t} "${r.name}", next ${p(c,u())}
|
|
16
16
|
`:`Disabled ${t} "${r.name}"
|
|
17
|
-
`)}finally{o.close()}}export{
|
|
17
|
+
`)}finally{o.close()}}export{pt as addSchedule,ut as listSchedules,ft as removeSchedule,dt as setScheduleEnabled};
|
package/dist/schedule/runner.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{log as a}from"../log.js";import{SHARE_FILE_TOOL as
|
|
1
|
+
import{log as a}from"../log.js";import{SHARE_FILE_TOOL as I}from"../outgoing.js";import{isRunning as R}from"../permissions/levels.js";import{principalLabel as _,SYSTEM_PRINCIPAL as L}from"../principals.js";import{describeTime as N,nextRun as A}from"./cron.js";import{schedulePresence as M}from"./presence.js";import{SCHEDULE_ORIGIN as C,scheduleNote as O}from"./prompt.js";import{ONCE as P}from"./store.js";const F=3e4,D=5,U=5e3;function K(n){return n.startsWith("cli:")}function H(n,d){return`schedule:${n}:${d}`}function Q(n){const d=n.now??Date.now,x=n.tickMs??F,v=n.authorized??K,c=new Map,p=new Map,f=new Set;let h,b=!1;function S(e,t){try{return n.schedules.setNextRun(e.id,A(e.cron??P,e.tz,t)),!0}catch(i){const r=i instanceof Error?i.message:String(i);return a.error({schedule:e.id,cron:e.cron,tz:e.tz,err:i},"disabling a schedule whose cron expression cannot be read"),n.schedules.setEnabled(e.id,!1),n.schedules.recordFailure(e.id,t,r),m(e,`The schedule "${e.name}" is off: Bishop can no longer read when it should run. ${r}
|
|
2
2
|
|
|
3
|
-
Remove it, or add it again with a cron expression that works.`),!1}}async function
|
|
3
|
+
Remove it, or add it again with a cron expression that works.`),!1}}async function m(e,t,i=e.destination){const r=n.deliver(i,{text:t,title:e.name}).then(()=>{}).catch(s=>{a.error({schedule:e.id,to:i.label,err:s},"could not say that a schedule failed")}).finally(()=>{f.delete(r)});f.add(r),await r}async function g(e,t,i){if(!e.cron){a.error({schedule:e.id,name:e.name,err:i},"a reminder failed"),await m(e,`The reminder "${e.name}" failed: ${i}`);return}const r=n.schedules.recordFailure(e.id,t,i);if(a.error({schedule:e.id,name:e.name,failures:r,err:i},"a scheduled run failed"),r>=D){n.schedules.setEnabled(e.id,!1),a.error({schedule:e.id,name:e.name,failures:r},"disabling a schedule after too many failures in a row"),await m(e,`The schedule "${e.name}" has failed ${r} times in a row and is now off. The last failure was: ${i}
|
|
4
4
|
|
|
5
|
-
Nothing more will run until \`bishop schedules enable ${e.id}\`.`);return}
|
|
5
|
+
Nothing more will run until \`bishop schedules enable ${e.id}\`.`);return}r===1&&await m(e,`The schedule "${e.name}" failed: ${i}`)}async function $(e,t,i){const r=M();a.info({schedule:e.id,name:e.name},"a schedule is firing");let s,l;try{l=n.firingLevel?await n.firingLevel(e):"write"}catch(o){await g(e,d(),o instanceof Error?o.message:String(o));return}if(!R(l)){a.warn({schedule:e.id,name:e.name,to:e.destination.label},"skipping a firing: its creator, or where it reports, is at deny");return}let E;try{E=await n.threads.remember(i)}catch(o){await g(e,d(),o instanceof Error?o.message:String(o));return}const z={thread:E,isNewThread:!0,level:l,freshSession:!0,unattended:!0,tools:[I],origin:C,note:O(e,t,n.principals?_(e.createdBy,n.principals):e.createdBy),async messages(){return[{principal:L,text:e.prompt}]},presence:()=>r,async notify(o){r.note(o)},async destination(){return e.destination}};try{await n.run(z)}catch(o){s=o instanceof Error?o.message:String(o)}const u=r.outcome(),T=u.failure??s,w=d();if(T){await g(e,w,T);return}if(u.silent){n.schedules.recordSuccess(e.id,w),a.info({schedule:e.id,name:e.name},"a schedule had nothing to report");return}let y;try{y=await n.deliver(e.destination,{text:u.text,title:e.name,...u.files.length>0?{files:u.files}:{}})}catch(o){await g(e,w,o instanceof Error?o.message:String(o));return}if(y.threadKey&&n.attach)try{await n.attach(y.threadKey,i)}catch(o){a.error({schedule:e.id,thread:y.threadKey,err:o},"a report was delivered but nothing will answer a reply to it")}n.schedules.recordSuccess(e.id,w),a.info({schedule:e.id,name:e.name,to:e.destination.label},"a schedule reported")}function k(e){n.schedules.remove(e.id);const t=N(e.nextRunAt,e.tz);if(!v(e.createdBy)){a.warn({schedule:e.id,createdBy:e.createdBy,due:t},"deleted a missed reminder whose creator can no longer be authorized");return}const i=`Bishop wasn't running at ${t}, when your reminder "${e.name}" was due, so it didn't run. It would have asked:
|
|
6
6
|
|
|
7
|
-
${e.prompt}`,
|
|
7
|
+
${e.prompt}`,r=(async()=>{let s;try{s=await n.reach?.(e.createdBy)}catch(l){a.warn({schedule:e.id,createdBy:e.createdBy,err:l},"can't message a reminder's creator directly, so telling its destination instead"),s=e.destination}if(!s){a.warn({schedule:e.id,name:e.name,createdBy:e.createdBy,due:t},"deleted a reminder that came due while Bishop was not running");return}a.info({schedule:e.id,name:e.name,due:t,to:s.label},"telling the creator about a reminder that came due while Bishop was not running"),await m(e,i,s)})().catch(s=>{a.error({schedule:e.id,err:s},"could not report a missed reminder")}).finally(()=>{f.delete(r)});f.add(r)}async function B(){if(b)return;const e=d();for(const t of n.schedules.due(e)){const i=!t.cron;if(!v(t.createdBy)){a.warn({schedule:t.id,createdBy:t.createdBy},i?"deleting a reminder whose creator can no longer be authorized":"skipping a schedule whose creator can no longer be authorized"),i?n.schedules.remove(t.id):S(t,e);continue}if(i){if(c.has(t.id))continue;n.schedules.remove(t.id)}else if(!S(t,e))continue;if(c.has(t.id)){a.warn({schedule:t.id,name:t.name},"skipping a firing while the previous one is still running");continue}const r=H(t.id,e);p.set(t.id,r);const s=$(t,e,r).catch(l=>{a.error({schedule:t.id,err:l},"a schedule firing threw")}).finally(()=>{c.delete(t.id),p.delete(t.id)});c.set(t.id,s)}}return{start(){const e=d(),t=n.schedules.due(e);for(const r of t){if(!r.cron){k(r);continue}a.info({schedule:r.id,name:r.name,due:new Date(r.nextRunAt).toISOString()},"skipping a firing that came due while Bishop was not running"),S(r,e)}const i=n.schedules.all().filter(r=>r.enabled);a.info({schedules:i.length,skipped:t.length},"watching the schedules"),h=setInterval(()=>{B().catch(r=>{a.error({err:r},"a scheduler pass failed; trying again on the next tick")})},x),h.unref()},tick:B,async settle(){await Promise.allSettled([...c.values(),...f])},async stop(){if(b=!0,h&&clearInterval(h),c.size>0){a.info({firings:c.size},"stopping scheduled runs still going");for(const r of c.keys()){const s=p.get(r);s&&n.cancel?.(s)}}const e=Promise.allSettled([...c.values(),...f]);let t;const i=new Promise(r=>{t=setTimeout(()=>{a.warn({firings:c.size},"giving up on scheduled runs that would not stop"),r()},U)});await Promise.race([e,i]),t&&clearTimeout(t)}}}export{D as MAX_CONSECUTIVE_FAILURES,K as authorizedToRun,H as firingThread,Q as makeScheduler};
|
package/dist/sessions/store.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import{mint as f}from"../ids.js";import{log as R}from"../log.js";const y=10080*60*1e3,
|
|
1
|
+
import{mint as f}from"../ids.js";import{log as R}from"../log.js";const y=10080*60*1e3,S="id, thread_key, dir_key";function g(e){return{id:e.id,threadKey:e.thread_key,dirKey:e.dir_key}}function I(e,t){const r=e.prepare("SELECT session_id, harness FROM sessions WHERE thread_id = ?"),a=e.prepare(`INSERT INTO sessions (thread_id, session_id, harness, created_at, updated_at)
|
|
2
2
|
VALUES (?, ?, ?, ?, ?)
|
|
3
3
|
ON CONFLICT (thread_id) DO UPDATE SET session_id = excluded.session_id,
|
|
4
4
|
harness = excluded.harness,
|
|
5
|
-
updated_at = excluded.updated_at`),o=e.prepare("INSERT OR IGNORE INTO processed_events (event_id, seen_at) VALUES (?, ?)"),s=e.prepare("SELECT 1 FROM processed_events WHERE event_id = ?"),c=e.prepare("SELECT COUNT(*) AS n FROM sessions"),l=e.prepare("SELECT agent_dir FROM threads WHERE id = ?"),E=e.prepare(`SELECT ${
|
|
6
|
-
ON CONFLICT (thread_key) DO NOTHING`),n=e.prepare("SELECT 1 FROM sessions s JOIN threads t ON t.id = s.thread_id WHERE t.thread_key = ?"),u=e.prepare("UPDATE threads SET thread_key = ? WHERE id = ?"),T=e.prepare("UPDATE threads SET agent_dir = ?, used_at = ? WHERE id = ?"),N=e.prepare("UPDATE threads SET used_at = ? WHERE id = ?");return{async get(d){const i=r.get(d);if(i?.session_id){if(i.harness!==t){R.warn({thread:d,recorded:i.harness,running:t},"this thread belongs to a different harness; starting a new session");return}return i.session_id}},async set(d,i){const p=Date.now();a.run(d,i,t,p,p)},async has(d){return n.get(d)!==void 0},async remember(d){const i=Date.now();return _.run(f("t"),d,d,i,i),
|
|
7
|
-
WHERE agent_dir IS NOT NULL GROUP BY agent_dir`),r=e.prepare("SELECT MAX(used_at) AS last_used FROM threads WHERE agent_dir = ?"),a=e.prepare(`SELECT ${
|
|
8
|
-
WHERE used_at < ? AND agent_dir IS NOT NULL ORDER BY used_at`),o=e.prepare("SELECT 1 FROM threads WHERE id = ? AND used_at < ?"),s=n=>`SELECT ${
|
|
5
|
+
updated_at = excluded.updated_at`),o=e.prepare("INSERT OR IGNORE INTO processed_events (event_id, seen_at) VALUES (?, ?)"),s=e.prepare("SELECT 1 FROM processed_events WHERE event_id = ?"),c=e.prepare("SELECT COUNT(*) AS n FROM sessions"),l=e.prepare("SELECT agent_dir FROM threads WHERE id = ?"),E=e.prepare(`SELECT ${S} FROM threads WHERE thread_key = ?`),_=e.prepare(`INSERT INTO threads (id, thread_key, dir_key, created_at, used_at) VALUES (?, ?, ?, ?, ?)
|
|
6
|
+
ON CONFLICT (thread_key) DO NOTHING`),n=e.prepare("SELECT 1 FROM sessions s JOIN threads t ON t.id = s.thread_id WHERE t.thread_key = ?"),u=e.prepare("UPDATE threads SET thread_key = ? WHERE id = ?"),T=e.prepare("UPDATE threads SET agent_dir = ?, used_at = ? WHERE id = ?"),N=e.prepare("UPDATE threads SET used_at = ? WHERE id = ?");return{async get(d){const i=r.get(d);if(i?.session_id){if(i.harness!==t){R.warn({thread:d,recorded:i.harness,running:t},"this thread belongs to a different harness; starting a new session");return}return i.session_id}},async set(d,i){const p=Date.now();a.run(d,i,t,p,p)},async has(d){return n.get(d)!==void 0},async remember(d){const i=Date.now();return _.run(f("t"),d,d,i,i),g(E.get(d))},async seen(d,i){return i?.record===!1?s.get(d)!==void 0:o.run(d,Date.now()).changes===0},count(){return Number(c.get().n)},async getDir(d){return l.get(d)?.agent_dir??void 0},async setDir(d,i){T.run(i,Date.now(),d)},async touchDir(d){N.run(Date.now(),d)},async readdress(d,i){const p=E.get(d);if(!p)return;const D=E.get(i);if(D?.id===p.id)return g(p);if(!D)return u.run(i,p.id),{id:p.id,threadKey:i,dirKey:p.dir_key}}}}function x(e){return async(t,r)=>{const a=await e.readdress(r,t);if(!a){R.warn({thread:t,firing:r},"nothing to attach: a reply here starts a fresh conversation");return}R.info({thread:t,firing:r,id:a.id},"a report thread continues its firing")}}function M(e){const t=e.prepare(`SELECT agent_dir AS dir, MAX(used_at) AS last_used FROM threads
|
|
7
|
+
WHERE agent_dir IS NOT NULL GROUP BY agent_dir`),r=e.prepare("SELECT MAX(used_at) AS last_used FROM threads WHERE agent_dir = ?"),a=e.prepare(`SELECT ${S}, agent_dir FROM threads
|
|
8
|
+
WHERE used_at < ? AND agent_dir IS NOT NULL ORDER BY used_at`),o=e.prepare("SELECT 1 FROM threads WHERE id = ? AND used_at < ?"),s=n=>`SELECT ${S}, agent_dir FROM threads WHERE used_at < ?${n} ORDER BY used_at`,c=e.prepare(s("")),l=e.prepare("DELETE FROM threads WHERE id = ? AND used_at < ?"),E=e.prepare("DELETE FROM processed_events WHERE seen_at < ?"),_=n=>({...g(n),dir:n.agent_dir??""});return{lastActivityByDir(){const n=t.all();return new Map(n.map(u=>[u.dir,Number(u.last_used)]))},lastTurnIn(n){const u=r.get(n);return u?.last_used==null?void 0:Number(u.last_used)},staleThreads(n){return a.all(n).map(_)},quietSince(n,u){return o.get(n,u)!==void 0},collectableThreads(n,u=[]){if(u.length===0)return c.all(n).map(_);const T=` AND id NOT IN (${u.map(()=>"?").join(", ")})`;return e.prepare(s(T)).all(n,...u).map(_)},forgetThreads(n,u){return n.filter(T=>Number(l.run(T.id,u).changes)>0)},pruneEvents(n=Date.now()){return Number(E.run(n-y).changes)}}}function v(e){const t=e.prepare("SELECT value FROM thread_meta WHERE thread_id = ? AND key = ?"),r=e.prepare(`INSERT INTO thread_meta (thread_id, key, value, updated_at) VALUES (?, ?, ?, ?)
|
|
9
9
|
ON CONFLICT (thread_id, key) DO UPDATE SET value = excluded.value,
|
|
10
10
|
updated_at = excluded.updated_at`),a=e.prepare("DELETE FROM thread_meta WHERE thread_id = ? AND key = ?");return{get(o,s){return t.get(o,s)?.value},set(o,s,c){r.run(o,s,c,Date.now())},clear(o,s){a.run(o,s)}}}function L(){const e=new Map,t=(r,a)=>`${r} ${a}`;return{get:(r,a)=>e.get(t(r,a)),set:(r,a,o)=>{e.set(t(r,a),o)},clear:(r,a)=>{e.delete(t(r,a))}}}function w(e){const t=e.prepare("SELECT value FROM interface_state WHERE key = ?"),r=e.prepare(`INSERT INTO interface_state (key, value, updated_at) VALUES (?, ?, ?)
|
|
11
11
|
ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`);return{get(a){return t.get(a)?.value},set(a,o){r.run(a,o,Date.now())}}}const h="context",O="guidance";function H(e,t){const r=e.prepare(`INSERT INTO locations (id, interface, external_id, kind, name, created_at, updated_at)
|
|
@@ -13,5 +13,6 @@ import{mint as f}from"../ids.js";import{log as R}from"../log.js";const y=10080*6
|
|
|
13
13
|
ON CONFLICT (interface, external_id) DO UPDATE SET kind = excluded.kind,
|
|
14
14
|
name = excluded.name,
|
|
15
15
|
updated_at = excluded.updated_at
|
|
16
|
-
RETURNING id`),a=e.prepare("UPDATE threads SET interface = ? WHERE id = ?"),o=e.prepare(`UPDATE threads SET interface = ?, location_id = ?, visibility = ?,
|
|
16
|
+
RETURNING id`),a=e.prepare("UPDATE threads SET interface = ? WHERE id = ?"),o=e.prepare(`UPDATE threads SET interface = ?, location_id = COALESCE(?, location_id), visibility = ?,
|
|
17
|
+
audience = ?
|
|
17
18
|
WHERE id = ?`);return{record(s,c,l){if(!l){a.run(c,s);return}const E=l.location,_=Date.now(),n=E?r.get(f("loc"),c,E.externalId,E.kind,E.name??"",_,_):void 0;o.run(c,n?.id??null,l.visibility,l.audience,s)},told:s=>t.get(s,h),tell:(s,c)=>t.set(s,h,c),guided:s=>t.get(s,O),guide:(s,c)=>t.set(s,O,c)}}function k(e=L()){return{record(){},told:t=>e.get(t,h),tell:(t,r)=>e.set(t,h,r),guided:t=>e.get(t,O),guide:(t,r)=>e.set(t,O,r)}}export{y as EVENT_TTL_MS,w as interfaceState,k as memoryThreadContexts,L as memoryThreadMeta,M as retentionStore,I as sessionStore,H as threadContexts,x as threadHandover,v as threadMeta};
|
package/dist/setup.js
CHANGED
|
@@ -1,48 +1,56 @@
|
|
|
1
|
-
import{appendFile as
|
|
2
|
-
`);function
|
|
3
|
-
`).map(
|
|
1
|
+
import{appendFile as C,readFile as w,writeFile as B}from"node:fs/promises";import{basename as b,join as g}from"node:path";import{createInterface as N}from"node:readline/promises";import{loadConfig as k,writeConfig as O}from"./config.js";import{BishopError as L}from"./errors.js";import{exec as E}from"./exec.js";import{log as f}from"./log.js";import{ENTRY_INTERFACES as P,EntryError as y,parseEntry as S}from"./permissions/entry.js";import{inspectBotToken as K,missingScopes as j,verifyAppToken as H}from"./slack/inspect.js";import{BOT_EVENTS as D}from"./slack/manifest.js";import{provisionSlackApp as R,slackAuthLogin as F,slackAuthTeams as I,slackCliVersion as Y}from"./slack/provision.js";class m extends L{constructor(t){super(t,"SetupError")}}const M=["Bishop needs the Slack CLI to create the app, and it is not installed.",""," brew install --cask slack-cli","","Or see https://docs.slack.dev/tools/slack-cli/guides/installing-the-slack-cli-for-mac-and-linux/"].join(`
|
|
2
|
+
`);function W(n,t){const e=n.slack?.app?.id?.trim(),i=t.BISHOP_SLACK_BOT_TOKEN?.trim(),s=t.BISHOP_SLACK_APP_TOKEN?.trim();if(e&&i&&s)return{appId:e}}function z(n){return b(n).toLowerCase().replaceAll(/[^a-z0-9-]+/g,"-").replaceAll(/^-+|-+$/g,"")||"agent"}function U(n){return n.split(/[-_\s]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}async function A(n,t,e){const i=n.name?.trim()||z(t),s=n.name?.trim()||await e("App name",i)||i,a=n.displayName?.trim()||U(s),o=n.displayName?.trim()||await e("Display name",a)||a,p=n.description?.trim()??await e("Description","");return{name:s,displayName:o,...p?{description:p}:{}}}async function V(n,t){const e=g(n,".gitignore");let i="";try{i=await w(e,"utf8")}catch{}const s=new Set(i.split(`
|
|
3
|
+
`).map(r=>r.trim())),a=t.filter(r=>!s.has(r));if(a.length===0)return[];const p=`${i&&!i.endsWith(`
|
|
4
4
|
`)?`
|
|
5
|
-
`:""}${
|
|
5
|
+
`:""}${i?`
|
|
6
6
|
`:""}# Bishop credentials and local state
|
|
7
|
-
${
|
|
7
|
+
${a.join(`
|
|
8
8
|
`)}
|
|
9
|
-
`;return await
|
|
10
|
-
`):[];for(const[
|
|
9
|
+
`;return await C(e,p,"utf8"),a}async function q(n,t){const e=g(n,".env");let i="";try{i=await w(e,"utf8")}catch{}const s=i?i.split(`
|
|
10
|
+
`):[];for(const[o,p]of Object.entries(t)){const r=s.findIndex(d=>d.startsWith(`${o}=`));r>=0?s[r]=`${o}=${p}`:s.push(`${o}=${p}`)}const a=`${s.filter((o,p)=>o!==""||p<s.length-1).join(`
|
|
11
11
|
`)}
|
|
12
|
-
`;return await
|
|
12
|
+
`;return await B(e,a,{encoding:"utf8",mode:384}),e}function T(n,t){const e=n.trim();return P.some(s=>e.toLowerCase().startsWith(`${s}:`))?e:`${t}:${e}`}async function x(n,t,e,i,s){if(!n.permissions?.admins?.length){if(e.given!==void 0)try{return T(S(e.given,{defaultInterface:t}).text,t)}catch(a){throw a instanceof y?new m(`The admin entry ${a.message}`):a}if(e.interactive)for(s(`
|
|
13
|
+
Nobody is an admin of this agent yet. Name yourself, like ${e.example}, and you can
|
|
14
|
+
give everyone else their level from a conversation. Leave it empty to skip.
|
|
15
|
+
`);;){const a=await i("Your admin entry","");if(!a)return;try{return T(S(a,{defaultInterface:t}).text,t)}catch(o){if(!(o instanceof y))throw o;s(`${o.message}
|
|
16
|
+
`)}}}}function G(n,t){return t?{...n,permissions:{...n.permissions,admins:[t]}}:n}function X(n,t){return n.permissions?.admins?.length||n.permissions?.default&&n.permissions.default!=="deny"?"":`
|
|
17
|
+
permissions.admins is empty, so Bishop won't start unless an admin was set with
|
|
18
|
+
\`bishop permissions set\`. Add your own entry, like
|
|
19
|
+
${t}, to permissions.admins in .bishop/config.json.
|
|
20
|
+
`}async function $(n,t,e=process.stdout){const i=n?N({input:process.stdin,output:e}):void 0,s=async(a,o)=>{if(!i)return o;const p=o?` [${o}]`:"";return(await i.question(`${a}${p}: `)).trim()||o};try{return await t(s)}finally{i?.close()}}function v(n,t){const e=W(n,process.env);return e?(t(`This agent is already set up in Slack as app ${e.appId}.
|
|
13
21
|
Its credentials are in .env and its configuration in .bishop/config.json.
|
|
14
22
|
|
|
15
23
|
To set it up again, remove slack.app.id from .bishop/config.json and the
|
|
16
24
|
BISHOP_SLACK_* lines from .env first.
|
|
17
|
-
`),!0):!1}async function
|
|
18
|
-
${
|
|
19
|
-
`+(
|
|
20
|
-
`:"")}async function
|
|
25
|
+
`),!0):!1}async function _(n,t,e){const i=G({...t,slack:{...t.slack,...e.workspace?{workspace:e.workspace}:{},app:e.app}},e.admin);await O(i,n);const s=await q(n,{BISHOP_SLACK_BOT_TOKEN:e.botToken,BISHOP_SLACK_APP_TOKEN:e.appToken}),a=await V(n,[".env","bishop.db*"]);return` .bishop/config.json app configuration${e.admin?`, ${e.admin} as admin`:""}
|
|
26
|
+
${s} credentials
|
|
27
|
+
`+(a.length?` .gitignore added ${a.join(", ")}
|
|
28
|
+
`:"")+X(i,h)}const h="slack:you@example.com";async function cn(n){const t=n.cwd??process.cwd(),e=n.prompt&&process.stdin.isTTY===!0,i=p=>process.stdout.write(p),s=await k(t);if(v(s,i))return;const a=await Y();if(!a)throw new m(M);f.debug({slackCli:a},"found the slack cli");let o=await I();if(o.length===0){if(!e)throw new m("The Slack CLI is not logged in to a workspace.\nRun `slack auth login`, then run this again.");if(i("The Slack CLI is not logged in to a workspace. Starting `slack auth login`.\n\n"),o=await F()?await I():[],o.length===0)throw new m("The Slack CLI is still not logged in, so the app cannot be created.\nRun `slack auth login` on its own to see what went wrong.");i(`
|
|
21
29
|
Logged in.
|
|
22
|
-
`)}await
|
|
23
|
-
Creating the Slack app for "${
|
|
24
|
-
`);const
|
|
30
|
+
`)}await $(e,async p=>{const r=await A(n,t,p),d=await x(s,"slack",{...n.admin===void 0?{}:{given:n.admin},interactive:e,example:h},p,i),l=o[0];i(`
|
|
31
|
+
Creating the Slack app for "${r.name}" in ${l?.domain??"your workspace"}...
|
|
32
|
+
`);const c=await R({app:r,...l?{teamId:l.id}:{}}),u=await _(t,s,{app:{...r,...c.appId?{id:c.appId}:{}},...d?{admin:d}:{},...l?.domain?{workspace:l.domain}:{},botToken:c.botToken,appToken:c.appToken});f.info({appId:c.appId,manifestCorrected:c.manifestCorrected},"slack app provisioned"),i(`
|
|
25
33
|
Done.
|
|
26
|
-
${
|
|
27
|
-
Note: the app is named "${
|
|
34
|
+
${u}`+(c.manifestCorrected?"":`
|
|
35
|
+
Note: the app is named "${r.displayName} (local)" in Slack. The Slack CLI
|
|
28
36
|
adds that suffix and Bishop could not remove it. Rename it in App Settings,
|
|
29
37
|
or re-run setup once \`slack auth login\` is refreshed.
|
|
30
|
-
`)+"\nRun `bishop` to start the agent.\n")})}async function
|
|
38
|
+
`)+"\nRun `bishop` to start the agent.\n")})}async function dn(n){const t=n.cwd??process.cwd(),e=n.prompt&&process.stdin.isTTY===!0,i=a=>process.stdout.write(a),s=await k(t);v(s,i)||await $(e,async a=>{const o=process.env.BISHOP_SLACK_BOT_TOKEN?.trim()||await a("Bot token (xoxb-...)",""),p=process.env.BISHOP_SLACK_APP_TOKEN?.trim()||await a("App-level token (xapp-...)","");if(!o||!p)throw new m(`Both tokens are needed.
|
|
31
39
|
Bot token: App Settings, OAuth & Permissions, after installing
|
|
32
40
|
App-level token: App Settings, Basic Information, with connections:write
|
|
33
41
|
|
|
34
42
|
Set BISHOP_SLACK_BOT_TOKEN and BISHOP_SLACK_APP_TOKEN, or run in a terminal
|
|
35
|
-
so they can be typed in.`);
|
|
43
|
+
so they can be typed in.`);i(`
|
|
36
44
|
Checking the tokens...
|
|
37
|
-
`);const
|
|
38
|
-
This app is missing scopes Bishop uses: ${
|
|
45
|
+
`);const r=await K(o);await H(p);const d=j(r.grantedScopes);d.length>0&&i(`
|
|
46
|
+
This app is missing scopes Bishop uses: ${d.join(", ")}
|
|
39
47
|
Add them in App Settings under OAuth & Permissions and reinstall the app.
|
|
40
48
|
Bishop will run without them, but the features that need them will fail.
|
|
41
|
-
`);const l=await
|
|
42
|
-
Done. Using app ${
|
|
43
|
-
${
|
|
49
|
+
`);const l=await A({...n,name:n.name??r.appName,displayName:n.displayName??r.appName},t,a),c=await x(s,"slack",{...n.admin===void 0?{}:{given:n.admin},interactive:e,example:h},a,i),u=await _(t,s,{app:{...l,...r.appId?{id:r.appId}:{}},...c?{admin:c}:{},...r.workspace?{workspace:r.workspace}:{},botToken:o,appToken:p});f.info({appId:r.appId,teamId:r.teamId},"slack app adopted"),i(`
|
|
50
|
+
Done. Using app ${r.appId??"(unknown id)"} in ${r.teamName??r.teamId}.
|
|
51
|
+
${u}
|
|
44
52
|
Bishop cannot check which events the app subscribes to. If the agent never
|
|
45
|
-
answers, confirm the app subscribes to: ${
|
|
53
|
+
answers, confirm the app subscribes to: ${D.join(", ")}
|
|
46
54
|
|
|
47
55
|
Run \`bishop\` to start the agent.
|
|
48
|
-
`)})}async function
|
|
56
|
+
`)})}async function ln(n){const[t,e]=process.platform==="darwin"?["open",[n]]:process.platform==="win32"?["cmd",["/c","start","",n]]:["xdg-open",[n]];await E(t,e)}export{m as SetupError,X as adminReminder,x as askForAdmin,z as defaultAppName,V as ensureGitignore,W as existingSetup,ln as openBrowser,A as resolveAppDetails,cn as setupSlack,dn as setupSlackManually,U as titleize,G as withAdmin,$ as withPrompt,q as writeEnv};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{log as i}from"../log.js";import{plainText as h}from"./mentions.js";async function
|
|
1
|
+
import{log as i}from"../log.js";import{plainText as h}from"./mentions.js";async function d(a,t,e,n){try{await a.agents.sessions.setStatus({channel_id:t.channelId,thread_ts:t.threadTs,status:e,...n?{initiator_user_id:n}:{}})}catch(o){i.debug({...t,status:e,err:o},"could not set the agent session status")}}function f(a){const t=new Map;return(e,n,o)=>{const r=`${e.channelId}:${e.threadTs}`,c=(t.get(r)??Promise.resolve()).then(()=>d(a,e,n,o)),s=c.catch(()=>{});return t.set(r,s),s.then(()=>{t.get(r)===s&&t.delete(r)}),c}}async function T(a,t,e){const n=g(e);if(n)try{await a.agents.sessions.rename({channel_id:t.channelId,thread_ts:t.threadTs,title:n})}catch(o){const r=[...n].length;i.warn({...t,length:r,err:o},"could not name the agent session")}}const l=80,u=/[^\p{L}\p{M}\p{Nd} !"&'(),\-.=?_|]/gu;function g(a){const e=h(a).normalize("NFC").replace(u," ").replace(/\s+/g," ").trim();if(!e)return"";if([...e].length<=l)return e;let n="",o=0;for(const{segment:c}of new Intl.Segmenter().segment(e)){const s=[...c].length;if(o+s>l-3)break;n+=c,o+=s}const r=n.trimEnd();return r?`${r}...`:""}export{T as renameSession,g as sessionTitle,d as setSessionStatus,f as statusQueue};
|
package/dist/slack/app.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{App as
|
|
2
|
-
Re-run \`bishop setup slack\`, or check the token in .env.`):new
|
|
1
|
+
import{App as p,LogLevel as d}from"@slack/bolt";import{WebAPIPlatformError as m,WebClient as u}from"@slack/web-api";import{BishopError as _}from"../errors.js";import{log as k}from"../log.js";import{boltLogger as l,socketPool as h}from"./sockets.js";class s extends _{constructor(r){super(r,"SlackStartupError")}}const S={invalid_auth:"BISHOP_SLACK_BOT_TOKEN was rejected by Slack",not_authed:"BISHOP_SLACK_BOT_TOKEN is missing or empty",account_inactive:"the bot token's account is deactivated",token_revoked:"BISHOP_SLACK_BOT_TOKEN has been revoked",token_expired:"BISHOP_SLACK_BOT_TOKEN has expired"};function b(t){if(t instanceof m)return t.data.error;const r=t instanceof Error?t.message:"";return/An API error occurred: (\w+)/.exec(r)?.[1]}async function g(t){const r=new u(t.botToken);let e;try{e=await r.auth.test()}catch(o){const a=b(o),c=a?S[a]:void 0;throw c?new s(`Slack rejected the bot token: ${c} (${a}).
|
|
2
|
+
Re-run \`bishop setup slack\`, or check the token in .env.`):new s(`Couldn't reach Slack: ${o instanceof Error?o.message:String(o)}`)}if(!e.user_id||!e.team_id)throw new s("auth.test returned no user_id or team_id");const n={botUserId:e.user_id,botId:e.bot_id??"",teamId:e.team_id,...e.enterprise_id?{enterpriseId:e.enterprise_id}:{},...e.user?.trim()?{username:e.user.trim()}:{},...e.app_name?.trim()?{appName:e.app_name.trim()}:{},scopes:e.response_metadata?.scopes??[]},i=new p({token:t.botToken,receiver:h({appToken:t.appToken}),logLevel:d.WARN,logger:l()});return k.info({botUserId:n.botUserId,teamId:n.teamId,url:e.url},"connected to Slack"),{app:i,identity:n}}export{s as SlackStartupError,g as createSlackApp};
|
package/dist/slack/bots.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const u=3;function o(e){return`I've answered ${e} bot ${e===1?"message":"messages"} in a row here, so I'm holding off until a person says something.`}function i(e=3){const
|
|
1
|
+
const u=3;function o(e){return`I've answered ${e} bot ${e===1?"message":"messages"} in a row here, so I'm holding off until a person says something.`}function i(e=3){const n=new Map;return{answersBots:e>0,get size(){return n.size},clear(s){n.delete(s)},counting:s=>n.has(s),admit(s,r){if(!r)return n.delete(s),{run:!0};const t=n.get(s)??0;return n.set(s,Math.min(t+1,e+1)),t<e?{run:!0}:t===e&&e>0?{run:!1,say:o(e)}:{run:!1}}}}export{u as DEFAULT_MAX_BOT_TURNS,i as botTurnCap};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BishopError as
|
|
1
|
+
import{BishopError as h}from"../errors.js";import{log as m}from"../log.js";import{retry as w}from"../retry.js";import{splitForSlack as _}from"./format.js";import{attachToSlack as S}from"./upload.js";function p(e){return e.threadTs?`${e.channel}:${e.threadTs}`:e.channel}function k(e){const[t,a]=e.split(":");if(!t)throw new h(`not a Slack destination: ${e}`);return{channel:t,...a?{threadTs:a}:{}}}function v(e){return/^[CG][A-Z0-9]{2,}$/.test(e)}function x(e){return/^D[A-Z0-9]{2,}$/.test(e)}function b(e){return/^[UW][A-Z0-9]{2,}$/.test(e)}const T=new Set(["ratelimited","rate_limited"]);function g(e){const t=e;if(!t)return!1;if(t.code==="slack_webapi_rate_limited_error")return{...t.retryAfter?{retryAfterMs:t.retryAfter*1e3}:{}};const a=t.data?.error;return!!(a&&T.has(a))}async function F(e,t){const{channel:a,threadTs:r}=k(t.handle),i=_(t.text),s=t.files??[],n=s.length>0?i.pop()??"":void 0;let l;for(const d of i){const c=r??l,f=await w(()=>e.chat.postMessage({channel:a,markdown_text:d,...c?{thread_ts:c}:{}}),{what:"chat.postMessage",retryable:g});l??=f.ts}const o=r??l;if(n!==void 0){const d={channel:a,...o?{threadTs:o}:{}};try{const c=await S(e,d,s,n);if(l??=c?.ts,!c&&n){const f=await w(()=>e.chat.postMessage({channel:a,markdown_text:n,...o?{thread_ts:o}:{}}),{what:"chat.postMessage",retryable:g});l??=f.ts}}catch(c){const f=s.map(u=>u.name).join(", ");m.error({channel:a,files:f,err:c},"could not send a file with a report");for(const u of[n,`_Could not upload ${f}._`]){if(!u)continue;const y=await e.chat.postMessage({channel:a,markdown_text:u,...o?{thread_ts:o}:{}}).catch(()=>{});l??=y?.ts}}}return m.info({channel:a,...o?{thread:o}:{},parts:i.length},"delivered to Slack"),r||!l?void 0:{channel:a,threadTs:l}}async function G(e,t){const{channel:a,threadTs:r}=k(t),i=r?" (thread)":"";try{const n=(await e.conversations.info({channel:a})).channel;if(n?.name)return`#${n.name}${i}`;if(n?.is_im&&n.user){const o=(await e.users.info({user:n.user})).user,d=o?.profile?.display_name?.trim()||(o?.is_bot?o.profile?.real_name?.trim():void 0)||o?.name;if(d)return`@${d}`}}catch(s){m.debug({channel:a,err:s},"could not name a Slack destination")}return`${a}${i}`}async function I(e,t){const a=t.toLowerCase();for await(const r of e.paginate("conversations.list",{types:"public_channel,private_channel",exclude_archived:!0,limit:200})){const s=(r.channels??[]).find(n=>n.name?.toLowerCase()===a);if(s)return s}}async function M(e,t,a){const r=await A(e,t);if(r)return r;const i=[...new Set(a?.(t)??[])];if(i.length===1&&i[0])return i[0];throw i.length>1?new h(`more than one person Bishop has heard from answers to @${t}. Give their Slack member ID instead, which starts with U.`):new h(`no Slack user matches @${t}. Somebody from another organization can be found by name only once Bishop has seen a message from them; until then, give their Slack member ID, which starts with U.`)}async function A(e,t){const a=t.toLowerCase();if(a.includes("@"))try{const r=await e.users.lookupByEmail({email:t});if(r.user?.id)return r.user.id}catch(r){m.debug({email:t,err:r},"no Slack user with that address")}for await(const r of e.paginate("users.list",{limit:200})){const i=r.members??[];for(const s of i){if(s.deleted||!s.id)continue;if([s.name,s.profile?.display_name,s.profile?.real_name].some(l=>l?.toLowerCase()===a))return s.id}}}async function R(e,t,a={}){try{return await U(e,t,a)}catch(r){throw r instanceof h?r:C(r,t)}}function C(e,t){const a=e,r=a?.data?.error;return r==="missing_scope"?new h(`Slack won't let this app look up ${t}: it is missing the ${a?.data?.needed??"required"} scope. Bishop's manifest asks for it, so an app installed before this existed has to be reinstalled: run \`bishop slack setup\` again.`):new h(`Slack could not resolve ${t}: ${r??(e instanceof Error?e.message:String(e))}`)}async function U(e,t,a){const r=t.trim();if(!r)throw new h("a Slack destination needs a channel or a person");const[i,s]=r.split(":"),n=(i??"").replace(/^[#@]/,"");if(!n)throw new h(`not a Slack destination: ${t}`);const l=r.startsWith("@")||b(n);if(x(n))return{interface:"slack",handle:p({channel:n,...s?{threadTs:s}:{}}),label:n};if(v(n)){const c=(await e.conversations.info({channel:n})).channel;if(!c?.id)throw new h(`Slack has no conversation ${n}`);return $(c,n),{interface:"slack",handle:p({channel:c.id,...s?{threadTs:s}:{}}),label:c.name?`#${c.name}`:c.id}}if(l){const d=b(n)?n:await M(e,n,a.seen);if(a.optedIn&&!await a.optedIn(d))throw new h(`@${n} 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 post to a channel they are in instead.`);const f=(await e.conversations.open({users:d})).channel?.id;if(!f)throw new h(`could not open a DM with @${n}`);return{interface:"slack",handle:p({channel:f,...s?{threadTs:s}:{}}),label:`@${n}`}}const o=await I(e,n);if(!o?.id)throw new h(`no Slack channel named #${n} that this app can see. A private channel has to have the app in it.`);return $(o,`#${n}`),{interface:"slack",handle:p({channel:o.id,...s?{threadTs:s}:{}}),label:`#${o.name??n}`}}function $(e,t){if(!(e.is_im||e.is_member!==!1))throw new h(`this app is not in ${t}. Invite it there first, or nothing sent to it will arrive.`)}export{F as deliverToSlack,G as describeSlackHandle,I as findChannel,k as parseSlackHandle,R as resolveSlackDestination,p as slackHandle,g as slackRetryable};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{log as l}from"../log.js";const g=300*1e3;function m(d,p={}){let s=[],n=new Map;async function o(){try{const r=await d.usergroups.list({include_users:!0}),a=[],t=new Map;for(const e of r.usergroups??[]){if(!e.id)continue;const c=e.users??[];a.push({id:e.id,...e.handle?{handle:e.handle}:{},...e.name?{name:e.name}:{},members:c});for(const i of c)t.set(i,[...t.get(i)??[],e.id])}s=a,n=t,l.debug({groups:s.length},"read the Slack user groups")}catch(r){l.warn({err:r},"could not read the Slack user groups; keeping the last read")}}const f=o(),u=setInterval(()=>{o()},p.refreshMs??g);return u.unref(),{of:r=>n.get(r)??[],list:()=>s,ready:()=>f,stop:()=>clearInterval(u)}}export{m as userGroups};
|
package/dist/slack/handlers.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{log as r}from"../log.js";import{markHeld as
|
|
1
|
+
import{commandLine as V}from"../commands/syntax.js";import{log as r}from"../log.js";import{atLeast as X,lowest as Y}from"../permissions/levels.js";import{refusalText as Z}from"../permissions/refusal.js";import{markHeld as ee,releaseHeld as te}from"./pending.js";import{FILE_SHARE as ne,isBotEvent as P,isSelfEvent as ae,routeAppMention as se,routeMessage as re}from"./route.js";import{say as oe}from"./say.js";import{slackLocation as ie}from"./subjects.js";import{mentionsBot as de,messageKeyString as ce,spokenAt as le,threadKeyOf as R,threadKeyString as W}from"./thread.js";const he=new Set(["channel_join","channel_leave","channel_name","group_join","group_leave","group_name"]);function ve(k,q){const{identity:h,botName:y,threads:p,events:F,run:$,stop:z,permissions:b,levelOf:U,bots:u,participants:H,command:K,changed:C,screen:L}=q,m=new Map,w=new Map;function x(e){if(!e.channelId.startsWith("D"))return b.location("slack",[ie(e.teamId,e.channelId)])}async function T(e,n,a){return e?X(Y([(await U(e)).level,a])??"deny",n):!1}async function A(e,n,a,s){const t=m.get(n);if(!t?.length)return[];m.set(n,[]),await w.get(n);const d=await te(s.client,e,t,{botUserId:h.botUserId,...y?{botName:y}:{}}),f=[],c=x(e);for(const i of d)await T(i.userId,a,c)?f.push(i):r.warn({thread:n,user:i.userId},"dropping a held message");return f}async function G(e,n,a){const s={source:n.source,thread:n.keyString,user:n.sender};if(n.fromBot){r.debug({...s,why:e.why},"ignoring a bot without the level to be answered");return}r.warn({...s,why:e.why},"refusing a message");try{await a.client.chat.postEphemeral({channel:n.key.channelId,user:n.sender,...n.inThread?{thread_ts:n.key.threadTs}:{},text:Z(e)})}catch(t){r.debug({err:t},"could not post the refusal")}}async function J(e,n,a){e.subtype&&he.has(e.subtype)&&e.channel&&C?.(e.channel);const s=R(e,h.teamId);if(!s){r.debug({source:a},"dropping event with no usable thread key");return}const t=W(s),d=await p.has(t),f={botUserId:h.botUserId,botId:h.botId,...y?{botName:y}:{},threadKnown:d},c=a==="app_mention"?se(e,f):re(e,f);if((d||c.action==="run")&&e.user&&!ae(e,f)&&(!e.subtype||e.subtype===ne)&&H.saw(t,e.user,le(e.ts)),c.action==="ignore"){if(e.user&&e.user!==h.botUserId&&!P(e)&&d&&u.counting(t)){const o=await p.remember(t);await T(e.user,b.thread(o.id)??"read",x(s))&&u.clear(t)}r.debug({source:a,thread:t,reason:c.reason},"ignoring event");return}const i=P(e);if(i&&!u.answersBots){r.debug({source:a,thread:t},"ignoring a bot: this agent answers none");return}const B=ce(s,e);if(B&&await F.seen(`slack:${B}`)){r.info({source:a,thread:t,message:B,eventId:e.event_id},"duplicate message, skipping");return}const l=e.user??"",O=l?await U(l):{level:"deny",source:{from:"default"}},Q=e.channel_type==="im"||s.channelId.startsWith("D"),j=x(s),E=await b.admit({sender:O.level,location:j,remember:()=>p.remember(t),known:d,command:V(c.text)!==void 0});if(!E.ok){await G(E,{source:a,keyString:t,key:s,sender:l,fromBot:i,inThread:!!e.thread_ts},n);return}const{thread:M,level:I}=E;if(K&&await K({key:s,keyString:t,thread:M,text:c.text,userId:l,isBot:i,sender:O,level:I,location:j},n)){i||u.clear(t),r.info({source:a,thread:t,user:l},"ran a command");return}const v={text:c.text,userId:l,ts:e.ts??s.threadTs,isBot:i,mentionsAgent:de(e.text??"",h.botUserId),files:c.files};if(L&&!await L({thread:M,keyString:t,inbound:v})){i||u.clear(t);return}const _=u.admit(t,i);if(!_.run){const o={source:a,thread:t,user:l},g="holding off: too many bot turns in a row in this thread";if(_.say?r.warn(o,g):r.debug(o,g),_.say)try{await oe(n.client,{channel:s.channelId,threadTs:s.threadTs},_.say)}catch(S){r.debug({err:S},"could not say why Bishop is holding off")}return}const N=m.get(t);if(N){N.push(v),r.info({source:a,thread:t,user:l},"holding a message until the turn ends");const o=(w.get(t)??Promise.resolve()).then(()=>ee(n.client,s.channelId,v.ts));w.set(t,o),await o;return}m.set(t,[]);try{let o=[v],g=!d;for(;o.length||m.get(t)?.length;){if(!o.length){o=await A(s,t,I,n);continue}r.info({thread:t,messages:o.length,newThread:g},"running a turn");try{await $({key:s,keyString:t,thread:M,channelId:s.channelId,threadTs:s.threadTs,messages:o,isNewThread:g,level:I,participants:H.count(t),isDirectMessage:Q},n)}catch(S){r.error({thread:t,err:S},"turn failed")}g=!1,o=await A(s,t,I,n)}}finally{m.delete(t),w.delete(t)}}async function D(e,n,a){try{await J(e,n,a)}catch(s){r.error({source:a,err:s},"failed to handle a Slack event")}}k.event("app_mention",async({event:e,body:n,client:a})=>{await D({...e,event_id:n.event_id},{client:a},"app_mention")}),k.event("message",async({event:e,body:n,client:a})=>{await D({...e,event_id:n.event_id},{client:a},"message")}),k.event("agent_session_stopped",async({event:e})=>{const n=R(e,h.teamId);if(!n)return;const a=W(n),s=await p.has(a)?await p.remember(a):void 0,t=(s&&b.thread(s.id))??"read";if(!await T(e.user,t)){r.warn({thread:a,user:e.user},"ignoring a stop from below the thread level");return}const d=z(a);r.info({thread:a,user:e.user,aborted:d},"stop requested")})}export{ve as registerHandlers};
|
package/dist/slack/history.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{describedFile as
|
|
1
|
+
import{describedFile as I}from"../files.js";import{declareUnread as g,trimHistory as w,withinFileBudget as k}from"../interface/history.js";import{log as f}from"../log.js";import{describeSlackFile as p,slackFilePayload as y}from"./files.js";import{renderMentions as x}from"./mentions.js";import{FILE_SHARE as S}from"./route.js";import{nameBotMentions as m,spokenAt as B}from"./thread.js";const T=200,P=3;function R(t){const e=t.messages[0]?.ts;if(!(!e||e===t.threadTs))return e}async function X(t){const e=await _(t);if(!e)return f.warn({thread:t.key.threadTs},"could not read the thread to catch the agent up"),[{kind:"omitted",reason:"unavailable"}];for(const o of e.messages)o.userId&&!u(o,t.self)&&t.saw?.(o.userId,B(o.ts));const s=await v(e.messages,t),r=M(e.messages,t,s),n=k(w(r.entries));return U(e.complete?n:g(n,r.opensWithParent),t)}async function _(t){const e=[],s=new Set;let r;try{for(let n=0;n<P;n+=1){const o=await t.client.conversations.replies({channel:t.key.channelId,ts:t.key.threadTs,latest:t.before,inclusive:!1,limit:T,...r?{cursor:r}:{}});for(const a of o.messages??[]){if(!a.ts||a.ts>=t.before||s.has(a.ts))continue;s.add(a.ts);const{subtype:i,files:d}=a;e.push({ts:a.ts,...a.user?{userId:a.user}:{},...a.bot_id?{botId:a.bot_id}:{},...i?{subtype:i}:{},text:a.text??"",files:d??[]})}if(r=o.response_metadata?.next_cursor,!r)return c(e,!0)}return c(e,!1)}catch(n){return f.warn({thread:t.key.threadTs,read:e.length,err:n},"could not read the whole thread"),e.length?c(e,!1):void 0}}function c(t,e){return{messages:[...t].sort((r,n)=>r.ts<n.ts?-1:r.ts>n.ts?1:0),complete:e}}function F(t,e,s){return t.botId&&!e.answersBots?!1:!!(t.userId&&s.has(t.userId))}async function v(t,e){const s=new Set;for(const n of t)n.userId&&!u(n,e.self)&&s.add(n.userId);const r=await Promise.all([...s].map(async n=>await e.admits(n).catch(()=>!1)?n:void 0));return new Set(r.filter(n=>!!n))}function u(t,e){return t.userId&&t.userId===e.botUserId?!0:!!e.botId&&t.botId===e.botId}function A(t,e){return t.map(s=>{const r=p(s),n=I(r);if(r.unavailable)return n;const o=e.remember({id:r.id,name:r.name,payload:y(s)});return o?{...n,ref:o}:{...n,unavailable:"Bishop could not record a reference for it"}})}function M(t,e,s){const r=[];let n=!1,o=0;const a=()=>{o&&(r.push({kind:"omitted",reason:"unauthorized",count:o}),o=0)};for(const i of t){const d=u(i,e.self),l=i.ts===e.key.threadTs;if(i.subtype&&i.subtype!==S&&!d)continue;if(!d&&!F(i,e,s)){l&&(n=!0),o+=1;continue}if(!m(i.text,e.self.botUserId)&&i.files.length===0)continue;const b=m(i.text,e.self.botUserId,e.self.botName);l&&(n=!0),a(),r.push({kind:"message",principal:h,sender:{id:d?e.self.botUserId:i.userId??i.botId??"",bot:!!i.botId,self:d},text:b,...i.files.length>0?{shared:i.files}:{}})}return a(),{entries:r,opensWithParent:n}}async function U(t,e){return Promise.all(t.map(async s=>{if(s.kind!=="message")return s;const{shared:r,sender:n,...o}=s,a=r?A(r,e):[];return{...o,principal:n?.id?await e.principal(n.id,n.bot,n.self):h,text:await x(s.text,e.users),...a.length>0?{files:a}:{}}}))}const h={id:"",externalId:"",handle:"unknown",name:"unknown",kind:"unknown",affiliation:"unknown"};export{R as landedMidThread,A as namedSlackFiles,X as threadHistory};
|