@agentdeploymentco/bishop 0.9.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.
Files changed (80) hide show
  1. package/README.md +2 -0
  2. package/dist/agent-env.js +1 -0
  3. package/dist/cli.js +25 -22
  4. package/dist/commands/run.js +5 -3
  5. package/dist/config.js +4 -4
  6. package/dist/db.js +62 -12
  7. package/dist/decision/model.js +1 -0
  8. package/dist/decision/providers.js +1 -0
  9. package/dist/env.js +6 -7
  10. package/dist/gmail/authorize.js +1 -1
  11. package/dist/gmail/create.js +1 -1
  12. package/dist/gmail/destination.js +1 -1
  13. package/dist/gmail/history.js +1 -1
  14. package/dist/gmail/interface.js +2 -2
  15. package/dist/gmail/route.js +1 -1
  16. package/dist/gmail/setup.js +8 -8
  17. package/dist/harness/claude-options.js +1 -1
  18. package/dist/harness/claude-processes.js +1 -1
  19. package/dist/harness/claude.js +7 -7
  20. package/dist/harness/codex.js +4 -4
  21. package/dist/harness/create.js +1 -1
  22. package/dist/harness/layers.js +1 -1
  23. package/dist/harness/principal.js +16 -13
  24. package/dist/interface/authorize.js +1 -1
  25. package/dist/interface/etiquette.js +1 -1
  26. package/dist/interface/phrases.js +1 -1
  27. package/dist/interface/reply-gate.js +2 -0
  28. package/dist/interface/search.js +1 -0
  29. package/dist/outgoing.js +2 -2
  30. package/dist/permissions/cli.js +12 -0
  31. package/dist/permissions/entry.js +1 -0
  32. package/dist/permissions/instructions.js +2 -0
  33. package/dist/permissions/levels.js +1 -0
  34. package/dist/permissions/offline.js +1 -0
  35. package/dist/permissions/permissions.js +1 -0
  36. package/dist/permissions/refusal.js +1 -0
  37. package/dist/permissions/store.js +30 -0
  38. package/dist/permissions/subjects.js +1 -0
  39. package/dist/principals.js +3 -3
  40. package/dist/sandbox.js +11 -11
  41. package/dist/schedule/cli.js +10 -10
  42. package/dist/schedule/runner.js +4 -4
  43. package/dist/sessions/store.js +7 -6
  44. package/dist/setup.js +34 -26
  45. package/dist/slack/agent-session.js +1 -1
  46. package/dist/slack/app.js +2 -2
  47. package/dist/slack/bots.js +1 -1
  48. package/dist/slack/destination.js +1 -1
  49. package/dist/slack/groups.js +1 -0
  50. package/dist/slack/handlers.js +1 -1
  51. package/dist/slack/history.js +1 -1
  52. package/dist/slack/interface.js +2 -2
  53. package/dist/slack/presence.js +3 -3
  54. package/dist/slack/read.js +1 -1
  55. package/dist/slack/search.js +1 -0
  56. package/dist/slack/sockets.js +1 -0
  57. package/dist/slack/subjects.js +1 -0
  58. package/dist/slack/users.js +1 -1
  59. package/dist/slack/working.js +1 -0
  60. package/dist/teams/create.js +2 -2
  61. package/dist/teams/destination.js +1 -1
  62. package/dist/teams/history.js +1 -1
  63. package/dist/teams/interface.js +4 -3
  64. package/dist/teams/mentions.js +1 -1
  65. package/dist/teams/permissions.js +1 -0
  66. package/dist/teams/server.js +1 -1
  67. package/dist/teams/setup.js +81 -81
  68. package/dist/tools/conversations.js +2 -0
  69. package/dist/tools/found.js +3 -0
  70. package/dist/tools/history.js +2 -0
  71. package/dist/tools/messages.js +2 -2
  72. package/dist/tools/schedules.js +6 -6
  73. package/dist/tools/server.js +1 -1
  74. package/dist/transcript.js +26 -3
  75. package/dist/turn.js +2 -2
  76. package/package.json +5 -4
  77. package/dist/slack/authorize.js +0 -2
  78. package/dist/slack/authorizer.js +0 -3
  79. package/dist/slack/directory.js +0 -1
  80. package/dist/teams/authorize.js +0 -1
package/README.md CHANGED
@@ -11,6 +11,8 @@ $ bishop slack setup
11
11
  $ bishop
12
12
  ```
13
13
 
14
+ Setup asks for your own address and makes you the agent's admin. Nobody else can use the agent until you give them a [permission level](https://bishop.agentdeployment.co/running/access).
15
+
14
16
  Bishop is an agent gateway: it sits between the places people work and the agents they work with. Today that is Slack, Gmail and Microsoft Teams, one agent, in a single process. It needs Node 24 or newer, and an agent directory where `claude` or `codex` already runs.
15
17
 
16
18
  ## Documentation
@@ -0,0 +1 @@
1
+ const a="BISHOP_";function f(n){const s=n.split("*").map(i=>i.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*"),t=new RegExp(`^${s}$`);return i=>t.test(i)}function p(n,s){const t=/^\$([A-Za-z_][A-Za-z0-9_]*)$/.exec(n);if(!t?.[1])return n;if(!t[1].startsWith(a))return s[t[1]]}function d(n,s=process.env){const t=(n?.allow??["*"]).map(f),i=(n?.deny??[]).map(f),c={};for(const[e,r]of Object.entries(s))r!==void 0&&(e.startsWith(a)||t.some(o=>o(e))&&(i.some(o=>o(e))||(c[e]=r)));const u=[];for(const[e,r]of Object.entries(n?.set??{})){if(e.startsWith(a))continue;const o=p(r,s);o===void 0?(u.push(e),delete c[e]):c[e]=o}return{env:c,missing:u}}export{a as BISHOP_PREFIX,d as agentEnv};
package/dist/cli.js CHANGED
@@ -1,35 +1,38 @@
1
1
  #!/usr/bin/env node
2
- import{stat as le}from"node:fs/promises";import{join as he,resolve as ue}from"node:path";import{Command as fe}from"commander";import{agentSnapshots as we,fixedAgentDir as ge}from"./agent-dir.js";import{looksRemote as Y,parseRepoSpec as W}from"./agent-source.js";import{everyStore as J,storePath as Q}from"./agent-store.js";import{attachmentStore as ye}from"./attachments.js";import{HARNESSES as ke,loadConfig as $,nonEmptyFlag as V,parseHarnessName as Se,positiveIntFlag as ve,resolveAgent as be,sandboxConfig as Te,writeConfig as Ie}from"./config.js";import{dbPath as X,openDb as Z}from"./db.js";import{describeMissing as Ee,loadEnv as T,readCredentials as Ae}from"./env.js";import{BishopError as I}from"./errors.js";import{fileStore as xe}from"./files.js";import{DEFAULT_MAX_AGE_DAYS as _e,makeCollector as Re,sweep as Ne}from"./gc.js";import{ghAuthLogin as Oe,ghCliIn as Ge,gitAuthenticatesToGithub as $e,withTemporaryGhConfig as Le}from"./github/gh.js";import{AGENT_SCOPES as Ce,checkGithubSetup as He}from"./github/setup.js";import{createGmail as Pe}from"./gmail/create.js";import{checkGmailSetup as De}from"./gmail/setup.js";import{createHarness as Me}from"./harness/create.js";import{sharedFileFetcher as Be}from"./interface/attachments.js";import{principalCheck as ee}from"./interface/authorize.js";import{deliveryRouter as Ue}from"./interface/delivery.js";import{conversationMatch as Fe,destinationResolver as Ke,directDestination as ze}from"./interface/destination.js";import{messageReader as je}from"./interface/messages.js";import{peopleFinder as qe}from"./interface/people.js";import{log as p,requestedLevel as Ye}from"./log.js";import{DEFAULT_PROFILE as We,setupNono as Je}from"./nono-setup.js";import{principalStore as Qe}from"./principals.js";import{startReviewer as Ve}from"./review.js";import{checkSandbox as Xe,clearedStaging as Ze,sandboxPolicy as et,writeLauncher as tt}from"./sandbox.js";import{addSchedule as ot,listSchedules as nt,removeSchedule as it,setScheduleEnabled as te}from"./schedule/cli.js";import{authorizedToRun as st,makeScheduler as rt}from"./schedule/runner.js";import{scheduleStore as at}from"./schedule/store.js";import{threadQueue as ct}from"./sessions/queue.js";import{interfaceState as pt,retentionStore as oe,sessionStore as dt,threadContexts as mt,threadHandover as lt,threadMeta as ht}from"./sessions/store.js";import{ensureGitignore as ut,openBrowser as ft,resolveAppDetails as wt,SetupError as ne,setupSlack as gt,setupSlackManually as yt,withPrompt as ie,writeEnv as se}from"./setup.js";import{createSlackInterface as kt}from"./slack/interface.js";import{buildManifest as St}from"./slack/manifest.js";import{createTeams as vt}from"./teams/create.js";import{administratorInstructions as bt,repointTeamsEndpoint as Tt,setupTeams as It,setupTeamsManually as Et}from"./teams/setup.js";import{threadModel as At}from"./thread-model.js";import{fileTools as xt}from"./tools/files.js";import{messageTools as _t}from"./tools/messages.js";import{peopleTools as Rt}from"./tools/people.js";import{scheduleTools as Nt}from"./tools/schedules.js";import{startToolServer as Ot}from"./tools/server.js";import{transcriptStore as Gt}from"./transcript.js";import{makeTurnRunner as $t}from"./turn.js";import{version as Lt}from"./version.js";import{hasGitIdentity as Ct,isGitRepo as Ht,sharedDirNotice as Pt,WORKTREE_DIR as Dt}from"./worktrees.js";function f(e){process.stderr.write(`${e}
3
- `),process.exit(1)}async function Mt(e){const t=ue(e??".");let n;try{n=(await le(t)).isDirectory()}catch{throw new I(`--agent directory doesn't exist: ${t}`)}if(!n)throw new I(`--agent is not a directory: ${t}`);return t}async function Bt(e){const t=await Ht(e),n={enabled:!0,isRepo:t};return t?(p.info({agentDir:e,worktrees:he(e,Dt)},"worktree mode is on"),await Ct(e)||p.warn({agentDir:e},"git has no user.name or user.email here, so the agent cannot commit what it does in a worktree"),n):(p.warn({agentDir:e},"worktree mode is on but the agent directory is not a git repository; threads share it"),n)}function Ut(e){if(e.kind==="options-replaced"){p.warn({harness:e.harness},`agent.harnesses.${e.harness} replaces agent.options, which is ignored for this run`);return}p.warn({harness:e.harness,configured:e.configured},`--harness overrides the configured harness, but agent.options is still written for that one; move it to agent.harnesses.${e.configured} and give ${e.harness} its own block`)}async function Ft(e=[],t={}){e.length>0&&f(`bishop: unknown command "${e[0]}"
2
+ import{stat as xe}from"node:fs/promises";import{join as Oe,resolve as Ne}from"node:path";import{Command as Re}from"commander";import{agentSnapshots as Le,fixedAgentDir as $e}from"./agent-dir.js";import{agentEnv as Ge}from"./agent-env.js";import{looksRemote as ie,parseRepoSpec as re}from"./agent-source.js";import{everyStore as ae,storePath as ce}from"./agent-store.js";import{attachmentStore as Me}from"./attachments.js";import{HARNESSES as Pe,loadConfig as M,nonEmptyFlag as de,parseHarnessName as Ce,positiveIntFlag as De,resolveAgent as pe,sandboxConfig as He,writeConfig as me}from"./config.js";import{dbPath as le,openDb as he}from"./db.js";import{createDecisionModel as Be,DEFAULT_DECISION_TIMEOUT_MS as Ue}from"./decision/model.js";import{describeDisabled as Fe,describeMissing as je,describeUnconfigured as Ke,loadEnv as R,readCredentials as ze}from"./env.js";import{BishopError as O}from"./errors.js";import{fileStore as qe}from"./files.js";import{DEFAULT_MAX_AGE_DAYS as Ye,makeCollector as We,sweep as Ve}from"./gc.js";import{ghAuthLogin as Je,ghCliIn as Qe,gitAuthenticatesToGithub as Xe,withTemporaryGhConfig as Ze}from"./github/gh.js";import{AGENT_SCOPES as et,checkGithubSetup as tt}from"./github/setup.js";import{createGmail as ot}from"./gmail/create.js";import{checkGmailSetup as nt}from"./gmail/setup.js";import{createHarness as st}from"./harness/create.js";import{sharedFileFetcher as it}from"./interface/attachments.js";import{canSchedule as rt,destinationCap as at,principalLevels as ct}from"./interface/authorize.js";import{deliveryRouter as dt}from"./interface/delivery.js";import{conversationMatch as pt,destinationResolver as mt,directDestination as lt}from"./interface/destination.js";import{messageReader as ht}from"./interface/messages.js";import{peopleFinder as ft}from"./interface/people.js";import{DEFAULT_REPLY_THRESHOLD as ut,replyGate as wt}from"./interface/reply-gate.js";import{messageSearcher as gt,SEARCH_HISTORY_TOOL as yt}from"./interface/search.js";import{log as c,requestedLevel as vt}from"./log.js";import{DEFAULT_PROFILE as kt,setupNono as bt}from"./nono-setup.js";import{listPermissions as St,setPermission as Tt}from"./permissions/cli.js";import{AmbiguousEntry as Et,EntryError as It,parseEntry as At}from"./permissions/entry.js";import{levelInstructions as _t}from"./permissions/instructions.js";import{isRunning as xt,lowest as Ot,RUNNING_LEVELS as I}from"./permissions/levels.js";import{permissions as Nt}from"./permissions/permissions.js";import{grantStore as Rt}from"./permissions/store.js";import{principalStore as Lt}from"./principals.js";import{startReviewer as $t}from"./review.js";import{checkSandbox as fe,clearedStaging as Gt,sandboxPolicy as Mt,writeLauncher as Pt}from"./sandbox.js";import{addSchedule as Ct,listSchedules as Dt,removeSchedule as Ht,setScheduleEnabled as ue}from"./schedule/cli.js";import{makeScheduler as Bt}from"./schedule/runner.js";import{scheduleStore as Ut}from"./schedule/store.js";import{threadQueue as Ft}from"./sessions/queue.js";import{interfaceState as jt,retentionStore as we,sessionStore as Kt,threadContexts as zt,threadHandover as qt,threadMeta as Yt}from"./sessions/store.js";import{ensureGitignore as Wt,openBrowser as Vt,resolveAppDetails as Jt,SetupError as ge,setupSlack as Qt,setupSlackManually as Xt,withPrompt as ye,writeEnv as ve}from"./setup.js";import{createSlackInterface as Zt}from"./slack/interface.js";import{buildManifest as eo}from"./slack/manifest.js";import{createTeams as to}from"./teams/create.js";import{administratorInstructions as oo,repointTeamsEndpoint as no,setupTeams as so,setupTeamsManually as io}from"./teams/setup.js";import{threadModel as ro}from"./thread-model.js";import{conversationTools as ao}from"./tools/conversations.js";import{fileTools as co}from"./tools/files.js";import{historyTools as po}from"./tools/history.js";import{messageTools as mo}from"./tools/messages.js";import{peopleTools as lo}from"./tools/people.js";import{scheduleTools as ho}from"./tools/schedules.js";import{startToolServer as fo}from"./tools/server.js";import{transcriptSearch as uo,transcriptStore as wo}from"./transcript.js";import{makeTurnRunner as go}from"./turn.js";import{version as yo}from"./version.js";import{hasGitIdentity as vo,isGitRepo as ko,sharedDirNotice as bo,WORKTREE_DIR as So}from"./worktrees.js";function w(e){process.stderr.write(`${e}
3
+ `),process.exit(1)}function To(e){const o=e.decisions;if(!o){c.info("no decision model is configured, so every message in a busy thread starts the agent; set decisions.model.provider to skip the ones that need no reply");return}const n=o.model;try{const a=Be({provider:n.provider,...n.name?{model:n.name}:{},...n.timeoutMs===void 0?{}:{timeoutMs:n.timeoutMs}});return c.info({provider:a.provider,model:a.model,keyVariable:a.keyVariable,timeoutMs:n.timeoutMs??Ue,threshold:o.reply?.threshold??ut},"decision model ready"),a}catch(a){throw a instanceof O&&w(a.message),a}}async function Eo(e){const o=Ne(e??".");let n;try{n=(await xe(o)).isDirectory()}catch{throw new O(`--agent directory doesn't exist: ${o}`)}if(!n)throw new O(`--agent is not a directory: ${o}`);return o}async function Io(e){const o=await ko(e),n={enabled:!0,isRepo:o};return o?(c.info({agentDir:e,worktrees:Oe(e,So)},"worktree mode is on"),await vo(e)||c.warn({agentDir:e},"git has no user.name or user.email here, so the agent cannot commit what it does in a worktree"),n):(c.warn({agentDir:e},"worktree mode is on but the agent directory is not a git repository; threads share it"),n)}async function Ao(e,o,n){const a=new Map(o.map(r=>[r.name,r])),s=[];for(const r of e){const m=At(r),l=a.get(m.interface);if(!l){c.warn({entry:r},"a permissions.admins entry names an interface that is not running");continue}try{s.push(await l.resolveSubject(m))}catch(p){if(p instanceof Et&&w(`permissions.admins: ${p.message}`),p instanceof It){c.warn({entry:r,err:p.message},"a permissions.admins entry matched nothing");continue}throw p}}n.bootstrap(s),c.info({admins:s.map(r=>r.label)},"resolved permissions.admins")}function ke(e){if(e.kind==="level-options-replaced"){c.warn({harness:e.harness,permission:e.level},`agent.permissionLevels.${e.level}.options layers over agent.options, which agent.harnesses.${e.harness} replaces, so it is ignored; move it to agent.permissionLevels.${e.level}.harnesses.${e.harness}.options`);return}if(e.kind==="flag-overrides-level"){c.info({permission:e.level,setting:e.setting},`--${e.setting} overrides agent.permissionLevels.${e.level}.${e.setting}`);return}if(e.kind==="options-replaced"){c.warn({harness:e.harness},`agent.harnesses.${e.harness} replaces agent.options, which is ignored for this run`);return}c.warn({harness:e.harness,configured:e.configured},`--harness overrides the configured harness, but agent.options is still written for that one; move it to agent.harnesses.${e.configured} and give ${e.harness} its own block`)}async function _o(e=[],o={}){e.length>0&&w(`bishop: unknown command "${e[0]}"
4
4
 
5
- Run \`bishop --help\` to see what's available.`);const n=process.cwd(),c=t.agent&&Y(t.agent)?W(t.agent):void 0;t.autoUpdate&&!c&&f("--auto-update needs --agent to be a git URL. Bishop never updates a directory it was pointed at; that state is yours to manage."),T(n);const i=await $(n),r=Ae();r.ok||f(Ee(r));const s=be(i,t);for(const o of s.warnings)Ut(o);const l=Te(i);if(l){const o=await Xe(l);p.info({nono:o,...l.profile?{profile:l.profile}:{}},"sandbox is on"),l.profile||p.warn("sandbox is enabled but agent.sandbox.profile is missing; run `bishop nono setup`")}const u=i.review?await Ve(i.review,{home:n}):void 0;u&&p.warn("review is configured, but this version only checks the reviewer at startup; no message is reviewed yet (#254)");const m=l?(o,d)=>et({home:n,cwd:o,...d?{dirKey:d}:{},...l.profile?{profile:l.profile}:{},...u?.unwritable.length?{unwritable:u.unwritable}:{}}):void 0,a=Z(X(n)),h=dt(a,s.harness);let x;const ae=async o=>await x?.check(o,await m?.(o))??{ok:!0},_=c?we({spec:c,store:Q(n,c.slug),dirs:h,autoUpdate:!!t.autoUpdate,recheck:ae}):void 0,y=_?await _.start():await Mt(t.agent),ce=_?_.forTurn:ge(y,h);p.info({bishopDir:n,agentDir:y,...y===n?{}:{separate:!0},...c?{source:c.cloneUrl,autoUpdate:!!t.autoUpdate}:{},app:i.slack?.app?.name},"bishop starting");const R=i.agent?.worktrees?await Bt(y):void 0,S=Me(s.harness,{...s.options?{options:s.options}:{},...s.model?{model:s.model}:{},...s.effort?{effort:s.effort}:{},...R?{worktrees:R}:{},...i.agent?.projectSettings===!1?{projectSettings:!1}:{},...l?{launcher:await tt(n)}:{},...s.keepAlive!==void 0?{keepAlive:s.keepAlive}:{},credentials:r.credentials}),N=await S.check(y,await m?.(y));N.ok||f(S.describeStartupFailure(y,N.error));const L=N.model??s.model;p.info({harness:S.name,credentials:N.credentialSource??"unreported",model:L,...s.effort?{effort:s.effort}:{},...s.options?{agentOptions:Object.keys(s.options)}:{},keepAlive:!!S.keepAlive},"harness ready"),x=S,p.info({sessions:h.count()},"opened session store");const D=Re({retention:oe(a),stores:()=>J(n),home:n,...i.gc?.maxAgeDays===void 0?{}:{maxAgeDays:i.gc.maxAgeDays}});D.start();let w,C;const pe=o=>w?ee(w,v)(o):st(o),de=async(o,d)=>{if(!w)throw new I("no interface is running, so there is nowhere to send");return Ke(w,{optedInOnly:!0})(o,d)},me=(o,d)=>w?Fe(w)(o,d):!1,M=xe({home:n,...i.files?.maxMb===void 0?{}:{maxMb:i.files.maxMb}}),B=ye(a),v=Qe(a),U=at(a),F=await Ot({tools:[...Nt({schedules:U,authorized:pe,resolve:de,sameConversation:me,principals:v}),...xt({fetch:Be({interfaces:()=>w??[],store:B,files:M})}),...r.credentials.slack?_t({read:je({interfaces:()=>w??[]})}):[],...r.credentials.teams?Rt({find:qe({interfaces:()=>w??[]})}):[]]}),O=ht(a),H=At(O),K={...L?{model:L}:{},...s.effort?{effort:s.effort}:{}},z=$t({harness:S,cwd:ce,sessions:h,model:H,tools:F,contexts:mt(a,O),transcript:Gt(a),principals:v,deliver:()=>C,...R&&!R.isRepo?{sharedDirNotice:Pt(y)}:{},...m?{sandbox:{policy:(o,d)=>m(o,d.dirKey),staging:await Ze(n)}}:{}}),j=ct(),E={threads:h,events:h,files:M,attachments:B,principals:v,run:o=>j.run(o.thread.threadKey,()=>z.run(o)),stop:o=>z.stop(o)},g=[];if(r.credentials.slack&&g.push(await kt({...E,credentials:r.credentials.slack,meta:O,model:H,configuredModel:K,...i.slack?.verbosity?{verbosity:i.slack.verbosity}:{},...i.slack?.allow?{allow:i.slack.allow}:{},...i.slack?.maxBotTurns===void 0?{}:{maxBotTurns:i.slack.maxBotTurns}})),r.credentials.gmail)try{g.push(await Pe({...E,credentials:r.credentials.gmail,...i.gmail?{config:i.gmail}:{},state:pt(a)}))}catch(o){o instanceof I&&f(o.message);const d=r.credentials.gmail,G=d.kind==="oauth"?"the authorized Gmail account":`${d.user}`;f(`Couldn't reach the mailbox for ${G}:
6
- ${o instanceof Error?o.message:String(o)}
5
+ Run \`bishop --help\` to see what's available.`);const n=process.cwd(),a=o.agent&&ie(o.agent)?re(o.agent):void 0;o.autoUpdate&&!a&&w("--auto-update needs --agent to be a git URL. Bishop never updates a directory it was pointed at; that state is yours to manage."),R(n);const s=await M(n),r=ze(s);r.ok||w(je(r));for(const t of r.unconfigured)c.warn({interface:t},Ke(t));for(const t of r.disabled)c.info({interface:t},Fe(t));const m=pe(s,o);for(const t of m.warnings)ke(t);const l=He(s),p=Object.fromEntries(I.map(t=>[t,pe(s,o,t)]));for(const t of I)for(const i of p[t].warnings)ke(i);if(l)for(const t of I){const i=p[t].sandboxProfile;i&&await fe({profile:i})}else c.warn("agent.sandbox is off, so permission levels hold only through the environment, the tools and what the agent is told: at any level the agent can read and write Bishop's .env, bishop.db, where levels live, and its config");if(l){const t=await fe(l);c.info({nono:t,...l.profile?{profile:l.profile}:{}},"sandbox is on"),l.profile||c.warn("sandbox is enabled but agent.sandbox.profile is missing; run `bishop nono setup`")}const u=s.review?await $t(s.review,{home:n}):void 0;u&&c.warn("review is configured, but this version only checks the reviewer at startup; no message is reviewed yet (#254)");const h=To(s),k=!!s.agent?.worktrees,N=l?(t,i,f)=>{const d=p[i].sandboxProfile??l.profile;return Mt({home:n,cwd:t,level:i,isolated:k,...f?{dirKey:f}:{},...d?{profile:d}:{},...u?.unwritable.length?{unwritable:u.unwritable}:{}})}:void 0,g=he(le(n)),b=Kt(g,m.harness);let z;const Te=async t=>{const i=await Promise.all(I.map(d=>N?.(t,d)));return(await Promise.all(I.map((d,j)=>z?.[d].check(t,i[j])))).find(d=>d&&!d.ok)??{ok:!0}},C=a?Le({spec:a,store:ce(n,a.slug),dirs:b,autoUpdate:!!o.autoUpdate,recheck:Te}):void 0,S=C?await C.start():await Eo(o.agent),Ee=C?C.forTurn:$e(S,b);c.info({bishopDir:n,agentDir:S,...S===n?{}:{separate:!0},...a?{source:a.cloneUrl,autoUpdate:!!o.autoUpdate}:{},app:s.slack?.app?.name},"bishop starting");const L=s.agent?.worktrees?await Io(S):void 0;!a&&!L&&c.warn({agentDir:S},"worktree mode is off, so a thread at write works in the agent's own directory and can change the agent itself; turn on agent.worktrees to keep write to a worktree");const q=l?await Pt(n):void 0,A={};for(const t of I){const i=p[t],{env:f,missing:d}=Ge(i.env);d.length>0&&c.warn({permission:t,missing:d},"agent.env.set names variables Bishop does not have, so the agent at this level goes without them"),A[t]=st(i.harness,{...i.options?{options:i.options}:{},...i.model?{model:i.model}:{},...i.effort?{effort:i.effort}:{},...L?{worktrees:L}:{},...s.agent?.projectSettings===!1?{projectSettings:!1}:{},...q?{launcher:q}:{},...i.keepAlive!==void 0?{keepAlive:i.keepAlive}:{},env:f,instructions:_t(t),...t==="read"?{readOnly:!0}:{},credentials:r.credentials})}const D=A.admin,H=await Promise.all(I.map(async t=>({level:t,check:await A[t].check(S,await N?.(S,t))})));for(const{level:t,check:i}of H)i.ok||w(`At the ${t} permission level:
6
+ `+A[t].describeStartupFailure(S,i.error));const Y=H.find(({level:t})=>t==="admin")?.check??{ok:!0},B=Y.model??m.model;c.info({harness:D.name,credentials:Y.credentialSource??"unreported",model:B,...m.effort?{effort:m.effort}:{},...m.options?{agentOptions:Object.keys(m.options)}:{},keepAlive:!!D.keepAlive},"harness ready"),z=A,c.info({sessions:b.count()},"opened session store");const W=We({retention:we(g),stores:()=>ae(n),home:n,...s.gc?.maxAgeDays===void 0?{}:{maxAgeDays:s.gc.maxAgeDays}});W.start();let y,U;const $=Yt(g),T=Lt(g),_=Nt({store:Rt(g),meta:$,principals:T,...s.permissions?.default?{fallback:s.permissions.default}:{}}),x=t=>y?ct(y,T,_)(t):t.startsWith("cli:")?"admin":"deny",Ie=rt(x),Ae=async(t,i)=>{if(!y)throw new O("no interface is running, so there is nowhere to send");return mt(y,{optedInOnly:!0})(t,i)},_e=(t,i)=>y?pt(y)(t,i):!1,V=qe({home:n,...s.files?.maxMb===void 0?{}:{maxMb:s.files.maxMb}}),J=Me(g),Q=Ut(g),X=await fo({tools:[...ho({schedules:Q,authorized:Ie,resolve:Ae,sameConversation:_e,principals:T}),...co({fetch:it({interfaces:()=>y??[],store:J,files:V})}),...r.credentials.slack?[...mo({read:ht({interfaces:()=>y??[]}),levelOf:x}),...po({search:gt({interfaces:()=>y??[]}),levelOf:x})]:[],...r.credentials.teams?lo({find:ft({interfaces:()=>y??[]})}):[],...r.credentials.slack||r.credentials.teams?ao({search:uo(g),principals:T,levelOf:x,...r.credentials.slack?{alongside:yt}:{}}):[]]}),F=ro($),Z={...B?{model:B}:{},...m.effort?{effort:m.effort}:{}},ee=Object.fromEntries(H.map(({level:t,check:i})=>{const f=i.model??p[t].model,d=p[t].effort;return[t,{...f?{model:f}:{},...d?{effort:d}:{}}]})),te=wo(g),oe=go({harness:D,harnesses:A,levels:_,cwd:Ee,sessions:b,model:F,tools:X,contexts:zt(g,$),transcript:te,principals:T,levelOf:x,deliver:()=>U,...L&&!L.isRepo?{sharedDirNotice:bo(S)}:{},...N?{sandbox:{policy:(t,i,f)=>N(t,f,i.dirKey),staging:await Gt(n)}}:{}}),ne=Ft(),G={threads:b,events:b,files:V,attachments:J,principals:T,permissions:_,run:t=>ne.run(t.thread.threadKey,()=>oe.run(t)),stop:t=>oe.stop(t),...h?{gate:wt({model:h,...s.decisions?.reply?.threshold===void 0?{}:{threshold:s.decisions.reply.threshold},...s.decisions?.reply?.instructions?{instructions:s.decisions.reply.instructions}:{},transcript:te,principals:T,touch:t=>b.touchDir(t)})}:{}},v=[];if(r.credentials.slack&&v.push(await Zt({...G,credentials:r.credentials.slack,meta:$,model:F,configuredModel:Z,configuredModelAt:ee,...s.slack?.verbosity?{verbosity:s.slack.verbosity}:{},...s.slack?.maxBotTurns===void 0?{}:{maxBotTurns:s.slack.maxBotTurns}})),r.credentials.gmail)try{v.push(await ot({...G,credentials:r.credentials.gmail,...s.gmail?{config:s.gmail}:{},state:jt(g)}))}catch(t){t instanceof O&&w(t.message);const i=r.credentials.gmail,f=i.kind==="oauth"?"the authorized Gmail account":`${i.user}`;w(`Couldn't reach the mailbox for ${f}:
7
+ ${t instanceof Error?t.message:String(t)}
7
8
 
8
- Run \`bishop gmail setup\` to check the credentials.`)}if(r.credentials.teams)try{g.push(await vt({...E,credentials:r.credentials.teams,meta:O,model:H,configuredModel:K,...i.teams?{config:i.teams}:{}}))}catch(o){o instanceof I&&f(o.message),f(`Couldn't start the Teams app for client ${r.credentials.teams.clientId}:
9
- ${o instanceof Error?o.message:String(o)}
9
+ Run \`bishop gmail setup\` to check the credentials.`)}if(r.credentials.teams)try{v.push(await to({...G,credentials:r.credentials.teams,meta:$,model:F,configuredModel:Z,configuredModelAt:ee,...s.teams?{config:s.teams}:{}}))}catch(t){t instanceof O&&w(t.message),w(`Couldn't start the Teams app for client ${r.credentials.teams.clientId}:
10
+ ${t instanceof Error?t.message:String(t)}
10
11
 
11
- Check the credentials in .env and the \`teams\` block in .bishop/config.json.`)}w=g,C=Ue(g);for(const o of g)await o.start();p.info({interfaces:g.map(o=>o.name)},"bishop is listening");const q=rt({schedules:U,run:E.run,threads:h,cancel:E.stop,deliver:C,authorized:ee(g,v),reach:ze(g,v),principals:v,attach:lt(h)});q.start();for(const o of["SIGINT","SIGTERM"])process.once(o,()=>{p.info({signal:o,inFlight:j.size},"shutting down"),q.stop().catch(d=>p.error({err:d},"the scheduler failed to stop cleanly")).then(()=>Promise.allSettled(g.map(d=>d.stop()))).then(async d=>{const G=d.filter(b=>b.status==="rejected");for(const b of G)p.error({err:b.reason},"an interface failed to stop cleanly");await S.keepAlive?.close().catch(b=>{p.error({err:b},"the processes kept alive failed to close cleanly")}),await F.stop().catch(b=>{p.error({err:b},"the tool endpoint failed to stop cleanly")}),await D.stop(),a.close(),process.exit(G.length>0?1:0)})})}function Kt(e){for(const t of e.snapshots)process.stdout.write(`removed snapshot ${t.commit} (unused for ${t.ageDays} days)
12
- `);for(const t of e.worktrees){const n=t.branch?`, branch ${t.branch}`:"";process.stdout.write(`released ${t.path}${n}
12
+ Check the credentials in .env and the \`teams\` block in .bishop/config.json.`)}y=v,U=dt(v),await Ao(s.permissions?.admins??[],v,_),_.fallback==="deny"&&!_.hasAdmin()&&w('Nobody is an admin, and permissions.default is deny, so nobody could use this agent or give anyone access. Add your own entry to permissions.admins in .bishop/config.json, like "slack:you@example.com", or run `bishop permissions set <entry> admin`.');for(const t of v)await t.start();c.info({interfaces:v.map(t=>t.name)},"bishop is listening");const se=Bt({schedules:Q,run:G.run,threads:b,cancel:G.stop,deliver:U,authorized:t=>xt(x(t)),firingLevel:async t=>{const i=await at(v,_)(t.destination);return Ot([x(t.createdBy),i])??"deny"},reach:lt(v,T),principals:T,attach:qt(b)});se.start();for(const t of["SIGINT","SIGTERM"])process.once(t,()=>{c.info({signal:t,inFlight:ne.size},"shutting down"),se.stop().catch(i=>c.error({err:i},"the scheduler failed to stop cleanly")).then(()=>Promise.allSettled(v.map(i=>i.stop()))).then(async i=>{const f=i.filter(d=>d.status==="rejected");for(const d of f)c.error({err:d.reason},"an interface failed to stop cleanly");await Promise.all(I.map(d=>A[d].keepAlive?.close().catch(j=>{c.error({err:j},"the processes kept alive failed to close cleanly")}))),await X.stop().catch(d=>{c.error({err:d},"the tool endpoint failed to stop cleanly")}),await W.stop(),g.close(),process.exit(f.length>0?1:0)})})}function xo(e){for(const o of e.snapshots)process.stdout.write(`removed snapshot ${o.commit} (unused for ${o.ageDays} days)
13
+ `);for(const o of e.worktrees){const n=o.branch?`, branch ${o.branch}`:"";process.stdout.write(`released ${o.path}${n}
13
14
  `)}process.stdout.write(`snapshots: removed ${e.snapshots.length}, kept ${e.keptSnapshots}
14
15
  worktrees: released ${e.worktrees.length}
15
16
  files: removed ${e.files} download directories
16
17
  rows: forgot ${e.threads} threads, ${e.events} events
17
- `)}async function zt(e){const t=process.cwd();T(t),e.agent&&!Y(e.agent)&&f("gc --agent takes the git URL Bishop cloned, not a path. It narrows the pass to the files Bishop owns for one agent, and it owns none for a directory agent. Run `bishop gc` with no --agent to collect what its threads left behind.");const n=e.agent?[Q(t,W(e.agent).slug)]:await J(t),c=await $(t),i=e.maxAgeDays??c.gc?.maxAgeDays;Ye()||(p.level="error");const r=Z(X(t));try{Kt(await Ne({retention:oe(r),stores:n,home:t,...e.agent?{only:n}:{},...i===void 0?{}:{maxAgeDays:i}}))}finally{r.close()}}function jt(){return!(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.env.SSH_CLIENT||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY)}async function qt(e={}){const t=process.cwd();T(t);const n=process.env.BISHOP_GMAIL_CLIENT_ID?.trim(),c=process.env.BISHOP_GMAIL_CLIENT_SECRET?.trim(),i=process.env.BISHOP_GMAIL_REFRESH_TOKEN?.trim(),r=process.env.BISHOP_GMAIL_USER?.trim(),s=process.env.BISHOP_GMAIL_SERVICE_ACCOUNT?.trim();n&&!c&&f("BISHOP_GMAIL_CLIENT_ID is set but BISHOP_GMAIL_CLIENT_SECRET is not.");const l=e.browser===!1||!jt()?"paste":"browser",u=await ie(!0,async m=>De({...n&&c?{client:{clientId:n,clientSecret:c}}:{},...i?{refreshToken:i}:{},...r?{user:r}:{},...s?{serviceAccount:s}:{},mode:l,openBrowser:ft,readPaste:async a=>(process.stdout.write(`Open this in a browser and approve it:
18
+ `)}async function Oo(e){const o=process.cwd();R(o),e.agent&&!ie(e.agent)&&w("gc --agent takes the git URL Bishop cloned, not a path. It narrows the pass to the files Bishop owns for one agent, and it owns none for a directory agent. Run `bishop gc` with no --agent to collect what its threads left behind.");const n=e.agent?[ce(o,re(e.agent).slug)]:await ae(o),a=await M(o),s=e.maxAgeDays??a.gc?.maxAgeDays;vt()||(c.level="error");const r=he(le(o));try{xo(await Ve({retention:we(r),stores:n,home:o,...e.agent?{only:n}:{},...s===void 0?{}:{maxAgeDays:s}}))}finally{r.close()}}function No(){return!(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.env.SSH_CLIENT||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY)}async function Ro(e={}){const o=process.cwd();R(o);const n=process.env.BISHOP_GMAIL_CLIENT_ID?.trim(),a=process.env.BISHOP_GMAIL_CLIENT_SECRET?.trim(),s=process.env.BISHOP_GMAIL_REFRESH_TOKEN?.trim(),r=process.env.BISHOP_GMAIL_USER?.trim(),m=process.env.BISHOP_GMAIL_SERVICE_ACCOUNT?.trim();n&&!a&&w("BISHOP_GMAIL_CLIENT_ID is set but BISHOP_GMAIL_CLIENT_SECRET is not.");const l=e.browser===!1||!No()?"paste":"browser",p=await ye(!0,async h=>nt({...n&&a?{client:{clientId:n,clientSecret:a}}:{},...s?{refreshToken:s}:{},...r?{user:r}:{},...m?{serviceAccount:m}:{},mode:l,openBrowser:Vt,readPaste:async k=>(process.stdout.write(`Open this in a browser and approve it:
18
19
 
19
- ${a}
20
+ ${k}
20
21
 
21
22
  It will finish on a http://127.0.0.1 address that fails to load. That is expected.
22
23
  Copy the whole address out of the browser and paste it here.
23
24
 
24
- `),m("Redirect URL",""))}));if(process.stdout.write(`${u.report}
25
- `),u.refreshToken){const m=await se(t,{BISHOP_GMAIL_REFRESH_TOKEN:u.refreshToken});process.stdout.write(`
26
- Saved BISHOP_GMAIL_REFRESH_TOKEN to ${m}
27
- `)}u.ok||process.exit(1)}async function Yt(e){const t=process.cwd(),n=process.env.GH_TOKEN?.trim();process.env.GH_TOKEN!==void 0&&!n&&delete process.env.GH_TOKEN,T(t);const c=process.env.GH_TOKEN?.trim(),i=!!c&&!n,r=e.prompt&&process.stdin.isTTY===!0,s=e.print?process.stderr:process.stdout,l=a=>s.write(a),u=a=>He({...c?{token:c,tokenIsSaved:i}:{},...r?{login:()=>Oe(Ce.map(h=>h.scope),a),confirm:async h=>/^y/i.test(await ie(!0,x=>x(h,"y"),s))}:{},gitConfigured:$e,gh:Ge(a),...e.temporary?{temporary:!0}:{}}),m=e.temporary&&!c?await Le(u):await u();if(l(`${m.report}
28
- `),e.print)m.token&&process.stdout.write(`${JSON.stringify({GH_TOKEN:m.token})}
29
- `);else if(m.token){if(m.source==="gh"){const h=await se(t,{GH_TOKEN:m.token});l(`
30
- Saved GH_TOKEN to ${h}
31
- `)}const a=await ut(t,[".env"]);a.length>0&&l(`Added ${a.join(", ")} to .gitignore
32
- `)}m.ok||process.exit(1)}async function Wt(e){const t=process.cwd(),n=await Je({config:await $(t),name:e.name});process.stdout.write(`${n.report}
33
- `),n.config&&process.stdout.write(`Saved ${await Ie(n.config,t)}
34
- `),n.ok||process.exit(1)}async function Jt(e){T(process.cwd());const t={...e.name===void 0?{}:{name:e.name},...e.displayName===void 0?{}:{displayName:e.displayName},...e.description===void 0?{}:{description:e.description},prompt:e.prompt};e.manual?await yt(t):await gt(t)}async function Qt(e){if(e.appId!==void 0&&!e.manual)throw new ne("--app-id adopts an app somebody else created, so it needs --manual too.");if(e.endpoint!==void 0&&e.manual)throw new ne("--endpoint sets the URL on an app Bishop is creating, so it cannot be used\nwith --manual. Point an adopted app with `bishop teams endpoint <url>`,\nor ask whoever created it to.");T(process.cwd());const t={...e.name===void 0?{}:{name:e.name},...e.displayName===void 0?{}:{displayName:e.displayName},...e.description===void 0?{}:{description:e.description},...e.endpoint===void 0?{}:{endpoint:e.endpoint},...e.appId===void 0?{}:{appId:e.appId},prompt:e.prompt};e.manual?await Et(t):await It(t)}async function Vt(e){const t=process.cwd(),n=await $(t),c=await wt({name:e.name??n.slack?.app?.name,displayName:e.displayName??n.slack?.app?.displayName,description:e.description??n.slack?.app?.description,prompt:!1},t,async(i,r)=>r);process.stdout.write(`${JSON.stringify(St(c),null,2)}
35
- `)}const k=new fe().name("bishop").description("An agent gateway. Runs an agent and connects it to Slack, email, and Teams.").version(Lt,"-v, --version").enablePositionalOptions().option("--agent <path-or-url>","the agent's directory, or a git URL to clone; defaults to the current directory").option(`--harness <${ke.join("|")}>`,"which SDK runs the agent",Se).option("--model <model>","the model to run, in the harness's own naming",V("--model")).option("--effort <effort>","how hard the model should think, in the harness's own naming",V("--effort")).option("--auto-update","for a git-URL --agent, check for a new commit at the start of every new thread").allowExcessArguments(!0).action((e,t)=>Ft(t.args,e));k.command("gc").description("Collect the snapshots, worktrees, and rows old conversations left behind").option("--max-age-days <days>",`how long a quiet thread's remains are kept; defaults to gc.maxAgeDays, then ${_e}`,ve("--max-age-days")).option("--agent <url>","only this agent's snapshots; defaults to every agent Bishop has cloned here").action(zt);const A=k.command("schedules").description("Prompts the agent runs on a clock, and where their answers go");A.command("list").description("Everything scheduled here, in your own time zone").action(()=>nt(process.cwd())),A.command("add").description("Add a schedule, or with --at a reminder that runs once and is then deleted").requiredOption("--name <name>","what a person sees in a list, and the subject of an email").option("--cron <expression>","five-field cron, or @daily and friends").option("--at <time>","run once instead, at an ISO 8601 time like 2026-10-09T15:00").requiredOption("--prompt <text>","what the agent is asked, including when to stay quiet").requiredOption("--to <destination>","#channel or @person for Slack, an address for Gmail").option("--tz <zone>","IANA zone --cron or --at is read in; defaults to this machine").option("--interface <name>","which interface delivers, when --to is ambiguous").action(e=>ot(process.cwd(),e)),A.command("rm <id>").description("Remove a schedule").action(e=>it(process.cwd(),e)),A.command("disable <id>").description("Stop a schedule firing, keeping it").action(e=>te(process.cwd(),e,!1)),A.command("enable <id>").description("Start a disabled schedule firing again, from now").action(e=>te(process.cwd(),e,!0));const Xt=k.command("gmail").description("Gmail interface commands");Xt.command("setup").description("Authorize a Gmail mailbox, or check the one already configured").option("--no-browser","print a URL to open elsewhere instead of opening one here").action(qt);const Zt=k.command("github").description("GitHub credentials for the agent");Zt.command("setup").description("Give the agent a GitHub token, or check the one it's using").option("--no-prompt","don't offer to run `gh auth login`").option("--print","write the credential to stdout as JSON instead of to .env").option("--temporary","log in without touching this machine's own gh login").action(Yt);const eo=k.command("nono").description("The nono sandbox the agent runs under");eo.command("setup").description("Write a nono profile that lets a sandboxed agent push").option("--name <name>","the profile name",We).action(Wt);const re=k.command("slack").description("Slack interface commands");re.command("setup").description("Create and install a Slack app, and save its credentials here").option("--name <name>","app name; defaults to the current directory name").option("--display-name <name>","bot display name in Slack; defaults to --name").option("--description <text>","short description shown in Slack").option("--no-prompt","don't prompt for anything left off").option("--manual","adopt an app you created in Slack yourself, using its tokens").action(Jt),re.command("manifest").description("Print the app manifest, for creating an app in Slack by hand").option("--name <name>","app name; defaults to config or the directory name").option("--display-name <name>","bot display name; defaults to --name").option("--description <text>","short description shown in Slack").action(Vt);const P=k.command("teams").description("Microsoft Teams interface commands");P.command("setup").description("Create a Teams app and save its credentials here, or check the one configured").option("--name <name>","app name; defaults to the current directory name").option("--display-name <name>","app name shown in Teams; defaults to --name").option("--description <text>","short description shown in Teams").option("--endpoint <url>","the URL Teams POSTs to; can be set later").option("--app-id <id>","with --manual, the Teams app ID you were given").option("--no-prompt","don't prompt for anything left off").option("--manual","adopt an app somebody else created, using its credentials").action(Qt),P.command("endpoint <url>").description("Point the Teams app at a different URL, changing nothing else").option("--app-id <id>","the Teams app to point; defaults to the one in config").action((e,t)=>Tt(e,t.appId===void 0?{}:{appId:t.appId})),P.command("instructions").description("Print what to send whoever creates the Teams app, when that is an administrator").option("--endpoint <url>","the URL Teams should POST to, if you already know it").action(e=>{process.stdout.write(bt(e.endpoint))});try{await k.parseAsync()}catch(e){throw e instanceof I&&f(e.message),e}
25
+ `),h("Redirect URL",""))}));if(process.stdout.write(`${p.report}
26
+ `),p.refreshToken){const h=await ve(o,{BISHOP_GMAIL_REFRESH_TOKEN:p.refreshToken});process.stdout.write(`
27
+ Saved BISHOP_GMAIL_REFRESH_TOKEN to ${h}
28
+ `)}p.ok||process.exit(1);const u=await M(o);if(!u.gmail){const h=await me({...u,gmail:{}},o);process.stdout.write(`
29
+ Added a "gmail" block to ${h}, so Bishop starts Gmail
30
+ `)}}async function Lo(e){const o=process.cwd(),n=process.env.GH_TOKEN?.trim();process.env.GH_TOKEN!==void 0&&!n&&delete process.env.GH_TOKEN,R(o);const a=process.env.GH_TOKEN?.trim(),s=!!a&&!n,r=e.prompt&&process.stdin.isTTY===!0,m=e.print?process.stderr:process.stdout,l=h=>m.write(h),p=h=>tt({...a?{token:a,tokenIsSaved:s}:{},...r?{login:()=>Je(et.map(k=>k.scope),h),confirm:async k=>/^y/i.test(await ye(!0,N=>N(k,"y"),m))}:{},gitConfigured:Xe,gh:Qe(h),...e.temporary?{temporary:!0}:{}}),u=e.temporary&&!a?await Ze(p):await p();if(l(`${u.report}
31
+ `),e.print)u.token&&process.stdout.write(`${JSON.stringify({GH_TOKEN:u.token})}
32
+ `);else if(u.token){if(u.source==="gh"){const k=await ve(o,{GH_TOKEN:u.token});l(`
33
+ Saved GH_TOKEN to ${k}
34
+ `)}const h=await Wt(o,[".env"]);h.length>0&&l(`Added ${h.join(", ")} to .gitignore
35
+ `)}u.ok||process.exit(1)}async function $o(e){const o=process.cwd(),n=await bt({config:await M(o),name:e.name});process.stdout.write(`${n.report}
36
+ `),n.config&&process.stdout.write(`Saved ${await me(n.config,o)}
37
+ `),n.ok||process.exit(1)}async function Go(e){R(process.cwd());const o={...e.name===void 0?{}:{name:e.name},...e.displayName===void 0?{}:{displayName:e.displayName},...e.description===void 0?{}:{description:e.description},...e.admin===void 0?{}:{admin:e.admin},prompt:e.prompt};e.manual?await Xt(o):await Qt(o)}async function Mo(e){if(e.appId!==void 0&&!e.manual)throw new ge("--app-id adopts an app somebody else created, so it needs --manual too.");if(e.endpoint!==void 0&&e.manual)throw new ge("--endpoint sets the URL on an app Bishop is creating, so it cannot be used\nwith --manual. Point an adopted app with `bishop teams endpoint <url>`,\nor ask whoever created it to.");R(process.cwd());const o={...e.name===void 0?{}:{name:e.name},...e.displayName===void 0?{}:{displayName:e.displayName},...e.description===void 0?{}:{description:e.description},...e.endpoint===void 0?{}:{endpoint:e.endpoint},...e.appId===void 0?{}:{appId:e.appId},...e.admin===void 0?{}:{admin:e.admin},prompt:e.prompt};e.manual?await io(o):await so(o)}async function Po(e){const o=process.cwd(),n=await M(o),a=await Jt({name:e.name??n.slack?.app?.name,displayName:e.displayName??n.slack?.app?.displayName,description:e.description??n.slack?.app?.description,prompt:!1},o,async(s,r)=>r);process.stdout.write(`${JSON.stringify(eo(a),null,2)}
38
+ `)}const E=new Re().name("bishop").description("An agent gateway. Runs an agent and connects it to Slack, email, and Teams.").version(yo,"-v, --version").enablePositionalOptions().option("--agent <path-or-url>","the agent's directory, or a git URL to clone; defaults to the current directory").option(`--harness <${Pe.join("|")}>`,"which SDK runs the agent",Ce).option("--model <model>","the model to run, in the harness's own naming",de("--model")).option("--effort <effort>","how hard the model should think, in the harness's own naming",de("--effort")).option("--auto-update","for a git-URL --agent, check for a new commit at the start of every new thread").allowExcessArguments(!0).action((e,o)=>_o(o.args,e));E.command("gc").description("Collect the snapshots, worktrees, and rows old conversations left behind").option("--max-age-days <days>",`how long a quiet thread's remains are kept; defaults to gc.maxAgeDays, then ${Ye}`,De("--max-age-days")).option("--agent <url>","only this agent's snapshots; defaults to every agent Bishop has cloned here").action(Oo);const P=E.command("schedules").description("Prompts the agent runs on a clock, and where their answers go");P.command("list").description("Everything scheduled here, in your own time zone").action(()=>Dt(process.cwd())),P.command("add").description("Add a schedule, or with --at a reminder that runs once and is then deleted").requiredOption("--name <name>","what a person sees in a list, and the subject of an email").option("--cron <expression>","five-field cron, or @daily and friends").option("--at <time>","run once instead, at an ISO 8601 time like 2026-10-09T15:00").requiredOption("--prompt <text>","what the agent is asked, including when to stay quiet").requiredOption("--to <destination>","#channel or @person for Slack, an address for Gmail").option("--tz <zone>","IANA zone --cron or --at is read in; defaults to this machine").option("--interface <name>","which interface delivers, when --to is ambiguous").action(e=>Ct(process.cwd(),e)),P.command("rm <id>").description("Remove a schedule").action(e=>Ht(process.cwd(),e)),P.command("disable <id>").description("Stop a schedule firing, keeping it").action(e=>ue(process.cwd(),e,!1)),P.command("enable <id>").description("Start a disabled schedule firing again, from now").action(e=>ue(process.cwd(),e,!0));const be=E.command("permissions").description("Who has which permission level");be.command("list").description("The default level, the configured admins, and every level set in the database").action(()=>St(process.cwd())),be.command("set <entry> <level>").description("Give a person, group or channel a level (deny, read, write, admin), or `default` to remove its own. Names need a running Bishop; use an address, a domain or an ID here").action((e,o)=>Tt(process.cwd(),e,o));const Co=E.command("gmail").description("Gmail interface commands");Co.command("setup").description("Authorize a Gmail mailbox, or check the one already configured").option("--no-browser","print a URL to open elsewhere instead of opening one here").action(Ro);const Do=E.command("github").description("GitHub credentials for the agent");Do.command("setup").description("Give the agent a GitHub token, or check the one it's using").option("--no-prompt","don't offer to run `gh auth login`").option("--print","write the credential to stdout as JSON instead of to .env").option("--temporary","log in without touching this machine's own gh login").action(Lo);const Ho=E.command("nono").description("The nono sandbox the agent runs under");Ho.command("setup").description("Write a nono profile that lets a sandboxed agent push").option("--name <name>","the profile name",kt).action($o);const Se=E.command("slack").description("Slack interface commands");Se.command("setup").description("Create and install a Slack app, and save its credentials here").option("--name <name>","app name; defaults to the current directory name").option("--display-name <name>","bot display name in Slack; defaults to --name").option("--description <text>","short description shown in Slack").option("--no-prompt","don't prompt for anything left off").option("--manual","adopt an app you created in Slack yourself, using its tokens").option("--admin <entry>","your own entry, like slack:you@example.com, made the first admin when there is none").action(Go),Se.command("manifest").description("Print the app manifest, for creating an app in Slack by hand").option("--name <name>","app name; defaults to config or the directory name").option("--display-name <name>","bot display name; defaults to --name").option("--description <text>","short description shown in Slack").action(Po);const K=E.command("teams").description("Microsoft Teams interface commands");K.command("setup").description("Create a Teams app and save its credentials here, or check the one configured").option("--name <name>","app name; defaults to the current directory name").option("--display-name <name>","app name shown in Teams; defaults to --name").option("--description <text>","short description shown in Teams").option("--endpoint <url>","the URL Teams POSTs to; can be set later").option("--app-id <id>","with --manual, the Teams app ID you were given").option("--no-prompt","don't prompt for anything left off").option("--manual","adopt an app somebody else created, using its credentials").option("--admin <entry>","your own entry, like teams:you@example.com, made the first admin when there is none").action(Mo),K.command("endpoint <url>").description("Point the Teams app at a different URL, changing nothing else").option("--app-id <id>","the Teams app to point; defaults to the one in config").action((e,o)=>no(e,o.appId===void 0?{}:{appId:o.appId})),K.command("instructions").description("Print what to send whoever creates the Teams app, when that is an administrator").option("--endpoint <url>","the URL Teams should POST to, if you already know it").action(e=>{process.stdout.write(oo(e.endpoint))});try{await E.parseAsync()}catch(e){throw e instanceof O&&w(e.message),e}
@@ -1,3 +1,5 @@
1
- import{Command as N,CommanderError as C,InvalidArgumentError as g}from"commander";import{VERBOSITY as b}from"../config.js";import{parseVerbosity as O}from"../interface/verbosity.js";import{log as w}from"../log.js";import{isHarnessName as L,MODEL_SETTINGS as E}from"../thread-model.js";import{commandOutput as S,tokenize as j}from"./syntax.js";const a="default";function k(o){if(o.trim().toLowerCase()===a)return a;const e=O(o);if(!e)throw new g(`Use one of ${b.join(", ")}, or ${a}.`);return e}function u(o){const e=o.trim();if(!e)throw new g(`Name one, or ${a} to follow the configured one.`);if(!L(e))throw new g(`"${e}" is not a model name. Letters, digits, and . : / @ - _ only.`);return e}function T(o,e,r){return e?`${o} is ${e}, set in this thread`:r?`${o} is ${r}, the default`:`${o} is whatever the harness runs by default`}function I(o,e){const r=e.model.of(o);return[T("Model",r.model,e.configured.model),T("Effort",r.effort,e.configured.effort)]}function G(o,e,r){const l=[];let h;const d=new N;d.name("!").description("Bishop commands. These are handled here and never reach the agent.").exitOverride().configureOutput({writeOut:t=>l.push(t),writeErr:t=>l.push(t),outputError:(t,n)=>n(t)}),d.command("verbosity").description("How much of a turn this thread shows while it is running.").argument("[level]",`${b.join(", ")}, or ${a} to follow the configured level. Omit it to see the current one.`,k).action(t=>{if(!t){const c=r.verbosity.of(e.thread.id),s=c.fromThread?"":" (the configured default)";h=`Thread verbosity is ${c.level}${s}`;return}if(t===a){r.verbosity.clear(e.thread.id),h=`Thread verbosity follows the configured default, which is ${r.verbosity.of(e.thread.id).level}`;return}const n=O(t);n&&(r.verbosity.set(e.thread.id,n),h=`Thread verbosity set to ${n}`)}),d.command("stop").description("Stops the turn running in this thread. Messages waiting behind it still run.").action(()=>{const t=r.stop(e.thread.threadKey);w.info({thread:e.thread.threadKey,stopped:t},"stop requested by command"),h=t?"Stopping the turn running in this thread":"Nothing is running in this thread"}),d.command("model").description("Which model this thread runs, and how hard it thinks.").argument("[model]",`a model name in the harness's own naming, or ${a} to follow the configured one. Omit everything to see where the thread stands.`,u).argument("[effort]",`how hard it should think, in the harness's own naming, or ${a}.`,u).option("-m, --model <model>","the model, named as a flag rather than in order",u).option("-e, --effort <effort>","the effort, named as a flag rather than in order",u).action((t,n,c)=>{const s=e.thread.id,f={...c},p=E.filter(i=>f[i]===void 0),v=[t,n].filter(i=>i!==void 0);if(v.length>p.length){h="Name each half once: a model and an effort, in order or as flags.";return}if(v.forEach((i,m)=>{const $=p[m];$&&(f[$]=i)}),!f.model&&!f.effort){h=I(s,r).join(`
2
- `);return}const y={};for(const i of E){const m=f[i];m&&(m.toLowerCase()===a?r.model.clear(s,i):y[i]=m)}r.model.set(s,y),w.info({thread:e.thread.threadKey,...f},"a thread changed the model it runs"),h=["Set. It takes effect on this thread's next turn.",...I(s,r)].join(`
3
- `)});try{d.parse(j(o),{from:"user"})}catch(t){if(!(t instanceof C)){const n=t instanceof Error?t.message:String(t);return w.debug({thread:e.thread.threadKey,line:o,err:t},"a command failed"),S(n)}}return S(h??(l.join("").trim()||d.helpInformation()))}export{G as runCommand};
1
+ import{Command as A,CommanderError as M,InvalidArgumentError as w}from"commander";import{VERBOSITY as I}from"../config.js";import{parseVerbosity as L}from"../interface/verbosity.js";import{log as g}from"../log.js";import{EntryError as N,parseEntry as Y}from"../permissions/entry.js";import{atLeast as j,LEVELS as S,parseLevel as _}from"../permissions/levels.js";import{CONFIG_GRANTOR as C}from"../permissions/permissions.js";import{isHarnessName as F,MODEL_SETTINGS as B}from"../thread-model.js";import{commandOutput as $,tokenize as R}from"./syntax.js";const s="default";function U(n){if(n.trim().toLowerCase()===s)return s;const e=L(n);if(!e)throw new w(`Use one of ${I.join(", ")}, or ${s}.`);return e}function p(n){const e=n.trim();if(!e)throw new w(`Name one, or ${s} to follow the configured one.`);if(!F(e))throw new w(`"${e}" is not a model name. Letters, digits, and . : / @ - _ only.`);return e}function G(n,e,t){return e?`${n} is ${e}, set in this thread`:t?`${n} is ${t}, the default`:`${n} is whatever the harness runs by default`}function K(n,e,t){const h=t&&e.configuredAt?.[t]||e.configured,i=e.model.of(n);return[G("Model",i.model,h.model),G("Effort",i.effort,h.effort)]}async function re(n,e,t){const h=[];let i,o;const a=new A;a.name("!").description("Bishop commands. These are handled here and never reach the agent.").exitOverride().configureOutput({writeOut:r=>h.push(r),writeErr:r=>h.push(r),outputError:(r,d)=>d(r)}),a.command("verbosity").description("How much of a turn this thread shows while it is running.").argument("[level]",`${I.join(", ")}, or ${s} to follow the configured level. Omit it to see the current one.`,U).action(r=>{if(!r){const f=t.verbosity.of(e.thread.id),c=f.fromThread?"":" (the configured default)";i=`Thread verbosity is ${f.level}${c}`;return}if(r===s){t.verbosity.clear(e.thread.id),i=`Thread verbosity follows the configured default, which is ${t.verbosity.of(e.thread.id).level}`;return}const d=L(r);d&&(t.verbosity.set(e.thread.id,d),i=`Thread verbosity set to ${d}`)}),a.command("stop").description("Stops the turn running in this thread and the background work the agent left running in it, like subagents. Messages waiting behind a turn still run.").action(()=>{const r=t.stop(e.thread.threadKey);g.info({thread:e.thread.threadKey,stopped:r},"stop requested by command"),i=r?"Stopping what the agent is running in this thread":"Nothing is running in this thread"}),a.command("model").description("Which model this thread runs, and how hard it thinks.").argument("[model]",`a model name in the harness's own naming, or ${s} to follow the configured one. Omit everything to see where the thread stands.`,p).argument("[effort]",`how hard it should think, in the harness's own naming, or ${s}.`,p).option("-m, --model <model>","the model, named as a flag rather than in order",p).option("-e, --effort <effort>","the effort, named as a flag rather than in order",p).action((r,d,f)=>{const c=e.thread.id,m={...f},k=B.filter(l=>m[l]===void 0),E=[r,d].filter(l=>l!==void 0);if(E.length>k.length){i="Name each half once: a model and an effort, in order or as flags.";return}if(E.forEach((l,u)=>{const T=k[u];T&&(m[T]=l)}),!m.model&&!m.effort){i=K(c,t,e.level).join(`
2
+ `);return}const v=e.sender?.level.level;if(v&&!j(v,"write")){i=`Changing the model needs write, and you're at ${v}.`;return}const O={};for(const l of B){const u=m[l];u&&(u.toLowerCase()===s?t.model.clear(c,l):O[l]=u)}t.model.set(c,O),g.info({thread:e.thread.threadKey,...m},"a thread changed the model it runs"),i=["Set. It takes effect on this thread's next turn.",...K(c,t,e.level)].join(`
3
+ `)});const y=t.permissions;if(y){const r=a.command("permissions").description("Who may direct the agent, and how much it may do for them.");r.command("set").description(`Gives a person, a group or a location a level. Needs admin. ${s} removes the one it has.`).argument("<who>","an entry, like @dana, #eng, *@example.com or slack:<U0123>").argument("<level>",`${S.join(", ")}, or ${s}`,V).action((d,f)=>{o=H(d,f,e,y)}),r.command("info").description("This thread's level and yours, or one entry's level.").argument("[who]","an entry, to see its level instead").action(d=>{o=z(d,e,y,t)})}try{a.parse(R(n),{from:"user"})}catch(r){if(!(r instanceof M)){const d=r instanceof Error?r.message:String(r);return g.debug({thread:e.thread.threadKey,line:n,err:r},"a command failed"),$(d)}}if(o)try{i=await o}catch(r){const d=r instanceof Error?r.message:String(r);return r instanceof N||g.warn({thread:e.thread.threadKey,line:n,err:r},"a command failed"),$(d)}return $(i??(h.join("").trim()||a.helpInformation()))}function V(n){if(n.trim().toLowerCase()===s)return s;const e=_(n);if(!e)throw new w(`Use one of ${S.join(", ")}, or ${s}.`);return e}async function W(n,e){if(!e.resolve)throw new N("Entries can't be looked up from here.");const t=Y(n,e.interface?{defaultInterface:e.interface}:{});return e.resolve(t)}function b(n,e){return n.grantedBy===C?"permissions.admins":e.nameOf?.(n.grantedBy)??n.grantedBy}function D(n,e,t){switch(e.from){case"own":return`You're at ${n}, set for you by ${b(e.grant,t)}.`;case"group":return`You're at ${n}, from the group ${e.grant.label}, set by ${b(e.grant,t)}.`;case"default":return`You're at ${n}, from permissions.default.`}}function x(n){return n.kind==="location"?"It doesn't cap the threads started there.":n.kind==="group"?"Its members' levels come from elsewhere.":"Their groups decide, or permissions.default when they're in none."}async function H(n,e,t,h){const i=t.sender?.level.level;if(!t.sender||i!=="admin")return`Setting levels needs admin, and you're at ${i??"no known level"}.`;const o=await W(n,t);if(h.grant(o)?.grantedBy===C)return`${o.label} is an admin in permissions.admins, which wins over anything set here.`;if(h.set(o,e===s?"default":e,t.sender.id),g.info({subject:o.label,interface:o.interface,permission:e,by:t.sender.id},"a permission level was set by command"),e===s)return`No level is set for ${o.label} now. ${x(o)}`;const a=[`${o.label} is at ${e} now.`];return o.kind==="group"&&a.push("A member's own level wins over a group's, and someone in more than one group gets the lowest of them."),o.kind==="location"&&a.push("Threads already running there keep their level, and any above this one stop answering until it is raised again."),o.kind==="pending"&&a.push("If Bishop has seen them under that name it applies now, and otherwise the first time it does."),a.join(`
4
+ `)}async function z(n,e,t,h){if(n){const o=await W(n,e),a=t.grant(o);return a?`${o.label} is at ${a.level}, set by ${b(a,h)}.`:`No level is set for ${o.label}. ${x(o)}`}const i=[e.level?`This thread runs at ${e.level}.`:"This thread hasn't started, so it has no level yet."];if(e.location&&i.push(e.level&&!j(e.location,e.level)?`This channel is at ${e.location}, so only commands reach this thread until it is raised.`:`This channel is at ${e.location}, which caps new threads here.`),e.sender){const{level:o,source:a}=e.sender.level;i.push(D(o,a,h))}return i.push(`permissions.default is ${t.fallback}.`),i.join(`
5
+ `)}export{re as runCommand};
package/dist/config.js CHANGED
@@ -1,4 +1,4 @@
1
- import{mkdir as v,readFile as y,writeFile as O}from"node:fs/promises";import{dirname as j,join as $}from"node:path";import{z as t}from"zod";import{BishopError as c}from"./errors.js";const E=".bishop",R="config.json",I=t.strictObject({id:t.string().optional(),name:t.string().min(1),displayName:t.string().optional(),description:t.string().optional()}),N=["low","medium","high"],K="high",h=t.string().transform(n=>n.trim().toLowerCase()).pipe(t.enum(N)),S=t.strictObject({workspace:t.string().optional(),app:I.optional(),verbosity:h.optional(),allow:t.array(t.string().min(1)).optional(),maxBotTurns:t.number().int().nonnegative().optional()}),A=t.strictObject({allow:t.array(t.string().min(1)).optional(),pollSeconds:t.number().int().positive().optional(),labelPrefix:t.string().trim().min(1).optional(),markRead:t.boolean().optional(),internalDomains:t.array(t.string().trim().toLowerCase().regex(/^[^\s@]+\.[^\s@]+$/,"must be a domain like example.com")).optional()}),C=t.strictObject({cert:t.string().trim().min(1),key:t.string().trim().min(1)}),_=t.strictObject({id:t.string().optional(),name:t.string().min(1),displayName:t.string().optional(),description:t.string().optional()}),F=t.strictObject({app:_.optional(),allow:t.array(t.string().min(1)).optional(),verbosity:h.optional(),port:t.number().int().min(1).max(65535).optional(),host:t.string().trim().min(1).optional(),tls:C.optional()}),p=["claude","codex"],T=t.union([t.literal(!1),t.strictObject({idleMinutes:t.number().positive().max(10080).optional(),max:t.number().int().positive().optional()})]),L=t.strictObject({model:t.string().trim().min(1).optional(),effort:t.string().trim().min(1).optional(),options:t.record(t.string(),t.unknown()).optional(),keepAlive:T.optional()}),z=t.strictObject({harness:t.enum(p).optional(),model:t.string().trim().min(1).optional(),effort:t.string().trim().min(1).optional(),harnesses:t.partialRecord(t.enum(p),L,{error:()=>`not a harness Bishop runs; supported: ${p.join(", ")}`}).superRefine((n,o)=>{n.codex?.keepAlive!==void 0&&o.addIssue({code:"custom",path:["codex","keepAlive"],message:"only the claude harness keeps an agent running between turns"})}).optional(),worktrees:t.boolean().optional(),projectSettings:t.boolean().optional(),sandbox:t.union([t.boolean(),t.strictObject({profile:t.string().trim().min(1).optional()})]).optional(),options:t.record(t.string(),t.unknown()).optional()}),B=t.strictObject({maxAgeDays:t.number().int().positive().optional()}),D=t.strictObject({maxMb:t.number().positive().optional()}),U=["all","external"],V=["reject","approve"],b=t.strictObject({scope:t.enum(U).optional(),onError:t.enum(V).optional()});function G(n){let o;try{o=new URL(n)}catch{return!1}return o.protocol==="https:"?!0:o.protocol!=="http:"?!1:o.hostname==="localhost"||o.hostname==="[::1]"||/^127(\.\d{1,3}){3}$/.test(o.hostname)}const P=t.strictObject({command:t.array(t.string().min(1)).min(1).optional(),url:t.string().trim().refine(G,"must be an https URL, or http on loopback").optional(),inbound:b.optional(),outbound:b.optional(),timeoutSeconds:t.number().positive().max(300).optional(),env:t.array(t.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/,"must be an environment variable name")).optional()}).superRefine((n,o)=>{n.command&&n.url?o.addIssue({code:"custom",message:"names both command and url; pick one"}):!n.command&&!n.url&&o.addIssue({code:"custom",message:"needs a command or a url"}),n.url&&n.env&&o.addIssue({code:"custom",path:["env"],message:"is only for a command reviewer"}),!n.inbound&&!n.outbound&&o.addIssue({code:"custom",message:"reviews nothing without inbound or outbound"})}),H=t.strictObject({slack:S.optional(),gmail:A.optional(),teams:F.optional(),agent:z.optional(),files:D.optional(),gc:B.optional(),review:P.optional()}).superRefine((n,o)=>{n.review&&!n.agent?.sandbox&&o.addIssue({code:"custom",path:["review"],message:"needs agent.sandbox on"})});class m extends c{path;constructor(o,e){super(o,"ConfigError"),this.path=e}}function q(n,o={}){const e=n.agent,i=e?.harness??"claude",r=o.harness??i,s=e?.harnesses?.[r],{keepAlive:x,...k}=s??{},a=s&&Object.keys(k).length>0?s:void 0,l=[];e?.options&&(a&&r===i?l.push({kind:"options-replaced",harness:r}):!a&&r!==i&&l.push({kind:"options-foreign",harness:r,configured:i}));const u=o.model??a?.model??e?.model,d=o.effort??a?.effort??e?.effort,g=a?a.options:e?.options,f=r==="claude"?x:void 0;return{harness:r,...u?{model:u}:{},...d?{effort:d}:{},...g?{options:g}:{},...f!==void 0?{keepAlive:f}:{},warnings:l}}function Q(n){const o=n.agent?.sandbox;if(o)return o===!0||!o.profile?{}:{profile:o.profile}}function X(n){return o=>{const e=o.trim();if(!e)throw new c(`${n} needs a value`);return e}}function tt(n){return o=>{const e=Number(o.trim());if(!Number.isInteger(e)||e<=0)throw new c(`${n} needs a positive whole number, got "${o}"`);return e}}function ot(n){const o=n.trim();if(p.includes(o))return o;throw new c(`unknown harness "${n}"; supported: ${p.join(", ")}`)}function w(n=process.cwd()){return $(n,E,R)}function J(n){return n.issues.flatMap(o=>{if(o.code==="unrecognized_keys"&&o.keys.length>0){const e=o.message.startsWith("Unrecognized key")?"unrecognized key":o.message;return o.keys.map(i=>`${[...o.path,i].join(".")}: ${e}`)}return[`${o.path.length>0?o.path.join("."):"(root)"}: ${o.message}`]}).join(`
2
- `)}async function nt(n=process.cwd()){const o=w(n);let e;try{e=await y(o,"utf8")}catch(s){if(s.code==="ENOENT")return{};throw new m(`Couldn't read ${o}: ${s.message}`,o)}let i;try{i=JSON.parse(e)}catch(s){throw new m(`${o} isn't valid JSON: ${s.message}`,o)}const r=H.safeParse(i);if(!r.success)throw new m(`${o} has invalid values:
3
- ${J(r.error)}`,o);return r.data}async function et(n,o=process.cwd()){const e=w(o);return await v(j(e),{recursive:!0}),await O(e,`${JSON.stringify(n,null,2)}
4
- `,"utf8"),e}function rt(n){return n.displayName?.trim()||n.name}export{E as CONFIG_DIR,R as CONFIG_FILE,m as ConfigError,H as ConfigSchema,K as DEFAULT_VERBOSITY,p as HARNESSES,V as REVIEW_ON_ERROR,U as REVIEW_SCOPES,N as VERBOSITY,w as configPath,rt as displayNameOf,nt as loadConfig,X as nonEmptyFlag,ot as parseHarnessName,tt as positiveIntFlag,q as resolveAgent,Q as sandboxConfig,et as writeConfig};
1
+ import{mkdir as z,readFile as T,writeFile as B}from"node:fs/promises";import{dirname as D,join as F}from"node:path";import{z as t}from"zod";import{DECISION_PROVIDERS as A}from"./decision/model.js";import{BishopError as u}from"./errors.js";import{EntryError as P,parseEntry as V}from"./permissions/entry.js";import{LEVELS as U,RUNNING_LEVELS as M}from"./permissions/levels.js";const Z=".bishop",G="config.json",H=t.strictObject({id:t.string().optional(),name:t.string().min(1),displayName:t.string().optional(),description:t.string().optional()}),J=["low","medium","high"],At="high",R=t.string().transform(o=>o.trim().toLowerCase()).pipe(t.enum(J)),g=t.boolean().optional(),W=t.strictObject({enabled:g,workspace:t.string().optional(),app:H.optional(),verbosity:R.optional(),maxBotTurns:t.number().int().nonnegative().optional()}),Y=t.strictObject({enabled:g,pollSeconds:t.number().int().positive().optional(),labelPrefix:t.string().trim().min(1).optional(),markRead:t.boolean().optional(),internalDomains:t.array(t.string().trim().toLowerCase().regex(/^[^\s@]+\.[^\s@]+$/,"must be a domain like example.com")).optional()}),K=t.strictObject({cert:t.string().trim().min(1),key:t.string().trim().min(1)}),q=t.strictObject({id:t.string().optional(),name:t.string().min(1),displayName:t.string().optional(),description:t.string().optional()}),Q=t.strictObject({enabled:g,app:q.optional(),verbosity:R.optional(),port:t.number().int().min(1).max(65535).optional(),host:t.string().trim().min(1).optional(),tls:K.optional(),healthPath:t.string().trim().refine(o=>{try{return new URL(o,"http://localhost").pathname===o}catch{return!1}},"must be a plain path starting with /, like /healthz").optional()}),c=["claude","codex"],X=t.union([t.literal(!1),t.strictObject({idleMinutes:t.number().positive().max(10080).optional(),max:t.number().int().positive().optional()})]),tt=t.strictObject({model:t.string().trim().min(1).optional(),effort:t.string().trim().min(1).optional(),options:t.record(t.string(),t.unknown()).optional(),keepAlive:X.optional()}),S=t.string().trim().regex(/^[A-Za-z_*][A-Za-z0-9_*]*$/,"must be a variable name, with * for any run of characters"),$=t.strictObject({allow:t.array(S).optional(),deny:t.array(S).optional(),set:t.record(t.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/,"must be an environment variable name"),t.string()).optional()}),nt=t.strictObject({model:t.string().trim().min(1).optional(),effort:t.string().trim().min(1).optional(),options:t.record(t.string(),t.unknown()).optional()}),h=t.strictObject({model:t.string().trim().min(1).optional(),effort:t.string().trim().min(1).optional(),options:t.record(t.string(),t.unknown()).optional(),env:$.optional(),sandbox:t.strictObject({profile:t.string().trim().min(1)}).optional(),harnesses:t.partialRecord(t.enum(c),nt,{error:()=>`not a harness Bishop runs; supported: ${c.join(", ")}`}).optional()}),ot=t.strictObject({harness:t.enum(c).optional(),model:t.string().trim().min(1).optional(),effort:t.string().trim().min(1).optional(),harnesses:t.partialRecord(t.enum(c),tt,{error:()=>`not a harness Bishop runs; supported: ${c.join(", ")}`}).superRefine((o,n)=>{o.codex?.keepAlive!==void 0&&n.addIssue({code:"custom",path:["codex","keepAlive"],message:"only the claude harness keeps an agent running between turns"})}).optional(),worktrees:t.boolean().optional(),projectSettings:t.boolean().optional(),sandbox:t.union([t.boolean(),t.strictObject({profile:t.string().trim().min(1).optional()})]).optional(),options:t.record(t.string(),t.unknown()).optional(),env:$.optional(),permissionLevels:t.strictObject({read:h.optional(),write:h.optional(),admin:h.optional()}).optional()}),et=t.strictObject({maxAgeDays:t.number().int().positive().optional()}),rt=t.strictObject({maxMb:t.number().positive().optional()}),it=["all","external"],st=["reject","approve"],I=t.strictObject({scope:t.enum(it).optional(),onError:t.enum(st).optional()});function at(o){let n;try{n=new URL(o)}catch{return!1}return n.protocol==="https:"?!0:n.protocol!=="http:"?!1:n.hostname==="localhost"||n.hostname==="[::1]"||/^127(\.\d{1,3}){3}$/.test(n.hostname)}const pt=t.strictObject({command:t.array(t.string().min(1)).min(1).optional(),url:t.string().trim().refine(at,"must be an https URL, or http on loopback").optional(),inbound:I.optional(),outbound:I.optional(),timeoutSeconds:t.number().positive().max(300).optional(),env:t.array(t.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/,"must be an environment variable name")).optional()}).superRefine((o,n)=>{o.command&&o.url?n.addIssue({code:"custom",message:"names both command and url; pick one"}):!o.command&&!o.url&&n.addIssue({code:"custom",message:"needs a command or a url"}),o.url&&o.env&&n.addIssue({code:"custom",path:["env"],message:"is only for a command reviewer"}),!o.inbound&&!o.outbound&&n.addIssue({code:"custom",message:"reviews nothing without inbound or outbound"})}),ct=t.strictObject({threshold:t.number().min(0).max(1).optional(),instructions:t.string().trim().min(1).optional()}),lt=t.strictObject({provider:t.enum(A,{error:()=>`not a decision provider; supported: ${A.join(", ")}`}),name:t.string().trim().min(1).optional(),timeoutMs:t.number().int().positive().max(1e4).optional()}),mt=t.strictObject({model:lt,reply:ct.optional()}),dt=t.string().transform(o=>o.trim().toLowerCase()).pipe(t.enum(U)),ut=t.string().trim().min(1).superRefine((o,n)=>{try{V(o)}catch(e){n.addIssue({code:"custom",message:e instanceof P?e.message:String(e)})}}),ft=t.strictObject({default:dt.optional(),admins:t.array(ut).optional()}),gt=t.strictObject({slack:W.optional(),gmail:Y.optional(),teams:Q.optional(),agent:ot.optional(),files:rt.optional(),gc:et.optional(),review:pt.optional(),decisions:mt.optional(),permissions:ft.optional()}).superRefine((o,n)=>{o.review&&!o.agent?.sandbox&&n.addIssue({code:"custom",path:["review"],message:"needs agent.sandbox on"});for(const e of M)o.agent?.permissionLevels?.[e]?.sandbox&&!o.agent.sandbox&&n.addIssue({code:"custom",path:["agent","permissionLevels",e,"sandbox"],message:"needs agent.sandbox on"})});class b extends u{path;constructor(n,e){super(n,"ConfigError"),this.path=e}}const ht=new Set(["disallowedTools"]);function N(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function f(o,n){if(!n)return o;if(!o)return n;const e={...o};for(const[r,s]of Object.entries(n)){const i=e[r];ht.has(r)&&Array.isArray(i)&&Array.isArray(s)?e[r]=[...i,...s.filter(m=>!i.includes(m))]:N(i)&&N(s)?e[r]=f(i,s):e[r]=s}return e}function bt(o,n){if(!n)return o;if(!o)return n;const e=n.allow??o.allow,r=[...new Set([...o.deny??[],...n.deny??[]])],s={...o.set,...n.set};return{...e?{allow:e}:{},...r.length?{deny:r}:{},...Object.keys(s).length?{set:s}:{}}}function Rt(o,n={},e){const r=o.agent,s=r?.harness??"claude",i=n.harness??s,m=r?.harnesses?.[i],{keepAlive:_,...C}=m??{},a=m&&Object.keys(C).length>0?m:void 0,p=e?r?.permissionLevels?.[e]:void 0,d=p?.harnesses?.[i],l=[];!e&&r?.options&&(a&&i===s?l.push({kind:"options-replaced",harness:i}):!a&&i!==s&&l.push({kind:"options-foreign",harness:i,configured:s})),e&&p?.options&&a&&l.push({kind:"level-options-replaced",harness:i,level:e});const y=d?.model??p?.model,w=d?.effort??p?.effort;e&&n.model&&y&&l.push({kind:"flag-overrides-level",level:e,setting:"model"}),e&&n.effort&&w&&l.push({kind:"flag-overrides-level",level:e,setting:"effort"});const x=n.model??y??a?.model??r?.model,O=n.effort??w??a?.effort??r?.effort,k=f(a?a.options:f(r?.options,p?.options),d?.options),v=i==="claude"?_:void 0,j=bt(r?.env,p?.env),E=p?.sandbox?.profile;return{harness:i,...x?{model:x}:{},...O?{effort:O}:{},...k?{options:k}:{},...v!==void 0?{keepAlive:v}:{},...j?{env:j}:{},...E?{sandboxProfile:E}:{},warnings:l}}function St(o){const n=o.agent?.sandbox;if(n)return n===!0||!n.profile?{}:{profile:n.profile}}function $t(o){return n=>{const e=n.trim();if(!e)throw new u(`${o} needs a value`);return e}}function It(o){return n=>{const e=Number(n.trim());if(!Number.isInteger(e)||e<=0)throw new u(`${o} needs a positive whole number, got "${n}"`);return e}}function Nt(o){const n=o.trim();if(c.includes(n))return n;throw new u(`unknown harness "${o}"; supported: ${c.join(", ")}`)}function L(o=process.cwd()){return F(o,Z,G)}function yt(o){return o.issues.flatMap(n=>{if(n.code==="unrecognized_keys"&&n.keys.length>0){const e=n.message.startsWith("Unrecognized key")?"unrecognized key":n.message;return n.keys.map(r=>`${[...n.path,r].join(".")}: ${e}`)}return[`${n.path.length>0?n.path.join("."):"(root)"}: ${n.message}`]}).join(`
2
+ `)}async function Lt(o=process.cwd()){const n=L(o);let e;try{e=await T(n,"utf8")}catch(i){if(i.code==="ENOENT")return{};throw new b(`Couldn't read ${n}: ${i.message}`,n)}let r;try{r=JSON.parse(e)}catch(i){throw new b(`${n} isn't valid JSON: ${i.message}`,n)}const s=gt.safeParse(r);if(!s.success)throw new b(`${n} has invalid values:
3
+ ${yt(s.error)}`,n);return s.data}async function _t(o,n=process.cwd()){const e=L(n);return await z(D(e),{recursive:!0}),await B(e,`${JSON.stringify(o,null,2)}
4
+ `,"utf8"),e}function Ct(o){return o.displayName?.trim()||o.name}export{Z as CONFIG_DIR,G as CONFIG_FILE,b as ConfigError,gt as ConfigSchema,At as DEFAULT_VERBOSITY,c as HARNESSES,st as REVIEW_ON_ERROR,it as REVIEW_SCOPES,J as VERBOSITY,L as configPath,Ct as displayNameOf,f as layerLevelOptions,Lt as loadConfig,$t as nonEmptyFlag,Nt as parseHarnessName,It as positiveIntFlag,Rt as resolveAgent,St as sandboxConfig,_t as writeConfig};
package/dist/db.js CHANGED
@@ -1,4 +1,4 @@
1
- import{existsSync as m,mkdirSync as C,renameSync as D,rmSync as w,writeFileSync as S}from"node:fs";import{dirname as l,join as O}from"node:path";import{DatabaseSync as u}from"node:sqlite";import{BishopError as U}from"./errors.js";import{mint as y}from"./ids.js";import{log as A}from"./log.js";const I="bishop.db",g=O(".bishop","backups");function K(r=process.cwd()){return O(r,I)}const L=[`CREATE TABLE sessions (
1
+ import{existsSync as m,mkdirSync as k,renameSync as D,rmSync as S,writeFileSync as g}from"node:fs";import{dirname as A,join as O}from"node:path";import{DatabaseSync as I}from"node:sqlite";import{BishopError as f}from"./errors.js";import{mint as u}from"./ids.js";import{log as l}from"./log.js";const y="bishop.db",w=O(".bishop","backups");function K(r=process.cwd()){return O(r,y)}const o=[`CREATE TABLE sessions (
2
2
  thread_key TEXT PRIMARY KEY,
3
3
  session_id TEXT NOT NULL,
4
4
  created_at INTEGER NOT NULL,
@@ -64,17 +64,17 @@ import{existsSync as m,mkdirSync as C,renameSync as D,rmSync as w,writeFileSync
64
64
  CREATE TABLE thread_ids (
65
65
  thread_key TEXT PRIMARY KEY,
66
66
  id TEXT NOT NULL
67
- );`);const s=r.prepare(`SELECT thread_key, workspace_key FROM sessions
68
- WHERE workspace_key IS NOT NULL ORDER BY updated_at DESC, thread_key`).all(),a=new Map,T=new Map;for(const t of s)a.has(t.workspace_key)||a.set(t.workspace_key,t.thread_key),T.set(t.thread_key,t.workspace_key);const E=(t,i)=>{const c=new Set([i]);let d=i;for(let N=t.get(d);N;N=t.get(d)){if(c.has(N))return i;c.add(N),d=N}return d},n=t=>E(a,t),_=t=>E(T,t),o=r.prepare(`SELECT thread_key FROM sessions
67
+ );`);const n=r.prepare(`SELECT thread_key, workspace_key FROM sessions
68
+ WHERE workspace_key IS NOT NULL ORDER BY updated_at DESC, thread_key`).all(),a=new Map,T=new Map;for(const t of n)a.has(t.workspace_key)||a.set(t.workspace_key,t.thread_key),T.set(t.thread_key,t.workspace_key);const E=(t,d)=>{const c=new Set([d]);let i=d;for(let N=t.get(i);N;N=t.get(i)){if(c.has(N))return d;c.add(N),i=N}return i},s=t=>E(a,t),_=t=>E(T,t),L=r.prepare(`SELECT thread_key FROM sessions
69
69
  UNION SELECT thread_key FROM thread_dirs
70
70
  UNION SELECT thread_key FROM thread_meta
71
- UNION SELECT thread_key FROM thread_files`).all().map(t=>t.thread_key),h=r.prepare(`SELECT d.agent_dir AS agent_dir,
71
+ UNION SELECT thread_key FROM thread_files`).all().map(t=>t.thread_key),R=r.prepare(`SELECT d.agent_dir AS agent_dir,
72
72
  d.used_at AS used_at,
73
73
  s.created_at AS created_at
74
74
  FROM (SELECT ? AS key, ? AS dir_key) k
75
75
  LEFT JOIN sessions s ON s.thread_key = k.key
76
- LEFT JOIN thread_dirs d ON d.thread_key = k.dir_key`),R=r.prepare(`INSERT INTO threads (id, thread_key, dir_key, agent_dir, created_at, used_at)
77
- VALUES (?, ?, ?, ?, ?, ?)`),k=r.prepare("INSERT INTO thread_ids (thread_key, id) VALUES (?, ?)"),f=new Map;for(const t of o){if(n(t)!==t)continue;const i=_(t),c=n(i)===t?i:t,d=h.get(t,c),N=d.used_at==null?e:Number(d.used_at),X=d.created_at==null?N:Number(d.created_at),p=y("t");R.run(p,t,c,d.agent_dir,X,N),f.set(t,p)}for(const t of o){const i=f.get(n(t));i&&k.run(t,i)}r.exec(`CREATE TABLE sessions_new (
76
+ LEFT JOIN thread_dirs d ON d.thread_key = k.dir_key`),h=r.prepare(`INSERT INTO threads (id, thread_key, dir_key, agent_dir, created_at, used_at)
77
+ VALUES (?, ?, ?, ?, ?, ?)`),X=r.prepare("INSERT INTO thread_ids (thread_key, id) VALUES (?, ?)"),p=new Map;for(const t of L){if(s(t)!==t)continue;const d=_(t),c=s(d)===t?d:t,i=R.get(t,c),N=i.used_at==null?e:Number(i.used_at),C=i.created_at==null?N:Number(i.created_at),U=u("t");h.run(U,t,c,i.agent_dir,C,N),p.set(t,U)}for(const t of L){const d=p.get(s(t));d&&X.run(t,d)}r.exec(`CREATE TABLE sessions_new (
78
78
  thread_id TEXT PRIMARY KEY REFERENCES threads (id) ON DELETE CASCADE,
79
79
  session_id TEXT NOT NULL,
80
80
  harness TEXT NOT NULL DEFAULT 'claude',
@@ -141,9 +141,9 @@ import{existsSync as m,mkdirSync as C,renameSync as D,rmSync as w,writeFileSync
141
141
  created_at INTEGER NOT NULL,
142
142
  updated_at INTEGER NOT NULL,
143
143
  UNIQUE (interface, external_id)
144
- );`);const s=r.prepare(`INSERT INTO principals
144
+ );`);const n=r.prepare(`INSERT INTO principals
145
145
  (id, interface, external_id, handle, name, email, kind, affiliation, created_at, updated_at)
146
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);s.run("p_0","system","0","bishop","Bishop",null,"system","internal",e,e);const a=r.prepare("SELECT DISTINCT created_by FROM schedules WHERE created_by NOT LIKE 'cli:%'").all(),T=r.prepare("UPDATE schedules SET created_by = ? WHERE created_by = ?");for(const{created_by:E}of a){const n=E.indexOf(":");if(n<=0||n===E.length-1)continue;const _=E.slice(0,n),o=E.slice(n+1);if(_==="system")continue;const h=y("p"),R=_==="gmail"?o:null;s.run(h,_,o,o,o,R,"unknown","unknown",e,e),T.run(h,E)}},`CREATE TABLE locations (
146
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);n.run("p_0","system","0","bishop","Bishop",null,"system","internal",e,e);const a=r.prepare("SELECT DISTINCT created_by FROM schedules WHERE created_by NOT LIKE 'cli:%'").all(),T=r.prepare("UPDATE schedules SET created_by = ? WHERE created_by = ?");for(const{created_by:E}of a){const s=E.indexOf(":");if(s<=0||s===E.length-1)continue;const _=E.slice(0,s),L=E.slice(s+1);if(_==="system")continue;const R=u("p"),h=_==="gmail"?L:null;n.run(R,_,L,L,L,h,"unknown","unknown",e,e),T.run(R,E)}},`CREATE TABLE locations (
147
147
  id TEXT PRIMARY KEY,
148
148
  interface TEXT NOT NULL,
149
149
  external_id TEXT NOT NULL,
@@ -175,13 +175,63 @@ import{existsSync as m,mkdirSync as C,renameSync as D,rmSync as w,writeFileSync
175
175
  at INTEGER NOT NULL
176
176
  );
177
177
  CREATE INDEX transcript_thread ON transcript (thread_id, seq);
178
- CREATE INDEX transcript_turn ON transcript (turn_id);`];function M(r,e){return O(l(r),g,`${I}.v${e}.backup`)}function B(r,e,s){const a=M(e,s);if(m(a)&&!b(a,s))throw new U(`${a} is already there, and it is not a copy of this database at schema v${s}.
178
+ CREATE INDEX transcript_turn ON transcript (turn_id);`,`ALTER TABLE transcript RENAME TO transcript_entries;
179
+ DROP INDEX transcript_thread;
180
+ DROP INDEX transcript_turn;
181
+ CREATE INDEX transcript_entries_thread ON transcript_entries (thread_id, seq);
182
+ CREATE INDEX transcript_entries_turn ON transcript_entries (turn_id);
183
+ ALTER TABLE transcript_entries ADD COLUMN body TEXT;
184
+ CREATE VIRTUAL TABLE transcript_search USING fts5 (
185
+ body,
186
+ content = 'transcript_entries',
187
+ content_rowid = 'seq',
188
+ tokenize = 'porter unicode61 remove_diacritics 2'
189
+ );
190
+ CREATE TRIGGER transcript_search_insert AFTER INSERT ON transcript_entries
191
+ WHEN new.body IS NOT NULL BEGIN
192
+ INSERT INTO transcript_search (rowid, body) VALUES (new.seq, new.body);
193
+ END;
194
+ CREATE TRIGGER transcript_search_delete AFTER DELETE ON transcript_entries
195
+ WHEN old.body IS NOT NULL BEGIN
196
+ INSERT INTO transcript_search (transcript_search, rowid, body)
197
+ VALUES ('delete', old.seq, old.body);
198
+ END;`,`ALTER TABLE transcript_entries ADD COLUMN pending INTEGER NOT NULL DEFAULT 0;
199
+ CREATE INDEX transcript_entries_pending ON transcript_entries (thread_id, seq)
200
+ WHERE pending = 1;`,`CREATE TABLE groups (
201
+ id TEXT PRIMARY KEY,
202
+ interface TEXT NOT NULL,
203
+ kind TEXT NOT NULL,
204
+ external_id TEXT NOT NULL,
205
+ name TEXT NOT NULL DEFAULT '',
206
+ created_at INTEGER NOT NULL,
207
+ updated_at INTEGER NOT NULL,
208
+ UNIQUE (interface, kind, external_id)
209
+ );
210
+ CREATE TABLE grants (
211
+ id TEXT PRIMARY KEY,
212
+ principal_id TEXT UNIQUE REFERENCES principals (id) ON DELETE CASCADE,
213
+ location_id TEXT UNIQUE REFERENCES locations (id) ON DELETE CASCADE,
214
+ group_id TEXT UNIQUE REFERENCES groups (id) ON DELETE CASCADE,
215
+ name_interface TEXT,
216
+ name_target TEXT CHECK (name_target = 'principal'),
217
+ name TEXT,
218
+ name_label TEXT,
219
+ level TEXT NOT NULL,
220
+ granted_by TEXT NOT NULL,
221
+ granted_at INTEGER NOT NULL,
222
+ CHECK ((principal_id IS NOT NULL) + (location_id IS NOT NULL) + (group_id IS NOT NULL) <= 1),
223
+ CHECK (principal_id IS NOT NULL OR location_id IS NOT NULL OR group_id IS NOT NULL
224
+ OR name IS NOT NULL),
225
+ CHECK ((name IS NULL) = (name_interface IS NULL) AND (name IS NULL) = (name_target IS NULL))
226
+ );
227
+ CREATE UNIQUE INDEX grants_name ON grants (name_interface, name_target, name)
228
+ WHERE name IS NOT NULL;`];function M(r,e){return O(A(r),w,`${y}.v${e}.backup`)}function B(r,e,n){const a=M(e,n);if(m(a)&&!b(a,n))throw new f(`${a} is already there, and it is not a copy of this database at schema v${n}.
179
229
 
180
230
  Nothing was migrated. Bishop copies the database before every schema
181
231
  change so a bad migration can be undone, and it will not overwrite
182
- whatever that file is. Move it aside and start Bishop again.`);const T=`${a}.partial`;try{C(l(a),{recursive:!0}),S(O(l(a),".gitignore"),`*
183
- `,"utf8"),w(T,{force:!0}),r.prepare("VACUUM INTO ?").run(T),D(T,a)}catch(E){const n=E instanceof Error?E.message:String(E);throw new U(`Couldn't copy ${e} to ${a} before migrating it: ${n}
232
+ whatever that file is. Move it aside and start Bishop again.`);const T=`${a}.partial`;try{k(A(a),{recursive:!0}),g(O(A(a),".gitignore"),`*
233
+ `,"utf8"),S(T,{force:!0}),r.prepare("VACUUM INTO ?").run(T),D(T,a)}catch(E){const s=E instanceof Error?E.message:String(E);throw new f(`Couldn't copy ${e} to ${a} before migrating it: ${s}
184
234
 
185
235
  Nothing was migrated. Bishop copies the database before every schema
186
236
  change so a bad migration can be undone, and it will not migrate
187
- without one. Free some space, or move that file aside, and start again.`)}return a}function b(r,e){try{const s=new u(r,{readOnly:!0});try{return s.prepare("PRAGMA user_version").get()?.user_version===e}finally{s.close()}}catch{return!1}}function H(r){const e=new u(r);e.exec("PRAGMA journal_mode = WAL"),e.exec("PRAGMA busy_timeout = 5000"),e.exec("PRAGMA foreign_keys = ON");const a=e.prepare("PRAGMA user_version").get()?.user_version??0;if(a>0&&a<L.length){const T=B(e,r,a);A.info({backup:T,from:a},"copied the database before migrating it")}for(let T=a;T<L.length;T+=1){const E=L[T];if(E){e.exec("BEGIN");try{typeof E=="string"?e.exec(E):E(e),e.exec(`PRAGMA user_version = ${T+1}`),e.exec("COMMIT")}catch(n){throw e.exec("ROLLBACK"),n}}}return a===0?A.debug({schema:L.length},"created the session database"):a<L.length&&A.info({from:a,to:L.length},"migrated the session database"),e}export{g as BACKUPS_DIR,I as DB_FILE,L as MIGRATIONS,M as backupPath,K as dbPath,H as openDb};
237
+ without one. Free some space, or move that file aside, and start again.`)}return a}function b(r,e){try{const n=new I(r,{readOnly:!0});try{return n.prepare("PRAGMA user_version").get()?.user_version===e}finally{n.close()}}catch{return!1}}function H(r){const e=new I(r);e.exec("PRAGMA journal_mode = WAL"),e.exec("PRAGMA busy_timeout = 5000"),e.exec("PRAGMA foreign_keys = ON");const a=e.prepare("PRAGMA user_version").get()?.user_version??0;if(a>0&&a<o.length){const T=B(e,r,a);l.info({backup:T,from:a},"copied the database before migrating it")}for(let T=a;T<o.length;T+=1){const E=o[T];if(E){e.exec("BEGIN");try{typeof E=="string"?e.exec(E):E(e),e.exec(`PRAGMA user_version = ${T+1}`),e.exec("COMMIT")}catch(s){throw e.exec("ROLLBACK"),s}}}return a===0?l.debug({schema:o.length},"created the session database"):a<o.length&&l.info({from:a,to:o.length},"migrated the session database"),e}export{w as BACKUPS_DIR,y as DB_FILE,o as MIGRATIONS,M as backupPath,K as dbPath,H as openDb};
@@ -0,0 +1 @@
1
+ import{BishopError as l}from"../errors.js";import{providers as m}from"./providers.js";const h=["jev","openai","gemini","openrouter"],v=500;function u(e){const r=m[e.provider],s=e.env??process.env;let i,t;for(const o of r.keys)if(t=s[o]?.trim(),t){i=o;break}if(!i||!t){const[o,...a]=r.keys;throw new l(`decisions.model.provider is ${e.provider}, but ${r.keys.join(" or ")} is not set; add ${o} to .env for a key the agent never sees, or ${a.join(" or ")} to share one with it`)}const n=e.model??r.defaultModel,c=e.timeoutMs??v,d=e.fetch??fetch;return{provider:e.provider,model:n,keyVariable:i,decide:o=>r.call({request:o,model:n,key:t,signal:AbortSignal.timeout(c),fetch:d})}}export{h as DECISION_PROVIDERS,v as DEFAULT_DECISION_TIMEOUT_MS,u as createDecisionModel};
@@ -0,0 +1 @@
1
+ import{z as t}from"zod";const d=300,p=t.object({answers:t.record(t.string(),t.union([t.object({type:t.literal("noul"),noul:t.number()}),t.object({type:t.literal("refusal")}),t.object({type:t.string()})]))}),f=t.object({answers:t.array(t.union([t.object({type:t.literal("predicate"),name:t.string().nullish(),probability:t.number()}),t.object({type:t.string(),name:t.string().nullish()})]))});async function l(e,a,n,r){const o=await e.fetch(a,{method:"POST",headers:{"content-type":"application/json",...n},body:JSON.stringify(r),signal:e.signal});if(!o.ok){const s=await o.text().catch(()=>"");throw new Error(`the decision API returned ${o.status}${s?`: ${s.slice(0,d)}`:""}`)}return o.json()}function c(e,a){const n=p.parse(e),r={};for(const o of Object.keys(a.questions)){const s=n.answers[o];s&&"noul"in s&&s.type==="noul"?r[o]={type:"noul",noul:s.noul}:s?.type==="refusal"?r[o]={type:"refusal"}:s?.type==="noul"&&u(o)}return r}function u(e){throw new Error(`the decision API answered ${e} without a probability`)}const E={jev:{defaultModel:"jev-latest",keys:["BISHOP_TYPESAFE_API_KEY","TYPESAFE_API_KEY"],async call(e){const a=await l(e,"https://api.typesafe.ai/v1/systemone",{authorization:`Bearer ${e.key}`},{model:e.model,state:e.request.state,questions:e.request.questions});return c(a,e.request)}},openrouter:{defaultModel:"~typesafe/jev-latest",keys:["BISHOP_OPENROUTER_API_KEY","OPENROUTER_API_KEY"],async call(e){const a=await l(e,"https://openrouter.ai/api/alpha/decisions",{authorization:`Bearer ${e.key}`},{model:e.model,state:e.request.state,questions:e.request.questions});return c(a,e.request)}},gemini:{defaultModel:"gemini-decision-1",keys:["BISHOP_GEMINI_API_KEY","GEMINI_API_KEY","GOOGLE_API_KEY"],async call(e){const a=await l(e,"https://generativelanguage.googleapis.com/v1beta/decisions",{"x-goog-api-key":e.key},{model:e.model,input:e.request.state,questions:e.request.questions});return c(a,e.request)}},openai:{defaultModel:"gpt-6-luna",keys:["BISHOP_OPENAI_API_KEY","OPENAI_API_KEY"],async call(e){const a=Object.keys(e.request.questions),n=await l(e,"https://api.openai.com/v1/decisions",{authorization:`Bearer ${e.key}`},{model:e.model,input:e.request.state,questions:a.map(s=>({type:"predicate",name:s,instructions:e.request.questions[s]?.instructions}))}),r=f.parse(n),o={};return r.answers.forEach((s,y)=>{const i=s.name??a[y];!i||!(i in e.request.questions)||("probability"in s&&s.type==="predicate"?o[i]={type:"noul",noul:s.probability}:s.type==="refusal"?o[i]={type:"refusal"}:s.type==="predicate"&&u(i))}),o}}};export{E as providers};
package/dist/env.js CHANGED
@@ -1,12 +1,11 @@
1
- import{config as S}from"dotenv";import{applyLogLevel as E}from"./log.js";const I=[{name:"BISHOP_GMAIL_CLIENT_ID",hint:"OAuth client ID for a Desktop app"},{name:"BISHOP_GMAIL_CLIENT_SECRET",hint:"the matching OAuth client secret"},{name:"BISHOP_GMAIL_REFRESH_TOKEN",hint:"issued by `bishop gmail setup`; copy it from the laptop you authorized on"}],u=[{name:"BISHOP_GMAIL_USER",hint:"the Workspace address the agent sends and receives as"},{name:"BISHOP_GMAIL_SERVICE_ACCOUNT",hint:"path to the service account JSON key, or the JSON itself"}],m=[{name:"slack",sets:[{label:"Slack",vars:[{name:"BISHOP_SLACK_BOT_TOKEN",hint:"the xoxb- token issued when the Slack app was installed"},{name:"BISHOP_SLACK_APP_TOKEN",hint:"the xapp- app-level token from the app\u2019s Basic Information page"}]}],setup:"run `bishop slack setup` for Slack"},{name:"gmail",sets:[{label:"Gmail over OAuth",vars:I},{label:"Gmail over domain-wide delegation",vars:u}],setup:"run `bishop gmail setup` for Gmail"},{name:"teams",sets:[{label:"Microsoft Teams",vars:[{name:"BISHOP_TEAMS_CLIENT_ID",hint:"the Teams app\u2019s client ID"},{name:"BISHOP_TEAMS_CLIENT_SECRET",hint:"the matching client secret"},{name:"BISHOP_TEAMS_TENANT_ID",hint:"the Entra tenant the app is registered in"}]}],setup:"run `bishop teams setup` for Teams"}];function d(e=process.cwd()){S({path:`${e}/.env`,override:!1,quiet:!0}),E()}function t(e,s){return e[s]?.trim()||void 0}function f(e,s){return s.sets.find(a=>a.vars.some(o=>t(e,o.name)))}function O(e=process.env){const s=new Map,a=[];let o;for(const p of m){const c=f(e,p);if(!c)continue;s.set(p.name,c);const h=c.vars.filter(l=>!t(e,l.name));h.length!==0&&(o??=c.label,a.push(...h.map(l=>({name:l.name,hint:l.hint,set:c.label}))))}if(a.length>0)return{ok:!1,missing:a,...o?{attempting:o}:{}};if(s.size===0)return{ok:!1,noInterface:!0,missing:m.flatMap(p=>p.sets[0]?.vars??[])};const n=t(e,"ANTHROPIC_API_KEY"),i=t(e,"CODEX_API_KEY"),_=s.get("gmail"),r=_?_.vars===I?{kind:"oauth",clientId:t(e,"BISHOP_GMAIL_CLIENT_ID"),clientSecret:t(e,"BISHOP_GMAIL_CLIENT_SECRET"),refreshToken:t(e,"BISHOP_GMAIL_REFRESH_TOKEN")}:{kind:"service-account",user:t(e,"BISHOP_GMAIL_USER"),serviceAccount:t(e,"BISHOP_GMAIL_SERVICE_ACCOUNT")}:void 0;return{ok:!0,credentials:{...s.has("slack")?{slack:{botToken:t(e,"BISHOP_SLACK_BOT_TOKEN"),appToken:t(e,"BISHOP_SLACK_APP_TOKEN")}}:{},...r?{gmail:r}:{},...s.has("teams")?{teams:{clientId:t(e,"BISHOP_TEAMS_CLIENT_ID"),clientSecret:t(e,"BISHOP_TEAMS_CLIENT_SECRET"),tenantId:t(e,"BISHOP_TEAMS_TENANT_ID")}}:{},...n?{anthropicApiKey:n}:{},...i?{codexApiKey:i}:{}}}}function g(e){const s=e.missing.map(n=>` ${n.name}: ${n.hint}`).join(`
2
- `);if(e.noInterface)return`Bishop has no interface configured, so nothing could reach the agent.
1
+ import{config as O}from"dotenv";import{applyLogLevel as b}from"./log.js";const I=[{name:"BISHOP_GMAIL_CLIENT_ID",hint:"OAuth client ID for a Desktop app"},{name:"BISHOP_GMAIL_CLIENT_SECRET",hint:"the matching OAuth client secret"},{name:"BISHOP_GMAIL_REFRESH_TOKEN",hint:"issued by `bishop gmail setup`; copy it from the laptop you authorized on"}],k=[{name:"BISHOP_GMAIL_USER",hint:"the Workspace address the agent sends and receives as"},{name:"BISHOP_GMAIL_SERVICE_ACCOUNT",hint:"path to the service account JSON key, or the JSON itself"}],S=[{name:"slack",sets:[{label:"Slack",vars:[{name:"BISHOP_SLACK_BOT_TOKEN",hint:"the xoxb- token issued when the Slack app was installed"},{name:"BISHOP_SLACK_APP_TOKEN",hint:"the xapp- app-level token from the app\u2019s Basic Information page"}]}],setup:"run `bishop slack setup` for Slack"},{name:"gmail",sets:[{label:"Gmail over OAuth",vars:I},{label:"Gmail over domain-wide delegation",vars:k}],setup:"run `bishop gmail setup` for Gmail"},{name:"teams",sets:[{label:"Microsoft Teams",vars:[{name:"BISHOP_TEAMS_CLIENT_ID",hint:"the Teams app\u2019s client ID"},{name:"BISHOP_TEAMS_CLIENT_SECRET",hint:"the matching client secret"},{name:"BISHOP_TEAMS_TENANT_ID",hint:"the Entra tenant the app is registered in"}]}],setup:"run `bishop teams setup` for Teams"}];function L(n=process.cwd()){O({path:`${n}/.env`,override:!1,quiet:!0}),b()}function t(n,e){return n[e]?.trim()||void 0}function C(n,e){return e.sets.find(a=>a.vars.some(s=>t(n,s.name)))}function B(n,e=process.env){const a=new Map,s=[],i={unconfigured:[],disabled:[]};let r;for(const o of S){const m=C(e,o),_=n[o.name];if(_?.enabled===!1){i.disabled.push(o.name);continue}if(!_){m&&i.unconfigured.push(o.name);continue}const l=m??o.sets[0];a.set(o.name,l);const f=l.vars.filter(p=>!t(e,p.name));f.length!==0&&(r??=l.label,s.push(...f.map(p=>({name:p.name,hint:p.hint,set:l.label}))))}if(a.size===0)return{ok:!1,noInterface:!0,missing:[],...i};if(s.length>0)return{ok:!1,missing:s,...r?{attempting:r}:{},...i};const c=t(e,"ANTHROPIC_API_KEY"),d=t(e,"CODEX_API_KEY"),u=a.get("gmail"),h=u?u.vars===I?{kind:"oauth",clientId:t(e,"BISHOP_GMAIL_CLIENT_ID"),clientSecret:t(e,"BISHOP_GMAIL_CLIENT_SECRET"),refreshToken:t(e,"BISHOP_GMAIL_REFRESH_TOKEN")}:{kind:"service-account",user:t(e,"BISHOP_GMAIL_USER"),serviceAccount:t(e,"BISHOP_GMAIL_SERVICE_ACCOUNT")}:void 0;return{ok:!0,credentials:{...a.has("slack")?{slack:{botToken:t(e,"BISHOP_SLACK_BOT_TOKEN"),appToken:t(e,"BISHOP_SLACK_APP_TOKEN")}}:{},...h?{gmail:h}:{},...a.has("teams")?{teams:{clientId:t(e,"BISHOP_TEAMS_CLIENT_ID"),clientSecret:t(e,"BISHOP_TEAMS_CLIENT_SECRET"),tenantId:t(e,"BISHOP_TEAMS_TENANT_ID")}}:{},...c?{anthropicApiKey:c}:{},...d?{codexApiKey:d}:{}},...i}}const E={slack:"Slack",gmail:"Gmail",teams:"Teams"};function T(n){return`${E[n]} credentials are set but .bishop/config.json has no "${n}" block, so it does not start. Add "${n}": {} to start it.`}function A(n){return`${E[n]} is turned off by "enabled": false in .bishop/config.json.`}function H(n,e){if(n.disabled?.includes(e))return A(e);if(n.unconfigured?.includes(e))return T(e)}function g(n){return[...(n.unconfigured??[]).map(T),...(n.disabled??[]).map(A)].map(e=>`
3
2
 
4
- ${s}
3
+ ${e}`).join("")}function M(n){if(n.noInterface)return`Bishop has no interface enabled, so nothing could reach the agent. An interface starts when .bishop/config.json has a block for it, like "slack": {}, and its credentials are in .env.${g(n)}
5
4
 
6
- Set one interface's variables: ${m.map(n=>n.setup).join(", ")}.`;const a=new Map;for(const n of e.missing){const i=n.set??e.attempting??"Missing credentials";a.set(i,[...a.get(i)??[],n])}return`${[...a].map(([n,i])=>{const _=i.map(r=>` ${r.name}: ${r.hint}`).join(`
7
- `);return`${n} is missing:
8
- ${_}`}).join(`
5
+ To set one up, ${S.map(s=>s.setup).join(", ")}.`;const e=new Map;for(const s of n.missing){const i=s.set??n.attempting??"Missing credentials";e.set(i,[...e.get(i)??[],s])}return`${[...e].map(([s,i])=>{const r=i.map(c=>` ${c.name}: ${c.hint}`).join(`
6
+ `);return`${s} is missing:
7
+ ${r}`}).join(`
9
8
 
10
9
  `)}
11
10
 
12
- Add them to .env, or re-run the setup for that interface.`}export{g as describeMissing,d as loadEnv,O as readCredentials};
11
+ Add them to .env, or re-run the setup for that interface.${g(n)}`}export{A as describeDisabled,M as describeMissing,T as describeUnconfigured,L as loadEnv,B as readCredentials,H as whyNotStarted};
@@ -1 +1 @@
1
- import{BishopError as l}from"../errors.js";class i extends l{constructor(t){super(t,"GmailAllowListError")}}const n=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,c=/^@[^\s@]+\.[^\s@]+$/;function m(e){return n.test(e.trim().toLowerCase())}function d(e){const t=e.trim().toLowerCase();if(n.test(t)||c.test(t))return t;throw new i(`"${e}" is not an email address or a domain. Write an address like person@example.com, or @example.com for everyone at a domain.`)}function f(e){if(!e||e.length===0)return{allows:()=>!0,open:!0};const t=new Set,s=new Set;for(const r of e){const o=d(r);o.startsWith("@")?s.add(o.slice(1)):t.add(o)}return{open:!1,allows(r){const o=r.trim().toLowerCase();if(!o)return!1;if(t.has(o))return!0;const a=o.slice(o.lastIndexOf("@")+1);return s.has(a)}}}export{i as GmailAllowListError,f as gmailAllowList,m as looksLikeAddress,d as validateAllowEntry};
1
+ import{EntryError as n}from"../permissions/entry.js";const a=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function m(e){return a.test(e.trim().toLowerCase())}function r(e){const i=e.trim().toLowerCase();return{externalId:i,handle:i,email:i,kind:"unknown",affiliation:"unknown"}}function t(e,i){const o=i.trim().toLowerCase();return{interface:"gmail",...e?{principalId:e}:{},groups:[],addresses:[o]}}function s(e){return t(e.id,e.email??e.externalId)}function u(e){if(!e.kind||e.kind==="user"){if(e.value.form==="domain"){const{domain:i}=e.value;return{kind:"group",interface:"gmail",label:`*@${i}`,group:"domain",externalId:i}}if(e.value.form==="email"){const{email:i}=e.value;return{kind:"principal",interface:"gmail",label:i,sighting:r(i)}}}throw new n(`${e.text}: Gmail names people by address, like dana@example.com, or everyone at a domain, like *@example.com. Email has no channels, DMs or groups to give a level to.`)}export{t as gmailMembership,r as gmailSighting,u as gmailSubject,m as looksLikeAddress,s as principalMembership};
@@ -1 +1 @@
1
- import{gmailApi as c}from"./api.js";import{accessTokens as n,readServiceAccountKey as s}from"./auth.js";import{gmailAllowList as l}from"./authorize.js";import{createGmailInterface as i}from"./interface.js";import{DEFAULT_LABEL_PREFIX as f,ensureLabels as m}from"./labels.js";import{oauthTokens as h}from"./oauth.js";const k=20;async function g(e,o){if(e.kind==="oauth")return h({client:{clientId:e.clientId,clientSecret:e.clientSecret},refreshToken:e.refreshToken,...o});const a=await s(e.serviceAccount);return n({key:a,subject:e.user,...o})}async function T(e){const o=l(e.config?.allow),a=e.fetch?{fetch:e.fetch}:{},r=c({tokens:await g(e.credentials,a),...a}),t=await m(r,e.config?.labelPrefix??f);return i({api:r,labels:t,allow:o,threads:e.threads,events:e.events,state:e.state,files:e.files,attachments:e.attachments,principals:e.principals,pollIntervalMs:(e.config?.pollSeconds??k)*1e3,...e.config?.markRead===void 0?{}:{markRead:e.config.markRead},...e.config?.internalDomains?{internalDomains:e.config.internalDomains}:{},run:e.run,stop:e.stop})}export{T as createGmail};
1
+ import{gmailApi as a}from"./api.js";import{accessTokens as c,readServiceAccountKey as n}from"./auth.js";import{createGmailInterface as t}from"./interface.js";import{DEFAULT_LABEL_PREFIX as i,ensureLabels as f}from"./labels.js";import{oauthTokens as m}from"./oauth.js";const l=20;async function h(e,o){if(e.kind==="oauth")return m({client:{clientId:e.clientId,clientSecret:e.clientSecret},refreshToken:e.refreshToken,...o});const r=await n(e.serviceAccount);return c({key:r,subject:e.user,...o})}async function D(e){const o=e.fetch?{fetch:e.fetch}:{},r=a({tokens:await h(e.credentials,o),...o}),s=await f(r,e.config?.labelPrefix??i);return t({api:r,labels:s,threads:e.threads,events:e.events,state:e.state,files:e.files,attachments:e.attachments,principals:e.principals,pollIntervalMs:(e.config?.pollSeconds??l)*1e3,...e.config?.markRead===void 0?{}:{markRead:e.config.markRead},...e.config?.internalDomains?{internalDomains:e.config.internalDomains}:{},run:e.run,stop:e.stop,permissions:e.permissions})}export{D as createGmail};
@@ -1 +1 @@
1
- import{BishopError as i}from"../errors.js";import{looksLikeAddress as t}from"./authorize.js";function l(e,s,n={}){const o=s.trim().toLowerCase();if(n.optedInOnly&&e.open)throw new i(`Bishop won't start mailing ${o} on its own: no gmail.allow is configured, so there is no list saying who agreed to hear from this agent. Set gmail.allow in .bishop/config.json.`);if(!t(o))throw new i(`"${s}" is not an email address. Write just the address, like person@example.com.`);if(!e.allows(o))throw new i(`${o} is not on this agent's Gmail allow list, so Bishop would never mail it. Add it to gmail.allow in .bishop/config.json first.`);return{interface:"gmail",handle:o,label:o}}export{l as resolveGmailDestination};
1
+ import{BishopError as o}from"../errors.js";import{looksLikeAddress as n}from"./authorize.js";function d(i,t){const e=i.trim().toLowerCase();if(!n(e))throw new o(`"${i}" is not an email address. Write just the address, like person@example.com.`);const{level:r,source:s}=t.levelOf(e);if(r==="deny")throw new o(`${e} is at deny on this agent, so Bishop would never mail it. Give it a level, or its domain, first.`);if(t.optedInOnly&&s.from==="default")throw new o(`Bishop won't start mailing ${e} on its own: nobody gave it or its domain a level, so nothing says it agreed to hear from this agent.`);return{interface:"gmail",handle:e,label:e}}export{d as resolveGmailDestination};
@@ -1 +1 @@
1
- import{describedFile as g}from"../files.js";import{trimHistory as b,withinFileBudget as w}from"../interface/history.js";import{log as k}from"../log.js";import{DRAFT as y,SPAM as A,TRASH as F}from"./api.js";import{mailAttachment as I,mailFile as H,mailFileId as v,mailFilePayload as x}from"./files.js";import{isSelf as B}from"./identity.js";import{header as P,mailHeaders as S,parseMessage as f}from"./message.js";import{senderVerified as T}from"./route.js";function u(e){return e.references.length>0||!!P(e.headers,"in-reply-to")}function q(e){return u(e)||e.id!==e.threadId}function z(e,a){return e.map(t=>{const i=g(I(a.api,t));if(!t.fetchable)return i;const m=a.remember({id:v(t),name:t.name,payload:x(t)});return m?{...i,ref:m}:{...i,unavailable:"Bishop could not record a reference for it"}})}async function E(e){let a;try{a=await e.api.thread(e.message.threadId)}catch(n){return k.warn({threadId:e.message.threadId,err:n},"could not read the thread to catch the agent up"),[{kind:"omitted",reason:"unavailable"}]}const t=[];let i=0;const m=()=>{i&&(t.push({kind:"omitted",reason:"unauthorized",count:i}),i=0)};for(const n of a){if(n.id===e.message.id)break;const r=f(n);if(r.labelIds.some(s=>s===y||s===A||s===F))continue;const o=r.from.email.toLowerCase();if(!o||!T(r)){i+=1;continue}if(!B(e.self,o)&&!e.allow.allows(o)){i+=1;continue}const c=r.attachments.map((s,p)=>H(r.id,p,s));!r.body.trim()&&c.length===0||(m(),t.push({kind:"message",principal:e.principal({email:o,...r.from.name?{name:r.from.name}:{}}),text:r.body,headers:S(r),...c.length>0?{shared:c}:{}}))}m();const l=w(b(t)).map(n=>{if(n.kind!=="message"||!n.shared)return n;const{shared:r,...o}=n,d=z(r,e);return d.length>0?{...o,files:d}:o}),h=a[0]?f(a[0]):e.message;return u(h)&&l.unshift({kind:"omitted",reason:"unavailable"}),l}export{q as continuesAThread,E as mailHistory};
1
+ import{describedFile as g}from"../files.js";import{trimHistory as b,withinFileBudget as k}from"../interface/history.js";import{log as y}from"../log.js";import{DRAFT as A,SPAM as F,TRASH as I}from"./api.js";import{mailAttachment as w,mailFile as H,mailFileId as v,mailFilePayload as x}from"./files.js";import{isSelf as B}from"./identity.js";import{header as P,mailHeaders as S,parseMessage as l}from"./message.js";import{senderVerified as T}from"./route.js";function u(e){return e.references.length>0||!!P(e.headers,"in-reply-to")}function q(e){return u(e)||e.id!==e.threadId}function z(e,a){return e.map(t=>{const i=g(w(a.api,t));if(!t.fetchable)return i;const m=a.remember({id:v(t),name:t.name,payload:x(t)});return m?{...i,ref:m}:{...i,unavailable:"Bishop could not record a reference for it"}})}async function E(e){let a;try{a=await e.api.thread(e.message.threadId)}catch(n){return y.warn({threadId:e.message.threadId,err:n},"could not read the thread to catch the agent up"),[{kind:"omitted",reason:"unavailable"}]}const t=[];let i=0;const m=()=>{i&&(t.push({kind:"omitted",reason:"unauthorized",count:i}),i=0)};for(const n of a){if(n.id===e.message.id)break;const r=l(n);if(r.labelIds.some(s=>s===A||s===F||s===I))continue;const o=r.from.email.toLowerCase();if(!o||!T(r)){i+=1;continue}if(!B(e.self,o)&&!e.admits(o)){i+=1;continue}const c=r.attachments.map((s,p)=>H(r.id,p,s));!r.body.trim()&&c.length===0||(m(),t.push({kind:"message",principal:e.principal({email:o,...r.from.name?{name:r.from.name}:{}}),text:r.body,headers:S(r),...c.length>0?{shared:c}:{}}))}m();const f=k(b(t)).map(n=>{if(n.kind!=="message"||!n.shared)return n;const{shared:r,...o}=n,d=z(r,e);return d.length>0?{...o,files:d}:o}),h=a[0]?l(a[0]):e.message;return u(h)&&f.unshift({kind:"omitted",reason:"unavailable"}),f}export{q as continuesAThread,E as mailHistory};