index.ts 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. import { App } from "@slack/bolt"
  2. import { createOpencode, type ToolPart } from "@opencode-ai/sdk"
  3. const app = new App({
  4. token: process.env.SLACK_BOT_TOKEN,
  5. signingSecret: process.env.SLACK_SIGNING_SECRET,
  6. socketMode: true,
  7. appToken: process.env.SLACK_APP_TOKEN,
  8. })
  9. console.log("🔧 Bot configuration:")
  10. console.log("- Bot token present:", !!process.env.SLACK_BOT_TOKEN)
  11. console.log("- Signing secret present:", !!process.env.SLACK_SIGNING_SECRET)
  12. console.log("- App token present:", !!process.env.SLACK_APP_TOKEN)
  13. console.log("🚀 Starting opencode server...")
  14. const opencode = await createOpencode({
  15. port: 0,
  16. })
  17. console.log("✅ Opencode server ready")
  18. const sessions = new Map<
  19. string,
  20. { client: any; server: any; sessionId: string; channel: string; thread: string }
  21. >()
  22. ;(async () => {
  23. const events = await opencode.client.event.subscribe()
  24. for await (const event of events.stream) {
  25. if (event.type === "message.part.updated") {
  26. const part = event.properties.part
  27. if (part.type === "tool") {
  28. // Find the session for this tool update
  29. for (const [sessionKey, session] of sessions.entries()) {
  30. if (session.sessionId === part.sessionID) {
  31. handleToolUpdate(part, session.channel, session.thread)
  32. break
  33. }
  34. }
  35. }
  36. }
  37. }
  38. })()
  39. async function handleToolUpdate(part: ToolPart, channel: string, thread: string) {
  40. if (part.state.status !== "completed") return
  41. const toolMessage = `*${part.tool}* - ${part.state.title}`
  42. await app.client.chat
  43. .postMessage({
  44. channel,
  45. thread_ts: thread,
  46. text: toolMessage,
  47. })
  48. .catch(() => {})
  49. }
  50. app.use(async ({ next, context }) => {
  51. console.log("📡 Raw Slack event:", JSON.stringify(context, null, 2))
  52. await next()
  53. })
  54. app.message(async ({ message, say }) => {
  55. console.log("📨 Received message event:", JSON.stringify(message, null, 2))
  56. if (message.subtype || !("text" in message) || !message.text) {
  57. console.log("⏭️ Skipping message - no text or has subtype")
  58. return
  59. }
  60. console.log("✅ Processing message:", message.text)
  61. const channel = message.channel
  62. const thread = (message as any).thread_ts || message.ts
  63. const sessionKey = `${channel}-${thread}`
  64. let session = sessions.get(sessionKey)
  65. if (!session) {
  66. console.log("🆕 Creating new opencode session...")
  67. const { client, server } = opencode
  68. const createResult = await client.session.create({
  69. body: { title: `Slack thread ${thread}` },
  70. })
  71. if (createResult.error) {
  72. console.error("❌ Failed to create session:", createResult.error)
  73. await say({
  74. text: "Sorry, I had trouble creating a session. Please try again.",
  75. thread_ts: thread,
  76. })
  77. return
  78. }
  79. console.log("✅ Created opencode session:", createResult.data.id)
  80. session = { client, server, sessionId: createResult.data.id, channel, thread }
  81. sessions.set(sessionKey, session)
  82. const shareResult = await client.session.share({ path: { id: createResult.data.id } })
  83. if (!shareResult.error && shareResult.data) {
  84. const sessionUrl = shareResult.data.share?.url!
  85. console.log("🔗 Session shared:", sessionUrl)
  86. await app.client.chat.postMessage({ channel, thread_ts: thread, text: sessionUrl })
  87. }
  88. }
  89. console.log("📝 Sending to opencode:", message.text)
  90. const result = await session.client.session.prompt({
  91. path: { id: session.sessionId },
  92. body: { parts: [{ type: "text", text: message.text }] },
  93. })
  94. console.log("📤 Opencode response:", JSON.stringify(result, null, 2))
  95. if (result.error) {
  96. console.error("❌ Failed to send message:", result.error)
  97. await say({
  98. text: "Sorry, I had trouble processing your message. Please try again.",
  99. thread_ts: thread,
  100. })
  101. return
  102. }
  103. const response = result.data
  104. // Build response text
  105. const responseText =
  106. response.info?.content ||
  107. response.parts
  108. ?.filter((p: any) => p.type === "text")
  109. .map((p: any) => p.text)
  110. .join("\n") ||
  111. "I received your message but didn't have a response."
  112. console.log("💬 Sending response:", responseText)
  113. // Send main response (tool updates will come via live events)
  114. await say({ text: responseText, thread_ts: thread })
  115. })
  116. app.command("/test", async ({ command, ack, say }) => {
  117. await ack()
  118. console.log("🧪 Test command received:", JSON.stringify(command, null, 2))
  119. await say("🤖 Bot is working! I can hear you loud and clear.")
  120. })
  121. await app.start()
  122. console.log("⚡️ Slack bot is running!")