index.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { App } from "./app";
  2. import { Server } from "./server/server";
  3. import fs from "node:fs/promises";
  4. import path from "node:path";
  5. import { Bus } from "./bus";
  6. import { Session } from "./session/session";
  7. import cac from "cac";
  8. import { Share } from "./share/share";
  9. const cli = cac("opencode");
  10. cli.command("", "Start the opencode in interactive mode").action(async () => {
  11. await App.provide({ directory: process.cwd() }, async () => {
  12. await Share.init();
  13. Server.listen();
  14. });
  15. });
  16. cli.command("generate", "Generate OpenAPI and event specs").action(async () => {
  17. const specs = await Server.openapi();
  18. const dir = "gen";
  19. await fs.rmdir(dir, { recursive: true }).catch(() => {});
  20. await fs.mkdir(dir, { recursive: true });
  21. await Bun.write(
  22. path.join(dir, "openapi.json"),
  23. JSON.stringify(specs, null, 2),
  24. );
  25. await Bun.write(
  26. path.join(dir, "event.json"),
  27. JSON.stringify(Bus.specs(), null, 2),
  28. );
  29. });
  30. cli
  31. .command("run [...message]", "Run a chat message")
  32. .action(async (message: string[]) => {
  33. await App.provide({ directory: process.cwd() }, async () => {
  34. console.log("Thinking...");
  35. await Share.init();
  36. const session = await Session.create();
  37. const shareID = await Session.share(session.id);
  38. if (shareID)
  39. console.log("Share ID: https://dev.opencode.ai/share?id=" + session.id);
  40. const result = await Session.chat(session.id, {
  41. type: "text",
  42. text: message.join(" "),
  43. });
  44. for (const part of result.parts) {
  45. if (part.type === "text") {
  46. console.log("opencode:", part.text);
  47. }
  48. if (part.type === "tool-invocation") {
  49. console.log(
  50. "tool:",
  51. part.toolInvocation.toolName,
  52. part.toolInvocation.args,
  53. part.toolInvocation.state === "result"
  54. ? part.toolInvocation.result
  55. : "",
  56. );
  57. }
  58. }
  59. });
  60. });
  61. cli.help();
  62. cli.version("1.0.0");
  63. cli.parse();