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,271 @@
1
+ // Actions agents take through connections (SSH commands and uploads, git push/pull,
2
+ // GitHub API). Symbio runs them itself with credentials from the vault — agents
3
+ // only see results. Connections set to "ask" queue an approval for the human; the
4
+ // result is delivered to the agent as a message once approved.
5
+ import { execFile } from "node:child_process";
6
+ import { randomUUID } from "node:crypto";
7
+ import { promises as fs, existsSync, realpathSync } from "node:fs";
8
+ import os from "node:os";
9
+ import path from "node:path";
10
+ import { promisify } from "node:util";
11
+ import { bus } from "./bus.js";
12
+ import { sshExec, sshUpload } from "./ssh.js";
13
+ import { globalDir, newId } from "./store.js";
14
+ const run = promisify(execFile);
15
+ export class RemoteOps {
16
+ connections;
17
+ host;
18
+ approvals = new Map(); // projectId → approvals
19
+ constructor(connections, host) {
20
+ this.connections = connections;
21
+ this.host = host;
22
+ }
23
+ /** Connections the project may use, with their policy. */
24
+ enabled(project) {
25
+ return project.connections
26
+ .map((link) => ({ link, conn: this.connections.get(link.id) }))
27
+ .filter((x) => !!x.conn);
28
+ }
29
+ describeFor(project) {
30
+ const list = this.enabled(project);
31
+ if (list.length === 0)
32
+ return "This project has no connections. If the work needs GitHub or a server, tell the human to add one in the project's sidebar (Connections).";
33
+ return list
34
+ .map(({ conn, link }) => {
35
+ const what = conn.type === "github"
36
+ ? `GitHub${conn.account ? ` account ${conn.account}` : ""} — git_push, git_pull, github_api`
37
+ : `server ${conn.username}@${conn.host} — remote_exec, remote_upload`;
38
+ return `- "${conn.name}": ${what} (${link.policy === "ask" ? "each action needs the human's approval" : "allowed without approval"})`;
39
+ })
40
+ .join("\n");
41
+ }
42
+ /** Runs an action now (policy "allow", or read-only) or queues it for approval. */
43
+ async request(project, agent, action, reason) {
44
+ const { conn, link } = this.resolve(project, action.connectionId, action.kind);
45
+ const summary = this.summarize(conn, action, agent);
46
+ const readOnly = action.kind === "github_api" && action.method.toUpperCase() === "GET";
47
+ if (link.policy === "allow" || readOnly) {
48
+ return this.execute(project, agent, conn, action, summary, reason);
49
+ }
50
+ const approval = {
51
+ id: newId("apr"),
52
+ projectId: project.id,
53
+ agentId: agent.id,
54
+ agentName: agent.name,
55
+ connectionName: conn.name,
56
+ action,
57
+ summary,
58
+ reason,
59
+ status: "pending",
60
+ note: null,
61
+ createdAt: Date.now(),
62
+ decidedAt: null,
63
+ };
64
+ (await this.load(project)).push(approval);
65
+ await this.save(project);
66
+ await this.host.log(project, { from: agent.id, to: "human", kind: "approval", text: `${summary}\n\nWhy: ${reason}` });
67
+ bus.publish({ type: "approvals.updated", projectId: project.id });
68
+ return (`Waiting for the human's approval (${approval.id}): ${summary}. ` +
69
+ `The result arrives as a message once they decide — continue with other work or end your turn. Don't request it again.`);
70
+ }
71
+ async list(project) {
72
+ return this.load(project);
73
+ }
74
+ async decide(project, agent, approvalId, approved, note) {
75
+ const approval = (await this.load(project)).find((a) => a.id === approvalId);
76
+ if (!approval)
77
+ throw new Error("Approval not found");
78
+ if (approval.status !== "pending")
79
+ throw new Error(`Already ${approval.status}`);
80
+ approval.status = approved ? "approved" : "denied";
81
+ approval.note = note?.trim() || null;
82
+ approval.decidedAt = Date.now();
83
+ await this.save(project);
84
+ bus.publish({ type: "approvals.updated", projectId: project.id });
85
+ if (!agent)
86
+ return;
87
+ if (!approved) {
88
+ await this.host.notify(project, agent, `Symbio: the human denied ${approval.summary}.${approval.note ? ` Their note: ${approval.note}` : ""}`);
89
+ return;
90
+ }
91
+ let result;
92
+ try {
93
+ const { conn } = this.resolve(project, approval.action.connectionId, approval.action.kind);
94
+ result = await this.execute(project, agent, conn, approval.action, approval.summary, approval.reason);
95
+ }
96
+ catch (err) {
97
+ result = `Failed: ${err.message}`;
98
+ }
99
+ await this.host.notify(project, agent, `Symbio: the human approved ${approval.summary}.${approval.note ? ` Their note: ${approval.note}` : ""}\n\nResult:\n${result}`);
100
+ }
101
+ // ---------------------------------------------------------------- internals
102
+ resolve(project, connectionRef, kind) {
103
+ const ref = connectionRef.trim().toLowerCase();
104
+ const found = this.enabled(project).find(({ conn }) => conn.id === connectionRef || conn.name.toLowerCase() === ref);
105
+ if (!found) {
106
+ const names = this.enabled(project).map(({ conn }) => conn.name).join(", ") || "none";
107
+ throw new Error(`No connection "${connectionRef}" in this project. Available: ${names}.`);
108
+ }
109
+ const needs = kind.startsWith("remote_") ? "server" : "github";
110
+ if (found.conn.type !== needs)
111
+ throw new Error(`"${found.conn.name}" is a ${found.conn.type} connection; ${kind} needs a ${needs} connection.`);
112
+ return found;
113
+ }
114
+ summarize(conn, a, agent) {
115
+ switch (a.kind) {
116
+ case "remote_exec":
117
+ return `run \`${a.command}\` on ${conn.name}`;
118
+ case "remote_upload":
119
+ return `upload ${a.localPath} to ${conn.name}:${a.remotePath}`;
120
+ case "git_push":
121
+ return `git push ${a.remote ?? "origin"} ${a.branch ?? "(current branch)"} from ${agent.name}'s workspace using ${conn.name}`;
122
+ case "git_pull":
123
+ return `git pull ${a.remote ?? "origin"} ${a.branch ?? "(current branch)"} into ${agent.name}'s workspace using ${conn.name}`;
124
+ case "github_api":
125
+ return `GitHub API ${a.method.toUpperCase()} ${a.path} using ${conn.name}`;
126
+ }
127
+ }
128
+ async execute(project, agent, conn, a, summary, reason) {
129
+ let output;
130
+ let ok = true;
131
+ try {
132
+ output = await this.perform(agent, conn, a);
133
+ }
134
+ catch (err) {
135
+ ok = false;
136
+ output = `Error: ${err.message}`;
137
+ }
138
+ await this.host.log(project, {
139
+ from: agent.id,
140
+ to: "human",
141
+ kind: "remote",
142
+ text: `${ok ? "✓" : "✕"} ${summary}\n\nWhy: ${reason}\n\n\`\`\`\n${output.slice(0, 4000)}\n\`\`\``,
143
+ });
144
+ return output;
145
+ }
146
+ async perform(agent, conn, a) {
147
+ switch (a.kind) {
148
+ case "remote_exec": {
149
+ const res = await sshExec(await this.connections.sshTarget(conn), a.command);
150
+ const parts = [`exit code ${res.code}`];
151
+ if (res.stdout.trim())
152
+ parts.push(`stdout:\n${res.stdout.trimEnd()}`);
153
+ if (res.stderr.trim())
154
+ parts.push(`stderr:\n${res.stderr.trimEnd()}`);
155
+ if (res.truncated)
156
+ parts.push("(output truncated)");
157
+ return parts.join("\n");
158
+ }
159
+ case "remote_upload": {
160
+ const local = insideWorkspace(agent, a.localPath);
161
+ const count = await sshUpload(await this.connections.sshTarget(conn), local, a.remotePath);
162
+ return `Uploaded ${count} file(s) to ${a.remotePath} (skipping .git, node_modules and .symbio).`;
163
+ }
164
+ case "git_push":
165
+ case "git_pull": {
166
+ const token = await this.connections.githubToken(conn);
167
+ const remote = a.remote ?? "origin";
168
+ const url = remote.startsWith("https://") ? remote : await gitOut(agent.directory, ["remote", "get-url", remote]);
169
+ if (!/^https:\/\/github\.com\//i.test(url)) {
170
+ throw new Error(`The remote must be a GitHub HTTPS URL (got ${url || "nothing"}). Add one with: git remote add origin https://github.com/<owner>/<repo>.git`);
171
+ }
172
+ const branch = a.branch ?? (await gitOut(agent.directory, ["rev-parse", "--abbrev-ref", "HEAD"]));
173
+ // The agent controls this repository, so its config and hooks are untrusted: a hook
174
+ // would see the token, a proxy or URL rewrite would send it elsewhere.
175
+ await refuseRiskyGitConfig(agent.directory);
176
+ const noHooks = path.join(os.tmpdir(), `symbio-no-hooks-${randomUUID()}`); // never exists
177
+ const safe = ["-c", `core.hooksPath=${noHooks}`, "-c", "http.proxy=", "-c", "http.sslVerify=true", "-c", "credential.helper="];
178
+ // The token goes in an HTTP header via environment-only git config: never in
179
+ // the command line, the repo config or the agent's view.
180
+ const header = `Authorization: Basic ${Buffer.from(`x-access-token:${token}`).toString("base64")}`;
181
+ const git = (args, withToken) => run("git", [...safe, ...args], {
182
+ cwd: agent.directory,
183
+ windowsHide: true,
184
+ timeout: 5 * 60_000,
185
+ env: {
186
+ ...process.env,
187
+ GIT_TERMINAL_PROMPT: "0",
188
+ ...(withToken
189
+ ? { GIT_CONFIG_COUNT: "1", GIT_CONFIG_KEY_0: "http.https://github.com/.extraheader", GIT_CONFIG_VALUE_0: header }
190
+ : {}),
191
+ },
192
+ }).catch((err) => {
193
+ throw new Error(scrub(String(err.stderr || err.message), token));
194
+ });
195
+ if (a.kind === "git_push") {
196
+ const { stdout, stderr } = await git(["push", "--no-verify", url, `HEAD:refs/heads/${branch}`], true);
197
+ return scrub(`${stdout}${stderr}`.trim() || "done", token);
198
+ }
199
+ // Pull = fetch with the token, then merge without it (merging can run filters).
200
+ const fetched = await git(["fetch", url, branch], true);
201
+ const merged = await git(["merge", "--no-edit", "FETCH_HEAD"], false);
202
+ return scrub(`${fetched.stdout}${fetched.stderr}${merged.stdout}${merged.stderr}`.trim() || "done", token);
203
+ }
204
+ case "github_api": {
205
+ const data = await this.connections.githubRequest(conn, a.method.toUpperCase(), a.path, a.body);
206
+ const text = JSON.stringify(data, null, 2) ?? "(no content)";
207
+ return text.length > 20_000 ? `${text.slice(0, 20_000)}\n… (truncated)` : text;
208
+ }
209
+ }
210
+ }
211
+ async load(project) {
212
+ let list = this.approvals.get(project.id);
213
+ if (!list) {
214
+ try {
215
+ list = JSON.parse(await fs.readFile(file(project), "utf8"));
216
+ }
217
+ catch {
218
+ list = [];
219
+ }
220
+ this.approvals.set(project.id, list);
221
+ }
222
+ return list;
223
+ }
224
+ async save(project) {
225
+ const list = this.approvals.get(project.id) ?? [];
226
+ await fs.mkdir(path.dirname(file(project)), { recursive: true });
227
+ await fs.writeFile(file(project), JSON.stringify(list.slice(-500), null, 2));
228
+ }
229
+ }
230
+ // Outside the project folder, where agents can't edit what the human is about to approve.
231
+ const file = (project) => path.join(globalDir, "approvals", `${project.id}.json`);
232
+ /** Resolves a path the agent gave, refusing anything outside its own working folder. */
233
+ function insideWorkspace(agent, p) {
234
+ const abs = path.resolve(agent.directory, p);
235
+ if (!existsSync(abs))
236
+ throw new Error(`Not found: ${p}`);
237
+ // Compare real paths, so a symlink inside the folder can't point outside it.
238
+ const rel = path.relative(realpathSync(agent.directory), realpathSync(abs));
239
+ if (rel.startsWith("..") || path.isAbsolute(rel))
240
+ throw new Error(`Only files inside your working folder can be uploaded (${agent.directory}).`);
241
+ return abs;
242
+ }
243
+ // Repository settings that could run code or redirect traffic while the token is in use.
244
+ const RISKY_GIT_CONFIG = [
245
+ /^include(if)?\./,
246
+ /\.(insteadof|pushinsteadof)$/,
247
+ /^http\./,
248
+ /^credential\./,
249
+ /^core\.(hookspath|fsmonitor|sshcommand|askpass|gitproxy)$/,
250
+ /^remote\.[^.]+\.(proxy|uploadpack|receivepack|pushurl)$/,
251
+ ];
252
+ /** Refuses to use credentials in a repository whose own config could leak them. */
253
+ export async function refuseRiskyGitConfig(dir) {
254
+ const { stdout } = await run("git", ["config", "--list", "--show-scope", "--name-only"], { cwd: dir, windowsHide: true });
255
+ const risky = stdout
256
+ .split(/\r?\n/)
257
+ .map((line) => line.split("\t"))
258
+ .filter(([scope, key]) => (scope === "local" || scope === "worktree") && key && RISKY_GIT_CONFIG.some((re) => re.test(key.toLowerCase())))
259
+ .map(([, key]) => key);
260
+ if (risky.length) {
261
+ throw new Error(`Refusing to use GitHub credentials: this repository's git config sets ${risky.join(", ")}, which could redirect or capture them. Remove ${risky.length > 1 ? "these settings" : "it"} (git config --unset <name>) and try again.`);
262
+ }
263
+ }
264
+ async function gitOut(cwd, args) {
265
+ const { stdout } = await run("git", args, { cwd, windowsHide: true }).catch(() => ({ stdout: "" }));
266
+ return stdout.trim();
267
+ }
268
+ function scrub(text, secret) {
269
+ const b64 = Buffer.from(`x-access-token:${secret}`).toString("base64");
270
+ return text.split(secret).join("***").split(b64).join("***");
271
+ }
@@ -0,0 +1,105 @@
1
+ // Secret storage for connections. Secrets are encrypted (AES-256-GCM) in
2
+ // ~/.symbio/secrets.enc with a random master key kept in the OS credential
3
+ // store (Windows Credential Manager / macOS Keychain / Secret Service), so the
4
+ // file is useless without the user's OS login. One keyring entry, no size limits.
5
+ //
6
+ // Secret values never leave the Symbio server process: they are not returned
7
+ // by the API and never reach agents or models.
8
+ import { Entry } from "@napi-rs/keyring";
9
+ import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
10
+ import { existsSync, promises as fs } from "node:fs";
11
+ import path from "node:path";
12
+ // Overridable so tests never touch the real credential entry.
13
+ const SERVICE = process.env.SYMBIO_KEYRING_SERVICE ?? "symbio";
14
+ const MASTER_KEY_ACCOUNT = "vault-master-key";
15
+ export class SecretVault {
16
+ file;
17
+ cache = null;
18
+ writing = Promise.resolve();
19
+ constructor(file) {
20
+ this.file = file;
21
+ }
22
+ static at(dir) {
23
+ return new SecretVault(path.join(dir, "secrets.enc"));
24
+ }
25
+ async get(key) {
26
+ return (await this.load())[key];
27
+ }
28
+ async has(key) {
29
+ return (await this.get(key)) !== undefined;
30
+ }
31
+ async set(key, value) {
32
+ const all = await this.load();
33
+ all[key] = value;
34
+ await this.save(all);
35
+ }
36
+ /** Deletes every secret whose key starts with the prefix (e.g. all of one connection's). */
37
+ async deletePrefix(prefix) {
38
+ const all = await this.load();
39
+ for (const k of Object.keys(all))
40
+ if (k.startsWith(prefix))
41
+ delete all[k];
42
+ await this.save(all);
43
+ }
44
+ masterKey() {
45
+ const entry = new Entry(SERVICE, MASTER_KEY_ACCOUNT);
46
+ let encoded = null;
47
+ try {
48
+ encoded = entry.getPassword() ?? null;
49
+ }
50
+ catch (err) {
51
+ // A locked or unavailable credential store must not be mistaken for "no key yet":
52
+ // replacing the key would make the existing secrets unreadable for good.
53
+ if (existsSync(this.file))
54
+ throw new Error(`Couldn't read the vault key from the OS credential store: ${err.message}`);
55
+ }
56
+ if (!encoded) {
57
+ if (existsSync(this.file)) {
58
+ throw new Error("The vault key is missing from the OS credential store, so the stored connection secrets can't be read. " +
59
+ `Delete ${this.file} and re-enter the credentials in Settings.`);
60
+ }
61
+ encoded = randomBytes(32).toString("base64");
62
+ entry.setPassword(encoded);
63
+ }
64
+ return Buffer.from(encoded, "base64");
65
+ }
66
+ async load() {
67
+ if (this.cache)
68
+ return this.cache;
69
+ let blob;
70
+ try {
71
+ blob = await fs.readFile(this.file);
72
+ }
73
+ catch (err) {
74
+ if (err.code === "ENOENT")
75
+ return (this.cache = {});
76
+ throw err;
77
+ }
78
+ // Layout: 12-byte IV | 16-byte auth tag | ciphertext
79
+ const decipher = createDecipheriv("aes-256-gcm", this.masterKey(), blob.subarray(0, 12));
80
+ decipher.setAuthTag(blob.subarray(12, 28));
81
+ try {
82
+ const plain = Buffer.concat([decipher.update(blob.subarray(28)), decipher.final()]);
83
+ this.cache = JSON.parse(plain.toString("utf8"));
84
+ }
85
+ catch {
86
+ throw new Error("Could not decrypt the connection secrets (the master key in the OS credential store doesn't match). " +
87
+ "Re-enter the credentials in Settings.");
88
+ }
89
+ return this.cache;
90
+ }
91
+ save(all) {
92
+ this.cache = all;
93
+ const write = async () => {
94
+ const iv = randomBytes(12);
95
+ const cipher = createCipheriv("aes-256-gcm", this.masterKey(), iv);
96
+ const enc = Buffer.concat([cipher.update(JSON.stringify(all), "utf8"), cipher.final()]);
97
+ await fs.mkdir(path.dirname(this.file), { recursive: true });
98
+ const tmp = `${this.file}.${process.pid}.tmp`;
99
+ await fs.writeFile(tmp, Buffer.concat([iv, cipher.getAuthTag(), enc]));
100
+ await fs.rename(tmp, this.file);
101
+ };
102
+ this.writing = this.writing.catch(() => { }).then(write);
103
+ return this.writing;
104
+ }
105
+ }
@@ -0,0 +1,146 @@
1
+ // SSH for server connections: run commands and upload files. Runs inside the
2
+ // Symbio process with credentials from the vault; agents only see results.
3
+ import { Client } from "ssh2";
4
+ import { createHash } from "node:crypto";
5
+ import { promises as fs } from "node:fs";
6
+ import path from "node:path";
7
+ const MAX_OUTPUT = 60_000;
8
+ export const fingerprint = (key) => `SHA256:${createHash("sha256").update(key).digest("base64").replace(/=+$/, "")}`;
9
+ function connect(target, timeoutMs = 20_000) {
10
+ return new Promise((resolve, reject) => {
11
+ const client = new Client();
12
+ let seen = null;
13
+ const config = {
14
+ host: target.host,
15
+ port: target.port,
16
+ username: target.username,
17
+ readyTimeout: timeoutMs,
18
+ // Without this any server would be accepted, and an impostor on the network would
19
+ // receive the password and the commands.
20
+ hostVerifier: (key) => {
21
+ seen = fingerprint(key);
22
+ return !target.hostKey || seen === target.hostKey;
23
+ },
24
+ ...(target.privateKey ? { privateKey: target.privateKey, passphrase: target.passphrase } : { password: target.password }),
25
+ };
26
+ client.once("ready", async () => {
27
+ if (!target.hostKey && seen)
28
+ await target.onFirstHostKey?.(seen);
29
+ resolve(client);
30
+ });
31
+ client.once("error", (err) => {
32
+ if (target.hostKey && seen && seen !== target.hostKey) {
33
+ reject(new Error(`The server at ${target.host} presented a different host key (${seen}) than before (${target.hostKey}). ` +
34
+ "This can mean someone is intercepting the connection. If the server was reinstalled, edit and save the connection in Settings to trust its new key."));
35
+ }
36
+ else
37
+ reject(friendlyError(err, target));
38
+ });
39
+ client.connect(config);
40
+ });
41
+ }
42
+ function friendlyError(err, t) {
43
+ if (err.level === "client-authentication")
44
+ return new Error(`Authentication failed for ${t.username}@${t.host} — check the key/password.`);
45
+ if (err.code === "ENOTFOUND")
46
+ return new Error(`Host not found: ${t.host}`);
47
+ if (err.code === "ECONNREFUSED")
48
+ return new Error(`Connection refused by ${t.host}:${t.port}`);
49
+ if (/timed out/i.test(err.message))
50
+ return new Error(`Timed out connecting to ${t.host}:${t.port}`);
51
+ if (/passphrase/i.test(err.message))
52
+ return new Error("The private key is encrypted — add its passphrase.");
53
+ return new Error(err.message);
54
+ }
55
+ /** Runs one command (non-interactive) and returns its output. */
56
+ export async function sshExec(target, command, timeoutMs = 10 * 60_000) {
57
+ const client = await connect(target);
58
+ try {
59
+ return await new Promise((resolve, reject) => {
60
+ client.exec(command, (err, stream) => {
61
+ if (err)
62
+ return reject(err);
63
+ let stdout = "";
64
+ let stderr = "";
65
+ let truncated = false;
66
+ const add = (which, chunk) => {
67
+ const text = chunk.toString("utf8");
68
+ if (stdout.length + stderr.length + text.length > MAX_OUTPUT) {
69
+ truncated = true;
70
+ return;
71
+ }
72
+ if (which === "out")
73
+ stdout += text;
74
+ else
75
+ stderr += text;
76
+ };
77
+ const timer = setTimeout(() => {
78
+ stream.close();
79
+ reject(new Error(`Command timed out after ${Math.round(timeoutMs / 1000)}s`));
80
+ }, timeoutMs);
81
+ // The exit status may arrive as an "exit" event before "close", or as close's argument.
82
+ let exitCode = null;
83
+ stream.on("exit", (code) => {
84
+ if (typeof code === "number")
85
+ exitCode = code;
86
+ });
87
+ stream.on("data", (c) => add("out", c));
88
+ stream.stderr.on("data", (c) => add("err", c));
89
+ stream.on("close", (code) => {
90
+ clearTimeout(timer);
91
+ resolve({ code: typeof code === "number" ? code : exitCode, stdout, stderr, truncated });
92
+ });
93
+ });
94
+ });
95
+ }
96
+ finally {
97
+ client.end();
98
+ }
99
+ }
100
+ /** Uploads a local file or folder (recursively) to a remote path. Returns the number of files. */
101
+ export async function sshUpload(target, localPath, remotePath) {
102
+ // SFTP doesn't expand "~"; relative paths are already relative to the home folder.
103
+ remotePath = remotePath.replace(/^~\/?/, "") || ".";
104
+ const client = await connect(target);
105
+ try {
106
+ const sftp = await new Promise((resolve, reject) => client.sftp((e, s) => (e ? reject(e) : resolve(s))));
107
+ const stat = await fs.stat(localPath);
108
+ if (stat.isFile()) {
109
+ await mkdirp(sftp, path.posix.dirname(remotePath));
110
+ await put(sftp, localPath, remotePath);
111
+ return 1;
112
+ }
113
+ let count = 0;
114
+ const walk = async (dir, remote) => {
115
+ await mkdirp(sftp, remote);
116
+ for (const entry of await fs.readdir(dir, { withFileTypes: true })) {
117
+ if (entry.name === ".git" || entry.name === "node_modules" || entry.name === ".symbio")
118
+ continue;
119
+ const local = path.join(dir, entry.name);
120
+ const target = path.posix.join(remote, entry.name);
121
+ if (entry.isDirectory())
122
+ await walk(local, target);
123
+ else if (entry.isFile()) {
124
+ await put(sftp, local, target);
125
+ count++;
126
+ }
127
+ }
128
+ };
129
+ await walk(localPath, remotePath);
130
+ return count;
131
+ }
132
+ finally {
133
+ client.end();
134
+ }
135
+ }
136
+ function put(sftp, local, remote) {
137
+ return new Promise((resolve, reject) => sftp.fastPut(local, remote, (e) => (e ? reject(e) : resolve())));
138
+ }
139
+ async function mkdirp(sftp, dir) {
140
+ const parts = dir.split("/").filter(Boolean);
141
+ let current = dir.startsWith("/") ? "" : ".";
142
+ for (const part of parts) {
143
+ current = current === "" ? `/${part}` : `${current}/${part}`;
144
+ await new Promise((resolve) => sftp.mkdir(current, () => resolve())); // ignore "exists"
145
+ }
146
+ }