@fro.bot/space-bus 0.5.0 → 0.6.1

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.
package/dist/index.js CHANGED
@@ -1,167 +1,91 @@
1
- // src/config.ts
2
- import { existsSync, readFileSync, realpathSync } from "node:fs";
3
- import { homedir } from "node:os";
4
- import { join } from "node:path";
5
- import { z } from "zod";
6
- var manifestSchema = z.object({
7
- server: z.object({ baseUrl: z.url() }),
8
- projects: z.array(z.object({
9
- name: z.string(),
10
- path: z.string(),
11
- description: z.string()
12
- }))
13
- });
14
- function expandHome(path) {
15
- return path.startsWith("~") ? join(homedir(), path.slice(1)) : path;
16
- }
17
- function resolveRosterPath(directory) {
18
- const override = process.env["SPACE_BUS_CONFIG"];
19
- if (override) {
20
- if (override.includes("://")) {
21
- throw new Error(`space-bus: SPACE_BUS_CONFIG must be an absolute path or start with ~ (got a URL: ${override})`);
22
- }
23
- const expanded = expandHome(override);
24
- if (!expanded.startsWith("/")) {
25
- throw new Error(`space-bus: SPACE_BUS_CONFIG must be an absolute path or start with ~ (got: ${override})`);
26
- }
27
- return existsSync(expanded) ? realpathSync(expanded) : expanded;
28
- }
29
- if (directory) {
30
- const candidate = join(directory, "spacebus.json");
31
- return existsSync(candidate) ? realpathSync(candidate) : candidate;
32
- }
33
- throw new Error("space-bus: cannot locate spacebus.json — pass a directory containing spacebus.json, or set SPACE_BUS_CONFIG to an absolute path (or ~-prefixed path) to the roster file");
34
- }
35
- function getRoster(directory) {
36
- const manifestPath = resolveRosterPath(directory);
37
- let raw;
38
- try {
39
- raw = readFileSync(manifestPath, "utf8");
40
- } catch (err) {
41
- throw new Error(`space-bus: cannot read roster at ${manifestPath}: ${err.message} (set SPACE_BUS_CONFIG or ensure spacebus.json exists in the workspace directory)`);
42
- }
43
- let json;
44
- try {
45
- json = JSON.parse(raw);
46
- } catch (err) {
47
- throw new Error(`space-bus: roster at ${manifestPath} is not valid JSON: ${err.message}`);
48
- }
49
- const parsed = manifestSchema.safeParse(json);
50
- if (!parsed.success) {
51
- throw new Error(`space-bus: roster at ${manifestPath} failed schema validation: ${parsed.error.message}`);
52
- }
53
- const url = new URL(parsed.data.server.baseUrl);
54
- const hostname = url.hostname;
55
- const allowedHosts = new Set(["127.0.0.1", "::1", "[::1]", "localhost"]);
56
- if (!allowedHosts.has(hostname)) {
57
- throw new Error(`space-bus: spacebus.json baseUrl must point to localhost (got ${hostname}) — refusing to send credentials off-machine`);
58
- }
59
- return parsed.data;
60
- }
61
- function getProjects(manifest) {
62
- return manifest.projects.map((p) => {
63
- const expandedPath = expandHome(p.path);
64
- return { ...p, expandedPath, exists: existsSync(expandedPath) };
65
- });
66
- }
67
- function getCredentials() {
68
- const password = process.env["OPENCODE_SERVER_PASSWORD"];
69
- if (!password)
70
- return {};
71
- const username = process.env["OPENCODE_SERVER_USERNAME"] ?? "opencode";
72
- return { username, password };
73
- }
74
- function loadContext(directory) {
75
- const manifest = getRoster(directory);
76
- const projects = getProjects(manifest);
77
- return {
78
- roster: { server: manifest.server, projects },
79
- credentials: getCredentials()
80
- };
81
- }
82
-
83
1
  // src/contract.ts
84
- import { z as z2 } from "zod";
85
- var sessionSchema = z2.looseObject({
86
- id: z2.string(),
87
- directory: z2.string().optional(),
88
- title: z2.string().optional()
2
+ import { z } from "zod";
3
+ var sessionSchema = z.looseObject({
4
+ id: z.string(),
5
+ directory: z.string().optional(),
6
+ title: z.string().optional()
89
7
  });
90
- var sessionListSchema = z2.array(sessionSchema);
91
- var sessionStatusMapSchema = z2.record(z2.string(), z2.looseObject({ type: z2.string() }));
92
- var todoSchema = z2.array(z2.looseObject({
93
- content: z2.string(),
94
- status: z2.string(),
95
- priority: z2.string()
8
+ var sessionListSchema = z.array(sessionSchema);
9
+ var sessionStatusMapSchema = z.record(z.string(), z.looseObject({ type: z.string() }));
10
+ var todoSchema = z.array(z.looseObject({
11
+ content: z.string(),
12
+ status: z.string(),
13
+ priority: z.string()
96
14
  })).default([]);
97
- var diffEntrySchema = z2.looseObject({
98
- file: z2.string().optional(),
99
- additions: z2.number(),
100
- deletions: z2.number(),
101
- status: z2.string().optional()
15
+ var diffEntrySchema = z.looseObject({
16
+ file: z.string().optional(),
17
+ additions: z.number(),
18
+ deletions: z.number(),
19
+ status: z.string().optional()
102
20
  });
103
- var diffSchema = z2.array(diffEntrySchema).default([]);
104
- var vcsStatusEntrySchema = z2.looseObject({
105
- file: z2.string(),
106
- additions: z2.number(),
107
- deletions: z2.number(),
108
- status: z2.string().optional()
21
+ var diffSchema = z.array(diffEntrySchema).default([]);
22
+ var vcsStatusEntrySchema = z.looseObject({
23
+ file: z.string(),
24
+ additions: z.number(),
25
+ deletions: z.number(),
26
+ status: z.string().optional()
109
27
  });
110
- var vcsStatusSchema = z2.array(vcsStatusEntrySchema).default([]);
28
+ var vcsStatusSchema = z.array(vcsStatusEntrySchema).default([]);
111
29
  var turnDiffEntrySchema = diffEntrySchema;
112
- var turnMessageSchema = z2.looseObject({
113
- info: z2.looseObject({
114
- role: z2.string(),
115
- summary: z2.looseObject({
116
- diffs: z2.array(turnDiffEntrySchema).optional()
30
+ var turnMessageSchema = z.looseObject({
31
+ info: z.looseObject({
32
+ role: z.string(),
33
+ summary: z.looseObject({
34
+ diffs: z.array(turnDiffEntrySchema).optional()
117
35
  }).optional()
118
36
  })
119
37
  });
120
- var turnMessageListSchema = z2.array(turnMessageSchema);
121
- var sessionSummarySchema = z2.looseObject({
122
- summary: z2.looseObject({
123
- diffs: z2.array(turnDiffEntrySchema).optional()
38
+ var turnMessageListSchema = z.array(turnMessageSchema);
39
+ var sessionSummarySchema = z.looseObject({
40
+ summary: z.looseObject({
41
+ diffs: z.array(turnDiffEntrySchema).optional()
124
42
  }).optional()
125
43
  });
126
- var messagePartSchema = z2.looseObject({
127
- type: z2.string(),
128
- text: z2.string().optional()
44
+ var messagePartSchema = z.looseObject({
45
+ type: z.string(),
46
+ text: z.string().optional()
129
47
  });
130
- var messageEnvelopeSchema = z2.looseObject({
131
- info: z2.looseObject({ role: z2.string() }),
132
- parts: z2.array(messagePartSchema)
48
+ var messageEnvelopeSchema = z.looseObject({
49
+ info: z.looseObject({ role: z.string() }),
50
+ parts: z.array(messagePartSchema)
133
51
  });
134
- var messageListSchema = z2.array(messageEnvelopeSchema);
135
- var pendingQuestionEntrySchema = z2.looseObject({
136
- id: z2.string(),
137
- sessionID: z2.string(),
138
- questions: z2.array(z2.looseObject({
139
- question: z2.string().optional(),
140
- options: z2.array(z2.looseObject({ label: z2.string().optional() })).optional()
52
+ var messageListSchema = z.array(messageEnvelopeSchema);
53
+ var pendingQuestionEntrySchema = z.looseObject({
54
+ id: z.string(),
55
+ sessionID: z.string(),
56
+ questions: z.array(z.looseObject({
57
+ question: z.string().optional(),
58
+ options: z.array(z.looseObject({ label: z.string().optional() })).optional()
141
59
  })).optional()
142
60
  });
143
- var pendingQuestionListSchema = z2.array(pendingQuestionEntrySchema);
144
- var questionEntrySchema = z2.looseObject({
145
- id: z2.string(),
146
- sessionID: z2.string()
61
+ var pendingQuestionListSchema = z.array(pendingQuestionEntrySchema);
62
+ var questionEntrySchema = z.looseObject({
63
+ id: z.string(),
64
+ sessionID: z.string()
147
65
  });
148
- var questionListSchema = z2.array(questionEntrySchema);
149
- var projectSchema = z2.looseObject({
150
- name: z2.string(),
151
- path: z2.string(),
152
- description: z2.string(),
153
- expandedPath: z2.string(),
154
- exists: z2.boolean()
66
+ var questionListSchema = z.array(questionEntrySchema);
67
+ var LOOPBACK_HOSTS = new Set([
68
+ "127.0.0.1",
69
+ "::1",
70
+ "[::1]",
71
+ "localhost"
72
+ ]);
73
+ var projectSchema = z.looseObject({
74
+ name: z.string(),
75
+ path: z.string(),
76
+ description: z.string(),
77
+ expandedPath: z.string(),
78
+ exists: z.boolean()
155
79
  });
156
- var rosterSchema = z2.object({
157
- server: z2.object({ baseUrl: z2.url() }),
158
- projects: z2.array(projectSchema)
80
+ var rosterSchema = z.object({
81
+ server: z.object({ baseUrl: z.url() }),
82
+ projects: z.array(projectSchema)
159
83
  });
160
- var credentialsSchema = z2.object({
161
- username: z2.string().optional(),
162
- password: z2.string().optional()
84
+ var credentialsSchema = z.object({
85
+ username: z.string().optional(),
86
+ password: z.string().optional()
163
87
  });
164
- var busContextSchema = z2.object({
88
+ var busContextSchema = z.object({
165
89
  roster: rosterSchema,
166
90
  credentials: credentialsSchema.optional()
167
91
  });
@@ -283,7 +207,6 @@ async function fetchDiffWithFallback(baseUrl, credentials, directory, sessionId)
283
207
  } catch {}
284
208
  return { diff, diffSource: "session" };
285
209
  }
286
- var ALLOWED_HOSTS = new Set(["127.0.0.1", "::1", "[::1]", "localhost"]);
287
210
  function validateContext(context) {
288
211
  const parsed = busContextSchema.safeParse(context);
289
212
  if (!parsed.success) {
@@ -296,7 +219,7 @@ function validateContext(context) {
296
219
  } catch {
297
220
  return err("space-bus: context roster server.baseUrl is not a valid URL");
298
221
  }
299
- if (!ALLOWED_HOSTS.has(hostname)) {
222
+ if (!LOOPBACK_HOSTS.has(hostname)) {
300
223
  return err(`space-bus: context roster server.baseUrl must point to localhost (got ${hostname}) — refusing to send credentials off-machine`);
301
224
  }
302
225
  return {
@@ -752,8 +675,737 @@ function formatResult(r) {
752
675
  `);
753
676
  }
754
677
 
678
+ // src/config.ts
679
+ import { existsSync, readFileSync as readFileSync2, realpathSync } from "node:fs";
680
+ import { homedir as homedir2 } from "node:os";
681
+ import { join as join2 } from "node:path";
682
+ import { z as z3 } from "zod";
683
+
684
+ // src/discovery.ts
685
+ import { execFileSync } from "node:child_process";
686
+ import { createHash, randomBytes } from "node:crypto";
687
+ import {
688
+ chmodSync,
689
+ closeSync,
690
+ constants as fsConstants,
691
+ mkdirSync,
692
+ openSync,
693
+ readFileSync,
694
+ renameSync,
695
+ statSync,
696
+ unlinkSync,
697
+ writeFileSync
698
+ } from "node:fs";
699
+ import { homedir } from "node:os";
700
+ import { join } from "node:path";
701
+ import { z as z2 } from "zod";
702
+ function stateDirFor(rosterPath) {
703
+ const base = process.env["XDG_STATE_HOME"] ?? join(homedir(), ".local", "state");
704
+ const hash = createHash("sha256").update(rosterPath).digest("hex").slice(0, 16);
705
+ return join(base, "space-bus", hash);
706
+ }
707
+ function discoveryFilePath(rosterPath) {
708
+ return join(stateDirFor(rosterPath), "discovery.json");
709
+ }
710
+ function lockFilePath(rosterPath) {
711
+ return join(stateDirFor(rosterPath), "spawn.lock");
712
+ }
713
+ function logFilePath(rosterPath) {
714
+ return join(stateDirFor(rosterPath), "server.log");
715
+ }
716
+ var managedSpawnConfigSchema = z2.object({
717
+ command: z2.array(z2.string()).optional(),
718
+ cwd: z2.string().optional(),
719
+ port: z2.number().int().nonnegative().optional()
720
+ });
721
+ var discoveryFileSchema = z2.object({
722
+ port: z2.number().int().nonnegative(),
723
+ pid: z2.number().int().positive(),
724
+ identity: z2.string(),
725
+ password: z2.string(),
726
+ spawnConfig: managedSpawnConfigSchema,
727
+ baseUrl: z2.url()
728
+ });
729
+ function writeDiscovery(rosterPath, data) {
730
+ const dir = stateDirFor(rosterPath);
731
+ mkdirSync(dir, { recursive: true, mode: 448 });
732
+ chmodSync(dir, 448);
733
+ const target = discoveryFilePath(rosterPath);
734
+ const tempPath = `${target}.tmp.${randomBytes(8).toString("hex")}`;
735
+ const fd = openSync(tempPath, fsConstants.O_EXCL | fsConstants.O_CREAT | fsConstants.O_WRONLY, 384);
736
+ try {
737
+ writeFileSync(fd, JSON.stringify(data));
738
+ } finally {
739
+ closeQuietly(fd);
740
+ }
741
+ renameSync(tempPath, target);
742
+ chmodSync(target, 384);
743
+ }
744
+ function readDiscovery(rosterPath) {
745
+ const target = discoveryFilePath(rosterPath);
746
+ let raw;
747
+ try {
748
+ raw = readFileSync(target, "utf8");
749
+ } catch {
750
+ return null;
751
+ }
752
+ let json;
753
+ try {
754
+ json = JSON.parse(raw);
755
+ } catch {
756
+ return null;
757
+ }
758
+ const parsed = discoveryFileSchema.safeParse(json);
759
+ return parsed.success ? parsed.data : null;
760
+ }
761
+ function removeDiscovery(rosterPath) {
762
+ try {
763
+ unlinkSync(discoveryFilePath(rosterPath));
764
+ } catch (err2) {
765
+ if (!isEnoent(err2))
766
+ throw err2;
767
+ }
768
+ }
769
+ function loopbackOk(baseUrl) {
770
+ try {
771
+ const url = new URL(baseUrl);
772
+ return LOOPBACK_HOSTS.has(url.hostname);
773
+ } catch {
774
+ return false;
775
+ }
776
+ }
777
+ function attachLive(rosterPath) {
778
+ const discovery = readDiscovery(rosterPath);
779
+ if (!discovery)
780
+ return null;
781
+ if (!loopbackOk(discovery.baseUrl))
782
+ return null;
783
+ if (!verifyIdentity(discovery.pid, discovery.identity))
784
+ return null;
785
+ return {
786
+ baseUrl: discovery.baseUrl,
787
+ credentials: { username: "opencode", password: discovery.password },
788
+ pid: discovery.pid,
789
+ port: discovery.port
790
+ };
791
+ }
792
+ function captureIdentity(pid) {
793
+ try {
794
+ const out = execFileSync("ps", ["-p", String(pid), "-o", "lstart=,comm="], {
795
+ env: { ...process.env, LC_ALL: "C" },
796
+ encoding: "utf8"
797
+ });
798
+ const trimmed = out.trim();
799
+ return trimmed.length > 0 ? trimmed : null;
800
+ } catch {
801
+ return null;
802
+ }
803
+ }
804
+ function isAlive(pid) {
805
+ try {
806
+ process.kill(pid, 0);
807
+ return true;
808
+ } catch {
809
+ return false;
810
+ }
811
+ }
812
+ function verifyIdentity(pid, storedIdentity) {
813
+ if (!isAlive(pid))
814
+ return false;
815
+ const current = captureIdentity(pid);
816
+ return current !== null && current === storedIdentity;
817
+ }
818
+ var lockFileSchema = z2.object({
819
+ pid: z2.number().int().positive(),
820
+ startTime: z2.string(),
821
+ since: z2.number()
822
+ });
823
+ var CORRUPT_LOCK_GRACE_MS = 2000;
824
+ function acquireLock(rosterPath) {
825
+ const dir = stateDirFor(rosterPath);
826
+ mkdirSync(dir, { recursive: true, mode: 448 });
827
+ chmodSync(dir, 448);
828
+ const target = lockFilePath(rosterPath);
829
+ const identity = captureIdentity(process.pid) ?? "";
830
+ const lock = {
831
+ pid: process.pid,
832
+ startTime: identity,
833
+ since: Date.now()
834
+ };
835
+ if (tryCreateLockFile(target, lock)) {
836
+ return { rosterPath };
837
+ }
838
+ const existing = readLockFile(target);
839
+ if (existing) {
840
+ if (verifyIdentity(existing.pid, existing.startTime))
841
+ return null;
842
+ } else if (!isOlderThan(target, CORRUPT_LOCK_GRACE_MS)) {
843
+ return null;
844
+ }
845
+ try {
846
+ unlinkSync(target);
847
+ } catch (err2) {
848
+ if (!isEnoent(err2))
849
+ throw err2;
850
+ }
851
+ if (tryCreateLockFile(target, lock)) {
852
+ return { rosterPath };
853
+ }
854
+ return null;
855
+ }
856
+ function isOlderThan(path, ageMs) {
857
+ try {
858
+ return Date.now() - statSync(path).mtimeMs > ageMs;
859
+ } catch {
860
+ return false;
861
+ }
862
+ }
863
+ function releaseLock(handle) {
864
+ try {
865
+ unlinkSync(lockFilePath(handle.rosterPath));
866
+ } catch {}
867
+ }
868
+ function readLockFile(target) {
869
+ let raw;
870
+ try {
871
+ raw = readFileSync(target, "utf8");
872
+ } catch {
873
+ return null;
874
+ }
875
+ let json;
876
+ try {
877
+ json = JSON.parse(raw);
878
+ } catch {
879
+ return null;
880
+ }
881
+ const parsed = lockFileSchema.safeParse(json);
882
+ return parsed.success ? parsed.data : null;
883
+ }
884
+ function tryCreateLockFile(target, lock) {
885
+ let fd;
886
+ try {
887
+ fd = openSync(target, fsConstants.O_EXCL | fsConstants.O_CREAT | fsConstants.O_WRONLY, 384);
888
+ } catch (err2) {
889
+ if (isErrnoCode(err2, "EEXIST"))
890
+ return false;
891
+ throw err2;
892
+ }
893
+ try {
894
+ writeFileSync(fd, JSON.stringify(lock));
895
+ } finally {
896
+ closeQuietly(fd);
897
+ }
898
+ return true;
899
+ }
900
+ function isEnoent(err2) {
901
+ return isErrnoCode(err2, "ENOENT");
902
+ }
903
+ function isErrnoCode(err2, code) {
904
+ return typeof err2 === "object" && err2 !== null && "code" in err2 && err2.code === code;
905
+ }
906
+ function closeQuietly(fd) {
907
+ try {
908
+ closeSync(fd);
909
+ } catch {}
910
+ }
911
+ function provisionalFilePath(rosterPath) {
912
+ return join(stateDirFor(rosterPath), "spawn.provisional.json");
913
+ }
914
+ var provisionalFileSchema = z2.object({
915
+ pid: z2.number().int().positive(),
916
+ identity: z2.string(),
917
+ password: z2.string(),
918
+ since: z2.number()
919
+ });
920
+ function writeProvisional(rosterPath, data) {
921
+ const dir = stateDirFor(rosterPath);
922
+ mkdirSync(dir, { recursive: true, mode: 448 });
923
+ chmodSync(dir, 448);
924
+ const target = provisionalFilePath(rosterPath);
925
+ const fd = openSync(target, fsConstants.O_CREAT | fsConstants.O_WRONLY | fsConstants.O_TRUNC, 384);
926
+ try {
927
+ writeFileSync(fd, JSON.stringify(data));
928
+ } finally {
929
+ closeQuietly(fd);
930
+ }
931
+ chmodSync(target, 384);
932
+ }
933
+ function readProvisional(rosterPath) {
934
+ const target = provisionalFilePath(rosterPath);
935
+ let raw;
936
+ try {
937
+ raw = readFileSync(target, "utf8");
938
+ } catch {
939
+ return null;
940
+ }
941
+ let json;
942
+ try {
943
+ json = JSON.parse(raw);
944
+ } catch {
945
+ return null;
946
+ }
947
+ const parsed = provisionalFileSchema.safeParse(json);
948
+ return parsed.success ? parsed.data : null;
949
+ }
950
+ function removeProvisional(rosterPath) {
951
+ try {
952
+ unlinkSync(provisionalFilePath(rosterPath));
953
+ } catch {}
954
+ }
955
+
956
+ // src/config.ts
957
+ var managedServerConfigSchema = z3.object({
958
+ command: z3.array(z3.string()).optional(),
959
+ cwd: z3.string().optional(),
960
+ port: z3.number().int().nonnegative().optional()
961
+ });
962
+ var serverConfigSchema = z3.object({
963
+ baseUrl: z3.url().optional(),
964
+ managed: managedServerConfigSchema.optional()
965
+ }).superRefine((val, ctx) => {
966
+ const hasBaseUrl = val.baseUrl !== undefined;
967
+ const hasManaged = val.managed !== undefined;
968
+ if (hasBaseUrl && hasManaged) {
969
+ ctx.addIssue({
970
+ code: "custom",
971
+ message: "space-bus: roster's server block must specify exactly one of `baseUrl` or `managed`, not both"
972
+ });
973
+ } else if (!hasBaseUrl && !hasManaged) {
974
+ ctx.addIssue({
975
+ code: "custom",
976
+ message: "space-bus: roster's server block must specify one of `baseUrl` (externally-managed) or `managed` (plugin-spawned) — neither was present"
977
+ });
978
+ }
979
+ });
980
+ var manifestSchema = z3.object({
981
+ server: serverConfigSchema,
982
+ projects: z3.array(z3.object({
983
+ name: z3.string(),
984
+ path: z3.string(),
985
+ description: z3.string()
986
+ }))
987
+ });
988
+ function expandHome(path) {
989
+ return path.startsWith("~") ? join2(homedir2(), path.slice(1)) : path;
990
+ }
991
+ function resolveRosterPath(directory) {
992
+ const override = process.env["SPACE_BUS_CONFIG"];
993
+ if (override) {
994
+ if (override.includes("://")) {
995
+ throw new Error(`space-bus: SPACE_BUS_CONFIG must be an absolute path or start with ~ (got a URL: ${override})`);
996
+ }
997
+ const expanded = expandHome(override);
998
+ if (!expanded.startsWith("/")) {
999
+ throw new Error(`space-bus: SPACE_BUS_CONFIG must be an absolute path or start with ~ (got: ${override})`);
1000
+ }
1001
+ return existsSync(expanded) ? realpathSync(expanded) : expanded;
1002
+ }
1003
+ if (directory) {
1004
+ const candidate = join2(directory, "spacebus.json");
1005
+ return existsSync(candidate) ? realpathSync(candidate) : candidate;
1006
+ }
1007
+ throw new Error("space-bus: cannot locate spacebus.json — pass a directory containing spacebus.json, or set SPACE_BUS_CONFIG to an absolute path (or ~-prefixed path) to the roster file");
1008
+ }
1009
+ function getRoster(directory) {
1010
+ const manifestPath = resolveRosterPath(directory);
1011
+ let raw;
1012
+ try {
1013
+ raw = readFileSync2(manifestPath, "utf8");
1014
+ } catch (err2) {
1015
+ throw new Error(`space-bus: cannot read roster at ${manifestPath}: ${err2.message} (set SPACE_BUS_CONFIG or ensure spacebus.json exists in the workspace directory)`);
1016
+ }
1017
+ let json;
1018
+ try {
1019
+ json = JSON.parse(raw);
1020
+ } catch (err2) {
1021
+ throw new Error(`space-bus: roster at ${manifestPath} is not valid JSON: ${err2.message}`);
1022
+ }
1023
+ const parsed = manifestSchema.safeParse(json);
1024
+ if (!parsed.success) {
1025
+ throw new Error(`space-bus: roster at ${manifestPath} failed schema validation: ${parsed.error.message}`);
1026
+ }
1027
+ if (parsed.data.server.baseUrl !== undefined) {
1028
+ const url = new URL(parsed.data.server.baseUrl);
1029
+ const hostname = url.hostname;
1030
+ if (!LOOPBACK_HOSTS.has(hostname)) {
1031
+ throw new Error(`space-bus: spacebus.json baseUrl must point to localhost (got ${hostname}) — refusing to send credentials off-machine`);
1032
+ }
1033
+ }
1034
+ return parsed.data;
1035
+ }
1036
+ function getProjects(manifest) {
1037
+ return manifest.projects.map((p) => {
1038
+ const expandedPath = expandHome(p.path);
1039
+ return { ...p, expandedPath, exists: existsSync(expandedPath) };
1040
+ });
1041
+ }
1042
+ function getCredentials() {
1043
+ const password = process.env["OPENCODE_SERVER_PASSWORD"];
1044
+ if (!password)
1045
+ return {};
1046
+ const username = process.env["OPENCODE_SERVER_USERNAME"] ?? "opencode";
1047
+ return { username, password };
1048
+ }
1049
+ function loadContext(directory) {
1050
+ const rosterPath = resolveRosterPath(directory);
1051
+ const manifest = getRoster(directory);
1052
+ const projects = getProjects(manifest);
1053
+ if (manifest.server.baseUrl === undefined) {
1054
+ const live = attachLive(rosterPath);
1055
+ if (!live) {
1056
+ throw new Error(`space-bus: managed server not running for ${rosterPath} — call ensureServer() or run \`space-bus serve\``);
1057
+ }
1058
+ return {
1059
+ roster: { server: { baseUrl: live.baseUrl }, projects },
1060
+ credentials: live.credentials
1061
+ };
1062
+ }
1063
+ return {
1064
+ roster: { server: { baseUrl: manifest.server.baseUrl }, projects },
1065
+ credentials: getCredentials()
1066
+ };
1067
+ }
1068
+ function isManagedRoster(directory) {
1069
+ const manifest = getRoster(directory);
1070
+ return manifest.server.managed !== undefined;
1071
+ }
1072
+
1073
+ // src/server.ts
1074
+ import { spawn } from "node:child_process";
1075
+ import { randomBytes as randomBytes2 } from "node:crypto";
1076
+ import { openSync as openSync2, readFileSync as readFileSync3 } from "node:fs";
1077
+ import { dirname } from "node:path";
1078
+ var DEFAULT_READINESS_BUDGET_MS = 15000;
1079
+ var DEFAULT_LOCK_WAIT_BUDGET_MS = 15000;
1080
+ var POLL_INTERVAL_MS = 50;
1081
+ var MIN_PROBE_PHASE_MS = 3000;
1082
+ var PROBE_FETCH_TIMEOUT_MS = 2000;
1083
+ var STOP_GRACE_MS = 2000;
1084
+ function sleep(ms) {
1085
+ return new Promise((resolve) => setTimeout(resolve, ms));
1086
+ }
1087
+ function readManifest(rosterPath) {
1088
+ const raw = readFileSync3(rosterPath, "utf8");
1089
+ const json = JSON.parse(raw);
1090
+ return manifestSchema.parse(json);
1091
+ }
1092
+ function readLogTail(logPath, maxChars = 4000) {
1093
+ try {
1094
+ const content = readFileSync3(logPath, "utf8");
1095
+ return content.length > maxChars ? content.slice(-maxChars) : content;
1096
+ } catch {
1097
+ return "";
1098
+ }
1099
+ }
1100
+ function basicAuthToken(password) {
1101
+ return Buffer.from(`opencode:${password}`).toString("base64");
1102
+ }
1103
+ function redactSensitive(tail, password) {
1104
+ return tail.replaceAll(basicAuthToken(password), "[REDACTED]").replaceAll(password, "[REDACTED]");
1105
+ }
1106
+ function redactedReadinessError(rosterPath, password, reason) {
1107
+ const tail = redactSensitive(readLogTail(logFilePath(rosterPath)), password);
1108
+ return new Error(`space-bus: managed server for roster ${rosterPath} ${reason}. Log tail:
1109
+ ${tail}`);
1110
+ }
1111
+ function killIdentifiedProcess(pid, identity) {
1112
+ try {
1113
+ if (identity !== null && identity !== undefined && identity !== "") {
1114
+ if (verifyIdentity(pid, identity))
1115
+ process.kill(pid, "SIGTERM");
1116
+ return;
1117
+ }
1118
+ process.kill(pid, "SIGTERM");
1119
+ } catch {}
1120
+ }
1121
+ function attachServer(rosterPath) {
1122
+ return attachLive(rosterPath);
1123
+ }
1124
+ async function waitForDiscoveryOrFail(rosterPath, budgetMs) {
1125
+ const deadline = Date.now() + budgetMs;
1126
+ const lockPath = lockFilePath(rosterPath);
1127
+ while (Date.now() < deadline) {
1128
+ const handle = attachServer(rosterPath);
1129
+ if (handle)
1130
+ return handle;
1131
+ const lockInfo2 = readLockFile(lockPath);
1132
+ const winnerAlive = lockInfo2 !== null && verifyIdentity(lockInfo2.pid, lockInfo2.startTime);
1133
+ if (!winnerAlive) {
1134
+ throw new Error(`space-bus: the process starting the managed server for roster ${rosterPath} failed before it could finish (lock released without a discovery file) — check its log for details`);
1135
+ }
1136
+ await sleep(POLL_INTERVAL_MS);
1137
+ }
1138
+ const lockInfo = readLockFile(lockPath);
1139
+ const holder = lockInfo ? `pid ${lockInfo.pid}` : "an unknown holder";
1140
+ throw new Error(`space-bus: timed out after ${budgetMs}ms waiting for ${holder} to finish starting the managed server for roster ${rosterPath}`);
1141
+ }
1142
+ async function probe(baseUrl, password) {
1143
+ try {
1144
+ const res = await fetch(`${baseUrl}/session?limit=1`, {
1145
+ headers: { authorization: `Basic ${basicAuthToken(password)}` },
1146
+ signal: AbortSignal.timeout(PROBE_FETCH_TIMEOUT_MS)
1147
+ });
1148
+ if (res.status === 200)
1149
+ return "ready";
1150
+ if (res.status === 401 || res.status === 403)
1151
+ return "auth-failure";
1152
+ return "retry";
1153
+ } catch {
1154
+ return "retry";
1155
+ }
1156
+ }
1157
+ function childDied(child, pid) {
1158
+ return child.exitCode !== null || child.signalCode !== null || !isAlive(pid);
1159
+ }
1160
+ async function waitForReadinessLine(logPath, child, pid, deadline) {
1161
+ const readinessLine = /opencode server listening on http:\/\/127\.0\.0\.1:(\d+)/;
1162
+ while (Date.now() < deadline) {
1163
+ if (childDied(child, pid))
1164
+ return null;
1165
+ const tail = readLogTail(logPath);
1166
+ const match = readinessLine.exec(tail);
1167
+ if (match?.[1]) {
1168
+ const port = Number.parseInt(match[1], 10);
1169
+ if (Number.isInteger(port) && port > 0 && port <= 65535) {
1170
+ return { port, baseUrl: `http://127.0.0.1:${port}` };
1171
+ }
1172
+ }
1173
+ await sleep(POLL_INTERVAL_MS);
1174
+ }
1175
+ return null;
1176
+ }
1177
+ async function pollAuthedEndpoint(baseUrl, password, child, pid, deadline) {
1178
+ while (Date.now() < deadline) {
1179
+ if (childDied(child, pid))
1180
+ return "died";
1181
+ const outcome = await probe(baseUrl, password);
1182
+ if (outcome === "ready")
1183
+ return "ready";
1184
+ if (outcome === "auth-failure")
1185
+ return "auth-failure";
1186
+ await sleep(POLL_INTERVAL_MS);
1187
+ }
1188
+ return "timeout";
1189
+ }
1190
+ async function waitForReadiness(rosterPath, password, pid, identity, child, budgetMs) {
1191
+ const deadline = Date.now() + budgetMs;
1192
+ const logPath = logFilePath(rosterPath);
1193
+ const phase2Reserve = Math.min(MIN_PROBE_PHASE_MS, budgetMs / 2);
1194
+ const phase1Deadline = Math.max(Date.now(), deadline - phase2Reserve);
1195
+ const lineResult = await waitForReadinessLine(logPath, child, pid, phase1Deadline);
1196
+ if (lineResult === null) {
1197
+ const diedEarly = childDied(child, pid);
1198
+ killIdentifiedProcess(pid, identity);
1199
+ throw redactedReadinessError(rosterPath, password, diedEarly ? "exited before printing a readiness line" : `did not print a readiness line within ${budgetMs}ms`);
1200
+ }
1201
+ const { port, baseUrl } = lineResult;
1202
+ const phase2Deadline = Math.max(deadline, Date.now() + phase2Reserve);
1203
+ const outcome = await pollAuthedEndpoint(baseUrl, password, child, pid, phase2Deadline);
1204
+ if (outcome === "ready")
1205
+ return { port, baseUrl };
1206
+ killIdentifiedProcess(pid, identity);
1207
+ if (outcome === "died") {
1208
+ throw redactedReadinessError(rosterPath, password, "exited before becoming ready");
1209
+ }
1210
+ if (outcome === "auth-failure") {
1211
+ throw redactedReadinessError(rosterPath, password, "rejected our generated password (401/403) — authentication regression, not retrying");
1212
+ }
1213
+ throw redactedReadinessError(rosterPath, password, `did not become ready within ${budgetMs}ms`);
1214
+ }
1215
+ var PROVISIONAL_FRESH_WINDOW_MS = 5000;
1216
+ function reapOrphanedProvisional(rosterPath) {
1217
+ const provisional = readProvisional(rosterPath);
1218
+ if (!provisional)
1219
+ return;
1220
+ const discovery = readDiscovery(rosterPath);
1221
+ if (discovery && discovery.pid === provisional.pid && verifyIdentity(discovery.pid, discovery.identity)) {
1222
+ removeProvisional(rosterPath);
1223
+ return;
1224
+ }
1225
+ const hasIdentity = provisional.identity !== null && provisional.identity !== undefined && provisional.identity !== "";
1226
+ const isFresh = Date.now() - provisional.since < PROVISIONAL_FRESH_WINDOW_MS;
1227
+ if (hasIdentity || isFresh) {
1228
+ killIdentifiedProcess(provisional.pid, provisional.identity);
1229
+ }
1230
+ removeProvisional(rosterPath);
1231
+ }
1232
+ async function spawnAndWaitReady(rosterPath, managedConfig, readinessBudgetMs) {
1233
+ reapOrphanedProvisional(rosterPath);
1234
+ const password = randomBytes2(32).toString("base64url");
1235
+ const command = managedConfig.command && managedConfig.command.length > 0 ? managedConfig.command : ["harness", "serve"];
1236
+ const cwd = managedConfig.cwd ?? dirname(rosterPath);
1237
+ const requestedPort = managedConfig.port ?? 0;
1238
+ const logPath = logFilePath(rosterPath);
1239
+ const logFd = openSync2(logPath, "w", 384);
1240
+ let child;
1241
+ let pid;
1242
+ let spawnError;
1243
+ try {
1244
+ child = spawn(command[0], [...command.slice(1), "--port", String(requestedPort)], {
1245
+ cwd,
1246
+ detached: true,
1247
+ stdio: ["ignore", logFd, logFd],
1248
+ env: { ...process.env, OPENCODE_SERVER_PASSWORD: password }
1249
+ });
1250
+ child.on("error", (err2) => {
1251
+ spawnError = err2;
1252
+ });
1253
+ child.unref();
1254
+ pid = child.pid;
1255
+ } finally {
1256
+ closeQuietly(logFd);
1257
+ }
1258
+ if (pid === undefined) {
1259
+ throw new Error(`space-bus: failed to spawn managed server (command: ${command.join(" ")}, cwd: ${cwd}, roster: ${rosterPath}, log: ${logPath})${spawnError ? `: ${spawnError.message}` : ""}`);
1260
+ }
1261
+ const identity = captureIdentity(pid);
1262
+ writeProvisional(rosterPath, {
1263
+ pid,
1264
+ identity: identity ?? "",
1265
+ password,
1266
+ since: Date.now()
1267
+ });
1268
+ let port;
1269
+ let baseUrl;
1270
+ try {
1271
+ const readiness = waitForReadiness(rosterPath, password, pid, identity, child, readinessBudgetMs);
1272
+ const spawnErrorWatch = new Promise((_resolve, reject) => {
1273
+ const check = setInterval(() => {
1274
+ if (spawnError) {
1275
+ clearInterval(check);
1276
+ reject(new Error(`space-bus: failed to spawn managed server (command: ${command.join(" ")}, cwd: ${cwd}, roster: ${rosterPath}, log: ${logPath}): ${spawnError.message}`));
1277
+ }
1278
+ }, POLL_INTERVAL_MS);
1279
+ readiness.finally(() => clearInterval(check)).catch(() => {});
1280
+ });
1281
+ const result2 = await Promise.race([readiness, spawnErrorWatch]);
1282
+ port = result2.port;
1283
+ baseUrl = result2.baseUrl;
1284
+ } finally {
1285
+ removeProvisional(rosterPath);
1286
+ }
1287
+ const finalIdentity = identity ?? captureIdentity(pid) ?? "";
1288
+ writeDiscovery(rosterPath, {
1289
+ port,
1290
+ pid,
1291
+ identity: finalIdentity,
1292
+ password,
1293
+ spawnConfig: { command, cwd, port: requestedPort },
1294
+ baseUrl
1295
+ });
1296
+ return {
1297
+ baseUrl,
1298
+ credentials: { username: "opencode", password },
1299
+ pid,
1300
+ port
1301
+ };
1302
+ }
1303
+ async function ensureServer(rosterPath, options = {}) {
1304
+ const readinessBudgetMs = options.readinessBudgetMs ?? DEFAULT_READINESS_BUDGET_MS;
1305
+ const lockWaitBudgetMs = options.lockWaitBudgetMs ?? DEFAULT_LOCK_WAIT_BUDGET_MS;
1306
+ const fastPath = attachServer(rosterPath);
1307
+ if (fastPath)
1308
+ return fastPath;
1309
+ const manifest = readManifest(rosterPath);
1310
+ if (manifest.server.managed === undefined) {
1311
+ throw new Error(`space-bus: ensureServer called on an externally-managed roster (server.baseUrl) at ${rosterPath} — nothing to spawn`);
1312
+ }
1313
+ const lock = acquireLock(rosterPath);
1314
+ if (lock === null) {
1315
+ return await waitForDiscoveryOrFail(rosterPath, lockWaitBudgetMs);
1316
+ }
1317
+ try {
1318
+ const attached = attachServer(rosterPath);
1319
+ if (attached)
1320
+ return attached;
1321
+ return await spawnAndWaitReady(rosterPath, manifest.server.managed, readinessBudgetMs);
1322
+ } finally {
1323
+ releaseLock(lock);
1324
+ }
1325
+ }
1326
+ function serverStatus(rosterPath) {
1327
+ const discovery = readDiscovery(rosterPath);
1328
+ if (!discovery || !verifyIdentity(discovery.pid, discovery.identity)) {
1329
+ return { running: false };
1330
+ }
1331
+ let configDrift;
1332
+ try {
1333
+ const manifest = readManifest(rosterPath);
1334
+ if (manifest.server.managed) {
1335
+ const current = manifest.server.managed;
1336
+ const currentCommand = current.command ?? ["harness", "serve"];
1337
+ const currentCwd = current.cwd ?? dirname(rosterPath);
1338
+ const currentPort = current.port ?? 0;
1339
+ const storedCommand = discovery.spawnConfig.command ?? [
1340
+ "harness",
1341
+ "serve"
1342
+ ];
1343
+ const storedCwd = discovery.spawnConfig.cwd ?? dirname(rosterPath);
1344
+ const storedPort = discovery.spawnConfig.port ?? 0;
1345
+ configDrift = JSON.stringify(currentCommand) !== JSON.stringify(storedCommand) || currentCwd !== storedCwd || currentPort !== storedPort;
1346
+ }
1347
+ } catch {}
1348
+ return {
1349
+ running: true,
1350
+ port: discovery.port,
1351
+ pid: discovery.pid,
1352
+ configDrift
1353
+ };
1354
+ }
1355
+ async function stopServer(rosterPath) {
1356
+ const discovery = readDiscovery(rosterPath);
1357
+ if (!discovery)
1358
+ return { stopped: false };
1359
+ if (!verifyIdentity(discovery.pid, discovery.identity)) {
1360
+ removeDiscovery(rosterPath);
1361
+ return { stopped: false };
1362
+ }
1363
+ const { pid } = discovery;
1364
+ try {
1365
+ process.kill(pid, "SIGTERM");
1366
+ } catch {
1367
+ removeDiscovery(rosterPath);
1368
+ return { stopped: true };
1369
+ }
1370
+ if (await waitForDeath(pid, STOP_GRACE_MS)) {
1371
+ removeDiscovery(rosterPath);
1372
+ return { stopped: true };
1373
+ }
1374
+ try {
1375
+ process.kill(pid, "SIGKILL");
1376
+ } catch {
1377
+ removeDiscovery(rosterPath);
1378
+ return { stopped: true };
1379
+ }
1380
+ if (await waitForDeath(pid, STOP_GRACE_MS)) {
1381
+ removeDiscovery(rosterPath);
1382
+ return { stopped: true };
1383
+ }
1384
+ return { stopped: false };
1385
+ }
1386
+ async function waitForDeath(pid, budgetMs) {
1387
+ const deadline = Date.now() + budgetMs;
1388
+ while (Date.now() < deadline) {
1389
+ if (!isAlive(pid))
1390
+ return true;
1391
+ await sleep(POLL_INTERVAL_MS);
1392
+ }
1393
+ return !isAlive(pid);
1394
+ }
1395
+
755
1396
  // src/tools/bus_result.ts
756
1397
  import { tool } from "@opencode-ai/plugin";
1398
+
1399
+ // src/tools/shared.ts
1400
+ async function ensureAndLoadContext(directory) {
1401
+ if (isManagedRoster(directory)) {
1402
+ const rosterPath = resolveRosterPath(directory);
1403
+ await ensureServer(rosterPath);
1404
+ }
1405
+ return loadContext(directory);
1406
+ }
1407
+
1408
+ // src/tools/bus_result.ts
757
1409
  var BUS_RESULT_DESCRIPTION = "Return a completed space-bus session's final assistant message and diff. Errors if the session is still running — use bus_status to check first.";
758
1410
  function makeBusResult(defaultDirectory) {
759
1411
  return tool({
@@ -765,7 +1417,7 @@ function makeBusResult(defaultDirectory) {
765
1417
  const directory = ctx.directory ?? defaultDirectory;
766
1418
  let context;
767
1419
  try {
768
- context = loadContext(directory);
1420
+ context = await ensureAndLoadContext(directory);
769
1421
  } catch (e) {
770
1422
  throw new Error(e.message);
771
1423
  }
@@ -788,7 +1440,7 @@ function makeBusRoster(defaultDirectory) {
788
1440
  const directory = ctx.directory ?? defaultDirectory;
789
1441
  let context;
790
1442
  try {
791
- context = loadContext(directory);
1443
+ context = await ensureAndLoadContext(directory);
792
1444
  } catch (e) {
793
1445
  throw new Error(e.message);
794
1446
  }
@@ -813,7 +1465,7 @@ function makeBusStatus(defaultDirectory) {
813
1465
  const directory = ctx.directory ?? defaultDirectory;
814
1466
  let context;
815
1467
  try {
816
- context = loadContext(directory);
1468
+ context = await ensureAndLoadContext(directory);
817
1469
  } catch (e) {
818
1470
  throw new Error(e.message);
819
1471
  }
@@ -844,7 +1496,7 @@ function makeBusTask(defaultDirectory) {
844
1496
  const directory = ctx.directory ?? defaultDirectory;
845
1497
  let context;
846
1498
  try {
847
- context = loadContext(directory);
1499
+ context = await ensureAndLoadContext(directory);
848
1500
  } catch (e) {
849
1501
  throw new Error(e.message);
850
1502
  }