@agentdeploymentco/bishop 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) 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/setup.js +81 -81
  67. package/dist/tools/conversations.js +2 -0
  68. package/dist/tools/found.js +3 -0
  69. package/dist/tools/history.js +2 -0
  70. package/dist/tools/messages.js +2 -2
  71. package/dist/tools/schedules.js +6 -6
  72. package/dist/tools/server.js +1 -1
  73. package/dist/transcript.js +26 -3
  74. package/dist/turn.js +2 -2
  75. package/package.json +4 -3
  76. package/dist/slack/authorize.js +0 -2
  77. package/dist/slack/authorizer.js +0 -3
  78. package/dist/slack/directory.js +0 -1
  79. package/dist/teams/authorize.js +0 -1
@@ -1,9 +1,9 @@
1
- import{loadConfig as y,writeConfig as F}from"../config.js";import{log as I}from"../log.js";import{ensureGitignore as he,resolveAppDetails as W,SetupError as m,withPrompt as G,writeEnv as de}from"../setup.js";import{AZ_LOGIN_COMMAND as j,azAccount as ce,FILES_READ_ALL as le,FILES_READ_WRITE_ALL as z,FILES_READ_WRITE_ALL_ROLE as me,GRAPH_APP_ID as ue,grantGraphFiles as fe,INSTALL_AZ_CLI as we}from"./entra.js";import{addRscPermission as ge,createTeamsApp as Te,describeTeamsApp as Ie,getRscPermissions as Ae,getTeamsApp as _e,INSTALL_TEAMS_CLI as x,INSTALL_TEAMS_CLI_COMMAND as Ee,LOGIN_DID_NOT_PERSIST as Se,RSC_PERMISSIONS as C,setTeamsEndpoint as be,setTeamsFiles as N,teamsCliVersion as U,teamsLogin as ye,teamsLoginWouldUseDeviceCode as v,teamsStatus as $}from"./provision.js";import{readGraphRoles as R,verifyTeamsCredentials as Ce}from"./verify.js";const Y=["The Teams CLI cannot log in from this machine. With no local browser it falls","back to the device code flow, which Microsoft blocks by default in every","tenant."].join(`
2
- `),K=[Y,"","So an app cannot be created over SSH. Two ways on from here:",""," Run `bishop teams setup` on a workstation and copy the three BISHOP_TEAMS_*"," lines it writes to .env over to this host.",""," Have somebody else create the app, then run `bishop teams setup --manual`"," here with what they send back. `bishop teams instructions` prints what to"," ask them for."].join(`
3
- `),V=[Y,"","So the app has to be re-pointed from a machine that can log in:",""," bishop teams endpoint <url> --app-id <the app id>","","or by editing the bot endpoint in the Teams Developer Portal."].join(`
4
- `);function Z(e){return new m(v()?`${x}
1
+ import{loadConfig as N,writeConfig as F}from"../config.js";import{log as T}from"../log.js";import{adminReminder as me,askForAdmin as W,ensureGitignore as ue,resolveAppDetails as G,SetupError as m,withAdmin as fe,withPrompt as j,writeEnv as we}from"../setup.js";import{AZ_LOGIN_COMMAND as x,azAccount as ge,FILES_READ_ALL as Te,FILES_READ_WRITE_ALL as z,FILES_READ_WRITE_ALL_ROLE as Ie,GRAPH_APP_ID as Ae,grantGraphFiles as _e,INSTALL_AZ_CLI as Ee}from"./entra.js";import{addRscPermission as Se,createTeamsApp as be,describeTeamsApp as ye,getRscPermissions as Ne,getTeamsApp as Ce,INSTALL_TEAMS_CLI as U,INSTALL_TEAMS_CLI_COMMAND as $e,LOGIN_DID_NOT_PERSIST as ve,RSC_PERMISSIONS as C,setTeamsEndpoint as Re,setTeamsFiles as $,teamsCliVersion as Y,teamsLogin as Le,teamsLoginWouldUseDeviceCode as v,teamsStatus as R}from"./provision.js";import{readGraphRoles as L,verifyTeamsCredentials as Oe}from"./verify.js";const K=["The Teams CLI cannot log in from this machine. With no local browser it falls","back to the device code flow, which Microsoft blocks by default in every","tenant."].join(`
2
+ `),V=[K,"","So an app cannot be created over SSH. Two ways on from here:",""," Run `bishop teams setup` on a workstation and copy the three BISHOP_TEAMS_*"," lines it writes to .env over to this host.",""," Have somebody else create the app, then run `bishop teams setup --manual`"," here with what they send back. `bishop teams instructions` prints what to"," ask them for."].join(`
3
+ `),Z=[K,"","So the app has to be re-pointed from a machine that can log in:",""," bishop teams endpoint <url> --app-id <the app id>","","or by editing the bot endpoint in the Teams Developer Portal."].join(`
4
+ `);function q(e){return new m(v()?`${U}
5
5
 
6
- ${e}`:x)}function L(e){return{...e.BISHOP_TEAMS_CLIENT_ID?.trim()?{clientId:e.BISHOP_TEAMS_CLIENT_ID.trim()}:{},...e.BISHOP_TEAMS_CLIENT_SECRET?.trim()?{clientSecret:e.BISHOP_TEAMS_CLIENT_SECRET.trim()}:{},...e.BISHOP_TEAMS_TENANT_ID?.trim()?{tenantId:e.BISHOP_TEAMS_TENANT_ID.trim()}:{}}}function O(e){const{clientId:n,clientSecret:t,tenantId:a}=L(e);if(n&&t&&a)return{clientId:n,clientSecret:t,tenantId:a}}function q(e,n){const t=e.teams?.app;if(t&&O(n))return{app:t}}async function J(e,n,t,a){let i;try{i=await de(e,{BISHOP_TEAMS_CLIENT_ID:a.clientId,BISHOP_TEAMS_CLIENT_SECRET:a.clientSecret,BISHOP_TEAMS_TENANT_ID:a.tenantId})}catch(r){throw new m(`The credentials could not be written to .env: ${r instanceof Error?r.message:String(r)}
6
+ ${e}`:U)}function O(e){return{...e.BISHOP_TEAMS_CLIENT_ID?.trim()?{clientId:e.BISHOP_TEAMS_CLIENT_ID.trim()}:{},...e.BISHOP_TEAMS_CLIENT_SECRET?.trim()?{clientSecret:e.BISHOP_TEAMS_CLIENT_SECRET.trim()}:{},...e.BISHOP_TEAMS_TENANT_ID?.trim()?{tenantId:e.BISHOP_TEAMS_TENANT_ID.trim()}:{}}}function M(e){const{clientId:n,clientSecret:t,tenantId:a}=O(e);if(n&&t&&a)return{clientId:n,clientSecret:t,tenantId:a}}function X(e,n){const t=e.teams?.app;if(t&&M(n))return{app:t}}function J(e,n){return{...e.admin!==void 0?{given:e.admin}:{},interactive:n,example:Q}}const Q="teams:you@example.com";async function ee(e,n,t,a,i){let s;try{s=await we(e,{BISHOP_TEAMS_CLIENT_ID:a.clientId,BISHOP_TEAMS_CLIENT_SECRET:a.clientSecret,BISHOP_TEAMS_TENANT_ID:a.tenantId})}catch(o){throw new m(`The credentials could not be written to .env: ${o instanceof Error?o.message:String(o)}
7
7
 
8
8
  The app was created, so save these somewhere before this scrolls away:
9
9
 
@@ -11,128 +11,128 @@ The app was created, so save these somewhere before this scrolls away:
11
11
  BISHOP_TEAMS_CLIENT_SECRET=${a.clientSecret}
12
12
  BISHOP_TEAMS_TENANT_ID=${a.tenantId}
13
13
 
14
- Then run \`bishop teams setup --manual\` once .env is writable.`)}await F({...n,teams:{...n.teams,app:t}},e);const s=await he(e,[".env","bishop.db*"]);return` .bishop/config.json app configuration
15
- ${i} credentials
16
- `+(s.length?` .gitignore added ${s.join(", ")}
17
- `:"")}async function k(e){if(e)try{return await _e(e)}catch(n){I.debug({err:n,teamsAppId:e},"could not read the Teams app back");return}}function Q(e,n){return n.map(t=>` teams app rsc add ${e} ${t} --type Application
18
- `).join("")}const S=`Without these the agent only hears a message that @mentions it, so a reply to
14
+ Then run \`bishop teams setup --manual\` once .env is writable.`)}const h=fe({...n,teams:{...n.teams,app:t}},i);await F(h,e);const p=await ue(e,[".env","bishop.db*"]);return` .bishop/config.json app configuration${i?`, and ${i} as an admin`:""}
15
+ ${s} credentials
16
+ `+(p.length?` .gitignore added ${p.join(", ")}
17
+ `:"")+me(h,Q)}async function k(e){if(e)try{return await Ce(e)}catch(n){T.debug({err:n,teamsAppId:e},"could not read the Teams app back");return}}function ne(e,n){return n.map(t=>` teams app rsc add ${e} ${t} --type Application
18
+ `).join("")}const b=`Without these the agent only hears a message that @mentions it, so a reply to
19
19
  its own answer never reaches it, and it can't tell who can read a channel.
20
- `;async function Ne(e){const n=[],t=[];for(const a of C){const i=await ge(e,a);i.applied||(n.push(a),t.push(` ${a}: ${i.reason}
20
+ `;async function Me(e){const n=[],t=[];for(const a of C){const i=await Se(e,a);i.applied||(n.push(a),t.push(` ${a}: ${i.reason}
21
21
  `))}return n.length===0?"":`
22
22
  These permissions could not be added to the app:
23
23
  `+t.join("")+`
24
- ${S}Add them with:
24
+ ${b}Add them with:
25
25
 
26
- `+Q(e,n)}async function X(e){if(e)try{const n=new Set(await Ae(e));return C.filter(t=>!n.has(t))}catch(n){I.debug({err:n,teamsAppId:e},"could not read the app\u2019s RSC permissions");return}}const ve=`Then remove the app from every team and chat it is in, and add it again.
26
+ `+ne(e,n)}async function te(e){if(e)try{const n=new Set(await Ne(e));return C.filter(t=>!n.has(t))}catch(n){T.debug({err:n,teamsAppId:e},"could not read the app\u2019s RSC permissions");return}}const ke=`Then remove the app from every team and chat it is in, and add it again.
27
27
  Teams asks for these permissions only when an app is installed. Updating an
28
28
  app that is already installed does not ask, and it will keep hearing nothing
29
29
  but mentions until it has been removed and installed again.
30
- `,M=`Without it Teams shows no attach button in a chat with the agent, so nobody
30
+ `,D=`Without it Teams shows no attach button in a chat with the agent, so nobody
31
31
  can send it a file. An image pasted into a message arrives either way, and a
32
32
  file attached in a channel never does.
33
- `;function b(e){return` teams app manifest update ${e} --set-json 'bots[0].supportsFiles=true' --yes
34
- `}function $e(e,n){return`
33
+ `;function y(e){return` teams app manifest update ${e} --set-json 'bots[0].supportsFiles=true' --yes
34
+ `}function De(e,n){return`
35
35
  File support could not be turned on for this app: ${n??"the update failed"}
36
36
 
37
- ${M}Turn it on with:
37
+ ${D}Turn it on with:
38
38
 
39
- `+b(e)}function Re(e){return`
39
+ `+y(e)}function Pe(e){return`
40
40
  Bishop could not check whether this app has file support: the Teams CLI is
41
41
  not installed here, or is not logged in. Run this again where it is, or turn
42
42
  it on with:
43
43
 
44
- `+b(e)}const Le=`This moved the app\u2019s manifest version, so update the app where it is already
44
+ `+y(e)}const Be=`This moved the app\u2019s manifest version, so update the app where it is already
45
45
  installed. Until that reaches a chat, it will go on showing no attach button.
46
- `;function ee(e){return`
46
+ `;function ae(e){return`
47
47
  This app does not have file support.
48
48
 
49
- ${M}Turn it on with:
49
+ ${D}Turn it on with:
50
50
 
51
- `+b(e)+`
52
- ${Le}`}function D(e,n=" "){const t=e??"<client id>",a=`${n} `;return`${n}az ad app permission add --id ${t} \\
53
- ${a}--api ${ue} \\
54
- ${a}--api-permissions ${me}=Role
51
+ `+y(e)+`
52
+ ${Be}`}function P(e,n=" "){const t=e??"<client id>",a=`${n} `;return`${n}az ad app permission add --id ${t} \\
53
+ ${a}--api ${Ae} \\
54
+ ${a}--api-permissions ${Ie}=Role
55
55
  ${n}az ad app permission admin-consent --id ${t}
56
- `}const Oe=`Without it the agent cannot send a file to a channel. Files.Read.All still
56
+ `}const He=`Without it the agent cannot send a file to a channel. Files.Read.All still
57
57
  lets it read files people attach there. A file in a direct chat needs none
58
58
  of this.
59
- `;function A(e,n){return`
59
+ `;function I(e,n){return`
60
60
  ${n}
61
61
 
62
- ${D(e)}
63
- ${Oe}`}const P=`A file attached in a channel is read through Microsoft Graph, which needs one
64
- grant in Entra.`;function ke(e,n=" "){return`${n}az ad app permission admin-consent --id ${e}
65
- `}const Me=`
62
+ ${P(e)}
63
+ ${He}`}const B=`A file attached in a channel is read through Microsoft Graph, which needs one
64
+ grant in Entra.`;function Fe(e,n=" "){return`${n}az ad app permission admin-consent --id ${e}
65
+ `}const We=`
66
66
  The Azure CLI accepted the grant for Files.ReadWrite.All, and the app cannot
67
67
  send a file to a channel yet: its own token does not carry the
68
68
  permission. Entra can take minutes to apply a consent on a registration
69
69
  made seconds earlier. Re-run \`bishop teams setup\` to see whether it took,
70
70
  and if it still reports the grant missing, run the consent again:
71
71
 
72
- `,De=`
72
+ `,Ge=`
73
73
  The Azure CLI accepted the grant for Files.ReadWrite.All, and Bishop could not
74
74
  reach Entra to check that it took. Re-run \`bishop teams setup\` to find out.
75
- `,ne=`
75
+ `,ie=`
76
76
  The app can read and send files in a channel: Files.ReadWrite.All is granted.
77
- `,Pe=`
77
+ `,je=`
78
78
  The app can read files attached in a channel, but cannot send them: Files.ReadWrite.All is not granted.
79
- `,Be=`Consenting an application permission takes an administrator, which is the
79
+ `,xe=`Consenting an application permission takes an administrator, which is the
80
80
  usual reason. An app registration made moments ago can also be too new for
81
81
  Entra to have it everywhere yet, so this is worth running once by hand
82
- before asking anybody. Re-run \`bishop teams setup\` to see whether it took.`;async function He(e,n=R){const t=await ce();if(!t.installed)return A(e.clientId,`${P} Bishop makes it with the Azure CLI,
83
- which is not installed here. ${we}
84
- Then run:`);if(!t.loggedIn)return A(e.clientId,`${P} Bishop makes it with the Azure CLI,
85
- which is not logged in here. Run \`${j}\`, which is
86
- what a tenant with no Azure subscription needs, and then:`);if(t.tenantId&&t.tenantId.toLowerCase()!==e.tenantId.toLowerCase())return A(e.clientId,`${P} The Azure CLI is signed in to tenant
82
+ before asking anybody. Re-run \`bishop teams setup\` to see whether it took.`;async function ze(e,n=L){const t=await ge();if(!t.installed)return I(e.clientId,`${B} Bishop makes it with the Azure CLI,
83
+ which is not installed here. ${Ee}
84
+ Then run:`);if(!t.loggedIn)return I(e.clientId,`${B} Bishop makes it with the Azure CLI,
85
+ which is not logged in here. Run \`${x}\`, which is
86
+ what a tenant with no Azure subscription needs, and then:`);if(t.tenantId&&t.tenantId.toLowerCase()!==e.tenantId.toLowerCase())return I(e.clientId,`${B} The Azure CLI is signed in to tenant
87
87
  ${t.tenantId}, and this app is in ${e.tenantId}, so
88
- Bishop left it alone. Sign in to the app\u2019s tenant and run:`);const a=await fe(e.clientId);if(!a.applied)return A(e.clientId,`Bishop could not grant Files.ReadWrite.All: ${a.reason}
88
+ Bishop left it alone. Sign in to the app\u2019s tenant and run:`);const a=await _e(e.clientId);if(!a.applied)return I(e.clientId,`Bishop could not grant Files.ReadWrite.All: ${a.reason}
89
89
 
90
- ${Be}
91
- An administrator makes the grant with:`);const i=await n(e);return i?.includes(z)?ne:i?Me+ke(e.clientId):De}function te(e,n){return n?n.includes(z)?ne:n.includes(le)?Pe:A(e,`The app cannot send a file to a channel: Files.ReadWrite.All is not
90
+ ${xe}
91
+ An administrator makes the grant with:`);const i=await n(e);return i?.includes(z)?ie:i?We+Fe(e.clientId):Ge}function se(e,n){return n?n.includes(z)?ie:n.includes(Te)?je:I(e,`The app cannot send a file to a channel: Files.ReadWrite.All is not
92
92
  granted on its app registration. An administrator grants it with:`):`
93
93
  Bishop could not check whether the app can read a file attached in a
94
94
  channel. That needs Files.ReadWrite.All on the app registration, which an
95
95
  administrator grants with:
96
96
 
97
- `+D(e)}function ae(e,n){return`
97
+ `+P(e)}function oe(e,n){return`
98
98
  The app is missing ${n.length===1?"a permission":"permissions"}:
99
99
  `+n.map(t=>` ${t}
100
100
  `).join("")+`
101
- ${S}Add them with:
101
+ ${b}Add them with:
102
102
 
103
- `+Q(e,n)+`
104
- ${ve}`}const Fe=`
105
- ${S}Bishop could not check whether this app has the permissions for that: the
103
+ `+ne(e,n)+`
104
+ ${ke}`}const Ue=`
105
+ ${b}Bishop could not check whether this app has the permissions for that: the
106
106
  Teams CLI is not installed here, or is not logged in. Run this again where it
107
107
  is, or see \`bishop teams instructions\` for what they are.
108
- `;function We(e,n){return n?n.length>0?ae(e,n):"":`
109
- ${S}Bishop cannot check this app, so confirm with whoever created it that it has
108
+ `;function Ye(e,n){return n?n.length>0?oe(e,n):"":`
109
+ ${b}Bishop cannot check this app, so confirm with whoever created it that it has
110
110
  the permissions \`bishop teams instructions\` asks for.
111
- `}function Ge(e,n){return!e||!n?.applied?`
112
- ${M}Bishop cannot check this app, so confirm with whoever created it that file
111
+ `}function Ke(e,n){return!e||!n?.applied?`
112
+ ${D}Bishop cannot check this app, so confirm with whoever created it that file
113
113
  support is on.
114
- `:n.changed?ee(e):""}async function ie(e,n,t){const a=await k(e.app.id),i=a?.endpoint,s=e.app.id?a?i??"not set":"unknown, the Teams CLI could not read the app":"unknown, no Teams app ID is recorded here";if(n(`This agent is already set up in Teams as "${e.app.displayName??e.app.name}".
114
+ `:n.changed?ae(e):""}async function re(e,n,t){const a=await k(e.app.id),i=a?.endpoint,s=e.app.id?a?i??"not set":"unknown, the Teams CLI could not read the app":"unknown, no Teams app ID is recorded here";if(n(`This agent is already set up in Teams as "${e.app.displayName??e.app.name}".
115
115
  `+(e.app.id?` App ID ${e.app.id}
116
116
  `:"")+` Endpoint ${s}
117
117
  Its credentials are in .env and its configuration in .bishop/config.json.
118
118
  `),a&&!i&&n(`
119
119
  Teams has nowhere to deliver to until the app is pointed at Bishop.
120
120
  Run \`bishop teams endpoint <url>\` with the URL that reaches this host.
121
- `),e.app.id){const p=await X(e.app.id);p?p.length>0&&n(ae(e.app.id,p)):n(Fe)}if(e.app.id){const p=await N(e.app.id,{check:!0});p.applied?p.changed&&n(ee(e.app.id)):n(Re(e.app.id))}const r=O(process.env);n(te(r?.clientId,r&&await t(r))),n(`
121
+ `),e.app.id){const p=await te(e.app.id);p?p.length>0&&n(oe(e.app.id,p)):n(Ue)}if(e.app.id){const p=await $(e.app.id,{check:!0});p.applied?p.changed&&n(ae(e.app.id)):n(Pe(e.app.id))}const h=M(process.env);n(se(h?.clientId,h&&await t(h))),n(`
122
122
  To change where Teams delivers, run \`bishop teams endpoint <url>\`.
123
123
  To set this up again, remove teams.app from .bishop/config.json and the
124
124
  BISHOP_TEAMS_* lines from .env first.
125
- `)}function je(e,n){if(!e)return;const{tenant:t,user:a}=e;t!==!1&&a!==!1||n(`
125
+ `)}function Ve(e,n){if(!e)return;const{tenant:t,user:a}=e;t!==!1&&a!==!1||n(`
126
126
  Note: custom apps cannot be installed in Teams from here.
127
127
  `+(t===!1?` The tenant-wide setting is off. An administrator turns it on in the Teams
128
128
  Admin Center, under Org-wide app settings, Custom apps.
129
129
  `:"")+(a===!1?` Your own app setup policy blocks it. An administrator changes it in the
130
130
  Teams Admin Center, under Users, Policies, App setup policy.
131
131
  `:"")+`Setup will still create the app, but somebody will have to install it.
132
- `)}function ze(e,n){const t=e.teams?.app,a=L(n),i=Object.keys(a).length>0;if(t&&!O(n)){const{clientId:s,clientSecret:r,tenantId:p}=a,h=[s?void 0:"BISHOP_TEAMS_CLIENT_ID",r?void 0:"BISHOP_TEAMS_CLIENT_SECRET",p?void 0:"BISHOP_TEAMS_TENANT_ID"].filter(Boolean);throw new m(`An app is already recorded here, but its credentials are not.
132
+ `)}function Ze(e,n){const t=e.teams?.app,a=O(n),i=Object.keys(a).length>0;if(t&&!M(n)){const{clientId:s,clientSecret:h,tenantId:p}=a,o=[s?void 0:"BISHOP_TEAMS_CLIENT_ID",h?void 0:"BISHOP_TEAMS_CLIENT_SECRET",p?void 0:"BISHOP_TEAMS_TENANT_ID"].filter(Boolean);throw new m(`An app is already recorded here, but its credentials are not.
133
133
 
134
134
  App ${t.displayName??t.name}${t.id?` (${t.id})`:""}
135
- Missing ${h.join(`
135
+ Missing ${o.join(`
136
136
  `)}
137
137
 
138
138
  Creating a new app would leave that one orphaned in your tenant. Either:
@@ -145,49 +145,49 @@ Creating a new app would overwrite them, and a client secret cannot be
145
145
  read back once it is lost.
146
146
 
147
147
  Run \`bishop teams setup --manual\` to record the app those credentials
148
- belong to, or remove the BISHOP_TEAMS_* lines from .env to start over.`)}async function qe(e,n=R){const t=e.cwd??process.cwd(),a=e.prompt&&process.stdin.isTTY===!0,i=o=>process.stdout.write(o),s=await y(t),r=q(s,process.env);if(r){await ie(r,i,n);return}ze(s,process.env);const p=await U();if(!p)throw Z(K);I.debug({teamsCli:p},"found the teams cli");let h=await $();if(!h.loggedIn){if(v())throw new m(K);if(!a)throw new m("The Teams CLI is not logged in to Microsoft 365.\nRun `teams login`, then run this again.");i("The Teams CLI is not logged in to Microsoft 365. Starting `teams login`.\n\n");const o=await ye();if(h=o?await $():h,!h.loggedIn)throw new m(`The Teams CLI is still not logged in, so the app cannot be created.
149
- `+(o?`
148
+ belong to, or remove the BISHOP_TEAMS_* lines from .env to start over.`)}async function tn(e,n=L){const t=e.cwd??process.cwd(),a=e.prompt&&process.stdin.isTTY===!0,i=r=>process.stdout.write(r),s=await N(t),h=X(s,process.env);if(h){await re(h,i,n);return}Ze(s,process.env);const p=await Y();if(!p)throw q(V);T.debug({teamsCli:p},"found the teams cli");let o=await R();if(!o.loggedIn){if(v())throw new m(V);if(!a)throw new m("The Teams CLI is not logged in to Microsoft 365.\nRun `teams login`, then run this again.");i("The Teams CLI is not logged in to Microsoft 365. Starting `teams login`.\n\n");const r=await Le();if(o=r?await R():o,!o.loggedIn)throw new m(`The Teams CLI is still not logged in, so the app cannot be created.
149
+ `+(r?`
150
150
  \`teams login\` reported success, but the login did not survive it.
151
- ${Se}`:"Run `teams login` on its own to see what went wrong."));i(`
151
+ ${ve}`:"Run `teams login` on its own to see what went wrong."));i(`
152
152
  Logged in.
153
- `)}je(h.sideloading,i),await G(a,async o=>{const d=await W(e,t,o),u=e.endpoint?.trim()||await o("Messaging endpoint URL (leave blank to set later)","");i(`
154
- Creating the Teams app for "${d.displayName}"${h.username?` in ${h.username}'s tenant`:""}...
155
- `);const c=await Te({name:d.displayName,...u?{endpoint:u}:{}}),w=d.description?await Ie(c.teamsAppId,d.description):{applied:!1,reason:void 0};d.description&&!w.applied&&i(`
156
- The description was not applied: ${w.reason}
157
- `);const f=await Ne(c.teamsAppId);f&&i(f);const l=await N(c.teamsAppId);l.applied||i($e(c.teamsAppId,l.reason));const g={id:c.teamsAppId,name:d.name,displayName:d.displayName,...w.applied&&d.description?{description:d.description}:{}},T=await J(t,s,g,c),_=await He(c,n);I.info({teamsAppId:c.teamsAppId,endpoint:u||void 0},"teams app created"),i(`
153
+ `)}Ve(o.sideloading,i),await j(a,async r=>{const d=await G(e,t,r),f=e.endpoint?.trim()||await r("Messaging endpoint URL (leave blank to set later)",""),A=await W(s,"teams",J(e,a),r,i);i(`
154
+ Creating the Teams app for "${d.displayName}"${o.username?` in ${o.username}'s tenant`:""}...
155
+ `);const c=await be({name:d.displayName,...f?{endpoint:f}:{}}),u=d.description?await ye(c.teamsAppId,d.description):{applied:!1,reason:void 0};d.description&&!u.applied&&i(`
156
+ The description was not applied: ${u.reason}
157
+ `);const l=await Me(c.teamsAppId);l&&i(l);const w=await $(c.teamsAppId);w.applied||i(De(c.teamsAppId,w.reason));const g={id:c.teamsAppId,name:d.name,displayName:d.displayName,...u.applied&&d.description?{description:d.description}:{}},_=await ee(t,s,g,c,A),E=await ze(c,n);T.info({teamsAppId:c.teamsAppId,endpoint:f||void 0},"teams app created"),i(`
158
158
  Done.
159
- ${T}`+_+(c.installLink?`
159
+ ${_}`+E+(c.installLink?`
160
160
  Install it in Teams:
161
161
  ${c.installLink}
162
- `:"")+(u?"":`
162
+ `:"")+(f?"":`
163
163
  The app has no messaging endpoint yet, so Teams has nowhere to deliver to.
164
164
  Run \`bishop teams endpoint <url>\` with the URL that reaches this host.
165
- `)+"\nRun `bishop` to start the agent.\n")})}async function Je(e,n=Ce,t=R){const a=e.cwd??process.cwd(),i=e.prompt&&process.stdin.isTTY===!0,s=o=>process.stdout.write(o),r=await y(a),p=r.teams?.app,h=q(r,process.env);if(h){const o=e.appId?.trim();if(o&&!h.app.id){await F({...r,teams:{...r.teams,app:{...h.app,id:o}}},a),s(`Recorded Teams app ID ${o} for "${h.app.displayName??h.app.name}".
166
- `);return}await ie(h,s,t);return}await G(i,async o=>{const d=L(process.env),u=d.clientId||await o("Client ID",""),c=d.clientSecret||await o("Client secret",""),w=d.tenantId||await o("Tenant ID","");if(!u||!c||!w)throw new m(`All three credentials are needed: a client ID, a client secret, and a
165
+ `)+"\nRun `bishop` to start the agent.\n")})}async function an(e,n=Oe,t=L){const a=e.cwd??process.cwd(),i=e.prompt&&process.stdin.isTTY===!0,s=r=>process.stdout.write(r),h=await N(a),p=h.teams?.app,o=X(h,process.env);if(o){const r=e.appId?.trim();if(r&&!o.app.id){await F({...h,teams:{...h.teams,app:{...o.app,id:r}}},a),s(`Recorded Teams app ID ${r} for "${o.app.displayName??o.app.name}".
166
+ `);return}await re(o,s,t);return}await j(i,async r=>{const d=O(process.env),f=d.clientId||await r("Client ID",""),A=d.clientSecret||await r("Client secret",""),c=d.tenantId||await r("Tenant ID","");if(!f||!A||!c)throw new m(`All three credentials are needed: a client ID, a client secret, and a
167
167
  tenant ID. Set BISHOP_TEAMS_CLIENT_ID, BISHOP_TEAMS_CLIENT_SECRET and
168
168
  BISHOP_TEAMS_TENANT_ID, or run this in a terminal so they can be typed in.
169
169
 
170
- Run \`bishop teams instructions\` for what to send whoever creates the app.`);const f={clientId:u,clientSecret:c,tenantId:w},l=e.appId?.trim()||p?.id||await o("Teams app ID (optional)","");s(`
170
+ Run \`bishop teams instructions\` for what to send whoever creates the app.`);const u={clientId:f,clientSecret:A,tenantId:c},l=e.appId?.trim()||p?.id||await r("Teams app ID (optional)","");s(`
171
171
  Checking the credentials...
172
- `);const g=await n(f);if(!g.ok)throw new m(`Microsoft rejected these credentials.
173
- ${g.detail}
172
+ `);const w=await n(u);if(!w.ok)throw new m(`Microsoft rejected these credentials.
173
+ ${w.detail}
174
174
 
175
175
  This is the same request Bishop makes on every turn, so the agent would
176
- not have been able to answer anything.`);g.detail?s(`${g.detail} Saving them anyway.
176
+ not have been able to answer anything.`);w.detail?s(`${w.detail} Saving them anyway.
177
177
  `):s(`Accepted.
178
- `);const T=await k(l||void 0),_=e.name??p?.name??T?.name,B=e.displayName??p?.displayName??T?.name,H=e.description??p?.description,E=await W({...e,..._?{name:_}:{},...B?{displayName:B}:{},...H?{description:H}:{}},a,o),se={...l?{id:l}:{},name:E.name,displayName:E.displayName,...E.description?{description:E.description}:{}},oe=await J(a,r,se,f),re=await X(l||void 0),pe=l?await N(l,{check:!0}):void 0;I.info({teamsAppId:l||void 0},"teams app adopted"),s(`
178
+ `);const g=await k(l||void 0),_=e.name??p?.name??g?.name,E=e.displayName??p?.displayName??g?.name,H=e.description??p?.description,S=await G({...e,..._?{name:_}:{},...E?{displayName:E}:{},...H?{description:H}:{}},a,r),pe={...l?{id:l}:{},name:S.name,displayName:S.displayName,...S.description?{description:S.description}:{}},he=await W(h,"teams",J(e,i),r,s),de=await ee(a,h,pe,u,he),ce=await te(l||void 0),le=l?await $(l,{check:!0}):void 0;T.info({teamsAppId:l||void 0},"teams app adopted"),s(`
179
179
  Done.
180
- ${oe}`+(T?.endpoint?`
181
- The app is pointed at ${T.endpoint}
180
+ ${de}`+(g?.endpoint?`
181
+ The app is pointed at ${g.endpoint}
182
182
  `:`
183
183
  Bishop cannot tell where this app is pointed, so confirm with whoever
184
184
  created it that its messaging endpoint reaches this host. Bishop serves it
185
185
  at /api/messages.
186
- `)+We(l,re)+Ge(l,pe)+te(f.clientId,await t(f))+"\nRun `bishop` to start the agent.\n")})}async function Qe(e,n={}){const t=n.cwd??process.cwd(),a=o=>process.stdout.write(o),i=await y(t),s=n.appId?.trim()||i.teams?.app?.id;if(!s)throw new m("No Teams app is recorded here, so there is nothing to point.\nRun `bishop teams setup` first, or pass --app-id.");if(!await U())throw Z(V);if(v()&&!(await $()).loggedIn)throw new m(V);const p=(await k(s))?.endpoint;if(p===e){a(`App ${s} already points at ${e}. Nothing to do.
187
- `);return}const{needsReinstall:h}=await be(s,e);I.info({teamsAppId:s,before:p,endpoint:e,needsReinstall:h},"teams messaging endpoint updated"),a(`App ${s} now points at ${e}
188
- `),h&&a(`
186
+ `)+Ye(l,ce)+Ke(l,le)+se(u.clientId,await t(u))+"\nRun `bishop` to start the agent.\n")})}async function sn(e,n={}){const t=n.cwd??process.cwd(),a=r=>process.stdout.write(r),i=await N(t),s=n.appId?.trim()||i.teams?.app?.id;if(!s)throw new m("No Teams app is recorded here, so there is nothing to point.\nRun `bishop teams setup` first, or pass --app-id.");if(!await Y())throw q(Z);if(v()&&!(await R()).loggedIn)throw new m(Z);const p=(await k(s))?.endpoint;if(p===e){a(`App ${s} already points at ${e}. Nothing to do.
187
+ `);return}const{needsReinstall:o}=await Re(s,e);T.info({teamsAppId:s,before:p,endpoint:e,needsReinstall:o},"teams messaging endpoint updated"),a(`App ${s} now points at ${e}
188
+ `),o&&a(`
189
189
  The app's manifest changed, which usually means its valid domains did.
190
190
  Reinstall it in Teams before expecting it to receive anything.
191
- `)}function Xe(e){const n=e?.trim()||"https://<the URL that reaches this host>/api/messages";return["Bishop needs a Microsoft Teams app. To create one for it:","","1. Create a Teams app with a bot. A Teams-managed bot is enough and needs no"," Azure subscription:","",` ${Ee}`," teams login"," teams app create --teams-managed --name <app name> --endpoint <url>",""," The install flags are not optional: without them the CLI cannot store a"," login and every command starts logged out.","","2. Point the bot at this messaging endpoint:","",` ${n}`,""," Teams POSTs every activity here, so it has to be reachable over HTTPS.","","3. Give the app these resource-specific consent permissions:","",...C.map(t=>` teams app rsc add <app id> ${t} --type Application`),""," Without them Teams only delivers a message that @mentions the agent, so a"," reply to its own answer never reaches it, and the agent cannot tell whether"," a channel is private or shared. Whoever installs the app in a team"," or a chat is who consents, and Teams only asks at install time. An app that"," is already installed has to be removed from every team and chat it is in and"," added again: updating it in place never asks, so it goes on hearing nothing"," but mentions.","","4. Turn on file support, so the agent can be sent a file at all:","",` ${b("<app id>").trim()}`,""," Without it Teams shows no attach button in a chat with the agent, so there"," is nothing for anyone to send. An image pasted into a message arrives either"," way. `--yes` is not optional: the CLI refuses the write without it unless"," somebody is there to answer a prompt.","","5. Let the agent read and send files in a channel. Those are on SharePoint"," rather than on the bot channel, so Bishop reads them through Microsoft"," Graph, which needs one application permission on the app registration:","",` ${j}`,...D("<client id>"," ").trimEnd().split(`
191
+ `)}function on(e){const n=e?.trim()||"https://<the URL that reaches this host>/api/messages";return["Bishop needs a Microsoft Teams app. To create one for it:","","1. Create a Teams app with a bot. A Teams-managed bot is enough and needs no"," Azure subscription:","",` ${$e}`," teams login"," teams app create --teams-managed --name <app name> --endpoint <url>",""," The install flags are not optional: without them the CLI cannot store a"," login and every command starts logged out.","","2. Point the bot at this messaging endpoint:","",` ${n}`,""," Teams POSTs every activity here, so it has to be reachable over HTTPS.","","3. Give the app these resource-specific consent permissions:","",...C.map(t=>` teams app rsc add <app id> ${t} --type Application`),""," Without them Teams only delivers a message that @mentions the agent, so a"," reply to its own answer never reaches it, and the agent cannot tell whether"," a channel is private or shared. Whoever installs the app in a team"," or a chat is who consents, and Teams only asks at install time. An app that"," is already installed has to be removed from every team and chat it is in and"," added again: updating it in place never asks, so it goes on hearing nothing"," but mentions.","","4. Turn on file support, so the agent can be sent a file at all:","",` ${y("<app id>").trim()}`,""," Without it Teams shows no attach button in a chat with the agent, so there"," is nothing for anyone to send. An image pasted into a message arrives either"," way. `--yes` is not optional: the CLI refuses the write without it unless"," somebody is there to answer a prompt.","","5. Let the agent read and send files in a channel. Those are on SharePoint"," rather than on the bot channel, so Bishop reads them through Microsoft"," Graph, which needs one application permission on the app registration:","",` ${x}`,...P("<client id>"," ").trimEnd().split(`
192
192
  `),""," That is Files.ReadWrite.All, and it is tenant-wide, which is why it takes an"," administrator. `--allow-no-subscriptions` is what a tenant with no Azure"," subscription needs, which is the ordinary case for a Teams-managed bot."," Skipping this keeps channel file sending unavailable. Files.Read.All still"," permits the agent to read files people attach there.","","6. Allow the app to be installed. Custom app installation has to be on for the"," tenant (Teams Admin Center, Org-wide app settings, Custom apps) and for"," whoever installs it (Users, Policies, App setup policy).","","7. Send back three values, which are credentials and should travel like any"," other secret:",""," the app registration\u2019s client ID"," a client secret for it"," the tenant ID","","Then run `bishop teams setup --manual` here and give it those three.",""].join(`
193
- `)}export{Xe as administratorInstructions,He as applyChannelFileGrant,q as existingTeamsSetup,Qe as repointTeamsEndpoint,qe as setupTeams,Je as setupTeamsManually};
193
+ `)}export{on as administratorInstructions,ze as applyChannelFileGrant,X as existingTeamsSetup,sn as repointTeamsEndpoint,tn as setupTeams,an as setupTeamsManually};
@@ -0,0 +1,2 @@
1
+ import{z as c}from"zod";import{withLevel as E}from"../interface/authorize.js";import{DEFAULT_CONTEXT as p}from"../interface/messages.js";import{describeTime as A,systemTimeZone as x}from"../schedule/cron.js";import{matchAll as O,SEARCH_CONVERSATIONS_TOOL as M}from"../transcript.js";import{excerpt as I,readMoment as _,renderWithin as q}from"./found.js";import{defineTool as R,ToolRefusal as m}from"./types.js";const b=10,v=25,T=10;import{MAX_ANSWER_CHARS as F,MAX_MESSAGE_CHARS as G}from"./found.js";const D="There is nothing to search from here. Bishop searches the other conversations in the channel, DM or chat this one takes place in, and has none on record for it. Email and Slack group DMs never have one. A conversation that started moments ago may not have one recorded yet, so one more try is worth it there and nowhere else.";function W(a){const f=a.zone??x;function l(e,s){return _(e,s,f())}function w(e,s){const d=e.map(({found:o,match:t})=>{const{text:r,cut:n}=I(o.body,o.matchedAt),i=o.kind==="history"||!o.principalId?void 0:a.principals.find(o.principalId)?.principal,h=i&&E(i,a.levelOf);return{id:String(o.id),threadId:o.threadId,at:A(o.at,f()),...h?{principal:h}:{},text:r,...o.kind==="history"?{history:!0}:{},...t?{match:!0}:{},...n?{cut:!0}:{}}});return q(d,[s])}function u(e,s){if(s===0)return e.map(t=>({found:t,match:!0}));const d=new Set(e.map(t=>t.id)),o=new Map;for(const t of e){const r=o.get(t.threadId)??new Map;o.set(t.threadId,r);const{before:n,after:i}=a.search.around(t,s);for(const h of[...n,t,...i])r.set(h.id,h)}return[...o.values()].flatMap(t=>[...t.values()].sort((r,n)=>r.id-n.id).map(r=>({found:r,match:d.has(r.id)})))}return[R({name:M,description:["Searches the other conversations in the channel, DM or chat this one takes place in,","however recent. This conversation isn't searched, since you already have it, and nothing","from anywhere else comes back, whoever asks. Only what people there saw is searched:","their messages and the answers you posted, not what you didn't post.","","Use it when somebody refers to something said in another conversation here, or asks","when or by whom something was said, and it isn't in this conversation. It is what was","said, not how things stand now: anything said here may since have changed, so if you","keep notes of your own, prefer them for the current state and use this for what was","said and when.","","Give query, a date range, or both. Every word in query has to match, and forms of a word","count, so deploy finds deploying. after and before take ISO 8601 dates or times; after is","inclusive and before isn't, and a date with no offset is read in Bishop's zone. Turn a",'phrase like "last week" into dates yourself. With a query the best matches come first;',"with only dates, the latest messages in the range, oldest first.","","Each message comes back under a <said> tag with its id, the conversation it was in,",'and when it was said. match="true" marks what was found rather than context. context',"adds that many messages either side of each match. To read more around one, pass its id","as message, alone or with context.","","Messages from before this tool existed weren't kept in a form it can search. A catch-up","from when you joined a conversation is dated when you joined.",...a.alongside?["",`In Slack, ${a.alongside} also searches here, including conversations you`,"weren't in. Use this one for a conversation you were in, or for anything older than","that one can read back to. Use that one for what people said here whether or not","you were in it, or when this one finds nothing."]:[]].join(`
2
+ `),input:{query:c.string().trim().min(1).optional().describe("Words to find, all of which must match"),after:c.string().trim().min(1).optional().describe("Only messages at or after this, as ISO 8601 like 2026-11-03"),before:c.string().trim().min(1).optional().describe("Only messages before this, as ISO 8601 like 2026-11-10"),limit:c.number().int().min(1).max(v).optional().describe(`How many matches, up to ${v}. Defaults to ${b}`),context:c.number().int().min(0).max(T).optional().describe(`Messages either side of each match, up to ${T}. Defaults to 0 for a search and ${p} when reading around a message`),message:c.number().int().min(1).optional().describe("The id of a message an earlier search returned, to read what was said around it")},async run(e,s){const d=a.search.locationOf(s.thread.id);if(!d)throw new m(D);const o=s.thread.id;if(e.message!==void 0){if(e.query||e.after||e.before||e.limit!==void 0)throw new m("message reads around one message, so it takes context and nothing else. Leave out query, after, before and limit.");const y=a.search.get(d,e.message,o);if(!y)throw new m(`There is no message ${e.message} in another conversation here. Ids come from a search made here.`);return w(u([y],e.context??p))}const t=e.query===void 0?void 0:O(e.query);if(e.query!==void 0&&!t)throw new m("query has no words in it to search for.");if(!t&&!e.after&&!e.before)throw new m("Give query, after or before, or message to read around one.");const r=e.after?l("after",e.after):void 0,n=e.before?l("before",e.before):void 0;if(r!==void 0&&n!==void 0&&r>=n)throw new m("after has to be earlier than before.");const i=e.limit??b,h=a.search.search(d,{except:o,...t?{match:t}:{},...r===void 0?{}:{after:r},...n===void 0?{}:{before:n},limit:i+1});if(h.length===0)return"Nothing here matched.";const k=h.length>i,g=h.slice(0,i);t||g.reverse();const S=k?`More than ${i} matched. Narrow the search, or raise limit, to see the rest.`:void 0;return w(u(g,e.context??0),S)}})]}export{b as DEFAULT_RESULTS,F as MAX_ANSWER_CHARS,T as MAX_CONTEXT,G as MAX_MESSAGE_CHARS,v as MAX_RESULTS,W as conversationTools};
@@ -0,0 +1,3 @@
1
+ import{DateTime as u}from"luxon";import{renderFoundMessage as l,renderFoundMessages as f}from"../harness/principal.js";import{ToolRefusal as h}from"./types.js";const s=2e3,m=4e4;function A(t,r,n){const e=u.fromISO(r.trim(),{zone:n});if(!e.isValid)throw new h(`${t} "${r}" is not a date Bishop can read. Write ISO 8601, like 2026-11-03 or 2026-11-03T15:00.`);return e.toMillis()}function p(t,r,n){const e=/[\uDC00-\uDFFF]/.test(t.charAt(r))?r+1:r,o=/[\uD800-\uDBFF]/.test(t.charAt(n-1))?n-1:n;return t.slice(e,o)}function S(t,r){if(t.length<=s)return{text:t,cut:!1};const n=(r??0)-s/2,e=Math.max(0,Math.min(n,t.length-s)),o=e+s,i=p(t,e,o);return{text:`${e>0?"\u2026":""}${i}${o<t.length?"\u2026":""}`,cut:!0}}function g(t,r=[]){const n=[];let e=0,o=!1;for(const c of t){const a=l(c).length;if(e+a>m){o=!0;break}e+=a,n.push(c)}const i=o?"the rest, left out to keep this short. Search again more narrowly, or with less context":void 0;return[...r,f(n,i)].filter(Boolean).join(`
2
+
3
+ `)}export{m as MAX_ANSWER_CHARS,s as MAX_MESSAGE_CHARS,S as excerpt,A as readMoment,g as renderWithin};
@@ -0,0 +1,2 @@
1
+ import{DateTime as E}from"luxon";import{z as n}from"zod";import{withLevel as O}from"../interface/authorize.js";import{DEFAULT_CONTEXT as w}from"../interface/messages.js";import{DEFAULT_SCAN as g,MAX_SCAN as f,SCAN_DEADLINE_MS as y,SEARCH_HISTORY_TOOL as v,wordMatcher as A}from"../interface/search.js";import{describeTime as x,systemTimeZone as N}from"../schedule/cron.js";import{SEARCH_CONVERSATIONS_TOOL as I}from"../transcript.js";import{DEFAULT_RESULTS as b,MAX_CONTEXT as p,MAX_RESULTS as k}from"./conversations.js";import{excerpt as D,readMoment as T,renderWithin as L}from"./found.js";import{defineTool as M,ToolRefusal as h}from"./types.js";function q(a,i,e,c){const d=a.oldest===void 0?void 0:E.fromMillis(a.oldest,{zone:c}).toISO({suppressMilliseconds:!0}),s=d?`The oldest message read was at ${d}, and nothing before it was searched. To look further back, search again with before set to ${d}.`:"Nothing was read, so nothing was searched.",r=a.partway?` It stopped partway through the thread started by message ${a.partway}, so that thread's later replies weren't searched either.`:"";switch(a.by){case"limit":return`Stopped at ${e} matches. ${s}${r}`;case"scan_limit":return`Stopped after reading ${i} messages, which is scan_limit. ${s}${r} Narrowing after and before, or raising scan_limit (up to ${f}), also reaches further.`;case"time":return`Stopped after ${y/1e3} seconds, the most one search may take. ${s}${r}`;case"unavailable":return`Slack stopped answering partway through. ${s}${r}`}}const C="Slack wouldn't return the replies in some threads, so they weren't searched.";function P(a){const i=a.zone??N;return[M({name:v,description:["Searches everything posted in this Slack channel or DM, threads included: messages from","before you were here, and conversations you weren't part of. This conversation isn't","searched, since you already have it, and nothing from any other channel or DM comes back,","whoever asks.","",`${I} also searches here, but only the conversations you took part`,"in. Use this one for what people said here, whether or not you were in it. Use that one",'for a conversation you were in, like "what did you tell me last month?", or for anything',"older than this one can read back to, since it searches its whole record at once. If that","one finds nothing, try this one before saying nothing was said.","","It reads Slack back from before, or from now, matching as it goes, so it is slower and","bounded. It stops at whichever comes first: limit matches, scan_limit messages read",`(replies included), ${y/1e3} seconds, or after. When it stops short it`,"says so and gives the time of the oldest message it read. Then say you did not look further","back, or narrow the dates and search again; don't report that nothing was said. A reply is","reached through the message that started its thread, so replies in a thread started before","after aren't searched.","","Give query, a date range, or both. Every word in query has to match, and forms of a word","mostly count, so deploy finds deploying. after and before take ISO 8601 dates or times;","after is inclusive and before isn't, and a date with no offset is read in Bishop's zone.",'Turn a phrase like "last week" into dates yourself. Matches come newest first; with only',"dates, the latest messages in the range, oldest first.","","Each message comes back under a <said> tag with its id, which is its Slack timestamp, the",'thread it is in, and when it was said. match="true" marks what was found rather than',"context. context adds that many messages either side of each match. To read more around","one, pass its id as message, alone or with context, or to slack_read_message.","","It reads Slack as it is now: an edited message reads as edited, and a deleted one is gone.","Files on a message aren't listed; slack_read_message on its id shows them."].join(`
2
+ `),input:{query:n.string().trim().min(1).optional().describe("Words to find, all of which must match"),after:n.string().trim().min(1).optional().describe("Only messages at or after this, as ISO 8601 like 2026-11-03"),before:n.string().trim().min(1).optional().describe("Only messages before this, as ISO 8601 like 2026-11-10"),limit:n.number().int().min(1).max(k).optional().describe(`How many matches, up to ${k}. Defaults to ${b}`),context:n.number().int().min(0).max(p).optional().describe(`Messages either side of each match, up to ${p}. Defaults to 0 for a search and ${w} when reading around a message`),message:n.string().trim().min(1).optional().describe("The id of a message an earlier search returned, to read what was said around it"),scan_limit:n.number().int().min(1).max(f).optional().describe(`The most messages to read looking for matches, replies included, up to ${f}. Defaults to ${g}`)},async run(e,c){const d=o=>x(o,i());if(e.message!==void 0&&(e.query||e.after||e.before||e.limit!==void 0||e.scan_limit!==void 0))throw new h("message reads around one message, so it takes context and nothing else. Leave out query, after, before, limit and scan_limit.");const s=e.query===void 0?void 0:A(e.query);if(e.message===void 0){if(e.query!==void 0&&!s)throw new h("query has no words in it to search for.");if(!s&&!e.after&&!e.before)throw new h("Give query, after or before, or message to read around one.")}const r=e.after?T("after",e.after,i()):void 0,m=e.before?T("before",e.before,i()):void 0;if(r!==void 0&&m!==void 0&&r>=m)throw new h("after has to be earlier than before.");const l=e.limit??b,t=await a.search(c.origin.name,c.thread,e.message!==void 0?{kind:"around",message:e.message,context:e.context??w}:{kind:"scan",...s?{match:s}:{},...r===void 0?{}:{after:r},...m===void 0?{}:{before:m},limit:l,scanLimit:e.scan_limit??g,context:e.context??0});if(t.kind==="refused")throw new h(t.reason);const u=[t.stopped?q(t.stopped,t.read,l,i()):void 0,t.incomplete?C:void 0];if(t.messages.length===0)return[t.stopped?`Nothing matched in the ${t.read} messages read.`:"Nothing here matched.",...u].filter(Boolean).join(" ");const S=t.messages.map(o=>{const{text:_,cut:$}=D(o.text,o.matchedAt);return{id:o.ref,threadId:o.thread,at:d(o.at),principal:O(o.principal,a.levelOf),text:_,...o.match?{match:!0}:{},...$?{cut:!0}:{}}});return L(S,u)}})]}export{P as historyTools};
@@ -1,2 +1,2 @@
1
- import{z as t}from"zod";import{renderReadMessages as r}from"../harness/principal.js";import{DEFAULT_CONTEXT as n,MAX_CONTEXT as o,READ_MESSAGE_TOOL as m}from"../interface/messages.js";import{defineTool as d,ToolRefusal as h}from"./types.js";function f(i){return[d({name:m,description:["Reads one Slack message from this conversation, with the messages around it.","",`Takes the link Slack's "Copy link" gives, or a bare timestamp. It reads this channel or`,"DM and nothing else: a link to anywhere else is refused, whoever sent it. Say so and","suggest asking again in the conversation that message is in.","","A message in a thread comes back with its parent and the replies around it. A message","outside a thread comes back with the channel either side of it. The one you named",'carries asked="true"; the rest are context.',"","This reads a message whose location you already know. It cannot search for one."].join(`
2
- `),input:{message:t.string().trim().min(1).describe("A Slack message link, or a timestamp like 1789419098.478749"),context_messages:t.number().int().min(0).max(o).optional().describe(`How many messages either side of it to include, up to ${o}. Defaults to ${n}`)},async run(s,a){const e=await i.read(a.origin.name,a.thread,{message:s.message,context:s.context_messages??n});if(e.kind==="refused")throw new h(e.reason);return r(e.entries,e.omitted)}})]}export{f as messageTools};
1
+ import{z as n}from"zod";import{renderReadMessages as c}from"../harness/principal.js";import{withLevel as d}from"../interface/authorize.js";import{DEFAULT_CONTEXT as o,MAX_CONTEXT as r,READ_MESSAGE_TOOL as h}from"../interface/messages.js";import{defineTool as l,ToolRefusal as g}from"./types.js";function T(s){return[l({name:h,description:["Reads one Slack message from this conversation, with the messages around it.","",`Takes the link Slack's "Copy link" gives, or a bare timestamp. It reads this channel or`,"DM and nothing else: a link to anywhere else is refused, whoever sent it. Say so and","suggest asking again in the conversation that message is in.","","A message in a thread comes back with its parent and the replies around it. A message","outside a thread comes back with the channel either side of it. The one you named",'carries asked="true"; the rest are context.',"","This reads a message whose location you already know. It cannot search for one."].join(`
2
+ `),input:{message:n.string().trim().min(1).describe("A Slack message link, or a timestamp like 1789419098.478749"),context_messages:n.number().int().min(0).max(r).optional().describe(`How many messages either side of it to include, up to ${r}. Defaults to ${o}`)},async run(a,t){const e=await s.read(t.origin.name,t.thread,{message:a.message,context:a.context_messages??o});if(e.kind==="refused")throw new g(e.reason);const m=e.entries.map(i=>({...i,principal:d(i.principal,s.levelOf)}));return c(m,e.omitted)}})]}export{T as messageTools};
@@ -1,9 +1,9 @@
1
- import{z as s}from"zod";import{BishopError as B}from"../errors.js";import{NO_OUTPUT as G}from"../harness/principal.js";import{log as R}from"../log.js";import{principalLabel as W}from"../principals.js";import{describeTime as $,describeTiming as I,nextRun as E,parseAt as O,systemTimeZone as C,validateCron as L,validateTimeZone as j}from"../schedule/cron.js";import{defineTool as A,ToolRefusal as d}from"./types.js";const Z=20;function _(e){return e.principal.id}function y(e){try{return e()}catch(n){throw n instanceof B?new d(n.message):n}}async function D(e){try{return await e()}catch(n){throw n instanceof B?new d(n.message):n}}function P(e,n,i){const o=[`${e.id} ${e.name}${e.enabled?"":" (disabled)"}`,` runs ${I(e)}`,` next ${e.enabled?$(e.nextRunAt,n):"never, while it is off"}`,` to ${e.destination.label}`,` prompt ${e.prompt}`,` by ${W(e.createdBy,i)}`];return e.lastError&&o.push(` error ${e.lastError} (${e.consecutiveFailures} in a row)`),o.join(`
2
- `)}async function k(e,n){const i=await n.destination(),o=_(n);return e.schedules.all().filter(t=>t.createdBy===o||e.sameConversation(t.destination,i))}function S(e,n,i){const o=_(n);if(!e.authorized(o))throw new d(`Bishop can't run a schedule created by ${n.principal.name}, so ${i?"changing this one":"making one"} would write something that never fires. Ask an operator to add it with \`bishop schedules add\`.`);if(i?.createdBy===o)return o;const t=e.schedules.all().filter(l=>l.createdBy===o).length;if(t>=Z)throw new d(`You already have ${t} schedules, which is the limit. Remove one with schedule_delete before ${i?"taking on":"adding"} another.`);return o}function U(e){const n=e.now??Date.now;return A({name:"schedule_create",description:["Runs a prompt on a cron schedule, or once at a set time, and posts the answer where you","say. Give cron for a schedule that repeats, or at for a reminder, which runs once and is","then deleted. Each firing is a fresh session with no memory of the last one, so the prompt","has to carry everything it needs.","",`The prompt must say when to stay quiet, and say that answering ${G} is how.`,"A schedule that reports every time it runs is one people learn to ignore."].join(`
3
- `),input:{name:s.string().trim().min(1).describe("What a person sees in a list, and an email subject"),cron:s.string().trim().min(1).optional().describe("Five-field cron, or @daily and friends. No more than once every five minutes. Leave it out when giving at"),at:s.string().trim().min(1).optional().describe("For a reminder: when it runs, as ISO 8601 like 2026-10-09T15:00, read in tz unless it carries an offset. Leave it out when giving cron"),prompt:s.string().trim().min(1).describe("What the agent is asked at each firing, including when to say nothing"),to:s.string().trim().min(1).optional().describe("Where the answer goes: #channel or @person, or an email address. In Teams a channel is one in this team, by its exact name, and a person is somebody in this conversation. Leave it out to post back into this conversation."),tz:s.string().trim().min(1).optional().describe("IANA zone cron or at is read in, like Europe/London. Defaults to Bishop's")},async run(i,o){const{cron:t,at:l}=i;if(t===void 0==(l===void 0))throw new d("Give exactly one of cron, for a schedule that repeats, or at.");const b=S(e,o),m=i.tz,c=m?y(()=>j(m)):C(),v=y(t?()=>(L(t,c),E(t,c,n())):()=>O(l??"",c,n())),u=i.to,p=await o.destination(),f=u?await D(()=>e.resolve(u,p)):p,r=e.schedules.add({name:i.name,...t?{cron:t}:{},tz:c,prompt:i.prompt,destination:f,createdBy:b,nextRunAt:v});return R.info({schedule:r.id,name:r.name,cron:r.cron,tz:r.tz,at:new Date(r.nextRunAt).toISOString(),by:r.createdBy,to:f.label},"the agent created a schedule"),r.cron?`Created ${r.id} "${r.name}", running ${r.cron} (${c}).
4
- Next ${$(r.nextRunAt,c)}, posting to ${f.label}.`:`Created reminder ${r.id} "${r.name}", running once at ${$(r.nextRunAt,c)}, posting to ${f.label}. It is deleted once it runs.`}})}function q(e){return A({name:"schedule_list",description:"Lists the schedules you created, and any that post into this conversation. Not schedules other people aimed elsewhere.",input:{},async run(n,i){const o=await k(e,i);if(o.length===0)return"Nothing is scheduled here, and you have not made any.";const t=C();return`${o.map(l=>P(l,t,e.principals)).join(`
1
+ import{z as s}from"zod";import{BishopError as N}from"../errors.js";import{NO_OUTPUT as G}from"../harness/principal.js";import{log as k}from"../log.js";import{principalLabel as W}from"../principals.js";import{describeTime as $,describeTiming as B,nextRun as E,parseAt as O,systemTimeZone as C,validateCron as L,validateTimeZone as D}from"../schedule/cron.js";import{defineTool as A,ToolRefusal as c}from"./types.js";const Z=20;function R(e){return e.principal.id}function y(e){try{return e()}catch(n){throw n instanceof N?new c(n.message):n}}async function S(e){try{return await e()}catch(n){throw n instanceof N?new c(n.message):n}}function P(e,n,o){const i=[`${e.id} ${e.name}${e.enabled?"":" (disabled)"}`,` runs ${B(e)}`,` next ${e.enabled?$(e.nextRunAt,n):"never, while it is off"}`,` to ${e.destination.label}`,` prompt ${e.prompt}`,` by ${W(e.createdBy,o)}`];return e.lastError&&i.push(` error ${e.lastError} (${e.consecutiveFailures} in a row)`),i.join(`
2
+ `)}async function _(e,n){const o=await n.destination(),i=R(n);return e.schedules.all().filter(t=>t.createdBy===i||e.sameConversation(t.destination,o))}function j(e,n,o){const i=R(n);if(!e.authorized(i))throw new c(`A schedule runs only for someone at write or above, and ${n.principal.name} isn't, so ${o?"changing this one":"making one"} would write something that never fires. Ask an admin for write, or an operator to add it with \`bishop schedules add\`.`);if(o?.createdBy===i)return i;const t=e.schedules.all().filter(l=>l.createdBy===i).length;if(t>=Z)throw new c(`You already have ${t} schedules, which is the limit. Remove one with schedule_delete before ${o?"taking on":"adding"} another.`);return i}function U(e){const n=e.now??Date.now;return A({name:"schedule_create",needs:"write",description:["Runs a prompt on a cron schedule, or once at a set time, and posts the answer where you","say. Give cron for a schedule that repeats, or at for a reminder, which runs once and is","then deleted. Each firing is a fresh session with no memory of the last one, so the prompt","has to carry everything it needs.","",`The prompt must say when to stay quiet, and say that answering ${G} is how.`,"A schedule that reports every time it runs is one people learn to ignore."].join(`
3
+ `),input:{name:s.string().trim().min(1).describe("What a person sees in a list, and an email subject"),cron:s.string().trim().min(1).optional().describe("Five-field cron, or @daily and friends. No more than once every five minutes. Leave it out when giving at"),at:s.string().trim().min(1).optional().describe("For a reminder: when it runs, as ISO 8601 like 2026-10-09T15:00, read in tz unless it carries an offset. Leave it out when giving cron"),prompt:s.string().trim().min(1).describe("What the agent is asked at each firing, including when to say nothing"),to:s.string().trim().min(1).optional().describe("Where the answer goes: #channel or @person, or an email address. In Slack a person's member ID works too, and is what reaches somebody from another organization whose messages you have not seen yet. In Teams a channel is one in this team, by its exact name, and a person is somebody in this conversation. Leave it out to post back into this conversation."),tz:s.string().trim().min(1).optional().describe("IANA zone cron or at is read in, like Europe/London. Defaults to Bishop's")},async run(o,i){const{cron:t,at:l}=o;if(t===void 0==(l===void 0))throw new c("Give exactly one of cron, for a schedule that repeats, or at.");const b=j(e,i),m=o.tz,d=m?y(()=>D(m)):C(),v=y(t?()=>(L(t,d),E(t,d,n())):()=>O(l??"",d,n())),u=o.to,f=await i.destination(),p=u?await S(()=>e.resolve(u,f)):f,r=e.schedules.add({name:o.name,...t?{cron:t}:{},tz:d,prompt:o.prompt,destination:p,createdBy:b,nextRunAt:v});return k.info({schedule:r.id,name:r.name,cron:r.cron,tz:r.tz,at:new Date(r.nextRunAt).toISOString(),by:r.createdBy,to:p.label},"the agent created a schedule"),r.cron?`Created ${r.id} "${r.name}", running ${r.cron} (${d}).
4
+ Next ${$(r.nextRunAt,d)}, posting to ${p.label}.`:`Created reminder ${r.id} "${r.name}", running once at ${$(r.nextRunAt,d)}, posting to ${p.label}. It is deleted once it runs.`}})}function q(e){return A({name:"schedule_list",description:"Lists the schedules you created, and any that post into this conversation. Not schedules other people aimed elsewhere.",input:{},async run(n,o){const i=await _(e,o);if(i.length===0)return"Nothing is scheduled here, and you have not made any.";const t=C();return`${i.map(l=>P(l,t,e.principals)).join(`
5
5
 
6
6
  `)}
7
7
 
8
- Times in ${t}.`}})}function M(e){const n=e.now??Date.now;return A({name:"schedule_update",description:"Changes a schedule by id and keeps the id. Only ones schedule_list shows you. Anything you leave out stays as it is.",input:{id:s.string().trim().min(1).describe("The id schedule_list reports"),name:s.string().trim().min(1).optional().describe("A new name"),cron:s.string().trim().min(1).optional().describe("A new five-field cron, or @daily and friends. No more than once every five minutes. Turns a reminder into a schedule that repeats"),at:s.string().trim().min(1).optional().describe("A new time to run once, as ISO 8601 like 2026-10-09T15:00. Turns a repeating schedule into a reminder"),prompt:s.string().trim().min(1).optional().describe("A new prompt, whole. It replaces the old one rather than adding to it"),to:s.string().trim().min(1).optional().describe("A new destination: #channel or @person, or an email address"),tz:s.string().trim().min(1).optional().describe("A new IANA zone, like Europe/London")},async run(i,o){const t=`No schedule ${i.id} that you can change. schedule_list has the ones you can.`;if(!(await k(e,o)).some(z=>z.id===i.id))throw new d(t);const{name:b,cron:m,at:c,prompt:v,to:u,tz:p}=i;if([b,m,c,v,u,p].every(z=>z===void 0))throw new d("Nothing to change. Name at least one of name, cron, at, prompt, to, or tz.");if(m!==void 0&&c!==void 0)throw new d("Give cron or at, not both.");const f=p?y(()=>j(p)):void 0,r=u?await D(async()=>e.resolve(u,await o.destination())):void 0,a=e.schedules.get(i.id);if(!a)throw new d(t);const x=S(e,o,a),w=f??a.tz,g=c===void 0?m??a.cron:void 0;let T=a.nextRunAt;c!==void 0?T=y(()=>O(c,w,n())):g&&(g!==a.cron||w!==a.tz)&&(y(()=>L(g,w)),T=E(g,w,n()));const h={...a,name:b??a.name,cron:g,tz:w,prompt:v??a.prompt,destination:r??a.destination,createdBy:x,nextRunAt:T};e.schedules.update(a.id,h);const{destination:N}=h;R.info({schedule:a.id,name:h.name,cron:h.cron,tz:h.tz,by:x,to:N.label},"the agent changed a schedule");const F=h.enabled?`Next ${$(h.nextRunAt,w)}`:`It is off, so nothing fires until an operator runs \`bishop schedules enable ${a.id}\``;return`Changed ${a.id} "${h.name}", running ${I(h)}.
9
- ${F}, posting to ${N.label}.`}})}function X(e){return A({name:"schedule_delete",description:"Removes a schedule by id. Only ones schedule_list shows you.",input:{id:s.string().trim().min(1).describe("The id schedule_list reports")},async run(n,i){const t=(await k(e,i)).find(l=>l.id===n.id);if(!t)throw new d(`No schedule ${n.id} that you can remove. schedule_list has the ones you can.`);return e.schedules.remove(t.id),R.info({schedule:t.id,name:t.name,by:_(i)},"the agent removed a schedule"),`Removed ${t.id} "${t.name}".`}})}function ne(e){return[U(e),q(e),M(e),X(e)]}export{Z as MAX_PER_CREATOR,_ as createdBy,ne as scheduleTools};
8
+ Times in ${t}.`}})}function M(e){const n=e.now??Date.now;return A({name:"schedule_update",needs:"write",description:"Changes a schedule by id and keeps the id. Only ones schedule_list shows you. Anything you leave out stays as it is.",input:{id:s.string().trim().min(1).describe("The id schedule_list reports"),name:s.string().trim().min(1).optional().describe("A new name"),cron:s.string().trim().min(1).optional().describe("A new five-field cron, or @daily and friends. No more than once every five minutes. Turns a reminder into a schedule that repeats"),at:s.string().trim().min(1).optional().describe("A new time to run once, as ISO 8601 like 2026-10-09T15:00. Turns a repeating schedule into a reminder"),prompt:s.string().trim().min(1).optional().describe("A new prompt, whole. It replaces the old one rather than adding to it"),to:s.string().trim().min(1).optional().describe("A new destination: #channel or @person, or an email address. In Slack a person's member ID works too"),tz:s.string().trim().min(1).optional().describe("A new IANA zone, like Europe/London")},async run(o,i){const t=`No schedule ${o.id} that you can change. schedule_list has the ones you can.`;if(!(await _(e,i)).some(z=>z.id===o.id))throw new c(t);const{name:b,cron:m,at:d,prompt:v,to:u,tz:f}=o;if([b,m,d,v,u,f].every(z=>z===void 0))throw new c("Nothing to change. Name at least one of name, cron, at, prompt, to, or tz.");if(m!==void 0&&d!==void 0)throw new c("Give cron or at, not both.");const p=f?y(()=>D(f)):void 0,r=u?await S(async()=>e.resolve(u,await i.destination())):void 0,a=e.schedules.get(o.id);if(!a)throw new c(t);const x=j(e,i,a),w=p??a.tz,g=d===void 0?m??a.cron:void 0;let T=a.nextRunAt;d!==void 0?T=y(()=>O(d,w,n())):g&&(g!==a.cron||w!==a.tz)&&(y(()=>L(g,w)),T=E(g,w,n()));const h={...a,name:b??a.name,cron:g,tz:w,prompt:v??a.prompt,destination:r??a.destination,createdBy:x,nextRunAt:T};e.schedules.update(a.id,h);const{destination:I}=h;k.info({schedule:a.id,name:h.name,cron:h.cron,tz:h.tz,by:x,to:I.label},"the agent changed a schedule");const F=h.enabled?`Next ${$(h.nextRunAt,w)}`:`It is off, so nothing fires until an operator runs \`bishop schedules enable ${a.id}\``;return`Changed ${a.id} "${h.name}", running ${B(h)}.
9
+ ${F}, posting to ${I.label}.`}})}function X(e){return A({name:"schedule_delete",needs:"write",description:"Removes a schedule by id. Only ones schedule_list shows you.",input:{id:s.string().trim().min(1).describe("The id schedule_list reports")},async run(n,o){const t=(await _(e,o)).find(l=>l.id===n.id);if(!t)throw new c(`No schedule ${n.id} that you can remove. schedule_list has the ones you can.`);return e.schedules.remove(t.id),k.info({schedule:t.id,name:t.name,by:R(o)},"the agent removed a schedule"),`Removed ${t.id} "${t.name}".`}})}function ne(e){return[U(e),q(e),M(e),X(e)]}export{Z as MAX_PER_CREATOR,R as createdBy,ne as scheduleTools};
@@ -1 +1 @@
1
- import{randomBytes as S,randomUUID as k}from"node:crypto";import{createServer as E}from"node:http";import{McpServer as x}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as T}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{isInitializeRequest as N}from"@modelcontextprotocol/sdk/types.js";import{log as m}from"../log.js";import{ToolRefusal as y}from"./types.js";const _="bishop",b="/mcp",v="BISHOP_TOOL_TOKEN",B=1048576;function O(t){const a=t.headers.authorization;return a&&/^Bearer\s+(.+)$/i.exec(a.trim())?.[1]?.trim()||void 0}function w(t,a,s){t.writeHead(a,{"content-type":"application/json"}),t.end(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32001,message:s}}))}async function R(t){const a=[];let s=0;for await(const c of t){if(s+=c.length,s>B)throw new Error("request body is too large");a.push(c)}if(a.length!==0)return JSON.parse(Buffer.concat(a).toString("utf8"))}const A="Bishop's tools answer to a person, and this message came from another bot. Ask someone in the conversation to do it.",I="No turn is running in this conversation, so Bishop's tools have nobody to act for. Say what you need in your reply, and it can be done when someone next writes.";function P(t){return t.length>0?`Nobody asked for this turn, so only ${t.join(", ")} can be used in it.`:"Nobody asked for this turn, so none of Bishop's tools can be used in it."}function z(t){const a=new x({name:_,version:"1"});for(const s of t.tools)a.registerTool(s.name,{description:s.description,inputSchema:s.input},async c=>{const f=t.binding;try{if(!f)throw new y(I);if(f.only&&!f.only.includes(s.name))throw new y(P(f.only));const{context:i}=f;if(i.principal.kind==="bot")throw new y(A);return{content:[{type:"text",text:await s.run(c,i)}]}}catch(i){const h=i instanceof Error?i.message:String(i),p=f?.context.thread.threadKey;return i instanceof y?m.info({tool:s.name,thread:p,reason:h},"a tool refused"):m.error({tool:s.name,thread:p,err:i},"a tool failed"),{content:[{type:"text",text:h}],isError:!0}}});return a}async function j(t){const a=t.host??"127.0.0.1",s=new Map,c=new Map;async function f(e,n){const o=new T({sessionIdGenerator:()=>k(),onsessioninitialized:r=>{if(s.get(e)!==n){o.close().catch(()=>{});return}c.set(r,{token:e,transport:o}),n.sessions.add(r)}});return o.onclose=()=>{const r=o.sessionId;r&&(c.delete(r),n.sessions.delete(r))},await z(n).connect(o),o}const i=E((e,n)=>{(async()=>{try{if(!e.url?.startsWith(b))return w(n,404,"no such endpoint");const o=O(e),r=o?s.get(o):void 0;if(!r||!o)return w(n,401,"this call carries no valid credential");const u=e.method==="POST"?await R(e):void 0,d=e.headers["mcp-session-id"],l=typeof d=="string"?c.get(d):void 0;if(l){if(l.token!==o)return w(n,404,"no such session");await l.transport.handleRequest(e,n,u);return}if(typeof d=="string")return w(n,404,"no such session");if(!N(u))return w(n,400,"the first call on a connection must be initialize");await(await f(o,r)).handleRequest(e,n,u)}catch(o){m.error({err:o},"a tool call could not be handled"),n.headersSent?n.end():w(n,400,"that request could not be handled")}})()});await new Promise((e,n)=>{i.once("error",n),i.listen(0,a,()=>{i.removeListener("error",n),e()})});const h=i.address();if(!h||typeof h=="string")throw new Error("the tool endpoint started without a port");const p=`http://${a}:${h.port}${b}`;m.info({url:p,tools:t.tools.map(e=>e.name)},"serving the agent its own tools");function g(e){const n=S(32).toString("base64url");return s.set(n,e),{token:n,revoke:()=>{if(s.delete(n)){e.binding=void 0;for(const r of e.sessions){const u=c.get(r);c.delete(r),u?.transport.close().catch(d=>{m.debug({err:d},"a tool connection did not close cleanly")})}e.sessions.clear()}}}}return{url:p,toolNames:t.tools.map(e=>e.name),grant(e,n){const o=n?.only,r=o?t.tools.filter(l=>o.includes(l.name)):t.tools;o&&r.length!==o.length&&m.error({asked:[...o],serving:r.map(l=>l.name)},"a turn asked for tools this endpoint does not serve");const{token:u,revoke:d}=g({binding:{context:e},tools:r,sessions:new Set});return{access:{url:p,tokenEnvVar:v,token:u},revoke:d}},lease(){const e={binding:void 0,tools:t.tools,sessions:new Set},{token:n,revoke:o}=g(e);return{access:{url:p,tokenEnvVar:v,token:n},bind(r,u){const d=u?.only,l={context:r,...d?{only:d}:{}};return e.binding=l,()=>{e.binding===l&&(e.binding=void 0)}},revoke:o}},async stop(){for(const{transport:e}of c.values())await e.close().catch(()=>{});c.clear(),s.clear(),i.closeAllConnections(),await new Promise(e=>i.close(()=>e()))}}}export{b as PATH,_ as SERVER_NAME,v as TOKEN_ENV_VAR,j as startToolServer};
1
+ import{randomBytes as S,randomUUID as k}from"node:crypto";import{createServer as E}from"node:http";import{McpServer as T}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as x}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{isInitializeRequest as N}from"@modelcontextprotocol/sdk/types.js";import{log as p}from"../log.js";import{atLeast as R}from"../permissions/levels.js";import{ToolRefusal as y}from"./types.js";const _="bishop",v="/mcp",b="BISHOP_TOOL_TOKEN",B=1048576;function O(s){const a=s.headers.authorization;return a&&/^Bearer\s+(.+)$/i.exec(a.trim())?.[1]?.trim()||void 0}function w(s,a,t){s.writeHead(a,{"content-type":"application/json"}),s.end(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32001,message:t}}))}async function $(s){const a=[];let t=0;for await(const c of s){if(t+=c.length,t>B)throw new Error("request body is too large");a.push(c)}if(a.length!==0)return JSON.parse(Buffer.concat(a).toString("utf8"))}const A="Bishop's tools answer to a person, and this message came from another bot. Ask someone in the conversation to do it.",I="No turn is running in this conversation, so Bishop's tools have nobody to act for. Say what you need in your reply, and it can be done when someone next writes.";function P(s,a,t){return`This conversation runs at ${t}, and ${s} needs ${a}. Someone with ${a} can start a new thread and ask there.`}function z(s){return s.length>0?`Nobody asked for this turn, so only ${s.join(", ")} can be used in it.`:"Nobody asked for this turn, so none of Bishop's tools can be used in it."}function L(s){const a=new T({name:_,version:"1"});for(const t of s.tools)a.registerTool(t.name,{description:t.description,inputSchema:t.input},async c=>{const f=s.binding;try{if(!f)throw new y(I);if(f.only&&!f.only.includes(t.name))throw new y(z(f.only));const{context:r}=f;if(r.principal.kind==="bot")throw new y(A);if(t.needs&&r.level&&!R(r.level,t.needs))throw new y(P(t.name,t.needs,r.level));return{content:[{type:"text",text:await t.run(c,r)}]}}catch(r){const h=r instanceof Error?r.message:String(r),m=f?.context.thread.threadKey;return r instanceof y?p.info({tool:t.name,thread:m,reason:h},"a tool refused"):p.error({tool:t.name,thread:m,err:r},"a tool failed"),{content:[{type:"text",text:h}],isError:!0}}});return a}async function Y(s){const a=s.host??"127.0.0.1",t=new Map,c=new Map;async function f(e,n){const o=new x({sessionIdGenerator:()=>k(),onsessioninitialized:i=>{if(t.get(e)!==n){o.close().catch(()=>{});return}c.set(i,{token:e,transport:o}),n.sessions.add(i)}});return o.onclose=()=>{const i=o.sessionId;i&&(c.delete(i),n.sessions.delete(i))},await L(n).connect(o),o}const r=E((e,n)=>{(async()=>{try{if(!e.url?.startsWith(v))return w(n,404,"no such endpoint");const o=O(e),i=o?t.get(o):void 0;if(!i||!o)return w(n,401,"this call carries no valid credential");const u=e.method==="POST"?await $(e):void 0,d=e.headers["mcp-session-id"],l=typeof d=="string"?c.get(d):void 0;if(l){if(l.token!==o)return w(n,404,"no such session");await l.transport.handleRequest(e,n,u);return}if(typeof d=="string")return w(n,404,"no such session");if(!N(u))return w(n,400,"the first call on a connection must be initialize");await(await f(o,i)).handleRequest(e,n,u)}catch(o){p.error({err:o},"a tool call could not be handled"),n.headersSent?n.end():w(n,400,"that request could not be handled")}})()});await new Promise((e,n)=>{r.once("error",n),r.listen(0,a,()=>{r.removeListener("error",n),e()})});const h=r.address();if(!h||typeof h=="string")throw new Error("the tool endpoint started without a port");const m=`http://${a}:${h.port}${v}`;p.info({url:m,tools:s.tools.map(e=>e.name)},"serving the agent its own tools");function g(e){const n=S(32).toString("base64url");return t.set(n,e),{token:n,revoke:()=>{if(t.delete(n)){e.binding=void 0;for(const i of e.sessions){const u=c.get(i);c.delete(i),u?.transport.close().catch(d=>{p.debug({err:d},"a tool connection did not close cleanly")})}e.sessions.clear()}}}}return{url:m,toolNames:s.tools.map(e=>e.name),grant(e,n){const o=n?.only,i=o?s.tools.filter(l=>o.includes(l.name)):s.tools;o&&i.length!==o.length&&p.error({asked:[...o],serving:i.map(l=>l.name)},"a turn asked for tools this endpoint does not serve");const{token:u,revoke:d}=g({binding:{context:e},tools:i,sessions:new Set});return{access:{url:m,tokenEnvVar:b,token:u},revoke:d}},lease(){const e={binding:void 0,tools:s.tools,sessions:new Set},{token:n,revoke:o}=g(e);return{access:{url:m,tokenEnvVar:b,token:n},bind(i,u){const d=u?.only,l={context:i,...d?{only:d}:{}};return e.binding=l,()=>{e.binding===l&&(e.binding=void 0)}},revoke:o}},async stop(){for(const{transport:e}of c.values())await e.close().catch(()=>{});c.clear(),t.clear(),r.closeAllConnections(),await new Promise(e=>r.close(()=>e()))}}}export{v as PATH,_ as SERVER_NAME,b as TOKEN_ENV_VAR,Y as startToolServer};
@@ -1,3 +1,26 @@
1
- import{promptParts as o}from"./harness/principal.js";import{log as a}from"./log.js";import{placedRefs as l}from"./outgoing.js";import{SYSTEM_PRINCIPAL as c}from"./principals.js";function h(t){const n=t.prepare(`INSERT INTO transcript
2
- (thread_id, turn_id, direction, kind, principal_id, external_id, text, files, at)
3
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`);return{record(i){if(i.length!==0)try{t.exec("BEGIN");try{for(const r of i)n.run(r.threadId,r.turnId,r.direction,r.kind,r.principalId??null,r.externalId??null,r.text,r.files?.length?JSON.stringify(r.files):null,r.at);t.exec("COMMIT")}catch(r){throw t.exec("ROLLBACK"),r}}catch(r){a.warn({err:r,thread:i[0]?.threadId,turn:i[0]?.turnId},"couldn't record the transcript")}}}}function u(t){const n=o(t),i={threadId:t.threadId,turnId:t.turnId,direction:"in"},r=[];if(n.history){const e=(t.history??[]).flatMap(d=>d.kind==="message"?d.files??[]:[]);r.push({...i,kind:"history",principalId:c.id,text:n.history,...e.length?{files:e}:{},at:t.at})}return t.messages.forEach((e,d)=>{r.push({...i,kind:"message",principalId:e.principal.id,...e.externalId?{externalId:e.externalId}:{},text:n.messages[d]??"",...e.files?.length?{files:e.files}:{},at:t.at})}),r}function x(t){const n=l(t.text).flatMap(i=>{const r=t.shared.get(i);return r?[r]:[]});return{threadId:t.threadId,turnId:t.turnId,direction:"out",kind:t.kind,...t.agent?{principalId:t.agent.id}:{},text:t.text,...n.length?{files:n}:{},at:t.at}}export{u as inbound,x as outbound,h as transcriptStore};
1
+ import{promptParts as N,saysNoOutput as x}from"./harness/principal.js";import{log as h}from"./log.js";import{namePlacements as O,placedRefs as m}from"./outgoing.js";import{SYSTEM_PRINCIPAL as E}from"./principals.js";function T(e){const t=e.prepare(`INSERT INTO transcript_entries
2
+ (thread_id, turn_id, direction, kind, principal_id, external_id, text, files, body, at,
3
+ pending)
4
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),s=e.prepare(`SELECT direction, principal_id, body FROM transcript_entries
5
+ WHERE thread_id = ? AND body IS NOT NULL AND kind != 'history'
6
+ ORDER BY seq DESC LIMIT ?`),c=e.prepare(`SELECT seq, principal_id, external_id, text, files, at FROM transcript_entries
7
+ WHERE thread_id = ? AND pending = 1 ORDER BY seq`),d=e.prepare("UPDATE transcript_entries SET pending = 0, turn_id = ? WHERE seq = ? AND pending = 1");return{recent(n,i){try{return s.all(n,i).reverse().map(a=>({direction:a.direction,...a.principal_id?{principalId:a.principal_id}:{},body:a.body}))}catch(r){return h.warn({err:r,thread:n},"couldn't read the transcript"),[]}},pending(n){try{return c.all(n).map(r=>({seq:r.seq,...r.principal_id?{principalId:r.principal_id}:{},...r.external_id?{externalId:r.external_id}:{},text:r.text,...r.files?{files:JSON.parse(r.files)}:{},at:r.at}))}catch(i){return h.warn({err:i,thread:n},"couldn't read the messages the agent skipped"),[]}},delivered(n,i){if(n.length!==0)try{e.exec("BEGIN");try{for(const r of n)d.run(i,r);e.exec("COMMIT")}catch(r){throw e.exec("ROLLBACK"),r}}catch(r){h.warn({err:r,turn:i},"couldn't mark skipped messages as delivered")}},record(n){if(n.length===0)return!0;try{e.exec("BEGIN");try{for(const i of n)t.run(i.threadId,i.turnId,i.direction,i.kind,i.principalId??null,i.externalId??null,i.text,i.files?.length?JSON.stringify(i.files):null,i.body??null,i.at,i.pending?1:0);e.exec("COMMIT")}catch(i){throw e.exec("ROLLBACK"),i}return!0}catch(i){return h.warn({err:i,thread:n[0]?.threadId,turn:n[0]?.turnId},"couldn't record the transcript"),!1}}}}function M(e){const t=N(e),s={threadId:e.threadId,turnId:e.turnId,direction:"in"},c=[];if(t.history){const d=(e.history??[]).flatMap(n=>n.kind==="message"?n.files??[]:[]);c.push({...s,kind:"history",principalId:E.id,text:t.history,...d.length?{files:d}:{},...f(R(e.history??[])),at:e.at})}return e.messages.forEach((d,n)=>{c.push({...s,kind:"message",principalId:d.principal.id,...d.externalId?{externalId:d.externalId}:{},text:t.messages[n]??"",...d.files?.length?{files:d.files}:{},...d.principal.id===E.id?{}:f(u(d.text,d.files)),at:e.at})}),c}function k(e){const t=e.posted??e.text,s=m(e.text).flatMap(c=>{const d=e.shared.get(c);return d?[d]:[]});return{threadId:e.threadId,turnId:e.turnId,direction:"out",kind:e.kind,...e.agent?{principalId:e.agent.id}:{},text:e.text,...s.length?{files:s}:{},...e.kind==="result"&&t!==!1&&!x(t)?f(O(t,c=>e.shared.get(c)?.name)):{},at:e.at}}function y(e){const{message:t}=e;return{threadId:e.threadId,turnId:e.decisionId,direction:"in",kind:"skipped",principalId:t.principal.id,...t.externalId?{externalId:t.externalId}:{},text:t.text,...t.files?.length?{files:t.files}:{},...f(u(t.text,t.files)),pending:!0,at:e.at}}function u(e,t){return[e,...(t??[]).map(s=>`[file: ${s.name}]`)].join(`
8
+ `)}function R(e){return e.flatMap(t=>t.kind==="message"?[`${t.principal.name||t.principal.handle}: ${u(t.text,t.files)}`]:[]).join(`
9
+
10
+ `)}function f(e){return e.trim()?{body:e.trim()}:{}}const C="conversation_search",_="";function I(e){return{id:e.seq,threadId:e.thread_id,kind:e.kind,...e.principal_id?{principalId:e.principal_id}:{},body:e.body,...e.marked?.includes(_)?{matchedAt:e.marked.indexOf(_)}:{},at:e.at}}const l="e.seq, e.thread_id, e.kind, e.principal_id, e.body, e.at";function B(e){const t=e.prepare("SELECT location_id FROM threads WHERE id = ?"),s=e.prepare(`SELECT ${l}, highlight(transcript_search, 0, char(1), char(2)) AS marked
11
+ FROM transcript_search s
12
+ JOIN transcript_entries e ON e.seq = s.rowid
13
+ JOIN threads t ON t.id = e.thread_id
14
+ WHERE transcript_search MATCH ? AND t.location_id = ? AND e.thread_id != ?
15
+ AND e.at >= ? AND e.at < ?
16
+ ORDER BY s.rank LIMIT ?`),c=e.prepare(`SELECT ${l} FROM transcript_entries e
17
+ JOIN threads t ON t.id = e.thread_id
18
+ WHERE t.location_id = ? AND e.thread_id != ? AND e.body IS NOT NULL
19
+ AND e.at >= ? AND e.at < ?
20
+ ORDER BY e.seq DESC LIMIT ?`),d=e.prepare(`SELECT ${l} FROM transcript_entries e
21
+ JOIN threads t ON t.id = e.thread_id
22
+ WHERE e.seq = ? AND t.location_id = ? AND e.thread_id != ? AND e.body IS NOT NULL`),n=e.prepare(`SELECT ${l} FROM transcript_entries e
23
+ WHERE e.thread_id = ? AND e.seq < ? AND e.body IS NOT NULL
24
+ ORDER BY e.seq DESC LIMIT ?`),i=e.prepare(`SELECT ${l} FROM transcript_entries e
25
+ WHERE e.thread_id = ? AND e.seq > ? AND e.body IS NOT NULL
26
+ ORDER BY e.seq LIMIT ?`);return{locationOf(r){return t.get(r)?.location_id??void 0},search(r,a){const o=a.after??0,p=a.before??Number.MAX_SAFE_INTEGER;return(a.match?s.all(a.match,r,a.except,o,p,a.limit):c.all(r,a.except,o,p,a.limit)).map(I)},get(r,a,o){const p=d.get(a,r,o);return p?I(p):void 0},around(r,a){if(a<=0)return{before:[],after:[]};const o=n.all(r.threadId,r.id,a).map(I).reverse(),p=i.all(r.threadId,r.id,a).map(I);return{before:o,after:p}}}}function H(e){const t=e.split(/\s+/).map(s=>s.replaceAll('"',"")).filter(s=>/[\p{L}\p{N}]/u.test(s));return t.length?t.map(s=>`"${s}"`).join(" "):void 0}export{C as SEARCH_CONVERSATIONS_TOOL,M as inbound,H as matchAll,k as outbound,u as said,y as skipped,B as transcriptSearch,T as transcriptStore};
package/dist/turn.js CHANGED
@@ -1,3 +1,3 @@
1
- import{createHash as le,randomUUID as Z}from"node:crypto";import{rm as ce}from"node:fs/promises";import{join as $}from"node:path";import{contextChangeNote as he,guidanceChangeNote as fe}from"./harness/principal.js";import{mint as ee}from"./ids.js";import{log as i}from"./log.js";import{SHARE_FILE_TOOL as ge}from"./outgoing.js";import{SYSTEM_PRINCIPAL as we}from"./principals.js";import{stageFile as te}from"./sandbox.js";import{schedulePresence as ue}from"./schedule/presence.js";import{inbound as ye,outbound as oe}from"./transcript.js";import{worktreeName as me}from"./worktrees.js";function pe(o){const{location:y,visibility:_,audience:H}=o;return{...y?{location:{kind:y.kind,...y.name?{name:y.name}:{}}}:{},visibility:_,audience:H}}const Y=Symbol("not yet");function be(o){if(o)try{return JSON.parse(o)}catch{return}}function Te(o){const y=new Map,_=new Set;async function H(e){const n=o.sharedDirNotice;if(!(!n||_.has(e.thread.threadKey))){_.add(e.thread.threadKey);try{await e.notify(n)}catch(r){i.debug({thread:e.thread.threadKey,err:r},"could not deliver the shared-directory notice")}}}const P=new Map,A=new Map;async function B(e){await ce(e,{recursive:!0,force:!0}).catch(n=>i.warn({dir:e,err:n},"couldn't remove a turn's shared-file copies"))}function q(e,n){const r=A.get(e);if(r){A.delete(e),r.files.length>0&&i.warn({threadId:e,files:r.files.length,why:n},"dropping files held follow-ups shared");for(const d of r.staging)B(d)}}o.harness.keepAlive?.attach({started(e,n){P.get(e)?.lease?.revoke();const r=o.tools?.lease();return P.set(e,{processId:n,...r?{lease:r}:{}}),r?.access},ended(e,n){const r=P.get(e);r?.processId===n&&(r.lease?.revoke(),P.delete(e),q(e,"the process ended before a follow-up was posted"))},followUp(e,n,r){re(e,n,r).catch(d=>{i.error({threadId:e,err:d},"a follow-up could not be handled")})}});function z(e,n,r,d,s,g,w){const u=s.share?.bind(s),m=u&&(async c=>{const h=await u(c);return g.set(h.ref,h),h});return{thread:e,principal:d,origin:n,destination:r,...m?{share:m}:{},...w?{stage:w}:{}}}function ne(e){if(!o.tools||e.tools===!1)return!1;const n=Array.isArray(e.tools)?e.tools:void 0;return n&&n.length===0?!1:n}async function re(e,n,r){const d=P.get(e),s=d?.followable,g=s?.thread.threadKey??e,w=ee("trn"),u=ue(),m=new Map;let c,h;const l=Date.now();i.info({thread:g,turn:w},"the agent is following up on its own");const f={thread:g,turn:w};try{if(s){let a;const O=s.sandbox;if(O&&o.sandbox){const M=$(o.sandbox.staging,Z());c=M,a=S=>te(O,S,M)}h=d?.lease?.bind(z(s.thread,s.origin,s.destination,we,u,m,a),{only:[ge]})}let v;try{for await(const a of n)s&&(a.type==="text"||a.type==="done")&&o.transcript?.record([oe({threadId:s.thread.id,turnId:w,kind:a.type==="done"?"result":"progress",agent:s.agent,text:a.text,shared:m,at:Date.now()})]),a.type==="tool"&&i.debug({thread:g,tool:a.name,detail:a.summary??a.detail},"tool activity"),await u.handle(a)}catch(a){v=a instanceof Error?a.message:String(a)}h?.(),h=void 0;const p=u.outcome(),k=v??p.failure,b={...f,totalMs:Date.now()-l};if(k){i.error({...b,err:k},"the agent failed while following up");return}const N=r();if(p.silent||!p.text){i.info(b,"the agent followed up with nothing to say"),N||q(e,"the agent finished with nothing to say");return}if(s&&N&&!s.showsProgress()){const a=A.get(e)??{files:[],staging:[]};a.files.push(...p.files),c&&a.staging.push(c),c=void 0,A.set(e,a),i.info({...b,files:p.files.length},"holding the follow-up: work the agent handed off is still running");return}const K=o.deliver?.();if(!s||!K){i.warn(b,"the agent followed up, but there's nowhere to post it; dropping it");return}const E=A.get(e);A.delete(e);const U=[...E?.files??[],...p.files];let D;try{D=await s.destination(),await K(D,{text:p.text,title:"Following up",...U.length>0?{files:U}:{}})}finally{for(const a of E?.staging??[])await B(a)}i.info({...b,to:D.label},"posted the agent's follow-up")}catch(v){i.error({...f,err:v},"couldn't post the agent's follow-up")}finally{h?.(),c&&await B(c)}}async function ae(e){const n=o.principals;if(!n)return;const r=n.agent(e.origin.name);if(r)return r;try{return n.agent((await e.destination()).interface)}catch(d){i.debug({thread:e.thread.threadKey,err:d},"couldn't name the agent's account");return}}async function ie(e){await H(e);const n=new AbortController,r=ee("trn"),d=new Map,s=e.presence();let g,w,u;const m=Date.now();let c,h;try{y.set(e.thread.threadKey,n);const l=e.observe?.().catch(t=>(i.warn({thread:e.thread.threadKey,err:t},"could not read where this conversation takes place"),{visibility:"unknown",audience:"unknown"})),f=e.freshSession?void 0:await o.sessions.get(e.thread.id),v=await o.cwd(e.thread),[p,k]=await Promise.all([e.messages(),f?void 0:e.history?.().catch(t=>{i.warn({thread:e.thread.threadKey,err:t},"could not read the history")})]),b=l&&await Promise.race([l,Promise.resolve(Y)]),N=b===Y?void 0:b;b===Y&&l&&(i.debug({thread:e.thread.threadKey},"where this conversation takes place isn't read yet; not waiting for it"),l.then(t=>o.contexts?.record(e.thread.id,e.origin.name,t)).catch(t=>{i.warn({thread:e.thread.threadKey,err:t},"could not record where this conversation takes place")}));const[K,...E]=p;if(!K)throw new Error("a turn with no messages");const U=E.at(-1)?.principal??K.principal,D=o.transcript?await ae(e):void 0;if(n.signal.aborted){i.info({thread:e.thread.threadKey},"turn stopped before the agent started");return}const a=await o.sandbox?.policy(v,e.thread);let O;if(a&&o.sandbox){const t=$(o.sandbox.staging,Z());u=t,O=J=>te(a,J,t)}const M=!!o.harness.keepAlive&&!e.unattended,S=ne(e),L=S===!1?void 0:z(e.thread,e.origin,()=>e.destination(),U,s,d,O);L&&!M&&(g=o.tools?.grant(L,...S?[{only:S}]:[]));const se=()=>{if(!M||w)return;const t=P.get(e.thread.id);t&&(t.followable={thread:e.thread,origin:e.origin,destination:()=>e.destination(),...D?{agent:D}:{},...a?{sandbox:a}:{},showsProgress:()=>e.showsProgress?.()??!1},L&&(w=t.lease?.bind(L,...S?[{only:S}]:[])))};c=Date.now()-m,o.contexts?.record(e.thread.id,e.origin.name,N);const G=o.contexts?.told(e.thread.id),x=N?pe(N):l&&be(G),T=x&&JSON.stringify(x),Q=!!(f&&T&&G!==T);Q&&x&&i.info({thread:e.thread.threadKey,...x},"this conversation changed since the agent was told about it; telling it again");const C=e.origin,I=le("sha256").update(C.guidance).digest("hex"),V=o.contexts?.guided(e.thread.id),W=!!(f&&V&&V!==I);W&&i.info({thread:e.thread.threadKey,interface:C.name},"the interface's guidance changed since the agent was given it; giving it again");const R=[e.note,Q&&x?he(x):void 0,W?fe(C.guidance):void 0].filter(Boolean).join(`
1
+ import{createHash as Ae,randomUUID as fe}from"node:crypto";import{rm as Oe}from"node:fs/promises";import{join as he}from"node:path";import{contextChangeNote as Se,guidanceChangeNote as De}from"./harness/principal.js";import{mint as ge}from"./ids.js";import{skippedHistory as Me}from"./interface/reply-gate.js";import{log as r}from"./log.js";import{SHARE_FILE_TOOL as Te}from"./outgoing.js";import{levelChangeNote as Ne}from"./permissions/instructions.js";import{atLeast as Ee}from"./permissions/levels.js";import{SYSTEM_PRINCIPAL as we}from"./principals.js";import{stageFile as ue}from"./sandbox.js";import{schedulePresence as Pe}from"./schedule/presence.js";import{inbound as Ce,outbound as $}from"./transcript.js";import{worktreeName as _e}from"./worktrees.js";const Fe=3e3;function Le(o){const{location:k,visibility:B,audience:Y}=o;return{...k?{location:{kind:k.kind,...k.name?{name:k.name}:{}}}:{},visibility:B,audience:Y}}const ee=Symbol("not yet");function Re(o){if(o)try{return JSON.parse(o)}catch{return}}function $e(o){const k=new Map,B=new Set;async function Y(e){const t=o.sharedDirNotice;if(!(!t||B.has(e.thread.threadKey))){B.add(e.thread.threadKey);try{await e.notify(t)}catch(i){r.debug({thread:e.thread.threadKey,err:i},"could not deliver the shared-directory notice")}}}const g=new Map,D=new Map;async function U(e){await Oe(e,{recursive:!0,force:!0}).catch(t=>r.warn({dir:e,err:t},"couldn't remove a turn's shared-file copies"))}function te(e,t){const i=D.get(e);if(i){D.delete(e),i.files.length>0&&r.warn({threadId:e,files:i.files.length,why:t},"dropping files held follow-ups shared");for(const a of i.staging)U(a)}}const pe=e=>o.harnesses?.[e]??o.harness,z=new Set([o.harness,...Object.values(o.harnesses??{})]),oe=e=>!o.levelOf||e.principal.id===we.id?e:{...e,principal:{...e.principal,level:o.levelOf(e.principal.id)}};function j(e){e.cooling&&clearTimeout(e.cooling),e.cooling=void 0,e.shown&&(e.shown=!1,e.followable?.working?.(!1))}function Q(e){const t=g.get(e);if(t){if(t.working||t.following.size>0){if(t.cooling&&clearTimeout(t.cooling),t.cooling=void 0,t.shown)return;t.shown=!0,t.followable?.working?.(!0);return}!t.shown||t.cooling||(t.cooling=setTimeout(()=>j(t),Fe),t.cooling.unref())}}const me={started(e,t){const i=g.get(e);i?.lease?.revoke(),i&&j(i);const a=o.tools?.lease();return g.set(e,{processId:t,...a?{lease:a}:{},working:!1,following:new Set,shown:!1}),a?.access},ended(e,t){const i=g.get(e);i?.processId===t&&(i.lease?.revoke(),j(i),g.delete(e),te(e,"the process ended before a follow-up was posted"))},working(e,t,i){const a=g.get(e);a?.processId===t&&(a.working=i,Q(e))},followUp(e,t,i){ve(e,t,i).catch(a=>{r.error({threadId:e,err:a},"a follow-up could not be handled")})}};for(const e of z)e.keepAlive?.attach(me);function ne(e,t,i,a,l,y,v,w){const b=l.share?.bind(l),u=b&&(async K=>{const p=await b(K);return y.set(p.ref,p),p});return{thread:e,principal:a,origin:t,destination:i,...u?{share:u}:{},...v?{stage:v}:{},...w?{level:w}:{}}}function ye(e){if(!o.tools||e.tools===!1)return!1;const t=Array.isArray(e.tools)?e.tools:void 0;return t&&t.length===0?!1:t}async function ve(e,t,i){const a=g.get(e),l=a?.followable,y=l?.thread.threadKey??e,v={stopped:!1};a&&(a.following.add(v),Q(e));const w=ge("trn"),b=Pe();let u,K=!1;const p=new Map;let d,c;const H=Date.now();r.info({thread:y,turn:w},"the agent is following up on its own");const W={thread:y,turn:w};try{if(l){let s;const x=l.sandbox;if(x&&o.sandbox){const C=he(o.sandbox.staging,fe());d=C,s=N=>ue(x,N,C)}c=a?.lease?.bind(ne(l.thread,l.origin,l.destination,we,b,p,s,l.level),{only:[Te]})}let A;try{for await(const s of t)l&&s.type==="text"&&o.transcript?.record([$({threadId:l.thread.id,turnId:w,kind:"progress",agent:l.agent,text:s.text,shared:p,at:Date.now()})]),s.type==="done"&&(u={text:s.text,at:Date.now()}),s.type==="tool"&&r.debug({thread:y,tool:s.name,detail:s.summary??s.detail},"tool activity"),await b.handle(s)}catch(s){A=s instanceof Error?s.message:String(s)}c?.(),c=void 0;const f=b.outcome(),M=A??f.failure,m={...W,totalMs:Date.now()-H};if(v.stopped){r.info(m,"the follow-up was stopped");return}if(M){r.error({...m,err:M},"the agent failed while following up");return}const q=i();if(f.silent||!f.text){r.info(m,"the agent followed up with nothing to say"),q||te(e,"the agent finished with nothing to say");return}if(l&&q&&!l.showsProgress()){const s=D.get(e)??{files:[],staging:[]};s.files.push(...f.files),d&&s.staging.push(d),d=void 0,D.set(e,s),r.info({...m,files:f.files.length},"holding the follow-up: work the agent handed off is still running");return}const E=o.deliver?.();if(!l||!E){r.warn(m,"the agent followed up, but there's nowhere to post it; dropping it");return}const S=D.get(e);D.delete(e);const T=[...S?.files??[],...f.files];let P;try{P=await l.destination(),await E(P,{text:f.text,title:"Following up",...T.length>0?{files:T}:{}})}finally{for(const s of S?.staging??[])await U(s)}K=f.text,r.info({...m,to:P.label},"posted the agent's follow-up")}catch(A){r.error({...W,err:A},"couldn't post the agent's follow-up")}finally{l&&u&&o.transcript?.record([$({threadId:l.thread.id,turnId:w,kind:"result",agent:l.agent,text:u.text,shared:p,posted:K,at:u.at})]),c?.(),d&&await U(d),a&&(a.following.delete(v),g.get(e)===a&&Q(e))}}async function be(e){const t=o.principals;if(!t)return;const i=t.agent(e.origin.name);if(i)return i;try{return t.agent((await e.destination()).interface)}catch(a){r.debug({thread:e.thread.threadKey,err:a},"couldn't name the agent's account");return}}async function ke(e){await Y(e);const t=new AbortController,i=ge("trn"),a=new Map,l=e.presence();let y,v,w;const b=Date.now();let u,K;const p=pe(e.level);try{o.levels?.fix(e.thread.id,e.level),k.set(e.thread.threadKey,t);for(const n of z){if(n===p||!n.keepAlive)continue;const h=await n.keepAlive.end(e.thread.id);h!=="none"&&(r.info({thread:e.thread.threadKey,to:e.level,stoppedWork:h==="busy"},"closed the thread's process from before its level changed"),h==="busy"&&await e.notify("This conversation's permission level changed, so the work I had running in the background at the old level was stopped. Ask again if you still need it.").catch(Z=>{r.debug({err:Z},"couldn't say that background work was stopped")}))}const d=e.observe?.().catch(n=>(r.warn({thread:e.thread.threadKey,err:n},"could not read where this conversation takes place"),{visibility:"unknown",audience:"unknown"})),c=e.freshSession?void 0:await o.sessions.get(e.thread.id),H=await o.cwd(e.thread),[W,A]=await Promise.all([e.messages(),c?void 0:e.history?.().catch(n=>{r.warn({thread:e.thread.threadKey,err:n},"could not read the history")})]),f=d&&await Promise.race([d,Promise.resolve(ee)]),M=f===ee?void 0:f;f===ee&&d&&(r.debug({thread:e.thread.threadKey},"where this conversation takes place isn't read yet; not waiting for it"),d.then(n=>o.contexts?.record(e.thread.id,e.origin.name,n)).catch(n=>{r.warn({thread:e.thread.threadKey,err:n},"could not record where this conversation takes place")}));const m=o.transcript?.pending(e.thread.id)??[],q=m.length?Me(m,{find:n=>o.principals?.find(n)?.principal,...o.levelOf?{allows:n=>Ee(o.levelOf(n),e.level)}:{}}):[],E=[...A??[],...q].map(n=>n.kind==="message"?oe(n):n),[S,...T]=W.map(oe);if(!S)throw new Error("a turn with no messages");const P=T.at(-1)?.principal??S.principal,s=o.transcript?await be(e):void 0;if(t.signal.aborted){r.info({thread:e.thread.threadKey},"turn stopped before the agent started");return}const x=await o.sandbox?.policy(H,e.thread,e.level);let C;if(x&&o.sandbox){const n=he(o.sandbox.staging,fe());w=n,C=h=>ue(x,h,n)}const N=!!p.keepAlive&&!e.unattended,_=ye(e),G=_===!1?void 0:ne(e.thread,e.origin,()=>e.destination(),P,l,a,C,e.level);G&&!N&&(y=o.tools?.grant(G,..._?[{only:_}]:[]));const xe=()=>{if(!N||v)return;const n=g.get(e.thread.id);n&&(n.followable={thread:e.thread,origin:e.origin,destination:()=>e.destination(),...s?{agent:s}:{},...x?{sandbox:x}:{},level:e.level,showsProgress:()=>e.showsProgress?.()??!1,...e.working?{working:h=>e.working?.(h)}:{}},n.shown&&e.working?.(!0),G&&(v=n.lease?.bind(G,..._?[{only:_}]:[])))};u=Date.now()-b,o.contexts?.record(e.thread.id,e.origin.name,M);const re=o.contexts?.told(e.thread.id),O=M?Le(M):d&&Re(re),F=O&&JSON.stringify(O),ae=!!(c&&F&&re!==F);ae&&O&&r.info({thread:e.thread.threadKey,...O},"this conversation changed since the agent was told about it; telling it again");const L=e.origin,V=Ae("sha256").update(L.guidance).digest("hex"),se=o.contexts?.guided(e.thread.id),le=!!(c&&se&&se!==V);le&&r.info({thread:e.thread.threadKey,interface:L.name},"the interface's guidance changed since the agent was given it; giving it again");const X=o.levels?.told(e.thread.id),de=!!(c&&X&&X!==e.level);de&&r.info({thread:e.thread.threadKey,from:X,to:e.level},"this conversation's level changed since the agent was told it; telling it again");const I=[e.note,ae&&O?Se(O):void 0,le?De(L.guidance):void 0,de?Ne(e.level):void 0].filter(Boolean).join(`
2
2
 
3
- `),de=x?{...C,context:x}:C,j=o.model?.of(e.thread.id)??{};let F;const X=(t,J)=>o.transcript?.record([oe({threadId:e.thread.id,turnId:r,kind:t,agent:D,text:J,shared:d,at:Date.now()})]);o.transcript?.record(ye({threadId:e.thread.id,turnId:r,messages:[K,...E],...R?{note:R}:{},...k?.length?{history:k}:{},at:Date.now()}));for await(const t of o.harness.runTurn({messages:[K,...E],cwd:v,threadKey:e.thread.threadKey,worktree:me(e.thread.dirKey),...f?{sessionId:f}:{},...j.model?{model:j.model}:{},...j.effort?{effort:j.effort}:{},...R?{note:R}:{},...k?.length?{history:k}:{},origin:de,...g?{tools:g.access}:{},...a?{sandbox:a}:{},threadId:e.thread.id,...M?{keepAlive:M}:{},signal:n.signal}))se(),t.type==="session"&&(h??=Date.now()-m,t.model&&(F=t.model),t.sessionId!==f&&await o.sessions.set(e.thread.id,t.sessionId),T&&o.contexts?.told(e.thread.id)!==T&&o.contexts?.tell(e.thread.id,T),o.contexts?.guided(e.thread.id)!==I&&o.contexts?.guide(e.thread.id,I)),t.type==="text"&&(X("progress",t.text),i.debug({thread:e.thread.threadKey,chars:t.text.length},"agent said something")),t.type==="tool"&&i.debug({thread:e.thread.threadKey,tool:t.name,detail:t.summary??t.detail},"tool activity"),t.type==="done"&&(X("result",t.text),i.info({thread:e.thread.threadKey,turn:r,...F?{model:F}:{},...t.usage},"turn complete")),t.type==="error"&&i.error({thread:e.thread.threadKey,turn:r,...F?{model:F}:{},kind:t.kind,err:t.message},"turn errored"),await s.handle(t)}catch(l){const f=l instanceof Error?l.message:String(l);throw i.error({thread:e.thread.threadKey,turn:r,err:l},"turn failed before the agent answered"),await s.handle({type:"error",kind:"turn_failed",message:f}),l}finally{i.debug({thread:e.thread.threadKey,turn:r,...c===void 0?{}:{preparedMs:c},...h===void 0?{}:{sessionMs:h},totalMs:Date.now()-m,...n.signal.aborted?{stopped:!0}:{}},"turn timing"),g?.revoke(),w?.(),y.get(e.thread.threadKey)===n&&y.delete(e.thread.threadKey),await s.finish(),u&&await B(u)}}return{run:ie,stop(e){const n=y.get(e);return n?(n.abort(),!0):!1}}}export{Te as makeTurnRunner};
3
+ `),Ke=O?{...L,context:O}:L,J=o.model?.of(e.thread.id)??{};let R;const ce=(n,h)=>o.transcript?.record([$({threadId:e.thread.id,turnId:i,kind:n,agent:s,text:h,shared:a,at:Date.now()})]);o.transcript?.record(Ce({threadId:e.thread.id,turnId:i,messages:[S,...T],...I?{note:I}:{},...A?.length?{history:A}:{},at:Date.now()}));for await(const n of p.runTurn({messages:[S,...T],cwd:H,threadKey:e.thread.threadKey,worktree:_e(e.thread.dirKey),...c?{sessionId:c}:{},...J.model?{model:J.model}:{},...J.effort?{effort:J.effort}:{},...I?{note:I}:{},...E.length?{history:E}:{},origin:Ke,...y?{tools:y.access}:{},...x?{sandbox:x}:{},threadId:e.thread.id,...N?{keepAlive:N}:{},signal:t.signal})){if(xe(),n.type==="session"){if(K??=Date.now()-b,n.model&&(R=n.model),m.length){const h=m.splice(0).map(Z=>Z.seq);o.transcript?.delivered(h,i),r.info({thread:e.thread.threadKey,skipped:h.length},"gave the agent the messages it skipped")}n.sessionId!==c&&await o.sessions.set(e.thread.id,n.sessionId),F&&o.contexts?.told(e.thread.id)!==F&&o.contexts?.tell(e.thread.id,F),o.contexts?.guided(e.thread.id)!==V&&o.contexts?.guide(e.thread.id,V),o.levels&&o.levels.told(e.thread.id)!==e.level&&o.levels.tell(e.thread.id,e.level)}n.type==="text"&&(ce("progress",n.text),r.debug({thread:e.thread.threadKey,chars:n.text.length},"agent said something")),n.type==="tool"&&r.debug({thread:e.thread.threadKey,tool:n.name,detail:n.summary??n.detail},"tool activity"),n.type==="done"&&(ce("result",n.text),r.info({thread:e.thread.threadKey,turn:i,...R?{model:R}:{},...n.usage},"turn complete")),n.type==="error"&&r.error({thread:e.thread.threadKey,turn:i,...R?{model:R}:{},kind:n.kind,err:n.message},"turn errored"),await l.handle(n)}}catch(d){const c=d instanceof Error?d.message:String(d);throw r.error({thread:e.thread.threadKey,turn:i,err:d},"turn failed before the agent answered"),await l.handle({type:"error",kind:"turn_failed",message:c}),d}finally{r.debug({thread:e.thread.threadKey,turn:i,...u===void 0?{}:{preparedMs:u},...K===void 0?{}:{sessionMs:K},totalMs:Date.now()-b,...t.signal.aborted?{stopped:!0}:{}},"turn timing"),y?.revoke(),v?.(),k.get(e.thread.threadKey)===t&&k.delete(e.thread.threadKey),t.signal.aborted&&ie(e.thread.id),await l.finish(),w&&await U(w)}}function ie(e){const t=g.get(e);if(!t)return!1;if([...z].some(i=>i.keepAlive?.stop(e))){for(const i of t.following)i.stopped=!0;return!0}return t.shown?(j(t),!0):!1}return{run:ke,stop(e){const t=k.get(e);if(t)return t.abort(),!0;for(const[i,a]of g)if(a.followable?.thread.threadKey===e)return ie(i);return!1}}}export{$e as makeTurnRunner};