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,154 @@
1
+ // Shared-asset register. An asset is anything more than one agent could change:
2
+ // path patterns inside the project, or a named external thing. Symbio never
3
+ // interprets what an asset is; it tracks who holds it and who is waiting.
4
+ //
5
+ // Protocol: agents request → coordinator grants/denies → holder releases.
6
+ // No holder means the coordinator holds it.
7
+ import { promises as fs } from "node:fs";
8
+ import path from "node:path";
9
+ export class AssetRegister {
10
+ file;
11
+ assets = [];
12
+ constructor(file) {
13
+ this.file = file;
14
+ }
15
+ static async load(projectDir) {
16
+ const reg = new AssetRegister(path.join(projectDir, ".symbio", "assets.json"));
17
+ try {
18
+ reg.assets = JSON.parse(await fs.readFile(reg.file, "utf8"));
19
+ }
20
+ catch (err) {
21
+ if (err.code !== "ENOENT")
22
+ throw err;
23
+ }
24
+ return reg;
25
+ }
26
+ list() {
27
+ return this.assets;
28
+ }
29
+ get(name) {
30
+ const key = name.trim().toLowerCase();
31
+ return this.assets.find((a) => a.name.toLowerCase() === key);
32
+ }
33
+ require(name) {
34
+ const asset = this.get(name);
35
+ if (!asset) {
36
+ const known = this.assets.map((a) => a.name).join(", ") || "none";
37
+ throw new Error(`Unknown shared asset "${name}". Declared assets: ${known}.`);
38
+ }
39
+ return asset;
40
+ }
41
+ async declare(name, description, paths = []) {
42
+ const existing = this.get(name);
43
+ if (existing) {
44
+ existing.description = description || existing.description;
45
+ if (paths.length)
46
+ existing.paths = paths;
47
+ await this.save();
48
+ return existing;
49
+ }
50
+ const asset = {
51
+ name: name.trim(),
52
+ description,
53
+ paths: paths.map(normalizePattern),
54
+ holder: null,
55
+ queue: [],
56
+ history: [{ time: Date.now(), type: "declared" }],
57
+ };
58
+ this.assets.push(asset);
59
+ await this.save();
60
+ return asset;
61
+ }
62
+ /** Queues a request. Returns the asset; the coordinator decides. */
63
+ async request(name, agentId, reason) {
64
+ const asset = this.require(name);
65
+ if (asset.holder === agentId)
66
+ return { asset, alreadyHeld: true };
67
+ if (!asset.queue.some((r) => r.agentId === agentId)) {
68
+ asset.queue.push({ agentId, reason, time: Date.now() });
69
+ asset.history.push({ time: Date.now(), type: "requested", agentId, note: reason });
70
+ await this.save();
71
+ }
72
+ return { asset, alreadyHeld: false };
73
+ }
74
+ async grant(name, agentId, note) {
75
+ const asset = this.require(name);
76
+ if (asset.holder && asset.holder !== agentId) {
77
+ throw new Error(`"${asset.name}" is held by another agent. Ask them to release it first (or wait for their release).`);
78
+ }
79
+ asset.holder = agentId;
80
+ asset.queue = asset.queue.filter((r) => r.agentId !== agentId);
81
+ asset.history.push({ time: Date.now(), type: "granted", agentId, note });
82
+ await this.save();
83
+ return asset;
84
+ }
85
+ async deny(name, agentId, reason) {
86
+ const asset = this.require(name);
87
+ asset.queue = asset.queue.filter((r) => r.agentId !== agentId);
88
+ asset.history.push({ time: Date.now(), type: "denied", agentId, note: reason });
89
+ await this.save();
90
+ return asset;
91
+ }
92
+ async release(name, agentId, summary) {
93
+ const asset = this.require(name);
94
+ if (asset.holder !== agentId)
95
+ throw new Error(`You don't hold "${asset.name}".`);
96
+ asset.holder = null;
97
+ asset.history.push({ time: Date.now(), type: "released", agentId, note: summary });
98
+ await this.save();
99
+ return asset;
100
+ }
101
+ /** Releases everything an agent holds and drops its queued requests (agent stopped). */
102
+ async forget(agentId) {
103
+ for (const asset of this.assets) {
104
+ if (asset.holder === agentId) {
105
+ asset.holder = null;
106
+ asset.history.push({ time: Date.now(), type: "released", agentId, note: "agent stopped" });
107
+ }
108
+ asset.queue = asset.queue.filter((r) => r.agentId !== agentId);
109
+ }
110
+ await this.save();
111
+ }
112
+ /**
113
+ * Assets (with path patterns) touched by the given changed files that the agent
114
+ * was not granted at any point since `since`.
115
+ */
116
+ violations(changedFiles, agentId, since) {
117
+ const result = [];
118
+ for (const asset of this.assets) {
119
+ if (asset.paths.length === 0)
120
+ continue;
121
+ const files = changedFiles.filter((f) => asset.paths.some((p) => matchPattern(p, f)));
122
+ if (files.length === 0)
123
+ continue;
124
+ const granted = asset.holder === agentId ||
125
+ asset.history.some((h) => h.type === "granted" && h.agentId === agentId && h.time >= since);
126
+ if (!granted)
127
+ result.push({ asset, files });
128
+ }
129
+ return result;
130
+ }
131
+ async save() {
132
+ await fs.mkdir(path.dirname(this.file), { recursive: true });
133
+ const tmp = `${this.file}.${process.pid}.tmp`;
134
+ await fs.writeFile(tmp, JSON.stringify(this.assets, null, 2));
135
+ await fs.rename(tmp, this.file);
136
+ }
137
+ }
138
+ function normalizePattern(p) {
139
+ return p.trim().replace(/\\/g, "/").replace(/^\.?\/+/, "");
140
+ }
141
+ /** Minimal glob: `**` any path, `*` any segment chars, a trailing `/` means the whole folder. */
142
+ export function matchPattern(pattern, file) {
143
+ let p = normalizePattern(pattern);
144
+ const f = file.replace(/\\/g, "/");
145
+ if (p.endsWith("/"))
146
+ p += "**";
147
+ if (!/[*?]/.test(p))
148
+ return f === p || f.startsWith(p + "/");
149
+ const re = p
150
+ .split("**")
151
+ .map((part) => part.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]"))
152
+ .join(".*");
153
+ return new RegExp(`^${re}$`, "i").test(f);
154
+ }
@@ -0,0 +1,9 @@
1
+ // Fan-out of events to connected browser clients.
2
+ import { EventEmitter } from "node:events";
3
+ class Bus extends EventEmitter {
4
+ publish(event) {
5
+ this.emit("ui", event);
6
+ }
7
+ }
8
+ export const bus = new Bus();
9
+ bus.setMaxListeners(100);
@@ -0,0 +1,227 @@
1
+ // Global connections (set once in Settings, used by any project): GitHub accounts
2
+ // and servers reachable over SSH. Public details live in ~/.symbio/connections.json;
3
+ // secrets live in the encrypted vault and are never returned by the API.
4
+ import { promises as fs, readFileSync } from "node:fs";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { SecretVault } from "./secrets.js";
8
+ import { sshExec } from "./ssh.js";
9
+ import { globalDir, newId } from "./store.js";
10
+ const SECRET_FIELDS = {
11
+ github: ["token"],
12
+ server: ["privateKey", "passphrase", "password"],
13
+ };
14
+ export class Connections {
15
+ list = [];
16
+ file = path.join(globalDir, "connections.json");
17
+ vault = SecretVault.at(globalDir);
18
+ async load() {
19
+ try {
20
+ this.list = JSON.parse(await fs.readFile(this.file, "utf8"));
21
+ }
22
+ catch (err) {
23
+ if (err.code !== "ENOENT")
24
+ throw err;
25
+ }
26
+ }
27
+ get(id) {
28
+ return this.list.find((c) => c.id === id);
29
+ }
30
+ async views() {
31
+ return Promise.all(this.list.map((c) => this.view(c)));
32
+ }
33
+ async view(c) {
34
+ const secrets = {};
35
+ for (const f of SECRET_FIELDS[c.type])
36
+ secrets[f] = await this.vault.has(`${c.id}:${f}`);
37
+ return { ...c, secrets };
38
+ }
39
+ async create(input) {
40
+ if (input.type !== "github" && input.type !== "server")
41
+ throw new Error("type must be github or server");
42
+ const now = Date.now();
43
+ const base = { id: newId("con"), name: "", createdAt: now, updatedAt: now, lastTest: null };
44
+ const conn = input.type === "github"
45
+ ? { ...base, type: "github", account: null }
46
+ : { ...base, type: "server", host: "", port: 22, username: "", auth: "key", keyPath: null };
47
+ this.apply(conn, input);
48
+ if (!conn.name)
49
+ throw new Error("Give the connection a name.");
50
+ this.validate(conn);
51
+ try {
52
+ await this.storeSecrets(conn, input);
53
+ }
54
+ catch (err) {
55
+ await this.vault.deletePrefix(`${conn.id}:`);
56
+ throw err;
57
+ }
58
+ this.list.push(conn);
59
+ await this.save();
60
+ return conn;
61
+ }
62
+ async update(id, input) {
63
+ const conn = this.get(id);
64
+ if (!conn)
65
+ throw new Error("Connection not found");
66
+ this.apply(conn, input);
67
+ this.validate(conn);
68
+ await this.storeSecrets(conn, input);
69
+ conn.updatedAt = Date.now();
70
+ conn.lastTest = null;
71
+ // Saving the connection is how the human says "trust this server's (new) key".
72
+ if (conn.type === "server")
73
+ conn.hostKey = null;
74
+ await this.save();
75
+ return conn;
76
+ }
77
+ async remove(id) {
78
+ this.list = this.list.filter((c) => c.id !== id);
79
+ await this.vault.deletePrefix(`${id}:`);
80
+ await this.save();
81
+ }
82
+ /** Checks the connection works, with the stored credentials. */
83
+ async test(id) {
84
+ const conn = this.get(id);
85
+ if (!conn)
86
+ throw new Error("Connection not found");
87
+ let result;
88
+ try {
89
+ if (conn.type === "github") {
90
+ const user = await this.githubRequest(conn, "GET", "/user");
91
+ conn.account = user.login;
92
+ result = { ok: true, message: `Signed in as ${user.login}${user.name ? ` (${user.name})` : ""}`, time: Date.now() };
93
+ }
94
+ else {
95
+ const res = await sshExec(await this.sshTarget(conn), "uname -srm 2>/dev/null || ver", 30_000);
96
+ const out = (res.stdout || res.stderr).trim().split("\n")[0];
97
+ result = { ok: res.code === 0, message: res.code === 0 ? `Connected — ${out}` : `Connected, but the test command failed: ${out}`, time: Date.now() };
98
+ }
99
+ }
100
+ catch (err) {
101
+ result = { ok: false, message: err.message, time: Date.now() };
102
+ }
103
+ conn.lastTest = result;
104
+ await this.save();
105
+ return result;
106
+ }
107
+ /** SSH credentials for a server connection (server-side use only). */
108
+ async sshTarget(conn) {
109
+ const target = {
110
+ host: conn.host,
111
+ port: conn.port,
112
+ username: conn.username,
113
+ hostKey: conn.hostKey ?? null,
114
+ onFirstHostKey: async (fp) => {
115
+ conn.hostKey = fp;
116
+ await this.save();
117
+ },
118
+ };
119
+ if (conn.auth === "password") {
120
+ target.password = await this.vault.get(`${conn.id}:password`);
121
+ if (!target.password)
122
+ throw new Error(`No password stored for "${conn.name}".`);
123
+ }
124
+ else {
125
+ target.privateKey = conn.keyPath ? readKeyFile(conn.keyPath) : await this.vault.get(`${conn.id}:privateKey`);
126
+ if (!target.privateKey)
127
+ throw new Error(`No private key for "${conn.name}".`);
128
+ target.passphrase = await this.vault.get(`${conn.id}:passphrase`);
129
+ }
130
+ return target;
131
+ }
132
+ async githubToken(conn) {
133
+ const token = await this.vault.get(`${conn.id}:token`);
134
+ if (!token)
135
+ throw new Error(`No token stored for "${conn.name}".`);
136
+ return token;
137
+ }
138
+ /** Calls the GitHub REST API with the connection's token. */
139
+ async githubRequest(conn, method, apiPath, body) {
140
+ const res = await fetch(`https://api.github.com${apiPath.startsWith("/") ? apiPath : `/${apiPath}`}`, {
141
+ method,
142
+ headers: {
143
+ authorization: `Bearer ${await this.githubToken(conn)}`,
144
+ accept: "application/vnd.github+json",
145
+ "x-github-api-version": "2022-11-28",
146
+ "user-agent": "symbio",
147
+ ...(body === undefined ? {} : { "content-type": "application/json" }),
148
+ },
149
+ body: body === undefined ? undefined : JSON.stringify(body),
150
+ });
151
+ const text = await res.text();
152
+ const data = text ? safeJson(text) : null;
153
+ if (!res.ok) {
154
+ const msg = data?.message ?? res.statusText;
155
+ throw new Error(res.status === 401 ? "GitHub rejected the token (expired or revoked?)" : `GitHub ${res.status}: ${msg}`);
156
+ }
157
+ return data;
158
+ }
159
+ apply(conn, input) {
160
+ if (input.name !== undefined)
161
+ conn.name = input.name.trim();
162
+ if (conn.type === "server") {
163
+ if (input.host !== undefined)
164
+ conn.host = input.host.trim();
165
+ if (input.port !== undefined)
166
+ conn.port = Number(input.port) || 22;
167
+ if (input.username !== undefined)
168
+ conn.username = input.username.trim();
169
+ if (input.auth !== undefined)
170
+ conn.auth = input.auth === "password" ? "password" : "key";
171
+ if (input.keyPath !== undefined)
172
+ conn.keyPath = input.keyPath?.trim() ? expandHome(input.keyPath.trim()) : null;
173
+ }
174
+ }
175
+ validate(conn) {
176
+ if (conn.type === "server") {
177
+ if (!conn.host)
178
+ throw new Error("Host is required.");
179
+ if (!conn.username)
180
+ throw new Error("User is required.");
181
+ if (conn.keyPath)
182
+ readKeyFile(conn.keyPath); // fail early on a wrong path
183
+ }
184
+ }
185
+ /** Stores the secrets present in the input; empty/missing ones keep their stored value. */
186
+ async storeSecrets(conn, input) {
187
+ for (const field of SECRET_FIELDS[conn.type]) {
188
+ const value = input[field];
189
+ if (typeof value === "string" && value.trim())
190
+ await this.vault.set(`${conn.id}:${field}`, value.trim());
191
+ }
192
+ if (conn.type === "github" && !(await this.vault.has(`${conn.id}:token`)))
193
+ throw new Error("The token is required.");
194
+ if (conn.type === "server") {
195
+ if (conn.auth === "password" && !(await this.vault.has(`${conn.id}:password`)))
196
+ throw new Error("The password is required.");
197
+ if (conn.auth === "key" && !conn.keyPath && !(await this.vault.has(`${conn.id}:privateKey`))) {
198
+ throw new Error("Paste the private key, or give the path to the key file.");
199
+ }
200
+ }
201
+ }
202
+ async save() {
203
+ await fs.mkdir(globalDir, { recursive: true });
204
+ const tmp = `${this.file}.${process.pid}.tmp`;
205
+ await fs.writeFile(tmp, JSON.stringify(this.list, null, 2));
206
+ await fs.rename(tmp, this.file);
207
+ }
208
+ }
209
+ function expandHome(p) {
210
+ return p.startsWith("~") ? path.join(os.homedir(), p.slice(1)) : p;
211
+ }
212
+ function readKeyFile(p) {
213
+ try {
214
+ return readFileSync(expandHome(p), "utf8");
215
+ }
216
+ catch {
217
+ throw new Error(`Can't read the key file ${p}`);
218
+ }
219
+ }
220
+ function safeJson(text) {
221
+ try {
222
+ return JSON.parse(text);
223
+ }
224
+ catch {
225
+ return text;
226
+ }
227
+ }
@@ -0,0 +1,175 @@
1
+ // Token usage per model and estimated cost.
2
+ //
3
+ // OpenCode reports totals per session, not per model, and agents can switch models (or
4
+ // get a fresh session). So each time a session's totals are read, the increase since
5
+ // the last read is attributed to the model the agent is on now (Agent.usageByModel).
6
+ // Data from before this existed is attributed to the agent's current model.
7
+ //
8
+ // Prices are USD per million tokens, kept in ~/.symbio/prices.json. Providers that don't
9
+ // publish prices to OpenCode (custom ones like an Azure deployment) get a suggestion from
10
+ // OpenCode's catalog for the same model, which the user can accept or correct.
11
+ import { promises as fs } from "node:fs";
12
+ import path from "node:path";
13
+ const ZERO = { cost: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0 };
14
+ const KEYS = ["cost", "input", "output", "reasoning", "cacheRead", "cacheWrite"];
15
+ export const emptyUsage = () => ({ ...ZERO });
16
+ export function addUsage(a, b) {
17
+ const out = emptyUsage();
18
+ for (const k of KEYS)
19
+ out[k] = (a[k] ?? 0) + (b[k] ?? 0);
20
+ return out;
21
+ }
22
+ /** Records a session's latest totals, attributing what's new to the agent's current model. */
23
+ export function accountUsage(agent, sessionTotals) {
24
+ if (!agent.usageByModel) {
25
+ // First time (or data from before per-model tracking): all of it goes to the current model.
26
+ agent.usageByModel = { [agent.model]: addUsage(agent.pastUsage ?? ZERO, sessionTotals) };
27
+ agent.usageSeen = { ...sessionTotals };
28
+ return;
29
+ }
30
+ const seen = agent.usageSeen ?? ZERO;
31
+ const delta = emptyUsage();
32
+ let reset = false;
33
+ for (const k of KEYS) {
34
+ const d = (sessionTotals[k] ?? 0) - (seen[k] ?? 0);
35
+ if (d < 0)
36
+ reset = true;
37
+ delta[k] = Math.max(0, d);
38
+ }
39
+ // Totals going down means a different session than the one last seen: all of it is new.
40
+ const add = reset ? sessionTotals : delta;
41
+ agent.usageByModel[agent.model] = addUsage(agent.usageByModel[agent.model] ?? ZERO, add);
42
+ agent.usageSeen = { ...sessionTotals };
43
+ }
44
+ /**
45
+ * Sub-agents (e.g. OpenCode's "explore") run in child sessions Symbio doesn't otherwise see.
46
+ * Their usage is added to the agent that started them, under the child's own model.
47
+ */
48
+ export function accountChildUsage(agent, childId, model, totals) {
49
+ agent.childSessions ??= {};
50
+ const seen = agent.childSessions[childId]?.seen ?? ZERO;
51
+ const delta = emptyUsage();
52
+ for (const k of KEYS)
53
+ delta[k] = Math.max(0, (totals[k] ?? 0) - (seen[k] ?? 0));
54
+ agent.usageByModel ??= {};
55
+ agent.usageByModel[model] = addUsage(agent.usageByModel[model] ?? ZERO, delta);
56
+ agent.childSessions[childId] = { model, seen: { ...totals } };
57
+ }
58
+ /** OpenCode session totals as a Usage. */
59
+ export function sessionUsage(s) {
60
+ if (!s?.tokens)
61
+ return null;
62
+ return {
63
+ cost: Number(s.cost) || 0,
64
+ input: s.tokens.input ?? 0,
65
+ output: s.tokens.output ?? 0,
66
+ reasoning: s.tokens.reasoning ?? 0,
67
+ cacheRead: s.tokens.cache?.read ?? 0,
68
+ cacheWrite: s.tokens.cache?.write ?? 0,
69
+ };
70
+ }
71
+ /** Everything the agent has used, across sessions and models. */
72
+ export function agentUsageByModel(agent) {
73
+ if (agent.usageByModel)
74
+ return agent.usageByModel;
75
+ const total = addUsage(agent.pastUsage ?? ZERO, agent.usage ?? ZERO);
76
+ return total.input + total.output + total.cacheRead + total.cacheWrite > 0 ? { [agent.model]: total } : {};
77
+ }
78
+ export function costOf(u, price) {
79
+ if (!price)
80
+ return null;
81
+ return (u.input * price.input + (u.output + u.reasoning) * price.output + u.cacheRead * price.cacheRead + u.cacheWrite * price.cacheWrite) / 1e6;
82
+ }
83
+ export const tokensOf = (u) => u.input + u.output + u.reasoning + u.cacheRead + u.cacheWrite;
84
+ // ---------------------------------------------------------------- prices
85
+ export class PriceBook {
86
+ file;
87
+ prices = {};
88
+ constructor(file) {
89
+ this.file = file;
90
+ }
91
+ static at(dir) {
92
+ return new PriceBook(path.join(dir, "prices.json"));
93
+ }
94
+ async load() {
95
+ try {
96
+ this.prices = JSON.parse(await fs.readFile(this.file, "utf8"));
97
+ }
98
+ catch {
99
+ this.prices = {};
100
+ }
101
+ return this;
102
+ }
103
+ async set(model, price) {
104
+ if (price)
105
+ this.prices[model] = price;
106
+ else
107
+ delete this.prices[model];
108
+ await fs.mkdir(path.dirname(this.file), { recursive: true });
109
+ await fs.writeFile(this.file, JSON.stringify(this.prices, null, 2));
110
+ }
111
+ }
112
+ /** OpenCode's base price for a model (first tier), USD per million tokens, if it has one. */
113
+ export function catalogPrice(model) {
114
+ const c = Array.isArray(model?.cost) ? model.cost[0] : model?.cost;
115
+ if (!c || typeof c.input !== "number")
116
+ return null;
117
+ return { input: c.input, output: c.output ?? 0, cacheRead: c.cache?.read ?? 0, cacheWrite: c.cache?.write ?? 0 };
118
+ }
119
+ /**
120
+ * Price for every model ref: the user's own, else OpenCode's, else a suggestion from a
121
+ * catalog model with the same name (e.g. "foundry/code-claude-opus-5-5" → "claude-opus-5-5").
122
+ */
123
+ export function resolvePrices(refs, book, catalog) {
124
+ const byRef = new Map(catalog.map((m) => [`${m.providerID}/${m.id}`, m]));
125
+ const priced = catalog.filter((m) => catalogPrice(m));
126
+ const out = {};
127
+ for (const ref of refs) {
128
+ if (book[ref]) {
129
+ out[ref] = { price: book[ref], source: "yours" };
130
+ continue;
131
+ }
132
+ const own = catalogPrice(byRef.get(ref));
133
+ if (own) {
134
+ out[ref] = { price: own, source: "opencode" };
135
+ continue;
136
+ }
137
+ const id = ref.split("/").slice(1).join("/").toLowerCase();
138
+ const match = priced
139
+ .filter((m) => id.includes(String(m.id).toLowerCase()) && String(m.id).length >= 6)
140
+ .sort((a, b) => String(b.id).length - String(a.id).length || rank(a.providerID) - rank(b.providerID))[0];
141
+ out[ref] = match ? { price: catalogPrice(match), source: "suggested", from: `${match.providerID}/${match.id}` } : { price: null, source: "none" };
142
+ }
143
+ return out;
144
+ }
145
+ const rank = (provider) => (provider === "anthropic" ? 0 : provider === "openai" ? 0 : provider === "opencode" ? 1 : 2);
146
+ /** Usage report for a project: per agent and model, with estimated costs. */
147
+ export function projectUsage(project, prices) {
148
+ let total = emptyUsage();
149
+ let totalCost = 0;
150
+ const unpriced = new Set();
151
+ const agents = project.agents.map((agent) => {
152
+ const byModel = Object.entries(agentUsageByModel(agent)).map(([model, usage]) => {
153
+ // A suggestion only counts once the user accepts it: the same model can cost something else (or
154
+ // nothing) at another provider.
155
+ const info = prices[model];
156
+ const cost = costOf(usage, info && (info.source === "yours" || info.source === "opencode") ? (info.price ?? undefined) : undefined);
157
+ if (cost === null && tokensOf(usage) > 0)
158
+ unpriced.add(model);
159
+ total = addUsage(total, usage);
160
+ totalCost += cost ?? 0;
161
+ return { model, usage, tokens: tokensOf(usage), cost };
162
+ });
163
+ const usage = byModel.reduce((s, m) => addUsage(s, m.usage), emptyUsage());
164
+ return {
165
+ id: agent.id,
166
+ name: agent.name,
167
+ status: agent.status,
168
+ sessions: 1 + (agent.previousSessions?.length ?? 0),
169
+ byModel,
170
+ tokens: tokensOf(usage),
171
+ cost: byModel.reduce((s, m) => s + (m.cost ?? 0), 0),
172
+ };
173
+ });
174
+ return { agents, total, tokens: tokensOf(total), cost: totalCost, unpriced: [...unpriced] };
175
+ }
@@ -0,0 +1,97 @@
1
+ // Agent documentation: AGENTS.md + docs/ in the project folder ("project"), or
2
+ // .symbio/docs/ ("private"). Only these locations are readable/writable here.
3
+ import { existsSync, promises as fs, realpathSync } from "node:fs";
4
+ import path from "node:path";
5
+ const TEXT_EXT = new Set([".md", ".markdown", ".txt"]);
6
+ const MAX_FILES = 500;
7
+ export function docsRoot(project) {
8
+ return project.docsLocation === "private" ? path.join(project.directory, ".symbio", "docs") : project.directory;
9
+ }
10
+ /** Where agents should write docs, as absolute paths, for briefs. */
11
+ export function docsPaths(project) {
12
+ const root = docsRoot(project);
13
+ return { entry: path.join(root, "AGENTS.md"), folder: path.join(root, project.docsLocation === "private" ? "" : "docs") };
14
+ }
15
+ export async function listDocs(project) {
16
+ const root = docsRoot(project);
17
+ const files = [];
18
+ const add = async (abs) => {
19
+ const st = await fs.stat(abs).catch(() => null);
20
+ if (st?.isFile())
21
+ files.push({ path: toRel(root, abs), size: st.size, modified: st.mtimeMs });
22
+ };
23
+ const walk = async (dir) => {
24
+ const entries = await fs.readdir(dir, { withFileTypes: true }).catch(() => []);
25
+ for (const e of entries) {
26
+ if (files.length >= MAX_FILES)
27
+ return;
28
+ const abs = path.join(dir, e.name);
29
+ if (e.isDirectory())
30
+ await walk(abs);
31
+ else if (TEXT_EXT.has(path.extname(e.name).toLowerCase()))
32
+ await add(abs);
33
+ }
34
+ };
35
+ if (project.docsLocation === "private") {
36
+ await walk(root);
37
+ }
38
+ else {
39
+ await add(path.join(root, "AGENTS.md"));
40
+ await walk(path.join(root, "docs"));
41
+ }
42
+ return files.sort((a, b) => (a.path === "AGENTS.md" ? -1 : b.path === "AGENTS.md" ? 1 : a.path.localeCompare(b.path)));
43
+ }
44
+ export async function readDoc(project, rel) {
45
+ return fs.readFile(resolveDoc(project, rel), "utf8");
46
+ }
47
+ export async function writeDoc(project, rel, content) {
48
+ const abs = resolveDoc(project, rel);
49
+ await fs.mkdir(path.dirname(abs), { recursive: true });
50
+ await fs.writeFile(abs, content);
51
+ }
52
+ /** Validates a doc path against the allowed locations. Throws on anything else. */
53
+ function resolveDoc(project, rel) {
54
+ const root = docsRoot(project);
55
+ const normalized = rel.replace(/\\/g, "/").replace(/^\/+/, "");
56
+ const abs = path.resolve(root, normalized);
57
+ const relBack = toRel(root, abs);
58
+ const insideRoot = !relBack.startsWith("..") && !path.isAbsolute(relBack);
59
+ const allowed = project.docsLocation === "private"
60
+ ? insideRoot
61
+ : insideRoot && (relBack === "AGENTS.md" || relBack.startsWith("docs/"));
62
+ if (!allowed || !TEXT_EXT.has(path.extname(abs).toLowerCase())) {
63
+ throw new Error(`Not a docs file: ${rel}`);
64
+ }
65
+ // A symlink inside the docs could point at any file (an SSH key, say); compare real
66
+ // paths (of the file, or of its folder for a file about to be written).
67
+ const probe = existsSync(abs) ? abs : path.dirname(abs);
68
+ if (existsSync(probe) && existsSync(root)) {
69
+ const real = path.relative(realpathSync(root), realpathSync(probe));
70
+ if (real.startsWith("..") || path.isAbsolute(real))
71
+ throw new Error(`Not a docs file: ${rel}`);
72
+ }
73
+ return abs;
74
+ }
75
+ /**
76
+ * For private docs: the text injected into every agent, since agents (and
77
+ * OpenCode's automatic AGENTS.md loading) can't see .symbio/docs on their own.
78
+ */
79
+ export async function privateDocsInstruction(project) {
80
+ if (project.docsLocation !== "private")
81
+ return null;
82
+ const files = await listDocs(project);
83
+ if (files.length === 0)
84
+ return null;
85
+ const root = docsRoot(project);
86
+ const entry = files.find((f) => f.path === "AGENTS.md");
87
+ const body = entry ? await readDoc(project, entry.path).catch(() => "") : "";
88
+ const others = files.filter((f) => f !== entry).map((f) => `- ${path.join(root, f.path)}`);
89
+ return [
90
+ "# Project documentation (private, kept outside the project files)",
91
+ body.slice(0, 40_000),
92
+ others.length ? `\nMore documentation you can read when relevant:\n${others.join("\n")}` : "",
93
+ ].join("\n");
94
+ }
95
+ function toRel(root, abs) {
96
+ return path.relative(root, abs).replace(/\\/g, "/");
97
+ }