symbio 0.0.0-stage → 0.2.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 (43) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/LICENSE +21 -0
  3. package/README.md +201 -3
  4. package/bin/symbio.js +217 -0
  5. package/dist/server/api.js +611 -0
  6. package/dist/server/assets.js +154 -0
  7. package/dist/server/bus.js +9 -0
  8. package/dist/server/connections.js +227 -0
  9. package/dist/server/costs.js +175 -0
  10. package/dist/server/docs.js +97 -0
  11. package/dist/server/folder-picker.js +121 -0
  12. package/dist/server/git.js +38 -0
  13. package/dist/server/guard.js +135 -0
  14. package/dist/server/housekeeping.js +119 -0
  15. package/dist/server/index.js +133 -0
  16. package/dist/server/inspect.js +136 -0
  17. package/dist/server/mcp.js +74 -0
  18. package/dist/server/opencode/client.js +152 -0
  19. package/dist/server/opencode/runtime.js +326 -0
  20. package/dist/server/origin.js +15 -0
  21. package/dist/server/plan.js +162 -0
  22. package/dist/server/prompts.js +265 -0
  23. package/dist/server/providers.js +131 -0
  24. package/dist/server/remote.js +271 -0
  25. package/dist/server/secrets.js +105 -0
  26. package/dist/server/ssh.js +146 -0
  27. package/dist/server/store.js +167 -0
  28. package/dist/server/team.js +1440 -0
  29. package/dist/server/tools.js +409 -0
  30. package/dist/server/ui-token.js +29 -0
  31. package/dist/server/updates.js +55 -0
  32. package/dist/server/workspaces.js +133 -0
  33. package/dist/web/assets/index-Cbd1sDvV.css +1 -0
  34. package/dist/web/assets/index-DrIslUUT.js +52 -0
  35. package/dist/web/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  36. package/dist/web/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  37. package/dist/web/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  38. package/dist/web/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  39. package/dist/web/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  40. package/dist/web/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  41. package/dist/web/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  42. package/dist/web/index.html +14 -0
  43. package/package.json +73 -6
@@ -0,0 +1,121 @@
1
+ // Native "choose a folder" dialog, opened by the Symbio server on the user's own
2
+ // machine (browsers can't reveal full paths). Windows uses the modern shell
3
+ // dialog (IFileOpenDialog with FOS_PICKFOLDERS) through Windows PowerShell 5.1,
4
+ // which every Windows has; macOS uses osascript, Linux zenity/kdialog.
5
+ import { execFile } from "node:child_process";
6
+ import { promises as fs } from "node:fs";
7
+ import os from "node:os";
8
+ import path from "node:path";
9
+ const WINDOWS_SCRIPT = String.raw `
10
+ param([string]$Initial = "", [string]$Title = "Choose the project folder")
11
+ $ErrorActionPreference = "Stop"
12
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
13
+ Add-Type -AssemblyName System.Windows.Forms
14
+ Add-Type -ReferencedAssemblies System.Windows.Forms -TypeDefinition @"
15
+ using System;
16
+ using System.Runtime.InteropServices;
17
+ using System.Windows.Forms;
18
+
19
+ public static class SymbioFolderPicker {
20
+ [ComImport, Guid("DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7")] private class FileOpenDialogCom {}
21
+
22
+ [ComImport, Guid("42f85136-db7e-439c-85f1-e4075d135fc8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
23
+ private interface IFileOpenDialog {
24
+ [PreserveSig] int Show(IntPtr hwndOwner);
25
+ void SetFileTypes(); void SetFileTypeIndex(); void GetFileTypeIndex(); void Advise(); void Unadvise();
26
+ void SetOptions(uint fos);
27
+ void GetOptions(out uint fos);
28
+ void SetDefaultFolder(IShellItem psi);
29
+ void SetFolder(IShellItem psi);
30
+ void GetFolder(); void GetCurrentSelection(); void SetFileName(); void GetFileName();
31
+ void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string pszTitle);
32
+ void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string pszText);
33
+ void SetFileNameLabel();
34
+ void GetResult(out IShellItem ppsi);
35
+ }
36
+
37
+ [ComImport, Guid("43826d1e-e718-42ee-bc55-a1e261c37bfe"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
38
+ private interface IShellItem {
39
+ void BindToHandler(); void GetParent();
40
+ void GetDisplayName(uint sigdnName, [MarshalAs(UnmanagedType.LPWStr)] out string ppszName);
41
+ void GetAttributes(); void Compare();
42
+ }
43
+
44
+ [DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = false)]
45
+ private static extern void SHCreateItemFromParsingName(string pszPath, IntPtr pbc, [MarshalAs(UnmanagedType.LPStruct)] Guid riid, out IShellItem ppv);
46
+
47
+ public static string Pick(string initial, string title) {
48
+ // An invisible topmost window owns the dialog so it opens in front of the browser.
49
+ var owner = new Form { ShowInTaskbar = false, TopMost = true, FormBorderStyle = FormBorderStyle.None, Opacity = 0, Width = 1, Height = 1, StartPosition = FormStartPosition.CenterScreen };
50
+ owner.Show();
51
+ owner.Activate();
52
+ try {
53
+ var dialog = (IFileOpenDialog)new FileOpenDialogCom();
54
+ dialog.SetOptions(0x20 | 0x40 | 0x800); // PICKFOLDERS | FORCEFILESYSTEM | PATHMUSTEXIST
55
+ dialog.SetTitle(title);
56
+ dialog.SetOkButtonLabel("Select folder");
57
+ if (!String.IsNullOrEmpty(initial)) {
58
+ try {
59
+ IShellItem folder;
60
+ SHCreateItemFromParsingName(initial, IntPtr.Zero, typeof(IShellItem).GUID, out folder);
61
+ dialog.SetFolder(folder);
62
+ } catch { }
63
+ }
64
+ int hr = dialog.Show(owner.Handle);
65
+ if (hr != 0) return null; // cancelled
66
+ IShellItem result;
67
+ dialog.GetResult(out result);
68
+ string p;
69
+ result.GetDisplayName(0x80058000, out p); // SIGDN_FILESYSPATH
70
+ return p;
71
+ } finally {
72
+ owner.Close();
73
+ }
74
+ }
75
+ }
76
+ "@
77
+ $picked = [SymbioFolderPicker]::Pick($Initial, $Title)
78
+ if ($picked) { [Console]::Out.Write($picked) }
79
+ `;
80
+ let busy = false;
81
+ /** Opens the native folder dialog. Resolves to the chosen path, or null if cancelled. */
82
+ export async function pickFolder(initial) {
83
+ if (busy)
84
+ throw new Error("A folder dialog is already open.");
85
+ busy = true;
86
+ try {
87
+ if (process.platform === "win32")
88
+ return await pickWindows(initial);
89
+ if (process.platform === "darwin") {
90
+ const out = await run("osascript", ["-e", `POSIX path of (choose folder with prompt "Choose the project folder")`]);
91
+ return out.trim().replace(/\/$/, "") || null;
92
+ }
93
+ const out = await run("zenity", ["--file-selection", "--directory", "--title=Choose the project folder"]).catch(() => run("kdialog", ["--getexistingdirectory", initial ?? os.homedir()]));
94
+ return out.trim() || null;
95
+ }
96
+ finally {
97
+ busy = false;
98
+ }
99
+ }
100
+ async function pickWindows(initial) {
101
+ const script = path.join(os.tmpdir(), "symbio-pick-folder.ps1");
102
+ // UTF-8 with BOM so Windows PowerShell 5.1 reads non-ASCII text correctly.
103
+ await fs.writeFile(script, "" + WINDOWS_SCRIPT, "utf8");
104
+ const args = ["-NoProfile", "-STA", "-ExecutionPolicy", "Bypass", "-File", script];
105
+ if (initial)
106
+ args.push("-Initial", initial);
107
+ const out = await run("powershell.exe", args);
108
+ return out.trim() || null;
109
+ }
110
+ function run(cmd, args) {
111
+ return new Promise((resolve, reject) => {
112
+ execFile(cmd, args, { encoding: "utf8", windowsHide: false, timeout: 15 * 60_000 }, (err, stdout, stderr) => {
113
+ // zenity/osascript exit non-zero when the user cancels.
114
+ if (err && !stdout) {
115
+ const cancelled = /cancel/i.test(stderr) || (err.code === 1 && !stderr.trim());
116
+ return cancelled ? resolve("") : reject(new Error(stderr.trim() || err.message));
117
+ }
118
+ resolve(stdout);
119
+ });
120
+ });
121
+ }
@@ -0,0 +1,38 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ const run = promisify(execFile);
4
+ export async function git(cwd, ...args) {
5
+ const { stdout } = await run("git", args, {
6
+ cwd,
7
+ windowsHide: true,
8
+ maxBuffer: 16 * 1024 * 1024,
9
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
10
+ });
11
+ return stdout.trim();
12
+ }
13
+ export async function gitAvailable() {
14
+ try {
15
+ await run("git", ["--version"], { windowsHide: true });
16
+ return true;
17
+ }
18
+ catch {
19
+ return false;
20
+ }
21
+ }
22
+ /**
23
+ * Turns a folder into a git repository with a first snapshot of whatever is in it,
24
+ * so worktrees (which only contain committed files) have the project's content.
25
+ */
26
+ export async function initRepository(dir) {
27
+ await git(dir, "init");
28
+ await git(dir, "add", "-A");
29
+ // Use a fallback identity only if the user has none configured.
30
+ const identity = [];
31
+ const name = await git(dir, "config", "user.name").catch(() => "");
32
+ const email = await git(dir, "config", "user.email").catch(() => "");
33
+ if (!name)
34
+ identity.push("-c", "user.name=Symbio");
35
+ if (!email)
36
+ identity.push("-c", "user.email=symbio@localhost");
37
+ await git(dir, ...identity, "commit", "--allow-empty", "-m", "Initial snapshot (created by Symbio)");
38
+ }
@@ -0,0 +1,135 @@
1
+ // Safety rules applied to every agent session (OpenCode permission rules).
2
+ //
3
+ // Agents run shell commands as the user, so a command like
4
+ // `taskkill /F /IM node.exe /T` kills every Node program on the machine — the
5
+ // user's terminals, editors, Claude Code and Symbio itself (this happened).
6
+ // Killing processes by name or PID is therefore denied for agents; they stop
7
+ // what they started through Symbio's stop_process tool instead.
8
+ //
9
+ // Patterns are whole-value wildcards over each command OpenCode's scanner
10
+ // extracts (compound commands are split; any deny blocks the call). Matching may
11
+ // be case-sensitive, hence the spelling variants.
12
+ const KILL_PATTERNS = [
13
+ "*taskkill*",
14
+ "*TASKKILL*",
15
+ "*Taskkill*",
16
+ "*tskill*",
17
+ "*Stop-Process*",
18
+ "*stop-process*",
19
+ "*STOP-PROCESS*",
20
+ "spps *",
21
+ "kill *",
22
+ "pkill *",
23
+ "killall *",
24
+ "*wmic*process*",
25
+ "*WMIC*PROCESS*",
26
+ "*Stop-Computer*",
27
+ "*Restart-Computer*",
28
+ "shutdown *",
29
+ ];
30
+ // Installing software on the machine needs the human's OK (asked in the UI).
31
+ const INSTALL_PATTERNS = [
32
+ "winget install*",
33
+ "winget upgrade*",
34
+ "choco install*",
35
+ "choco upgrade*",
36
+ "scoop install*",
37
+ "npm install -g*",
38
+ "npm i -g*",
39
+ "npm install --global*",
40
+ "npm i --global*",
41
+ "pnpm add -g*",
42
+ "yarn global add*",
43
+ "pip install*",
44
+ "pip3 install*",
45
+ "py -m pip install*",
46
+ "python -m pip install*",
47
+ "python3 -m pip install*",
48
+ "pipx install*",
49
+ "cargo install*",
50
+ "go install*",
51
+ "dotnet tool install*",
52
+ "msiexec*",
53
+ "*Install-Module*",
54
+ "*Install-Package*",
55
+ "*Add-AppxPackage*",
56
+ // "download and run" installers
57
+ "*| iex*",
58
+ "*|iex*",
59
+ "*Invoke-Expression*",
60
+ "*| sh",
61
+ "*| bash",
62
+ "*|sh",
63
+ "*|bash",
64
+ "*| sh *",
65
+ "*| bash *",
66
+ "*|sh *",
67
+ "*|bash *",
68
+ "*| sudo *",
69
+ "*|sudo *",
70
+ "*| pwsh*",
71
+ "*| powershell*",
72
+ ];
73
+ // Agents never read private keys, Symbio's secret store, the UI key (which would let
74
+ // them approve their own actions), their approvals or OpenCode's provider logins.
75
+ const SECRET_PATHS = [
76
+ "*\\.ssh\\*",
77
+ "*/.ssh/*",
78
+ "*\\.symbio\\secrets*",
79
+ "*/.symbio/secrets*",
80
+ "*\\.symbio\\ui-token*",
81
+ "*/.symbio/ui-token*",
82
+ "*\\.symbio\\approvals*",
83
+ "*/.symbio/approvals*",
84
+ "*\\.symbio\\backups*",
85
+ "*/.symbio/backups*",
86
+ "*\\opencode\\auth.json",
87
+ "*/opencode/auth.json",
88
+ ];
89
+ const SECRET_SHELL = [
90
+ "*.ssh/*",
91
+ "*.ssh\\*",
92
+ "*id_rsa*",
93
+ "*id_ed25519*",
94
+ "*id_ecdsa*",
95
+ "*.ppk*",
96
+ "*.symbio*secrets*",
97
+ "*ui-token*",
98
+ "*.symbio*approvals*",
99
+ "*.symbio*backups*",
100
+ "*opencode*auth.json*",
101
+ ];
102
+ const rules = (action, effect, patterns) => patterns.map((resource) => ({ action, resource, effect }));
103
+ // Any matching deny blocks a call; otherwise any ask prompts. Deny rules come last
104
+ // so they also win under "last match wins".
105
+ export const AGENT_PERMISSIONS = [
106
+ ...rules("shell", "ask", INSTALL_PATTERNS),
107
+ ...rules("shell", "deny", KILL_PATTERNS),
108
+ ...rules("shell", "deny", SECRET_SHELL),
109
+ ...rules("read", "deny", SECRET_PATHS),
110
+ ...rules("edit", "deny", SECRET_PATHS),
111
+ ];
112
+ /** Text for agent briefs explaining the rule and the alternative. */
113
+ export const PROCESS_RULES = `- Never kill processes by name or PID (taskkill, Stop-Process, kill, pkill…):
114
+ other programs on this machine — the human's terminals and editors, other
115
+ agents, Symbio itself — run the same executables. Those commands are
116
+ blocked.
117
+ - Run anything long-lived (a server, a watcher) as a background shell (the shell
118
+ tool's \`background\` option). Stop it with Symbio's \`stop_process\` tool
119
+ (see \`list_processes\` for what you have running). Stop what you started when
120
+ you are done with it.
121
+ - Installing software on the machine (winget, choco, npm -g, pip install…) asks
122
+ the human first; your command waits until they answer. Only install what the
123
+ task really needs, and say why in your message before running it.
124
+ - Never read SSH keys or anything under ~/.ssh or Symbio's secret store —
125
+ servers and GitHub are reached through Symbio's connection tools.`;
126
+ /** OpenCode-style wildcard: "*" any run, "?" one char; "x *" also matches bare "x". */
127
+ export function wildcardMatch(pattern, value) {
128
+ const body = pattern
129
+ .split("")
130
+ .map((ch) => (ch === "*" ? ".*" : ch === "?" ? "." : ch.replace(/[.+^${}()|[\]\\]/g, "\\$&")))
131
+ .join("");
132
+ if (new RegExp(`^${body}$`, "s").test(value))
133
+ return true;
134
+ return pattern.endsWith(" *") && value === pattern.slice(0, -2);
135
+ }
@@ -0,0 +1,119 @@
1
+ // Daily care of a project's surroundings: backups of Symbio's state, work that exists only on
2
+ // this machine (commits not on any remote), and disk used by helpers' folders (mostly build
3
+ // outputs). Symbio reports; the coordinator (or the human) acts.
4
+ import { existsSync, promises as fs } from "node:fs";
5
+ import path from "node:path";
6
+ import { git } from "./git.js";
7
+ import { globalDir } from "./store.js";
8
+ // ---------------------------------------------------------------- backups
9
+ const BACKUP_KEEP = Number(process.env.SYMBIO_BACKUP_DAYS ?? 7);
10
+ export const backupsDir = () => path.join(globalDir, "backups");
11
+ /**
12
+ * Today's backup of every project's .symbio folder and Symbio's own small files (not the
13
+ * helpers' worktrees, logs or the UI key). One per day; the last BACKUP_KEEP days are kept.
14
+ * Returns the folder, or null when today's backup already exists.
15
+ */
16
+ export async function dailyBackup(projects, now = new Date()) {
17
+ const day = now.toISOString().slice(0, 10);
18
+ const dest = path.join(backupsDir(), day);
19
+ if (existsSync(dest))
20
+ return null;
21
+ const tmp = `${dest}.partial`;
22
+ await fs.rm(tmp, { recursive: true, force: true });
23
+ for (const p of projects) {
24
+ const src = path.join(p.directory, ".symbio");
25
+ if (existsSync(src))
26
+ await fs.cp(src, path.join(tmp, "projects", `${path.basename(p.directory)}-${p.id}`), { recursive: true });
27
+ }
28
+ for (const name of ["config.json", "connections.json", "secrets.enc", "prices.json", "approvals"]) {
29
+ const src = path.join(globalDir, name);
30
+ if (existsSync(src))
31
+ await fs.cp(src, path.join(tmp, "symbio", name), { recursive: true });
32
+ }
33
+ await fs.mkdir(tmp, { recursive: true });
34
+ await fs.rename(tmp, dest);
35
+ // Keep the newest days only.
36
+ const days = (await fs.readdir(backupsDir())).filter((d) => /^\d{4}-\d{2}-\d{2}$/.test(d)).sort();
37
+ for (const old of days.slice(0, Math.max(0, days.length - BACKUP_KEEP))) {
38
+ await fs.rm(path.join(backupsDir(), old), { recursive: true, force: true }).catch(() => { });
39
+ }
40
+ return dest;
41
+ }
42
+ export async function lastBackup() {
43
+ const days = (await fs.readdir(backupsDir()).catch(() => [])).filter((d) => /^\d{4}-\d{2}-\d{2}$/.test(d)).sort();
44
+ return days.at(-1) ?? null;
45
+ }
46
+ /** The project's current branch and the helpers' branches, with commits that exist only here. */
47
+ export async function unpushedWork(project) {
48
+ if (!existsSync(path.join(project.directory, ".git")))
49
+ return { remote: null, branches: [] };
50
+ const remote = (await git(project.directory, "remote").catch(() => "")).split("\n")[0]?.trim() || null;
51
+ if (!remote)
52
+ return { remote: null, branches: [] };
53
+ const current = await git(project.directory, "rev-parse", "--abbrev-ref", "HEAD").catch(() => "");
54
+ const helpers = (await git(project.directory, "branch", "--list", "symbio/*", "--format=%(refname:short)").catch(() => ""))
55
+ .split("\n")
56
+ .map((b) => b.trim())
57
+ .filter(Boolean);
58
+ const branches = [];
59
+ for (const branch of [...new Set([current, ...helpers].filter((b) => b && b !== "HEAD"))]) {
60
+ const commits = Number(await git(project.directory, "rev-list", "--count", branch, "--not", "--remotes").catch(() => "0")) || 0;
61
+ if (commits > 0)
62
+ branches.push({ branch, commits, latest: await git(project.directory, "log", "-1", "--format=%s", branch).catch(() => "") });
63
+ }
64
+ return { remote, branches };
65
+ }
66
+ // ---------------------------------------------------------------- disk
67
+ // Folders that are rebuilt or reinstalled on demand. Only removed when git ignores them.
68
+ const BUILD_DIRS = new Set(["bin", "obj", "node_modules", ".vs", "dist", "build", "target", "out", ".next", "__pycache__", ".pytest_cache"]);
69
+ async function sizeOf(dir) {
70
+ let total = 0;
71
+ const walk = async (d) => {
72
+ const entries = await fs.readdir(d, { withFileTypes: true }).catch(() => []);
73
+ await Promise.all(entries.map(async (e) => {
74
+ const p = path.join(d, e.name);
75
+ if (e.isDirectory())
76
+ await walk(p);
77
+ else if (e.isFile())
78
+ total += (await fs.stat(p).catch(() => ({ size: 0 }))).size;
79
+ }));
80
+ };
81
+ await walk(dir);
82
+ return total;
83
+ }
84
+ /** Git-ignored build folders in a helper's working copy (relative paths). */
85
+ async function buildOutputs(dir) {
86
+ const out = await git(dir, "ls-files", "--others", "--ignored", "--exclude-standard", "--directory").catch(() => "");
87
+ return out
88
+ .split("\n")
89
+ .map((l) => l.trim().replace(/\/$/, ""))
90
+ .filter((p) => p && BUILD_DIRS.has(path.basename(p)));
91
+ }
92
+ export async function helperFolders(project) {
93
+ const out = [];
94
+ for (const a of project.agents.filter((a) => a.branch && a.directory !== project.directory && existsSync(a.directory))) {
95
+ const builds = await buildOutputs(a.directory);
96
+ let buildBytes = 0;
97
+ for (const b of builds)
98
+ buildBytes += await sizeOf(path.join(a.directory, b));
99
+ out.push({ agentId: a.id, name: a.name, status: a.status, bytes: await sizeOf(a.directory), buildBytes });
100
+ }
101
+ return out;
102
+ }
103
+ /** Deletes a helper's git-ignored build folders. Never touches the project folder itself. */
104
+ export async function cleanBuildOutputs(project, agent) {
105
+ if (!agent.branch || agent.directory === project.directory)
106
+ throw new Error(`${agent.name} works in the project folder; only helpers' own folders are cleaned.`);
107
+ if (agent.status === "busy" || agent.status === "waiting")
108
+ throw new Error(`${agent.name} is working; clean its folder when it's idle.`);
109
+ let freed = 0;
110
+ for (const rel of await buildOutputs(agent.directory)) {
111
+ const abs = path.resolve(agent.directory, rel);
112
+ if (!abs.startsWith(path.resolve(agent.directory) + path.sep))
113
+ continue;
114
+ freed += await sizeOf(abs);
115
+ await fs.rm(abs, { recursive: true, force: true, maxRetries: 3 });
116
+ }
117
+ return freed;
118
+ }
119
+ export const gb = (bytes) => `${(bytes / 1024 ** 3).toFixed(1)} GB`;
@@ -0,0 +1,133 @@
1
+ import { serve } from "@hono/node-server";
2
+ import { Hono } from "hono";
3
+ import { promises as fs, existsSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { exec } from "node:child_process";
7
+ import { createApi } from "./api.js";
8
+ import { Connections } from "./connections.js";
9
+ import { RemoteOps } from "./remote.js";
10
+ import { handleMcp } from "./mcp.js";
11
+ import { isAllowedRequest } from "./origin.js";
12
+ import { loadUiToken, tokenMatches } from "./ui-token.js";
13
+ import { OpencodeRuntime } from "./opencode/runtime.js";
14
+ import { Store, globalDir } from "./store.js";
15
+ import { Team } from "./team.js";
16
+ import { removeOrphanWorkspaces } from "./workspaces.js";
17
+ const PORT = Number(process.env.SYMBIO_PORT ?? 4310);
18
+ const here = path.dirname(fileURLToPath(import.meta.url));
19
+ // dist/server/index.js → dist/web ; src/server/index.ts → dist/web (after a build)
20
+ const webRoot = [path.resolve(here, "../web"), path.resolve(here, "../../dist/web")].find((p) => existsSync(path.join(p, "index.html")));
21
+ const MIME = {
22
+ ".html": "text/html; charset=utf-8",
23
+ ".js": "text/javascript",
24
+ ".css": "text/css",
25
+ ".svg": "image/svg+xml",
26
+ ".png": "image/png",
27
+ ".json": "application/json",
28
+ ".woff2": "font/woff2",
29
+ };
30
+ /** True when a Symbio is already answering on our port (its API asks for the UI key). */
31
+ async function alreadyRunning() {
32
+ try {
33
+ const res = await fetch(`http://127.0.0.1:${PORT}/api/runtime`, { signal: AbortSignal.timeout(2000) });
34
+ const body = (await res.json().catch(() => null));
35
+ return res.status === 401 && body?.code === "locked";
36
+ }
37
+ catch {
38
+ return false;
39
+ }
40
+ }
41
+ async function main() {
42
+ // Starting Symbio twice must not disturb the running one (or its OpenCode server);
43
+ // just open its page.
44
+ if (await alreadyRunning()) {
45
+ const url = `http://127.0.0.1:${PORT}/?token=${loadUiToken(globalDir)}`;
46
+ console.log(`Symbio is already running: ${url}`);
47
+ if (process.env.SYMBIO_NO_OPEN !== "1")
48
+ openBrowser(url);
49
+ return;
50
+ }
51
+ const store = new Store();
52
+ await store.load();
53
+ // Folders of removed projects that couldn't be deleted at the time (e.g. a file was open).
54
+ const orphans = await removeOrphanWorkspaces(new Set(store.list().map((p) => p.id)));
55
+ if (orphans.length)
56
+ console.log(`Removed ${orphans.length} leftover helper folder(s) of removed projects`);
57
+ const connections = new Connections();
58
+ await connections.load();
59
+ const runtime = new OpencodeRuntime(path.join(globalDir, "opencode.pid"));
60
+ const team = new Team(store, runtime, `http://127.0.0.1:${PORT}`);
61
+ team.remote = new RemoteOps(connections, {
62
+ log: (project, m) => team.log(project, m),
63
+ notify: (project, agent, text) => team.notify(project, agent, text),
64
+ });
65
+ // Agents that were working when Symbio last went down (crash, killed, machine off)
66
+ // are told to continue once OpenCode is up again.
67
+ team.markInterrupted("Symbio was stopped and has been restarted");
68
+ const uiToken = loadUiToken(globalDir);
69
+ const app = new Hono();
70
+ app.use("*", async (c, next) => {
71
+ const ok = isAllowedRequest({ method: c.req.method, host: c.req.header("host"), origin: c.req.header("origin") }, PORT);
72
+ if (!ok)
73
+ return c.json({ error: "Requests must come from Symbio's own page on this computer." }, 403);
74
+ await next();
75
+ });
76
+ // The UI's key: a header, or a query parameter for the event stream (EventSource can't set headers).
77
+ app.use("/api/*", async (c, next) => {
78
+ const given = c.req.header("x-symbio-token") ?? (c.req.method === "GET" ? c.req.query("token") : undefined);
79
+ if (!tokenMatches(uiToken, given)) {
80
+ return c.json({ error: "Open Symbio from the link it printed when it started (or run it again).", code: "locked" }, 401);
81
+ }
82
+ await next();
83
+ });
84
+ // `sym stop`: a clean shutdown (agents are left as they are and resumed on the next start).
85
+ let shutdown = null;
86
+ app.post("/api/shutdown", (c) => {
87
+ setTimeout(() => void shutdown?.(), 200);
88
+ return c.json({ ok: true });
89
+ });
90
+ app.route("/api", createApi(store, runtime, team, connections));
91
+ // Agents' tool server. Only reachable from this machine (we bind to 127.0.0.1) and only with a per-run token.
92
+ app.all("/mcp/:token", (c) => handleMcp(c, team.mcpResolver));
93
+ if (webRoot) {
94
+ app.get("*", async (c) => {
95
+ const rel = decodeURIComponent(new URL(c.req.url).pathname).replace(/^\/+/, "");
96
+ let file = path.resolve(webRoot, rel || "index.html");
97
+ if (!file.startsWith(webRoot + path.sep) || !existsSync(file) || (await fs.stat(file)).isDirectory()) {
98
+ file = path.join(webRoot, "index.html"); // SPA fallback
99
+ }
100
+ const body = await fs.readFile(file);
101
+ return c.body(body, 200, { "content-type": MIME[path.extname(file)] ?? "application/octet-stream" });
102
+ });
103
+ }
104
+ serve({ fetch: app.fetch, port: PORT, hostname: "127.0.0.1" }, () => {
105
+ // The link carries the UI key; once opened, the browser remembers it.
106
+ const url = `http://127.0.0.1:${PORT}/?token=${uiToken}`;
107
+ console.log(`Symbio running at ${url}${webRoot ? "" : " (API only — run the web dev server or build the UI)"}`);
108
+ if (webRoot && process.env.SYMBIO_NO_OPEN !== "1")
109
+ openBrowser(url);
110
+ });
111
+ console.log("Starting OpenCode…");
112
+ runtime
113
+ .start()
114
+ .then(() => console.log(`OpenCode ${runtime.version} ready`))
115
+ .catch((err) => console.error("OpenCode failed to start:", err.message));
116
+ team.startWatchdog();
117
+ shutdown = async () => {
118
+ team.shuttingDown = true;
119
+ team.stopWatchdog();
120
+ await runtime.stop();
121
+ process.exit(0);
122
+ };
123
+ process.on("SIGINT", () => void shutdown?.());
124
+ process.on("SIGTERM", () => void shutdown?.());
125
+ }
126
+ function openBrowser(url) {
127
+ const cmd = process.platform === "win32" ? `start "" "${url}"` : process.platform === "darwin" ? `open "${url}"` : `xdg-open "${url}"`;
128
+ exec(cmd, () => { });
129
+ }
130
+ main().catch((err) => {
131
+ console.error(err);
132
+ process.exit(1);
133
+ });