@fro.bot/space-bus 0.10.0 → 0.11.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.
- package/README.md +22 -0
- package/dist/cli.d.ts +14 -0
- package/dist/cli.js +765 -8
- package/dist/config.js +10 -8
- package/dist/contract.js +0 -3
- package/dist/core.js +0 -10
- package/dist/discovery.d.ts +7 -0
- package/dist/format.js +0 -3
- package/dist/index.js +1333 -1419
- package/dist/launchd.d.ts +108 -0
- package/dist/mcp.js +1338 -1424
- package/dist/server.js +10 -8
- package/dist/service.d.ts +105 -0
- package/package.json +1 -1
package/dist/mcp.js
CHANGED
|
@@ -2,6 +2,12 @@
|
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
3
|
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
|
4
4
|
|
|
5
|
+
// src/config.ts
|
|
6
|
+
import { existsSync, readFileSync as readFileSync2, realpathSync } from "node:fs";
|
|
7
|
+
import { homedir as homedir2 } from "node:os";
|
|
8
|
+
import { join as join2 } from "node:path";
|
|
9
|
+
import { z as z3 } from "zod";
|
|
10
|
+
|
|
5
11
|
// src/contract.ts
|
|
6
12
|
import { z } from "zod";
|
|
7
13
|
var sessionSchema = z.looseObject({
|
|
@@ -131,1634 +137,1542 @@ var discoveryFileSchema = z.object({
|
|
|
131
137
|
baseUrl: z.url()
|
|
132
138
|
});
|
|
133
139
|
|
|
134
|
-
// src/
|
|
135
|
-
|
|
136
|
-
|
|
140
|
+
// src/discovery.ts
|
|
141
|
+
import { execFileSync } from "node:child_process";
|
|
142
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
143
|
+
import {
|
|
144
|
+
chmodSync,
|
|
145
|
+
closeSync,
|
|
146
|
+
constants as fsConstants,
|
|
147
|
+
mkdirSync,
|
|
148
|
+
openSync,
|
|
149
|
+
readFileSync,
|
|
150
|
+
renameSync,
|
|
151
|
+
statSync,
|
|
152
|
+
unlinkSync,
|
|
153
|
+
writeFileSync
|
|
154
|
+
} from "node:fs";
|
|
155
|
+
import { homedir } from "node:os";
|
|
156
|
+
import { join } from "node:path";
|
|
157
|
+
import { z as z2 } from "zod";
|
|
158
|
+
function rosterKey(rosterPath) {
|
|
159
|
+
return createHash("sha256").update(rosterPath).digest("hex").slice(0, 16);
|
|
137
160
|
}
|
|
138
|
-
function
|
|
139
|
-
|
|
161
|
+
function stateDirFor(rosterPath) {
|
|
162
|
+
const base = process.env["XDG_STATE_HOME"] ?? join(homedir(), ".local", "state");
|
|
163
|
+
return join(base, "space-bus", rosterKey(rosterPath));
|
|
140
164
|
}
|
|
141
|
-
function
|
|
142
|
-
|
|
143
|
-
let bin = "";
|
|
144
|
-
for (const b of bytes)
|
|
145
|
-
bin += String.fromCharCode(b);
|
|
146
|
-
return btoa(bin);
|
|
165
|
+
function discoveryFilePath(rosterPath) {
|
|
166
|
+
return join(stateDirFor(rosterPath), "discovery.json");
|
|
147
167
|
}
|
|
148
|
-
function
|
|
149
|
-
|
|
150
|
-
return {};
|
|
151
|
-
const username = credentials.username ?? "opencode";
|
|
152
|
-
const token = toBase64(`${username}:${credentials.password}`);
|
|
153
|
-
return { Authorization: `Basic ${token}` };
|
|
168
|
+
function lockFilePath(rosterPath) {
|
|
169
|
+
return join(stateDirFor(rosterPath), "spawn.lock");
|
|
154
170
|
}
|
|
155
|
-
|
|
171
|
+
function logFilePath(rosterPath) {
|
|
172
|
+
return join(stateDirFor(rosterPath), "server.log");
|
|
173
|
+
}
|
|
174
|
+
function writeDiscovery(rosterPath, data) {
|
|
175
|
+
const dir = stateDirFor(rosterPath);
|
|
176
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
177
|
+
chmodSync(dir, 448);
|
|
178
|
+
const target = discoveryFilePath(rosterPath);
|
|
179
|
+
const tempPath = `${target}.tmp.${randomBytes(8).toString("hex")}`;
|
|
180
|
+
const fd = openSync(tempPath, fsConstants.O_EXCL | fsConstants.O_CREAT | fsConstants.O_WRONLY, 384);
|
|
156
181
|
try {
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
"content-type": "application/json",
|
|
161
|
-
"x-opencode-directory": directory,
|
|
162
|
-
...authHeader(credentials),
|
|
163
|
-
...init?.headers
|
|
164
|
-
},
|
|
165
|
-
redirect: "error",
|
|
166
|
-
signal: AbortSignal.timeout(30000)
|
|
167
|
-
});
|
|
168
|
-
const bodyText = await res.text().catch(() => "<unreadable body>");
|
|
169
|
-
return { res, bodyText };
|
|
170
|
-
} catch (e) {
|
|
171
|
-
const message = e.message;
|
|
172
|
-
return {
|
|
173
|
-
res: new Response(null, {
|
|
174
|
-
status: 599,
|
|
175
|
-
statusText: "space-bus: request failed"
|
|
176
|
-
}),
|
|
177
|
-
bodyText: `space-bus: request failed: ${message}`
|
|
178
|
-
};
|
|
182
|
+
writeFileSync(fd, JSON.stringify(data));
|
|
183
|
+
} finally {
|
|
184
|
+
closeQuietly(fd);
|
|
179
185
|
}
|
|
186
|
+
renameSync(tempPath, target);
|
|
187
|
+
chmodSync(target, 384);
|
|
180
188
|
}
|
|
181
|
-
|
|
182
|
-
const
|
|
183
|
-
|
|
184
|
-
return [];
|
|
185
|
-
let messages;
|
|
189
|
+
function readDiscovery(rosterPath) {
|
|
190
|
+
const target = discoveryFilePath(rosterPath);
|
|
191
|
+
let raw;
|
|
186
192
|
try {
|
|
187
|
-
|
|
193
|
+
raw = readFileSync(target, "utf8");
|
|
188
194
|
} catch {
|
|
189
|
-
return
|
|
190
|
-
}
|
|
191
|
-
const byFile = new Map;
|
|
192
|
-
for (const m of messages) {
|
|
193
|
-
if (m.info.role !== "user")
|
|
194
|
-
continue;
|
|
195
|
-
const diffs = m.info.summary?.diffs;
|
|
196
|
-
if (!diffs || diffs.length === 0)
|
|
197
|
-
continue;
|
|
198
|
-
for (const d of diffs) {
|
|
199
|
-
const key = d.file ?? `<unknown:${byFile.size}>`;
|
|
200
|
-
byFile.set(key, d);
|
|
201
|
-
}
|
|
195
|
+
return null;
|
|
202
196
|
}
|
|
203
|
-
|
|
204
|
-
}
|
|
205
|
-
async function fetchDiffWithFallback(baseUrl, credentials, directory, sessionId) {
|
|
206
|
-
const diffRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/diff`);
|
|
207
|
-
let diff = [];
|
|
197
|
+
let json;
|
|
208
198
|
try {
|
|
209
|
-
|
|
199
|
+
json = JSON.parse(raw);
|
|
210
200
|
} catch {
|
|
211
|
-
|
|
212
|
-
}
|
|
213
|
-
if (diff.length > 0) {
|
|
214
|
-
return { diff, diffSource: "session" };
|
|
201
|
+
return null;
|
|
215
202
|
}
|
|
203
|
+
const parsed = discoveryFileSchema.safeParse(json);
|
|
204
|
+
return parsed.success ? parsed.data : null;
|
|
205
|
+
}
|
|
206
|
+
function removeDiscovery(rosterPath) {
|
|
216
207
|
try {
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
}
|
|
225
|
-
} catch {}
|
|
226
|
-
try {
|
|
227
|
-
const turnDiffs = await fetchTurnDiffs(baseUrl, credentials, directory, sessionId);
|
|
228
|
-
if (turnDiffs.length > 0) {
|
|
229
|
-
return { diff: turnDiffs, diffSource: "turns" };
|
|
230
|
-
}
|
|
231
|
-
} catch {}
|
|
208
|
+
unlinkSync(discoveryFilePath(rosterPath));
|
|
209
|
+
} catch (err) {
|
|
210
|
+
if (!isEnoent(err))
|
|
211
|
+
throw err;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
function removeDiscoveryIfMatches(rosterPath, expected) {
|
|
232
215
|
try {
|
|
233
|
-
const
|
|
234
|
-
if (
|
|
235
|
-
|
|
236
|
-
if (vcsStatus.length > 0) {
|
|
237
|
-
return {
|
|
238
|
-
diff: vcsStatus.map((v) => ({
|
|
239
|
-
file: v.file,
|
|
240
|
-
additions: v.additions,
|
|
241
|
-
deletions: v.deletions,
|
|
242
|
-
status: v.status
|
|
243
|
-
})),
|
|
244
|
-
diffSource: "working-tree"
|
|
245
|
-
};
|
|
246
|
-
}
|
|
216
|
+
const current = readDiscovery(rosterPath);
|
|
217
|
+
if (current && current.pid === expected.pid && current.identity === expected.identity) {
|
|
218
|
+
removeDiscovery(rosterPath);
|
|
247
219
|
}
|
|
248
220
|
} catch {}
|
|
249
|
-
return { diff, diffSource: "session" };
|
|
250
221
|
}
|
|
251
|
-
function
|
|
252
|
-
const
|
|
253
|
-
if (!
|
|
254
|
-
return
|
|
222
|
+
function attachLive(rosterPath) {
|
|
223
|
+
const discovery = readDiscovery(rosterPath);
|
|
224
|
+
if (!discovery)
|
|
225
|
+
return null;
|
|
226
|
+
if (!loopbackOk(discovery.baseUrl))
|
|
227
|
+
return null;
|
|
228
|
+
if (!verifyIdentity(discovery.pid, discovery.identity)) {
|
|
229
|
+
removeDiscoveryIfMatches(rosterPath, {
|
|
230
|
+
pid: discovery.pid,
|
|
231
|
+
identity: discovery.identity
|
|
232
|
+
});
|
|
233
|
+
return null;
|
|
255
234
|
}
|
|
256
|
-
|
|
257
|
-
|
|
235
|
+
return {
|
|
236
|
+
baseUrl: discovery.baseUrl,
|
|
237
|
+
credentials: { username: "opencode", password: discovery.password },
|
|
238
|
+
pid: discovery.pid,
|
|
239
|
+
port: discovery.port
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
function captureIdentity(pid) {
|
|
258
243
|
try {
|
|
259
|
-
|
|
244
|
+
const out = execFileSync("ps", ["-p", String(pid), "-o", "lstart=,comm="], {
|
|
245
|
+
env: { ...process.env, LC_ALL: "C" },
|
|
246
|
+
encoding: "utf8"
|
|
247
|
+
});
|
|
248
|
+
const trimmed = out.trim();
|
|
249
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
260
250
|
} catch {
|
|
261
|
-
return
|
|
251
|
+
return null;
|
|
262
252
|
}
|
|
263
|
-
|
|
264
|
-
|
|
253
|
+
}
|
|
254
|
+
function isAlive(pid) {
|
|
255
|
+
try {
|
|
256
|
+
process.kill(pid, 0);
|
|
257
|
+
return true;
|
|
258
|
+
} catch {
|
|
259
|
+
return false;
|
|
265
260
|
}
|
|
266
|
-
return {
|
|
267
|
-
ok: true,
|
|
268
|
-
baseUrl: roster.server.baseUrl,
|
|
269
|
-
projects: roster.projects,
|
|
270
|
-
credentials: credentials ?? {}
|
|
271
|
-
};
|
|
272
261
|
}
|
|
273
|
-
function
|
|
274
|
-
|
|
262
|
+
function verifyIdentity(pid, storedIdentity) {
|
|
263
|
+
if (!isAlive(pid))
|
|
264
|
+
return false;
|
|
265
|
+
const current = captureIdentity(pid);
|
|
266
|
+
return current !== null && current === storedIdentity;
|
|
275
267
|
}
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
268
|
+
var lockFileSchema = z2.object({
|
|
269
|
+
pid: z2.number().int().min(2),
|
|
270
|
+
startTime: z2.string(),
|
|
271
|
+
since: z2.number()
|
|
272
|
+
});
|
|
273
|
+
var CORRUPT_LOCK_GRACE_MS = 2000;
|
|
274
|
+
function acquireLock(rosterPath) {
|
|
275
|
+
const dir = stateDirFor(rosterPath);
|
|
276
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
277
|
+
chmodSync(dir, 448);
|
|
278
|
+
const target = lockFilePath(rosterPath);
|
|
279
|
+
const identity = captureIdentity(process.pid) ?? "";
|
|
280
|
+
const lock = {
|
|
281
|
+
pid: process.pid,
|
|
282
|
+
startTime: identity,
|
|
283
|
+
since: Date.now()
|
|
284
|
+
};
|
|
285
|
+
if (tryCreateLockFile(target, lock)) {
|
|
286
|
+
return { rosterPath };
|
|
281
287
|
}
|
|
282
|
-
|
|
283
|
-
|
|
288
|
+
const existing = readLockFile(target);
|
|
289
|
+
if (existing) {
|
|
290
|
+
if (verifyIdentity(existing.pid, existing.startTime))
|
|
291
|
+
return null;
|
|
292
|
+
} else if (!isOlderThan(target, CORRUPT_LOCK_GRACE_MS)) {
|
|
293
|
+
return null;
|
|
284
294
|
}
|
|
285
|
-
return { ok: true, project };
|
|
286
|
-
}
|
|
287
|
-
async function roster(opts) {
|
|
288
|
-
const ctx = validateContext(opts.context);
|
|
289
|
-
if (!ctx.ok)
|
|
290
|
-
return ctx;
|
|
291
|
-
const { baseUrl, projects, credentials } = ctx;
|
|
292
|
-
const results = await Promise.all(projects.map(async (p) => {
|
|
293
|
-
if (!p.exists) {
|
|
294
|
-
return {
|
|
295
|
-
name: p.name,
|
|
296
|
-
path: p.expandedPath,
|
|
297
|
-
description: p.description,
|
|
298
|
-
pathExists: false
|
|
299
|
-
};
|
|
300
|
-
}
|
|
301
|
-
try {
|
|
302
|
-
const [statusRes, listRes] = await Promise.all([
|
|
303
|
-
api(baseUrl, credentials, p.expandedPath, "/session/status"),
|
|
304
|
-
api(baseUrl, credentials, p.expandedPath, "/session?limit=101")
|
|
305
|
-
]);
|
|
306
|
-
if (!statusRes.res.ok || !listRes.res.ok) {
|
|
307
|
-
return {
|
|
308
|
-
name: p.name,
|
|
309
|
-
path: p.expandedPath,
|
|
310
|
-
description: p.description,
|
|
311
|
-
pathExists: true,
|
|
312
|
-
statusError: `status=${statusRes.res.status}/${listRes.res.status}`
|
|
313
|
-
};
|
|
314
|
-
}
|
|
315
|
-
const statusMap = sessionStatusMapSchema.parse(JSON.parse(statusRes.bodyText));
|
|
316
|
-
const sessions = sessionListSchema.parse(JSON.parse(listRes.bodyText));
|
|
317
|
-
const busyCount = Object.values(statusMap).filter((s) => isStatusBusy(s)).length;
|
|
318
|
-
const capped = sessions.length > 100;
|
|
319
|
-
return {
|
|
320
|
-
name: p.name,
|
|
321
|
-
path: p.expandedPath,
|
|
322
|
-
description: p.description,
|
|
323
|
-
pathExists: true,
|
|
324
|
-
busyCount,
|
|
325
|
-
sessionCount: capped ? 100 : sessions.length,
|
|
326
|
-
sessionCountCapped: capped
|
|
327
|
-
};
|
|
328
|
-
} catch (e) {
|
|
329
|
-
return {
|
|
330
|
-
name: p.name,
|
|
331
|
-
path: p.expandedPath,
|
|
332
|
-
description: p.description,
|
|
333
|
-
pathExists: true,
|
|
334
|
-
statusError: e.message
|
|
335
|
-
};
|
|
336
|
-
}
|
|
337
|
-
}));
|
|
338
|
-
return { ok: true, projects: results };
|
|
339
|
-
}
|
|
340
|
-
async function dispatchNew(baseUrl, credentials, projects, project, prompt, title) {
|
|
341
|
-
const resolved = resolveProjectOrErr(projects, project);
|
|
342
|
-
if (!resolved.ok)
|
|
343
|
-
return resolved;
|
|
344
|
-
const directory = resolved.project.expandedPath;
|
|
345
|
-
const sessionTitle = title ?? `bus: ${prompt.slice(0, 60)}`;
|
|
346
|
-
const createRes = await api(baseUrl, credentials, directory, "/session", {
|
|
347
|
-
method: "POST",
|
|
348
|
-
body: JSON.stringify({ title: sessionTitle })
|
|
349
|
-
});
|
|
350
|
-
if (!createRes.res.ok) {
|
|
351
|
-
return err(`space-bus: failed to create session in "${project}" (${createRes.res.status}): ${createRes.bodyText}`);
|
|
352
|
-
}
|
|
353
|
-
let session;
|
|
354
295
|
try {
|
|
355
|
-
|
|
356
|
-
} catch (
|
|
357
|
-
|
|
296
|
+
unlinkSync(target);
|
|
297
|
+
} catch (err) {
|
|
298
|
+
if (!isEnoent(err))
|
|
299
|
+
throw err;
|
|
358
300
|
}
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
body: JSON.stringify({ parts: [{ type: "text", text: prompt }] })
|
|
362
|
-
});
|
|
363
|
-
if (promptRes.res.status !== 204) {
|
|
364
|
-
return err(`space-bus: dispatch to "${project}" failed sending prompt (${promptRes.res.status}): ${promptRes.bodyText}`);
|
|
301
|
+
if (tryCreateLockFile(target, lock)) {
|
|
302
|
+
return { rosterPath };
|
|
365
303
|
}
|
|
366
|
-
return
|
|
304
|
+
return null;
|
|
367
305
|
}
|
|
368
|
-
function
|
|
369
|
-
|
|
370
|
-
return
|
|
371
|
-
}
|
|
372
|
-
|
|
373
|
-
if (!input.project) {
|
|
374
|
-
return err("space-bus: project is required when starting a new session");
|
|
375
|
-
}
|
|
376
|
-
return {
|
|
377
|
-
ok: true,
|
|
378
|
-
prompt: input.prompt,
|
|
379
|
-
title: input.title,
|
|
380
|
-
project: input.project
|
|
381
|
-
};
|
|
306
|
+
function isOlderThan(path, ageMs) {
|
|
307
|
+
try {
|
|
308
|
+
return Date.now() - statSync(path).mtimeMs > ageMs;
|
|
309
|
+
} catch {
|
|
310
|
+
return false;
|
|
382
311
|
}
|
|
383
|
-
return {
|
|
384
|
-
ok: true,
|
|
385
|
-
prompt: input.prompt,
|
|
386
|
-
title: input.title,
|
|
387
|
-
sessionId: input.sessionId,
|
|
388
|
-
project: input.project
|
|
389
|
-
};
|
|
390
312
|
}
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
}
|
|
403
|
-
const r = await dispatchNew(baseUrl, credentials, projects, args.project, args.prompt, args.title);
|
|
404
|
-
if (!r.ok)
|
|
405
|
-
return r;
|
|
406
|
-
return {
|
|
407
|
-
ok: true,
|
|
408
|
-
sessionId: r.sessionId,
|
|
409
|
-
project: r.project,
|
|
410
|
-
mode: "new",
|
|
411
|
-
directory: r.directory
|
|
412
|
-
};
|
|
313
|
+
function releaseLock(handle) {
|
|
314
|
+
try {
|
|
315
|
+
unlinkSync(lockFilePath(handle.rosterPath));
|
|
316
|
+
} catch {}
|
|
317
|
+
}
|
|
318
|
+
function readLockFile(target) {
|
|
319
|
+
let raw;
|
|
320
|
+
try {
|
|
321
|
+
raw = readFileSync(target, "utf8");
|
|
322
|
+
} catch {
|
|
323
|
+
return null;
|
|
413
324
|
}
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
return err(`space-bus: session ${args.sessionId} belongs to project "${project}", not "${args.project}" — refusing to steer the wrong session`);
|
|
325
|
+
let json;
|
|
326
|
+
try {
|
|
327
|
+
json = JSON.parse(raw);
|
|
328
|
+
} catch {
|
|
329
|
+
return null;
|
|
420
330
|
}
|
|
421
|
-
|
|
331
|
+
const parsed = lockFileSchema.safeParse(json);
|
|
332
|
+
return parsed.success ? parsed.data : null;
|
|
422
333
|
}
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
if (
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
try {
|
|
432
|
-
session = sessionSchema.parse(JSON.parse(bodyText));
|
|
433
|
-
} catch {
|
|
434
|
-
continue;
|
|
435
|
-
}
|
|
436
|
-
const owner = session.directory ? projects.find((proj) => proj.expandedPath === session.directory) : undefined;
|
|
437
|
-
if (owner) {
|
|
438
|
-
return { ok: true, directory: owner.expandedPath, project: owner.name };
|
|
439
|
-
}
|
|
440
|
-
return err(`space-bus: session ${sessionId} belongs to ${session.directory ?? "an unknown directory"}, which is not a manifest project`);
|
|
334
|
+
function tryCreateLockFile(target, lock) {
|
|
335
|
+
let fd;
|
|
336
|
+
try {
|
|
337
|
+
fd = openSync(target, fsConstants.O_EXCL | fsConstants.O_CREAT | fsConstants.O_WRONLY, 384);
|
|
338
|
+
} catch (err) {
|
|
339
|
+
if (isErrnoCode(err, "EEXIST"))
|
|
340
|
+
return false;
|
|
341
|
+
throw err;
|
|
441
342
|
}
|
|
442
|
-
|
|
343
|
+
try {
|
|
344
|
+
writeFileSync(fd, JSON.stringify(lock));
|
|
345
|
+
} finally {
|
|
346
|
+
closeQuietly(fd);
|
|
347
|
+
}
|
|
348
|
+
return true;
|
|
443
349
|
}
|
|
444
|
-
function
|
|
445
|
-
|
|
446
|
-
return "not_found";
|
|
447
|
-
if (input.failed)
|
|
448
|
-
return "failed";
|
|
449
|
-
if (input.pendingQuestion)
|
|
450
|
-
return "blocked";
|
|
451
|
-
if (input.busy)
|
|
452
|
-
return "running";
|
|
453
|
-
return "complete";
|
|
350
|
+
function isEnoent(err) {
|
|
351
|
+
return isErrnoCode(err, "ENOENT");
|
|
454
352
|
}
|
|
455
|
-
function
|
|
456
|
-
|
|
457
|
-
const text = firstQuestion?.question ?? "";
|
|
458
|
-
const preview = text.length > 140 ? `${text.slice(0, 140)}…` : text;
|
|
459
|
-
const options = (firstQuestion?.options ?? []).map((o) => o.label ?? "").filter((l) => l.length > 0);
|
|
460
|
-
return { sessionId: entry.sessionID, preview, options };
|
|
353
|
+
function isErrnoCode(err, code) {
|
|
354
|
+
return typeof err === "object" && err !== null && "code" in err && err.code === code;
|
|
461
355
|
}
|
|
462
|
-
|
|
356
|
+
function closeQuietly(fd) {
|
|
463
357
|
try {
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
358
|
+
closeSync(fd);
|
|
359
|
+
} catch {}
|
|
360
|
+
}
|
|
361
|
+
function provisionalFilePath(rosterPath) {
|
|
362
|
+
return join(stateDirFor(rosterPath), "spawn.provisional.json");
|
|
363
|
+
}
|
|
364
|
+
var provisionalFileSchema = z2.object({
|
|
365
|
+
pid: z2.number().int().min(2),
|
|
366
|
+
identity: z2.string(),
|
|
367
|
+
password: z2.string(),
|
|
368
|
+
since: z2.number()
|
|
369
|
+
});
|
|
370
|
+
function writeProvisional(rosterPath, data) {
|
|
371
|
+
const dir = stateDirFor(rosterPath);
|
|
372
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
373
|
+
chmodSync(dir, 448);
|
|
374
|
+
const target = provisionalFilePath(rosterPath);
|
|
375
|
+
const fd = openSync(target, fsConstants.O_CREAT | fsConstants.O_WRONLY | fsConstants.O_TRUNC, 384);
|
|
376
|
+
try {
|
|
377
|
+
writeFileSync(fd, JSON.stringify(data));
|
|
378
|
+
} finally {
|
|
379
|
+
closeQuietly(fd);
|
|
380
|
+
}
|
|
381
|
+
chmodSync(target, 384);
|
|
382
|
+
}
|
|
383
|
+
function readProvisional(rosterPath) {
|
|
384
|
+
const target = provisionalFilePath(rosterPath);
|
|
385
|
+
let raw;
|
|
386
|
+
try {
|
|
387
|
+
raw = readFileSync(target, "utf8");
|
|
473
388
|
} catch {
|
|
474
|
-
return;
|
|
389
|
+
return null;
|
|
390
|
+
}
|
|
391
|
+
let json;
|
|
392
|
+
try {
|
|
393
|
+
json = JSON.parse(raw);
|
|
394
|
+
} catch {
|
|
395
|
+
return null;
|
|
475
396
|
}
|
|
397
|
+
const parsed = provisionalFileSchema.safeParse(json);
|
|
398
|
+
return parsed.success ? parsed.data : null;
|
|
476
399
|
}
|
|
477
|
-
|
|
478
|
-
const ctx = validateContext(opts.context);
|
|
479
|
-
if (!ctx.ok)
|
|
480
|
-
return ctx;
|
|
481
|
-
const { baseUrl, projects, credentials } = ctx;
|
|
482
|
-
const loc = await findSessionDirectory(baseUrl, credentials, projects, sessionId);
|
|
483
|
-
if (!loc.ok)
|
|
484
|
-
return loc;
|
|
485
|
-
const { directory, project } = loc;
|
|
486
|
-
const [sessionRes, statusMapRes, todoRes, diffResult, pendingQuestion] = await Promise.all([
|
|
487
|
-
api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}`),
|
|
488
|
-
api(baseUrl, credentials, directory, "/session/status"),
|
|
489
|
-
api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/todo`),
|
|
490
|
-
fetchDiffWithFallback(baseUrl, credentials, directory, sessionId),
|
|
491
|
-
fetchPendingQuestion(baseUrl, credentials, directory, sessionId)
|
|
492
|
-
]);
|
|
493
|
-
if (!sessionRes.res.ok) {
|
|
494
|
-
return err(`space-bus: failed to fetch session ${sessionId} (${sessionRes.res.status}): ${sessionRes.bodyText}`);
|
|
495
|
-
}
|
|
496
|
-
let session;
|
|
497
|
-
let statusMap;
|
|
498
|
-
let todos;
|
|
400
|
+
function removeProvisional(rosterPath) {
|
|
499
401
|
try {
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
402
|
+
unlinkSync(provisionalFilePath(rosterPath));
|
|
403
|
+
} catch {}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// src/config.ts
|
|
407
|
+
var managedServerConfigSchema = z3.object({
|
|
408
|
+
command: z3.array(z3.string()).optional(),
|
|
409
|
+
cwd: z3.string().optional(),
|
|
410
|
+
port: z3.number().int().nonnegative().optional()
|
|
411
|
+
});
|
|
412
|
+
var serverConfigSchema = z3.object({
|
|
413
|
+
baseUrl: z3.url().optional(),
|
|
414
|
+
managed: managedServerConfigSchema.optional()
|
|
415
|
+
}).superRefine((val, ctx) => {
|
|
416
|
+
const hasBaseUrl = val.baseUrl !== undefined;
|
|
417
|
+
const hasManaged = val.managed !== undefined;
|
|
418
|
+
if (hasBaseUrl && hasManaged) {
|
|
419
|
+
ctx.addIssue({
|
|
420
|
+
code: "custom",
|
|
421
|
+
message: "space-bus: roster's server block must specify exactly one of `baseUrl` or `managed`, not both"
|
|
422
|
+
});
|
|
423
|
+
} else if (!hasBaseUrl && !hasManaged) {
|
|
424
|
+
ctx.addIssue({
|
|
425
|
+
code: "custom",
|
|
426
|
+
message: "space-bus: roster's server block must specify one of `baseUrl` (externally-managed) or `managed` (plugin-spawned) — neither was present"
|
|
427
|
+
});
|
|
505
428
|
}
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
title: session.title,
|
|
518
|
-
todos,
|
|
519
|
-
diff: { files: diff.length, additions, deletions },
|
|
520
|
-
diffSource,
|
|
521
|
-
pendingQuestion,
|
|
522
|
-
state,
|
|
523
|
-
resultAvailable: state === "complete"
|
|
524
|
-
};
|
|
429
|
+
});
|
|
430
|
+
var manifestSchema = z3.object({
|
|
431
|
+
server: serverConfigSchema,
|
|
432
|
+
projects: z3.array(z3.object({
|
|
433
|
+
name: z3.string(),
|
|
434
|
+
path: z3.string(),
|
|
435
|
+
description: z3.string()
|
|
436
|
+
}))
|
|
437
|
+
});
|
|
438
|
+
function expandHome(path) {
|
|
439
|
+
return path.startsWith("~") ? join2(homedir2(), path.slice(1)) : path;
|
|
525
440
|
}
|
|
526
|
-
|
|
527
|
-
const
|
|
528
|
-
if (
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
questions = questionListSchema.parse(JSON.parse(questionsRes.bodyText));
|
|
532
|
-
} catch {
|
|
533
|
-
questions = [];
|
|
441
|
+
function resolveRosterPath(directory) {
|
|
442
|
+
const override = process.env["SPACE_BUS_CONFIG"];
|
|
443
|
+
if (override) {
|
|
444
|
+
if (override.includes("://")) {
|
|
445
|
+
throw new Error(`space-bus: SPACE_BUS_CONFIG must be an absolute path or start with ~ (got a URL: ${override})`);
|
|
534
446
|
}
|
|
535
|
-
const
|
|
536
|
-
if (
|
|
537
|
-
|
|
538
|
-
method: "POST",
|
|
539
|
-
body: JSON.stringify({ answers: [[message]] })
|
|
540
|
-
});
|
|
541
|
-
if (!replyRes.res.ok) {
|
|
542
|
-
return err(`space-bus: failed to reply to question ${pending.id} for session ${sessionId} (${replyRes.res.status}): ${replyRes.bodyText}`);
|
|
543
|
-
}
|
|
544
|
-
return { ok: true, sessionId, project, mode: "question-reply" };
|
|
447
|
+
const expanded = expandHome(override);
|
|
448
|
+
if (!expanded.startsWith("/")) {
|
|
449
|
+
throw new Error(`space-bus: SPACE_BUS_CONFIG must be an absolute path or start with ~ (got: ${override})`);
|
|
545
450
|
}
|
|
451
|
+
return existsSync(expanded) ? realpathSync(expanded) : expanded;
|
|
546
452
|
}
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
});
|
|
551
|
-
if (promptRes.res.status !== 204) {
|
|
552
|
-
return err(`space-bus: follow-up prompt to session ${sessionId} failed (${promptRes.res.status}): ${promptRes.bodyText}`);
|
|
453
|
+
if (directory) {
|
|
454
|
+
const candidate = join2(directory, "spacebus.json");
|
|
455
|
+
return existsSync(candidate) ? realpathSync(candidate) : candidate;
|
|
553
456
|
}
|
|
554
|
-
|
|
457
|
+
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");
|
|
555
458
|
}
|
|
556
|
-
|
|
557
|
-
const
|
|
558
|
-
|
|
559
|
-
return ctx;
|
|
560
|
-
const { baseUrl, projects, credentials } = ctx;
|
|
561
|
-
const loc = await findSessionDirectory(baseUrl, credentials, projects, sessionId);
|
|
562
|
-
if (!loc.ok)
|
|
563
|
-
return loc;
|
|
564
|
-
const { directory, project } = loc;
|
|
565
|
-
const statusMapRes = await api(baseUrl, credentials, directory, "/session/status");
|
|
566
|
-
if (statusMapRes.res.ok) {
|
|
567
|
-
try {
|
|
568
|
-
const statusMap = sessionStatusMapSchema.parse(JSON.parse(statusMapRes.bodyText));
|
|
569
|
-
const entry = statusMap[sessionId];
|
|
570
|
-
if (isStatusBusy(entry)) {
|
|
571
|
-
return err(`space-bus: session ${sessionId} is still running, use bus_status`);
|
|
572
|
-
}
|
|
573
|
-
} catch {}
|
|
574
|
-
}
|
|
575
|
-
const [messageRes, diffResult] = await Promise.all([
|
|
576
|
-
api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/message?limit=50`),
|
|
577
|
-
fetchDiffWithFallback(baseUrl, credentials, directory, sessionId)
|
|
578
|
-
]);
|
|
579
|
-
if (!messageRes.res.ok) {
|
|
580
|
-
return err(`space-bus: failed to fetch messages for ${sessionId} (${messageRes.res.status}): ${messageRes.bodyText}`);
|
|
581
|
-
}
|
|
582
|
-
let messages;
|
|
459
|
+
function getRoster(directory) {
|
|
460
|
+
const manifestPath = resolveRosterPath(directory);
|
|
461
|
+
let raw;
|
|
583
462
|
try {
|
|
584
|
-
|
|
585
|
-
} catch (
|
|
586
|
-
|
|
463
|
+
raw = readFileSync2(manifestPath, "utf8");
|
|
464
|
+
} catch (err) {
|
|
465
|
+
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)`);
|
|
587
466
|
}
|
|
588
|
-
|
|
589
|
-
const last = messages.filter((m) => m.info.role === "assistant").at(-1);
|
|
590
|
-
const text = last ? last.parts.filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join(`
|
|
591
|
-
`).trim() : "";
|
|
592
|
-
return { ok: true, sessionId, project, text, diff, diffSource };
|
|
593
|
-
}
|
|
594
|
-
async function fetchSnapshotProject(baseUrl, credentials, project) {
|
|
595
|
-
const directory = project.expandedPath;
|
|
467
|
+
let json;
|
|
596
468
|
try {
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
};
|
|
610
|
-
}
|
|
611
|
-
const statusMap = sessionStatusMapSchema.parse(JSON.parse(statusRes.bodyText));
|
|
612
|
-
const sessions = sessionListSchema.parse(JSON.parse(listRes.bodyText));
|
|
613
|
-
const busyCount = Object.values(statusMap).filter((s) => isStatusBusy(s)).length;
|
|
614
|
-
const capped = sessions.length > 100;
|
|
615
|
-
let pendingQuestions;
|
|
616
|
-
let pendingQuestionsBySession = new Map;
|
|
617
|
-
if (questionRes.res.ok) {
|
|
618
|
-
try {
|
|
619
|
-
const entries = pendingQuestionListSchema.parse(JSON.parse(questionRes.bodyText));
|
|
620
|
-
const formatted = entries.map((e) => formatQuestionEntry(e));
|
|
621
|
-
pendingQuestions = formatted;
|
|
622
|
-
pendingQuestionsBySession = new Map(formatted.map((q) => [q.sessionId, q]));
|
|
623
|
-
} catch {
|
|
624
|
-
pendingQuestions = undefined;
|
|
625
|
-
}
|
|
469
|
+
json = JSON.parse(raw);
|
|
470
|
+
} catch (err) {
|
|
471
|
+
throw new Error(`space-bus: roster at ${manifestPath} is not valid JSON: ${err.message}`);
|
|
472
|
+
}
|
|
473
|
+
const parsed = manifestSchema.safeParse(json);
|
|
474
|
+
if (!parsed.success) {
|
|
475
|
+
throw new Error(`space-bus: roster at ${manifestPath} failed schema validation: ${parsed.error.message}`);
|
|
476
|
+
}
|
|
477
|
+
if (parsed.data.server.baseUrl !== undefined) {
|
|
478
|
+
const url = new URL(parsed.data.server.baseUrl);
|
|
479
|
+
const hostname = url.hostname;
|
|
480
|
+
if (!LOOPBACK_HOSTS.has(hostname)) {
|
|
481
|
+
throw new Error(`space-bus: spacebus.json baseUrl must point to localhost (got ${hostname}) — refusing to send credentials off-machine`);
|
|
626
482
|
}
|
|
627
|
-
const sessionStates = sessions.map((s) => {
|
|
628
|
-
const entry = statusMap[s.id];
|
|
629
|
-
const busy = isStatusBusy(entry);
|
|
630
|
-
const pendingQuestion = pendingQuestionsBySession.get(s.id);
|
|
631
|
-
const state = deriveSessionState({
|
|
632
|
-
busy,
|
|
633
|
-
pendingQuestion,
|
|
634
|
-
resolved: true
|
|
635
|
-
});
|
|
636
|
-
return {
|
|
637
|
-
sessionId: s.id,
|
|
638
|
-
state,
|
|
639
|
-
resultAvailable: state === "complete"
|
|
640
|
-
};
|
|
641
|
-
});
|
|
642
|
-
return {
|
|
643
|
-
name: project.name,
|
|
644
|
-
path: directory,
|
|
645
|
-
exists: true,
|
|
646
|
-
description: project.description,
|
|
647
|
-
busyCount,
|
|
648
|
-
sessionCount: capped ? 100 : sessions.length,
|
|
649
|
-
sessionCountCapped: capped,
|
|
650
|
-
pendingQuestions,
|
|
651
|
-
sessions: sessionStates
|
|
652
|
-
};
|
|
653
|
-
} catch (e) {
|
|
654
|
-
return {
|
|
655
|
-
name: project.name,
|
|
656
|
-
path: directory,
|
|
657
|
-
exists: true,
|
|
658
|
-
description: project.description,
|
|
659
|
-
error: e.message
|
|
660
|
-
};
|
|
661
483
|
}
|
|
484
|
+
return parsed.data;
|
|
662
485
|
}
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
const workers = Array.from({ length: limit }, async () => {
|
|
668
|
-
while (true) {
|
|
669
|
-
const i = next++;
|
|
670
|
-
if (i >= items.length)
|
|
671
|
-
return;
|
|
672
|
-
results[i] = await fn(items[i]);
|
|
673
|
-
}
|
|
486
|
+
function getProjects(manifest) {
|
|
487
|
+
return manifest.projects.map((p) => {
|
|
488
|
+
const expandedPath = expandHome(p.path);
|
|
489
|
+
return { ...p, expandedPath, exists: existsSync(expandedPath) };
|
|
674
490
|
});
|
|
675
|
-
await Promise.all(workers);
|
|
676
|
-
return results;
|
|
677
491
|
}
|
|
678
|
-
|
|
679
|
-
const
|
|
680
|
-
if (!
|
|
681
|
-
return
|
|
682
|
-
const
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
492
|
+
function getCredentials() {
|
|
493
|
+
const password = process.env["OPENCODE_SERVER_PASSWORD"];
|
|
494
|
+
if (!password)
|
|
495
|
+
return {};
|
|
496
|
+
const username = process.env["OPENCODE_SERVER_USERNAME"] ?? "opencode";
|
|
497
|
+
return { username, password };
|
|
498
|
+
}
|
|
499
|
+
function loadContext(directory) {
|
|
500
|
+
const rosterPath = resolveRosterPath(directory);
|
|
501
|
+
const manifest = getRoster(directory);
|
|
502
|
+
const projects = getProjects(manifest);
|
|
503
|
+
if (manifest.server.baseUrl === undefined) {
|
|
504
|
+
const live = attachLive(rosterPath);
|
|
505
|
+
if (!live) {
|
|
506
|
+
throw new Error(`space-bus: managed server not running for ${rosterPath} — call ensureServer() or run \`space-bus serve\``);
|
|
692
507
|
}
|
|
693
|
-
return
|
|
694
|
-
|
|
695
|
-
|
|
508
|
+
return {
|
|
509
|
+
roster: { server: { baseUrl: live.baseUrl }, projects },
|
|
510
|
+
credentials: live.credentials
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
return {
|
|
514
|
+
roster: { server: { baseUrl: manifest.server.baseUrl }, projects },
|
|
515
|
+
credentials: getCredentials()
|
|
516
|
+
};
|
|
696
517
|
}
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
var NEEDS_ATTENTION_STATES = [
|
|
701
|
-
"complete",
|
|
702
|
-
"blocked",
|
|
703
|
-
"failed",
|
|
704
|
-
"not_found"
|
|
705
|
-
];
|
|
706
|
-
function sleep(ms) {
|
|
707
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
518
|
+
function isManagedRoster(directory) {
|
|
519
|
+
const manifest = getRoster(directory);
|
|
520
|
+
return manifest.server.managed !== undefined;
|
|
708
521
|
}
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
522
|
+
|
|
523
|
+
// src/server.ts
|
|
524
|
+
import { spawn } from "node:child_process";
|
|
525
|
+
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
526
|
+
import { openSync as openSync2, readFileSync as readFileSync3 } from "node:fs";
|
|
527
|
+
import { dirname } from "node:path";
|
|
528
|
+
var DEFAULT_READINESS_BUDGET_MS = 15000;
|
|
529
|
+
var DEFAULT_LOCK_WAIT_BUDGET_MS = 15000;
|
|
530
|
+
var POLL_INTERVAL_MS = 50;
|
|
531
|
+
var MIN_PROBE_PHASE_MS = 3000;
|
|
532
|
+
var PROBE_FETCH_TIMEOUT_MS = 2000;
|
|
533
|
+
var STOP_GRACE_MS = 2000;
|
|
534
|
+
var SUPERVISE_INTERVAL_MS = 5000;
|
|
535
|
+
var SUPERVISE_FAILURE_THRESHOLD = 3;
|
|
536
|
+
var SUPERVISE_UNHEALTHY_BUDGET_MS = 60000;
|
|
537
|
+
function sleep(ms) {
|
|
538
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
539
|
+
}
|
|
540
|
+
function readManifest(rosterPath) {
|
|
541
|
+
const raw = readFileSync3(rosterPath, "utf8");
|
|
542
|
+
const json = JSON.parse(raw);
|
|
543
|
+
return manifestSchema.parse(json);
|
|
544
|
+
}
|
|
545
|
+
function readLogTail(logPath, maxChars = 4000) {
|
|
546
|
+
try {
|
|
547
|
+
const content = readFileSync3(logPath, "utf8");
|
|
548
|
+
return content.length > maxChars ? content.slice(-maxChars) : content;
|
|
549
|
+
} catch {
|
|
550
|
+
return "";
|
|
717
551
|
}
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
552
|
+
}
|
|
553
|
+
function basicAuthToken(password) {
|
|
554
|
+
return Buffer.from(`opencode:${password}`).toString("base64");
|
|
555
|
+
}
|
|
556
|
+
function redactSensitive(tail, password) {
|
|
557
|
+
return tail.replaceAll(basicAuthToken(password), "[REDACTED]").replaceAll(password, "[REDACTED]");
|
|
558
|
+
}
|
|
559
|
+
function redactedReadinessError(rosterPath, password, reason) {
|
|
560
|
+
const tail = redactSensitive(readLogTail(logFilePath(rosterPath)), password);
|
|
561
|
+
return new Error(`space-bus: managed server for roster ${rosterPath} ${reason}. Log tail:
|
|
562
|
+
${tail}`);
|
|
563
|
+
}
|
|
564
|
+
function isEpermError(err) {
|
|
565
|
+
return typeof err === "object" && err !== null && "code" in err && err.code === "EPERM";
|
|
566
|
+
}
|
|
567
|
+
function signalGroup(pid, sig) {
|
|
568
|
+
if (pid <= 1) {
|
|
569
|
+
try {
|
|
570
|
+
process.kill(pid, sig);
|
|
571
|
+
} catch {}
|
|
572
|
+
return false;
|
|
729
573
|
}
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
resultAvailable: false
|
|
738
|
-
});
|
|
574
|
+
try {
|
|
575
|
+
process.kill(-pid, sig);
|
|
576
|
+
return true;
|
|
577
|
+
} catch (err) {
|
|
578
|
+
if (err.code === "EPERM") {
|
|
579
|
+
throw err;
|
|
580
|
+
}
|
|
739
581
|
}
|
|
740
|
-
|
|
582
|
+
try {
|
|
583
|
+
process.kill(pid, sig);
|
|
584
|
+
} catch {}
|
|
585
|
+
return false;
|
|
741
586
|
}
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
return
|
|
587
|
+
function signalGroupOnly(pid, sig) {
|
|
588
|
+
if (pid <= 1)
|
|
589
|
+
return false;
|
|
590
|
+
try {
|
|
591
|
+
process.kill(-pid, sig);
|
|
592
|
+
return true;
|
|
593
|
+
} catch {
|
|
594
|
+
return false;
|
|
750
595
|
}
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
api(baseUrl, credentials, group.directory, "/session/status"),
|
|
758
|
-
api(baseUrl, credentials, group.directory, "/question")
|
|
759
|
-
]);
|
|
760
|
-
if (!statusRes.res.ok)
|
|
761
|
-
return;
|
|
762
|
-
let statusMap;
|
|
763
|
-
try {
|
|
764
|
-
statusMap = sessionStatusMapSchema.parse(JSON.parse(statusRes.bodyText));
|
|
765
|
-
} catch {
|
|
596
|
+
}
|
|
597
|
+
function killIdentifiedProcess(pid, identity) {
|
|
598
|
+
try {
|
|
599
|
+
if (identity !== null && identity !== undefined && identity !== "") {
|
|
600
|
+
if (verifyIdentity(pid, identity))
|
|
601
|
+
signalGroup(pid, "SIGTERM");
|
|
766
602
|
return;
|
|
767
603
|
}
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
});
|
|
785
|
-
}
|
|
786
|
-
}
|
|
787
|
-
while (true) {
|
|
788
|
-
await mapWithConcurrency(groupList, DEFAULT_WAIT_CONCURRENCY, pollGroup);
|
|
789
|
-
const sessions = uniqueIds.map((id) => lastKnown.get(id));
|
|
790
|
-
const waker = sessions.filter((s) => NEEDS_ATTENTION_STATES.includes(s.state)).map((s) => s.sessionId);
|
|
791
|
-
if (waker.length > 0) {
|
|
792
|
-
return { ok: true, sessions, waker, timedOut: false };
|
|
793
|
-
}
|
|
794
|
-
if (Date.now() >= deadline) {
|
|
795
|
-
return { ok: true, sessions, waker: [], timedOut: true };
|
|
604
|
+
process.kill(pid, "SIGTERM");
|
|
605
|
+
} catch {}
|
|
606
|
+
}
|
|
607
|
+
function attachServer(rosterPath) {
|
|
608
|
+
return attachLive(rosterPath);
|
|
609
|
+
}
|
|
610
|
+
async function waitForDiscoveryOrFail(rosterPath, budgetMs) {
|
|
611
|
+
const deadline = Date.now() + budgetMs;
|
|
612
|
+
const lockPath = lockFilePath(rosterPath);
|
|
613
|
+
while (Date.now() < deadline) {
|
|
614
|
+
const handle = attachServer(rosterPath);
|
|
615
|
+
if (handle)
|
|
616
|
+
return handle;
|
|
617
|
+
const lockInfo2 = readLockFile(lockPath);
|
|
618
|
+
const winnerAlive = lockInfo2 !== null && verifyIdentity(lockInfo2.pid, lockInfo2.startTime);
|
|
619
|
+
if (!winnerAlive) {
|
|
620
|
+
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`);
|
|
796
621
|
}
|
|
797
|
-
|
|
798
|
-
await sleep(Math.min(pollIntervalMs, Math.max(0, remaining)));
|
|
622
|
+
await sleep(POLL_INTERVAL_MS);
|
|
799
623
|
}
|
|
624
|
+
const lockInfo = readLockFile(lockPath);
|
|
625
|
+
const holder = lockInfo ? `pid ${lockInfo.pid}` : "an unknown holder";
|
|
626
|
+
throw new Error(`space-bus: timed out after ${budgetMs}ms waiting for ${holder} to finish starting the managed server for roster ${rosterPath}`);
|
|
800
627
|
}
|
|
801
|
-
function
|
|
802
|
-
if (!questionRes.res.ok)
|
|
803
|
-
return new Map;
|
|
628
|
+
async function probe(baseUrl, password) {
|
|
804
629
|
try {
|
|
805
|
-
const
|
|
806
|
-
|
|
630
|
+
const res = await fetch(`${baseUrl}/session?limit=1`, {
|
|
631
|
+
headers: { authorization: `Basic ${basicAuthToken(password)}` },
|
|
632
|
+
signal: AbortSignal.timeout(PROBE_FETCH_TIMEOUT_MS)
|
|
633
|
+
});
|
|
634
|
+
if (res.status === 200)
|
|
635
|
+
return "ready";
|
|
636
|
+
if (res.status === 401 || res.status === 403)
|
|
637
|
+
return "auth-failure";
|
|
638
|
+
return "retry";
|
|
807
639
|
} catch {
|
|
808
|
-
return
|
|
640
|
+
return "retry";
|
|
809
641
|
}
|
|
810
642
|
}
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
function formatRoster(projects) {
|
|
814
|
-
return projects.map((p) => {
|
|
815
|
-
if (!p.pathExists)
|
|
816
|
-
return `${p.name}: MISSING PATH (${p.path}) — ${p.description}`;
|
|
817
|
-
if (p.statusError)
|
|
818
|
-
return `${p.name}: status error (${p.statusError}) — ${p.description}`;
|
|
819
|
-
const count = `${p.sessionCount ?? 0}${p.sessionCountCapped ? "+" : ""}`;
|
|
820
|
-
return `${p.name}: ${p.busyCount ?? 0} busy / ${count} sessions — ${p.description} (${p.path})`;
|
|
821
|
-
}).join(`
|
|
822
|
-
`);
|
|
643
|
+
function childDied(child, pid) {
|
|
644
|
+
return child.exitCode !== null || child.signalCode !== null || !isAlive(pid);
|
|
823
645
|
}
|
|
824
|
-
function
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
646
|
+
async function waitForReadinessLine(logPath, child, pid, deadline) {
|
|
647
|
+
const readinessLine = /opencode server listening on http:\/\/127\.0\.0\.1:(\d+)/;
|
|
648
|
+
while (Date.now() < deadline) {
|
|
649
|
+
if (childDied(child, pid))
|
|
650
|
+
return null;
|
|
651
|
+
const tail = readLogTail(logPath);
|
|
652
|
+
const match = readinessLine.exec(tail);
|
|
653
|
+
if (match?.[1]) {
|
|
654
|
+
const port = Number.parseInt(match[1], 10);
|
|
655
|
+
if (Number.isInteger(port) && port > 0 && port <= 65535) {
|
|
656
|
+
return { port, baseUrl: `http://127.0.0.1:${port}` };
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
await sleep(POLL_INTERVAL_MS);
|
|
832
660
|
}
|
|
661
|
+
return null;
|
|
833
662
|
}
|
|
834
|
-
function
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
];
|
|
845
|
-
if (r.pendingQuestion) {
|
|
846
|
-
lines.push(`blocked: waiting on a question — "${r.pendingQuestion.preview}"`);
|
|
847
|
-
if (r.pendingQuestion.options.length > 0) {
|
|
848
|
-
lines.push(` options: ${r.pendingQuestion.options.join(" | ")}`);
|
|
849
|
-
}
|
|
850
|
-
lines.push(` (answer with bus_task using sessionId)`);
|
|
663
|
+
async function pollAuthedEndpoint(baseUrl, password, child, pid, deadline) {
|
|
664
|
+
while (Date.now() < deadline) {
|
|
665
|
+
if (childDied(child, pid))
|
|
666
|
+
return "died";
|
|
667
|
+
const outcome = await probe(baseUrl, password);
|
|
668
|
+
if (outcome === "ready")
|
|
669
|
+
return "ready";
|
|
670
|
+
if (outcome === "auth-failure")
|
|
671
|
+
return "auth-failure";
|
|
672
|
+
await sleep(POLL_INTERVAL_MS);
|
|
851
673
|
}
|
|
852
|
-
|
|
853
|
-
return lines.join(`
|
|
854
|
-
`);
|
|
674
|
+
return "timeout";
|
|
855
675
|
}
|
|
856
|
-
function
|
|
857
|
-
const
|
|
858
|
-
const
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
`--- reply ---`,
|
|
881
|
-
r.text || "(empty)",
|
|
882
|
-
r.diffSource === "working-tree" ? `--- diff (working tree — repo-wide, may include changes from other sessions) ---` : `--- diff ---`,
|
|
883
|
-
diffLines
|
|
884
|
-
].join(`
|
|
885
|
-
`);
|
|
886
|
-
}
|
|
887
|
-
|
|
888
|
-
// src/config.ts
|
|
889
|
-
import { existsSync, readFileSync as readFileSync2, realpathSync } from "node:fs";
|
|
890
|
-
import { homedir as homedir2 } from "node:os";
|
|
891
|
-
import { join as join2 } from "node:path";
|
|
892
|
-
import { z as z3 } from "zod";
|
|
893
|
-
|
|
894
|
-
// src/discovery.ts
|
|
895
|
-
import { execFileSync } from "node:child_process";
|
|
896
|
-
import { createHash, randomBytes } from "node:crypto";
|
|
897
|
-
import {
|
|
898
|
-
chmodSync,
|
|
899
|
-
closeSync,
|
|
900
|
-
constants as fsConstants,
|
|
901
|
-
mkdirSync,
|
|
902
|
-
openSync,
|
|
903
|
-
readFileSync,
|
|
904
|
-
renameSync,
|
|
905
|
-
statSync,
|
|
906
|
-
unlinkSync,
|
|
907
|
-
writeFileSync
|
|
908
|
-
} from "node:fs";
|
|
909
|
-
import { homedir } from "node:os";
|
|
910
|
-
import { join } from "node:path";
|
|
911
|
-
import { z as z2 } from "zod";
|
|
912
|
-
function stateDirFor(rosterPath) {
|
|
913
|
-
const base = process.env["XDG_STATE_HOME"] ?? join(homedir(), ".local", "state");
|
|
914
|
-
const hash = createHash("sha256").update(rosterPath).digest("hex").slice(0, 16);
|
|
915
|
-
return join(base, "space-bus", hash);
|
|
916
|
-
}
|
|
917
|
-
function discoveryFilePath(rosterPath) {
|
|
918
|
-
return join(stateDirFor(rosterPath), "discovery.json");
|
|
919
|
-
}
|
|
920
|
-
function lockFilePath(rosterPath) {
|
|
921
|
-
return join(stateDirFor(rosterPath), "spawn.lock");
|
|
676
|
+
async function waitForReadiness(rosterPath, password, pid, identity, child, budgetMs) {
|
|
677
|
+
const deadline = Date.now() + budgetMs;
|
|
678
|
+
const logPath = logFilePath(rosterPath);
|
|
679
|
+
const phase2Reserve = Math.min(MIN_PROBE_PHASE_MS, budgetMs / 2);
|
|
680
|
+
const phase1Deadline = Math.max(Date.now(), deadline - phase2Reserve);
|
|
681
|
+
const lineResult = await waitForReadinessLine(logPath, child, pid, phase1Deadline);
|
|
682
|
+
if (lineResult === null) {
|
|
683
|
+
const diedEarly = childDied(child, pid);
|
|
684
|
+
killIdentifiedProcess(pid, identity);
|
|
685
|
+
throw redactedReadinessError(rosterPath, password, diedEarly ? "exited before printing a readiness line" : `did not print a readiness line within ${budgetMs}ms`);
|
|
686
|
+
}
|
|
687
|
+
const { port, baseUrl } = lineResult;
|
|
688
|
+
const phase2Deadline = Math.max(deadline, Date.now() + phase2Reserve);
|
|
689
|
+
const outcome = await pollAuthedEndpoint(baseUrl, password, child, pid, phase2Deadline);
|
|
690
|
+
if (outcome === "ready")
|
|
691
|
+
return { port, baseUrl };
|
|
692
|
+
killIdentifiedProcess(pid, identity);
|
|
693
|
+
if (outcome === "died") {
|
|
694
|
+
throw redactedReadinessError(rosterPath, password, "exited before becoming ready");
|
|
695
|
+
}
|
|
696
|
+
if (outcome === "auth-failure") {
|
|
697
|
+
throw redactedReadinessError(rosterPath, password, "rejected our generated password (401/403) — authentication regression, not retrying");
|
|
698
|
+
}
|
|
699
|
+
throw redactedReadinessError(rosterPath, password, `did not become ready within ${budgetMs}ms`);
|
|
922
700
|
}
|
|
923
|
-
|
|
924
|
-
|
|
701
|
+
var PROVISIONAL_FRESH_WINDOW_MS = 5000;
|
|
702
|
+
function reapOrphanedProvisional(rosterPath) {
|
|
703
|
+
const provisional = readProvisional(rosterPath);
|
|
704
|
+
if (!provisional)
|
|
705
|
+
return;
|
|
706
|
+
const discovery = readDiscovery(rosterPath);
|
|
707
|
+
if (discovery && discovery.pid === provisional.pid && verifyIdentity(discovery.pid, discovery.identity)) {
|
|
708
|
+
removeProvisional(rosterPath);
|
|
709
|
+
return;
|
|
710
|
+
}
|
|
711
|
+
const hasIdentity = provisional.identity !== null && provisional.identity !== undefined && provisional.identity !== "";
|
|
712
|
+
const isFresh = Date.now() - provisional.since < PROVISIONAL_FRESH_WINDOW_MS;
|
|
713
|
+
if (hasIdentity || isFresh) {
|
|
714
|
+
killIdentifiedProcess(provisional.pid, provisional.identity);
|
|
715
|
+
}
|
|
716
|
+
removeProvisional(rosterPath);
|
|
925
717
|
}
|
|
926
|
-
function
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
const
|
|
931
|
-
const
|
|
932
|
-
const
|
|
718
|
+
async function spawnAndWaitReady(rosterPath, managedConfig, readinessBudgetMs) {
|
|
719
|
+
reapOrphanedProvisional(rosterPath);
|
|
720
|
+
const password = randomBytes2(32).toString("base64url");
|
|
721
|
+
const command = managedConfig.command && managedConfig.command.length > 0 ? managedConfig.command : ["harness", "serve"];
|
|
722
|
+
const cwd = managedConfig.cwd ?? dirname(rosterPath);
|
|
723
|
+
const requestedPort = managedConfig.port ?? 0;
|
|
724
|
+
const logPath = logFilePath(rosterPath);
|
|
725
|
+
const logFd = openSync2(logPath, "w", 384);
|
|
726
|
+
let child;
|
|
727
|
+
let pid;
|
|
728
|
+
let spawnError;
|
|
933
729
|
try {
|
|
934
|
-
|
|
730
|
+
child = spawn(command[0], [...command.slice(1), "--port", String(requestedPort)], {
|
|
731
|
+
cwd,
|
|
732
|
+
detached: true,
|
|
733
|
+
stdio: ["ignore", logFd, logFd],
|
|
734
|
+
env: { ...process.env, OPENCODE_SERVER_PASSWORD: password }
|
|
735
|
+
});
|
|
736
|
+
child.on("error", (err) => {
|
|
737
|
+
spawnError = err;
|
|
738
|
+
});
|
|
739
|
+
child.unref();
|
|
740
|
+
pid = child.pid;
|
|
935
741
|
} finally {
|
|
936
|
-
closeQuietly(
|
|
742
|
+
closeQuietly(logFd);
|
|
937
743
|
}
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
}
|
|
941
|
-
function readDiscovery(rosterPath) {
|
|
942
|
-
const target = discoveryFilePath(rosterPath);
|
|
943
|
-
let raw;
|
|
944
|
-
try {
|
|
945
|
-
raw = readFileSync(target, "utf8");
|
|
946
|
-
} catch {
|
|
947
|
-
return null;
|
|
744
|
+
if (pid === undefined) {
|
|
745
|
+
throw new Error(`space-bus: failed to spawn managed server (command: ${command.join(" ")}, cwd: ${cwd}, roster: ${rosterPath}, log: ${logPath})${spawnError ? `: ${spawnError.message}` : ""}`);
|
|
948
746
|
}
|
|
949
|
-
|
|
747
|
+
const identity = captureIdentity(pid);
|
|
748
|
+
writeProvisional(rosterPath, {
|
|
749
|
+
pid,
|
|
750
|
+
identity: identity ?? "",
|
|
751
|
+
password,
|
|
752
|
+
since: Date.now()
|
|
753
|
+
});
|
|
754
|
+
let port;
|
|
755
|
+
let baseUrl;
|
|
950
756
|
try {
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
757
|
+
const readiness = waitForReadiness(rosterPath, password, pid, identity, child, readinessBudgetMs);
|
|
758
|
+
const spawnErrorWatch = new Promise((_resolve, reject) => {
|
|
759
|
+
const check = setInterval(() => {
|
|
760
|
+
if (spawnError) {
|
|
761
|
+
clearInterval(check);
|
|
762
|
+
reject(new Error(`space-bus: failed to spawn managed server (command: ${command.join(" ")}, cwd: ${cwd}, roster: ${rosterPath}, log: ${logPath}): ${spawnError.message}`));
|
|
763
|
+
}
|
|
764
|
+
}, POLL_INTERVAL_MS);
|
|
765
|
+
readiness.finally(() => clearInterval(check)).catch(() => {});
|
|
766
|
+
});
|
|
767
|
+
const result = await Promise.race([readiness, spawnErrorWatch]);
|
|
768
|
+
port = result.port;
|
|
769
|
+
baseUrl = result.baseUrl;
|
|
770
|
+
} finally {
|
|
771
|
+
removeProvisional(rosterPath);
|
|
954
772
|
}
|
|
955
|
-
const
|
|
956
|
-
|
|
773
|
+
const finalIdentity = identity ?? captureIdentity(pid) ?? "";
|
|
774
|
+
writeDiscovery(rosterPath, {
|
|
775
|
+
port,
|
|
776
|
+
pid,
|
|
777
|
+
identity: finalIdentity,
|
|
778
|
+
password,
|
|
779
|
+
spawnConfig: { command, cwd, port: requestedPort },
|
|
780
|
+
baseUrl
|
|
781
|
+
});
|
|
782
|
+
return {
|
|
783
|
+
baseUrl,
|
|
784
|
+
credentials: { username: "opencode", password },
|
|
785
|
+
pid,
|
|
786
|
+
port
|
|
787
|
+
};
|
|
957
788
|
}
|
|
958
|
-
function
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
789
|
+
async function ensureServer(rosterPath, options = {}) {
|
|
790
|
+
const readinessBudgetMs = options.readinessBudgetMs ?? DEFAULT_READINESS_BUDGET_MS;
|
|
791
|
+
const lockWaitBudgetMs = options.lockWaitBudgetMs ?? DEFAULT_LOCK_WAIT_BUDGET_MS;
|
|
792
|
+
const fastPath = attachServer(rosterPath);
|
|
793
|
+
if (fastPath)
|
|
794
|
+
return fastPath;
|
|
795
|
+
const manifest = readManifest(rosterPath);
|
|
796
|
+
if (manifest.server.managed === undefined) {
|
|
797
|
+
throw new Error(`space-bus: ensureServer called on an externally-managed roster (server.baseUrl) at ${rosterPath} — nothing to spawn`);
|
|
798
|
+
}
|
|
799
|
+
const lock = acquireLock(rosterPath);
|
|
800
|
+
if (lock === null) {
|
|
801
|
+
return await waitForDiscoveryOrFail(rosterPath, lockWaitBudgetMs);
|
|
964
802
|
}
|
|
965
|
-
}
|
|
966
|
-
function removeDiscoveryIfMatches(rosterPath, expected) {
|
|
967
803
|
try {
|
|
968
|
-
const
|
|
969
|
-
if (
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
}
|
|
804
|
+
const attached = attachServer(rosterPath);
|
|
805
|
+
if (attached)
|
|
806
|
+
return attached;
|
|
807
|
+
return await spawnAndWaitReady(rosterPath, manifest.server.managed, readinessBudgetMs);
|
|
808
|
+
} finally {
|
|
809
|
+
releaseLock(lock);
|
|
810
|
+
}
|
|
973
811
|
}
|
|
974
|
-
function
|
|
812
|
+
function serverStatus(rosterPath) {
|
|
975
813
|
const discovery = readDiscovery(rosterPath);
|
|
976
|
-
if (!discovery)
|
|
977
|
-
return
|
|
978
|
-
|
|
979
|
-
return null;
|
|
814
|
+
if (!discovery) {
|
|
815
|
+
return { running: false };
|
|
816
|
+
}
|
|
980
817
|
if (!verifyIdentity(discovery.pid, discovery.identity)) {
|
|
981
818
|
removeDiscoveryIfMatches(rosterPath, {
|
|
982
819
|
pid: discovery.pid,
|
|
983
820
|
identity: discovery.identity
|
|
984
821
|
});
|
|
985
|
-
return
|
|
822
|
+
return { running: false };
|
|
986
823
|
}
|
|
824
|
+
let configDrift;
|
|
825
|
+
try {
|
|
826
|
+
const manifest = readManifest(rosterPath);
|
|
827
|
+
if (manifest.server.managed) {
|
|
828
|
+
const current = manifest.server.managed;
|
|
829
|
+
const currentCommand = current.command ?? ["harness", "serve"];
|
|
830
|
+
const currentCwd = current.cwd ?? dirname(rosterPath);
|
|
831
|
+
const currentPort = current.port ?? 0;
|
|
832
|
+
const storedCommand = discovery.spawnConfig.command ?? [
|
|
833
|
+
"harness",
|
|
834
|
+
"serve"
|
|
835
|
+
];
|
|
836
|
+
const storedCwd = discovery.spawnConfig.cwd ?? dirname(rosterPath);
|
|
837
|
+
const storedPort = discovery.spawnConfig.port ?? 0;
|
|
838
|
+
configDrift = JSON.stringify(currentCommand) !== JSON.stringify(storedCommand) || currentCwd !== storedCwd || currentPort !== storedPort;
|
|
839
|
+
}
|
|
840
|
+
} catch {}
|
|
987
841
|
return {
|
|
988
|
-
|
|
989
|
-
|
|
842
|
+
running: true,
|
|
843
|
+
port: discovery.port,
|
|
990
844
|
pid: discovery.pid,
|
|
991
|
-
|
|
845
|
+
configDrift
|
|
992
846
|
};
|
|
993
847
|
}
|
|
994
|
-
function
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
return
|
|
1002
|
-
} catch {
|
|
1003
|
-
return null;
|
|
848
|
+
async function stopServer(rosterPath) {
|
|
849
|
+
const discovery = readDiscovery(rosterPath);
|
|
850
|
+
if (!discovery)
|
|
851
|
+
return { stopped: false };
|
|
852
|
+
if (!verifyIdentity(discovery.pid, discovery.identity)) {
|
|
853
|
+
await reapSurvivingGroup(discovery.pid);
|
|
854
|
+
removeDiscovery(rosterPath);
|
|
855
|
+
return { stopped: false };
|
|
1004
856
|
}
|
|
1005
|
-
}
|
|
1006
|
-
|
|
857
|
+
const { pid } = discovery;
|
|
858
|
+
let groupSignaled;
|
|
859
|
+
const waitForCompletion = (budgetMs) => groupSignaled ? waitForGroupDeath(pid, budgetMs) : waitForDeath(pid, budgetMs);
|
|
1007
860
|
try {
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
if (!isAlive(pid))
|
|
1016
|
-
return false;
|
|
1017
|
-
const current = captureIdentity(pid);
|
|
1018
|
-
return current !== null && current === storedIdentity;
|
|
1019
|
-
}
|
|
1020
|
-
var lockFileSchema = z2.object({
|
|
1021
|
-
pid: z2.number().int().min(2),
|
|
1022
|
-
startTime: z2.string(),
|
|
1023
|
-
since: z2.number()
|
|
1024
|
-
});
|
|
1025
|
-
var CORRUPT_LOCK_GRACE_MS = 2000;
|
|
1026
|
-
function acquireLock(rosterPath) {
|
|
1027
|
-
const dir = stateDirFor(rosterPath);
|
|
1028
|
-
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
1029
|
-
chmodSync(dir, 448);
|
|
1030
|
-
const target = lockFilePath(rosterPath);
|
|
1031
|
-
const identity = captureIdentity(process.pid) ?? "";
|
|
1032
|
-
const lock = {
|
|
1033
|
-
pid: process.pid,
|
|
1034
|
-
startTime: identity,
|
|
1035
|
-
since: Date.now()
|
|
1036
|
-
};
|
|
1037
|
-
if (tryCreateLockFile(target, lock)) {
|
|
1038
|
-
return { rosterPath };
|
|
861
|
+
groupSignaled = signalGroup(pid, "SIGTERM");
|
|
862
|
+
} catch (err) {
|
|
863
|
+
if (isEpermError(err)) {
|
|
864
|
+
return { stopped: false };
|
|
865
|
+
}
|
|
866
|
+
removeDiscovery(rosterPath);
|
|
867
|
+
return { stopped: true };
|
|
1039
868
|
}
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
return null;
|
|
1044
|
-
} else if (!isOlderThan(target, CORRUPT_LOCK_GRACE_MS)) {
|
|
1045
|
-
return null;
|
|
869
|
+
if (await waitForCompletion(STOP_GRACE_MS)) {
|
|
870
|
+
removeDiscovery(rosterPath);
|
|
871
|
+
return { stopped: true };
|
|
1046
872
|
}
|
|
1047
873
|
try {
|
|
1048
|
-
|
|
1049
|
-
} catch (
|
|
1050
|
-
if (
|
|
1051
|
-
|
|
874
|
+
groupSignaled = signalGroup(pid, "SIGKILL");
|
|
875
|
+
} catch (err) {
|
|
876
|
+
if (isEpermError(err)) {
|
|
877
|
+
return { stopped: false };
|
|
878
|
+
}
|
|
879
|
+
removeDiscovery(rosterPath);
|
|
880
|
+
return { stopped: true };
|
|
1052
881
|
}
|
|
1053
|
-
if (
|
|
1054
|
-
|
|
882
|
+
if (await waitForCompletion(STOP_GRACE_MS)) {
|
|
883
|
+
removeDiscovery(rosterPath);
|
|
884
|
+
return { stopped: true };
|
|
1055
885
|
}
|
|
1056
|
-
return
|
|
886
|
+
return { stopped: false };
|
|
1057
887
|
}
|
|
1058
|
-
function
|
|
888
|
+
async function reapSurvivingGroup(pid) {
|
|
1059
889
|
try {
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
890
|
+
if (isAlive(pid))
|
|
891
|
+
return;
|
|
892
|
+
let groupAlive;
|
|
893
|
+
try {
|
|
894
|
+
process.kill(-pid, 0);
|
|
895
|
+
groupAlive = true;
|
|
896
|
+
} catch {
|
|
897
|
+
groupAlive = false;
|
|
898
|
+
}
|
|
899
|
+
if (!groupAlive)
|
|
900
|
+
return;
|
|
901
|
+
if (!signalGroupOnly(pid, "SIGTERM"))
|
|
902
|
+
return;
|
|
903
|
+
if (await waitForGroupDeath(pid, STOP_GRACE_MS))
|
|
904
|
+
return;
|
|
905
|
+
signalGroupOnly(pid, "SIGKILL");
|
|
906
|
+
await waitForGroupDeath(pid, STOP_GRACE_MS);
|
|
907
|
+
} catch {}
|
|
1064
908
|
}
|
|
1065
|
-
function
|
|
909
|
+
async function stopForHung(tick) {
|
|
1066
910
|
try {
|
|
1067
|
-
|
|
911
|
+
await tick.stop(tick.rosterPath);
|
|
1068
912
|
} catch {}
|
|
913
|
+
return { kind: "outcome", outcome: { reason: "hung" } };
|
|
1069
914
|
}
|
|
1070
|
-
function
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
return null;
|
|
1076
|
-
}
|
|
1077
|
-
let json;
|
|
1078
|
-
try {
|
|
1079
|
-
json = JSON.parse(raw);
|
|
1080
|
-
} catch {
|
|
1081
|
-
return null;
|
|
915
|
+
async function superviseTick(tick, state) {
|
|
916
|
+
const st = tick.status(tick.rosterPath);
|
|
917
|
+
if (!st.running) {
|
|
918
|
+
await reapSurvivingGroup(tick.handle.pid);
|
|
919
|
+
return { kind: "outcome", outcome: { reason: "died" } };
|
|
1082
920
|
}
|
|
1083
|
-
const
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
try {
|
|
1089
|
-
fd = openSync(target, fsConstants.O_EXCL | fsConstants.O_CREAT | fsConstants.O_WRONLY, 384);
|
|
1090
|
-
} catch (err2) {
|
|
1091
|
-
if (isErrnoCode(err2, "EEXIST"))
|
|
1092
|
-
return false;
|
|
1093
|
-
throw err2;
|
|
921
|
+
const probeOutcome = await tick.probe(tick.handle.baseUrl, tick.password);
|
|
922
|
+
const failures = probeOutcome === "retry" ? state.failures + 1 : 0;
|
|
923
|
+
const lastReadyAt = probeOutcome === "ready" ? tick.now() : state.lastReadyAt;
|
|
924
|
+
if (failures >= tick.threshold) {
|
|
925
|
+
return stopForHung(tick);
|
|
1094
926
|
}
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
} finally {
|
|
1098
|
-
closeQuietly(fd);
|
|
927
|
+
if (tick.now() - lastReadyAt >= tick.unhealthyBudgetMs) {
|
|
928
|
+
return stopForHung(tick);
|
|
1099
929
|
}
|
|
1100
|
-
return
|
|
1101
|
-
}
|
|
1102
|
-
function isEnoent(err2) {
|
|
1103
|
-
return isErrnoCode(err2, "ENOENT");
|
|
1104
|
-
}
|
|
1105
|
-
function isErrnoCode(err2, code) {
|
|
1106
|
-
return typeof err2 === "object" && err2 !== null && "code" in err2 && err2.code === code;
|
|
1107
|
-
}
|
|
1108
|
-
function closeQuietly(fd) {
|
|
1109
|
-
try {
|
|
1110
|
-
closeSync(fd);
|
|
1111
|
-
} catch {}
|
|
930
|
+
return { kind: "tick", failures, lastReadyAt };
|
|
1112
931
|
}
|
|
1113
|
-
function
|
|
1114
|
-
return
|
|
932
|
+
function makeSuperviseTick(rosterPath, handle, opts) {
|
|
933
|
+
return {
|
|
934
|
+
rosterPath,
|
|
935
|
+
handle,
|
|
936
|
+
password: handle.credentials.password ?? "",
|
|
937
|
+
threshold: opts.threshold ?? SUPERVISE_FAILURE_THRESHOLD,
|
|
938
|
+
unhealthyBudgetMs: opts.unhealthyBudgetMs ?? SUPERVISE_UNHEALTHY_BUDGET_MS,
|
|
939
|
+
now: opts.now ?? Date.now,
|
|
940
|
+
status: opts.status ?? serverStatus,
|
|
941
|
+
probe: opts.probe ?? probe,
|
|
942
|
+
stop: opts.stop ?? stopServer
|
|
943
|
+
};
|
|
1115
944
|
}
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
chmodSync(dir, 448);
|
|
1126
|
-
const target = provisionalFilePath(rosterPath);
|
|
1127
|
-
const fd = openSync(target, fsConstants.O_CREAT | fsConstants.O_WRONLY | fsConstants.O_TRUNC, 384);
|
|
945
|
+
async function interruptibleSleep(doSleep, intervalMs, interrupt) {
|
|
946
|
+
if (!interrupt) {
|
|
947
|
+
await doSleep(intervalMs);
|
|
948
|
+
return;
|
|
949
|
+
}
|
|
950
|
+
let timer;
|
|
951
|
+
const timed = new Promise((resolve) => {
|
|
952
|
+
timer = setTimeout(resolve, intervalMs);
|
|
953
|
+
});
|
|
1128
954
|
try {
|
|
1129
|
-
|
|
955
|
+
await Promise.race([timed, interrupt]);
|
|
1130
956
|
} finally {
|
|
1131
|
-
|
|
957
|
+
if (timer !== undefined)
|
|
958
|
+
clearTimeout(timer);
|
|
1132
959
|
}
|
|
1133
|
-
chmodSync(target, 384);
|
|
1134
960
|
}
|
|
1135
|
-
function
|
|
1136
|
-
const
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
961
|
+
async function superviseServer(rosterPath, handle, opts = {}) {
|
|
962
|
+
const intervalMs = opts.intervalMs ?? SUPERVISE_INTERVAL_MS;
|
|
963
|
+
const tick = makeSuperviseTick(rosterPath, handle, opts);
|
|
964
|
+
const doSleep = opts.sleep ?? sleep;
|
|
965
|
+
const shouldStop = opts.shouldStop ?? (() => false);
|
|
966
|
+
let state = { failures: 0, lastReadyAt: tick.now() };
|
|
967
|
+
for (;; ) {
|
|
968
|
+
if (shouldStop())
|
|
969
|
+
return { reason: "signal" };
|
|
970
|
+
const result = await superviseTick(tick, state);
|
|
971
|
+
if (result.kind === "outcome")
|
|
972
|
+
return result.outcome;
|
|
973
|
+
state = { failures: result.failures, lastReadyAt: result.lastReadyAt };
|
|
974
|
+
if (shouldStop())
|
|
975
|
+
return { reason: "signal" };
|
|
976
|
+
await interruptibleSleep(doSleep, intervalMs, opts.interrupt);
|
|
1142
977
|
}
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
978
|
+
}
|
|
979
|
+
async function waitForDeath(pid, budgetMs) {
|
|
980
|
+
const deadline = Date.now() + budgetMs;
|
|
981
|
+
while (Date.now() < deadline) {
|
|
982
|
+
if (!isAlive(pid))
|
|
983
|
+
return true;
|
|
984
|
+
await sleep(POLL_INTERVAL_MS);
|
|
1148
985
|
}
|
|
1149
|
-
|
|
1150
|
-
return parsed.success ? parsed.data : null;
|
|
986
|
+
return !isAlive(pid);
|
|
1151
987
|
}
|
|
1152
|
-
function
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
988
|
+
async function waitForGroupDeath(pid, budgetMs) {
|
|
989
|
+
const deadline = Date.now() + budgetMs;
|
|
990
|
+
const groupAlive = () => {
|
|
991
|
+
try {
|
|
992
|
+
process.kill(-pid, 0);
|
|
993
|
+
return true;
|
|
994
|
+
} catch {
|
|
995
|
+
return false;
|
|
996
|
+
}
|
|
997
|
+
};
|
|
998
|
+
while (Date.now() < deadline) {
|
|
999
|
+
if (!groupAlive())
|
|
1000
|
+
return true;
|
|
1001
|
+
await sleep(POLL_INTERVAL_MS);
|
|
1002
|
+
}
|
|
1003
|
+
return !groupAlive();
|
|
1156
1004
|
}
|
|
1157
1005
|
|
|
1158
|
-
// src/
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
managed: managedServerConfigSchema.optional()
|
|
1167
|
-
}).superRefine((val, ctx) => {
|
|
1168
|
-
const hasBaseUrl = val.baseUrl !== undefined;
|
|
1169
|
-
const hasManaged = val.managed !== undefined;
|
|
1170
|
-
if (hasBaseUrl && hasManaged) {
|
|
1171
|
-
ctx.addIssue({
|
|
1172
|
-
code: "custom",
|
|
1173
|
-
message: "space-bus: roster's server block must specify exactly one of `baseUrl` or `managed`, not both"
|
|
1174
|
-
});
|
|
1175
|
-
} else if (!hasBaseUrl && !hasManaged) {
|
|
1176
|
-
ctx.addIssue({
|
|
1177
|
-
code: "custom",
|
|
1178
|
-
message: "space-bus: roster's server block must specify one of `baseUrl` (externally-managed) or `managed` (plugin-spawned) — neither was present"
|
|
1179
|
-
});
|
|
1180
|
-
}
|
|
1181
|
-
});
|
|
1182
|
-
var manifestSchema = z3.object({
|
|
1183
|
-
server: serverConfigSchema,
|
|
1184
|
-
projects: z3.array(z3.object({
|
|
1185
|
-
name: z3.string(),
|
|
1186
|
-
path: z3.string(),
|
|
1187
|
-
description: z3.string()
|
|
1188
|
-
}))
|
|
1189
|
-
});
|
|
1190
|
-
function expandHome(path) {
|
|
1191
|
-
return path.startsWith("~") ? join2(homedir2(), path.slice(1)) : path;
|
|
1192
|
-
}
|
|
1193
|
-
function resolveRosterPath(directory) {
|
|
1194
|
-
const override = process.env["SPACE_BUS_CONFIG"];
|
|
1195
|
-
if (override) {
|
|
1196
|
-
if (override.includes("://")) {
|
|
1197
|
-
throw new Error(`space-bus: SPACE_BUS_CONFIG must be an absolute path or start with ~ (got a URL: ${override})`);
|
|
1198
|
-
}
|
|
1199
|
-
const expanded = expandHome(override);
|
|
1200
|
-
if (!expanded.startsWith("/")) {
|
|
1201
|
-
throw new Error(`space-bus: SPACE_BUS_CONFIG must be an absolute path or start with ~ (got: ${override})`);
|
|
1202
|
-
}
|
|
1203
|
-
return existsSync(expanded) ? realpathSync(expanded) : expanded;
|
|
1204
|
-
}
|
|
1205
|
-
if (directory) {
|
|
1206
|
-
const candidate = join2(directory, "spacebus.json");
|
|
1207
|
-
return existsSync(candidate) ? realpathSync(candidate) : candidate;
|
|
1208
|
-
}
|
|
1209
|
-
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");
|
|
1006
|
+
// src/mcp.ts
|
|
1007
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
1008
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
1009
|
+
import { z as z4 } from "zod";
|
|
1010
|
+
|
|
1011
|
+
// src/core.ts
|
|
1012
|
+
function findProject(projects, name) {
|
|
1013
|
+
return projects.find((p) => p.name === name);
|
|
1210
1014
|
}
|
|
1211
|
-
function
|
|
1212
|
-
|
|
1213
|
-
let raw;
|
|
1214
|
-
try {
|
|
1215
|
-
raw = readFileSync2(manifestPath, "utf8");
|
|
1216
|
-
} catch (err2) {
|
|
1217
|
-
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)`);
|
|
1218
|
-
}
|
|
1219
|
-
let json;
|
|
1220
|
-
try {
|
|
1221
|
-
json = JSON.parse(raw);
|
|
1222
|
-
} catch (err2) {
|
|
1223
|
-
throw new Error(`space-bus: roster at ${manifestPath} is not valid JSON: ${err2.message}`);
|
|
1224
|
-
}
|
|
1225
|
-
const parsed = manifestSchema.safeParse(json);
|
|
1226
|
-
if (!parsed.success) {
|
|
1227
|
-
throw new Error(`space-bus: roster at ${manifestPath} failed schema validation: ${parsed.error.message}`);
|
|
1228
|
-
}
|
|
1229
|
-
if (parsed.data.server.baseUrl !== undefined) {
|
|
1230
|
-
const url = new URL(parsed.data.server.baseUrl);
|
|
1231
|
-
const hostname = url.hostname;
|
|
1232
|
-
if (!LOOPBACK_HOSTS.has(hostname)) {
|
|
1233
|
-
throw new Error(`space-bus: spacebus.json baseUrl must point to localhost (got ${hostname}) — refusing to send credentials off-machine`);
|
|
1234
|
-
}
|
|
1235
|
-
}
|
|
1236
|
-
return parsed.data;
|
|
1015
|
+
function err(error) {
|
|
1016
|
+
return { ok: false, error };
|
|
1237
1017
|
}
|
|
1238
|
-
function
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1018
|
+
function toBase64(s) {
|
|
1019
|
+
const bytes = new TextEncoder().encode(s);
|
|
1020
|
+
let bin = "";
|
|
1021
|
+
for (const b of bytes)
|
|
1022
|
+
bin += String.fromCharCode(b);
|
|
1023
|
+
return btoa(bin);
|
|
1243
1024
|
}
|
|
1244
|
-
function
|
|
1245
|
-
|
|
1246
|
-
if (!password)
|
|
1025
|
+
function authHeader(credentials) {
|
|
1026
|
+
if (!credentials.password)
|
|
1247
1027
|
return {};
|
|
1248
|
-
const username =
|
|
1249
|
-
|
|
1028
|
+
const username = credentials.username ?? "opencode";
|
|
1029
|
+
const token = toBase64(`${username}:${credentials.password}`);
|
|
1030
|
+
return { Authorization: `Basic ${token}` };
|
|
1250
1031
|
}
|
|
1251
|
-
function
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1032
|
+
async function api(baseUrl, credentials, directory, path, init) {
|
|
1033
|
+
try {
|
|
1034
|
+
const res = await fetch(`${baseUrl}${path}`, {
|
|
1035
|
+
...init,
|
|
1036
|
+
headers: {
|
|
1037
|
+
"content-type": "application/json",
|
|
1038
|
+
"x-opencode-directory": directory,
|
|
1039
|
+
...authHeader(credentials),
|
|
1040
|
+
...init?.headers
|
|
1041
|
+
},
|
|
1042
|
+
redirect: "error",
|
|
1043
|
+
signal: AbortSignal.timeout(30000)
|
|
1044
|
+
});
|
|
1045
|
+
const bodyText = await res.text().catch(() => "<unreadable body>");
|
|
1046
|
+
return { res, bodyText };
|
|
1047
|
+
} catch (e) {
|
|
1048
|
+
const message = e.message;
|
|
1260
1049
|
return {
|
|
1261
|
-
|
|
1262
|
-
|
|
1050
|
+
res: new Response(null, {
|
|
1051
|
+
status: 599,
|
|
1052
|
+
statusText: "space-bus: request failed"
|
|
1053
|
+
}),
|
|
1054
|
+
bodyText: `space-bus: request failed: ${message}`
|
|
1263
1055
|
};
|
|
1264
1056
|
}
|
|
1265
|
-
return {
|
|
1266
|
-
roster: { server: { baseUrl: manifest.server.baseUrl }, projects },
|
|
1267
|
-
credentials: getCredentials()
|
|
1268
|
-
};
|
|
1269
1057
|
}
|
|
1270
|
-
function
|
|
1271
|
-
const
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
// src/server.ts
|
|
1276
|
-
import { spawn } from "node:child_process";
|
|
1277
|
-
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
1278
|
-
import { openSync as openSync2, readFileSync as readFileSync3 } from "node:fs";
|
|
1279
|
-
import { dirname } from "node:path";
|
|
1280
|
-
var DEFAULT_READINESS_BUDGET_MS = 15000;
|
|
1281
|
-
var DEFAULT_LOCK_WAIT_BUDGET_MS = 15000;
|
|
1282
|
-
var POLL_INTERVAL_MS = 50;
|
|
1283
|
-
var MIN_PROBE_PHASE_MS = 3000;
|
|
1284
|
-
var PROBE_FETCH_TIMEOUT_MS = 2000;
|
|
1285
|
-
var STOP_GRACE_MS = 2000;
|
|
1286
|
-
var SUPERVISE_INTERVAL_MS = 5000;
|
|
1287
|
-
var SUPERVISE_FAILURE_THRESHOLD = 3;
|
|
1288
|
-
var SUPERVISE_UNHEALTHY_BUDGET_MS = 60000;
|
|
1289
|
-
function sleep2(ms) {
|
|
1290
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1291
|
-
}
|
|
1292
|
-
function readManifest(rosterPath) {
|
|
1293
|
-
const raw = readFileSync3(rosterPath, "utf8");
|
|
1294
|
-
const json = JSON.parse(raw);
|
|
1295
|
-
return manifestSchema.parse(json);
|
|
1296
|
-
}
|
|
1297
|
-
function readLogTail(logPath, maxChars = 4000) {
|
|
1058
|
+
async function fetchTurnDiffs(baseUrl, credentials, directory, sessionId) {
|
|
1059
|
+
const { res, bodyText } = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/message?limit=100`);
|
|
1060
|
+
if (!res.ok)
|
|
1061
|
+
return [];
|
|
1062
|
+
let messages;
|
|
1298
1063
|
try {
|
|
1299
|
-
|
|
1300
|
-
return content.length > maxChars ? content.slice(-maxChars) : content;
|
|
1064
|
+
messages = turnMessageListSchema.parse(JSON.parse(bodyText));
|
|
1301
1065
|
} catch {
|
|
1302
|
-
return
|
|
1303
|
-
}
|
|
1304
|
-
}
|
|
1305
|
-
function basicAuthToken(password) {
|
|
1306
|
-
return Buffer.from(`opencode:${password}`).toString("base64");
|
|
1307
|
-
}
|
|
1308
|
-
function redactSensitive(tail, password) {
|
|
1309
|
-
return tail.replaceAll(basicAuthToken(password), "[REDACTED]").replaceAll(password, "[REDACTED]");
|
|
1310
|
-
}
|
|
1311
|
-
function redactedReadinessError(rosterPath, password, reason) {
|
|
1312
|
-
const tail = redactSensitive(readLogTail(logFilePath(rosterPath)), password);
|
|
1313
|
-
return new Error(`space-bus: managed server for roster ${rosterPath} ${reason}. Log tail:
|
|
1314
|
-
${tail}`);
|
|
1315
|
-
}
|
|
1316
|
-
function isEpermError(err2) {
|
|
1317
|
-
return typeof err2 === "object" && err2 !== null && "code" in err2 && err2.code === "EPERM";
|
|
1318
|
-
}
|
|
1319
|
-
function signalGroup(pid, sig) {
|
|
1320
|
-
if (pid <= 1) {
|
|
1321
|
-
try {
|
|
1322
|
-
process.kill(pid, sig);
|
|
1323
|
-
} catch {}
|
|
1324
|
-
return false;
|
|
1066
|
+
return [];
|
|
1325
1067
|
}
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1068
|
+
const byFile = new Map;
|
|
1069
|
+
for (const m of messages) {
|
|
1070
|
+
if (m.info.role !== "user")
|
|
1071
|
+
continue;
|
|
1072
|
+
const diffs = m.info.summary?.diffs;
|
|
1073
|
+
if (!diffs || diffs.length === 0)
|
|
1074
|
+
continue;
|
|
1075
|
+
for (const d of diffs) {
|
|
1076
|
+
const key = d.file ?? `<unknown:${byFile.size}>`;
|
|
1077
|
+
byFile.set(key, d);
|
|
1332
1078
|
}
|
|
1333
1079
|
}
|
|
1334
|
-
|
|
1335
|
-
process.kill(pid, sig);
|
|
1336
|
-
} catch {}
|
|
1337
|
-
return false;
|
|
1080
|
+
return Array.from(byFile.values());
|
|
1338
1081
|
}
|
|
1339
|
-
function
|
|
1340
|
-
|
|
1341
|
-
|
|
1082
|
+
async function fetchDiffWithFallback(baseUrl, credentials, directory, sessionId) {
|
|
1083
|
+
const diffRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/diff`);
|
|
1084
|
+
let diff = [];
|
|
1342
1085
|
try {
|
|
1343
|
-
|
|
1344
|
-
return true;
|
|
1086
|
+
diff = diffRes.res.ok ? diffSchema.parse(JSON.parse(diffRes.bodyText)) : [];
|
|
1345
1087
|
} catch {
|
|
1346
|
-
|
|
1088
|
+
diff = [];
|
|
1089
|
+
}
|
|
1090
|
+
if (diff.length > 0) {
|
|
1091
|
+
return { diff, diffSource: "session" };
|
|
1347
1092
|
}
|
|
1348
|
-
}
|
|
1349
|
-
function killIdentifiedProcess(pid, identity) {
|
|
1350
1093
|
try {
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1094
|
+
const sessionRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}`);
|
|
1095
|
+
if (sessionRes.res.ok) {
|
|
1096
|
+
const parsed = sessionSummarySchema.parse(JSON.parse(sessionRes.bodyText));
|
|
1097
|
+
const summaryDiffs = parsed.summary?.diffs;
|
|
1098
|
+
if (summaryDiffs && summaryDiffs.length > 0) {
|
|
1099
|
+
return { diff: summaryDiffs, diffSource: "session" };
|
|
1100
|
+
}
|
|
1355
1101
|
}
|
|
1356
|
-
process.kill(pid, "SIGTERM");
|
|
1357
1102
|
} catch {}
|
|
1358
|
-
}
|
|
1359
|
-
function attachServer(rosterPath) {
|
|
1360
|
-
return attachLive(rosterPath);
|
|
1361
|
-
}
|
|
1362
|
-
async function waitForDiscoveryOrFail(rosterPath, budgetMs) {
|
|
1363
|
-
const deadline = Date.now() + budgetMs;
|
|
1364
|
-
const lockPath = lockFilePath(rosterPath);
|
|
1365
|
-
while (Date.now() < deadline) {
|
|
1366
|
-
const handle = attachServer(rosterPath);
|
|
1367
|
-
if (handle)
|
|
1368
|
-
return handle;
|
|
1369
|
-
const lockInfo2 = readLockFile(lockPath);
|
|
1370
|
-
const winnerAlive = lockInfo2 !== null && verifyIdentity(lockInfo2.pid, lockInfo2.startTime);
|
|
1371
|
-
if (!winnerAlive) {
|
|
1372
|
-
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`);
|
|
1373
|
-
}
|
|
1374
|
-
await sleep2(POLL_INTERVAL_MS);
|
|
1375
|
-
}
|
|
1376
|
-
const lockInfo = readLockFile(lockPath);
|
|
1377
|
-
const holder = lockInfo ? `pid ${lockInfo.pid}` : "an unknown holder";
|
|
1378
|
-
throw new Error(`space-bus: timed out after ${budgetMs}ms waiting for ${holder} to finish starting the managed server for roster ${rosterPath}`);
|
|
1379
|
-
}
|
|
1380
|
-
async function probe(baseUrl, password) {
|
|
1381
1103
|
try {
|
|
1382
|
-
const
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
}
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
if (childDied(child, pid))
|
|
1402
|
-
return null;
|
|
1403
|
-
const tail = readLogTail(logPath);
|
|
1404
|
-
const match = readinessLine.exec(tail);
|
|
1405
|
-
if (match?.[1]) {
|
|
1406
|
-
const port = Number.parseInt(match[1], 10);
|
|
1407
|
-
if (Number.isInteger(port) && port > 0 && port <= 65535) {
|
|
1408
|
-
return { port, baseUrl: `http://127.0.0.1:${port}` };
|
|
1104
|
+
const turnDiffs = await fetchTurnDiffs(baseUrl, credentials, directory, sessionId);
|
|
1105
|
+
if (turnDiffs.length > 0) {
|
|
1106
|
+
return { diff: turnDiffs, diffSource: "turns" };
|
|
1107
|
+
}
|
|
1108
|
+
} catch {}
|
|
1109
|
+
try {
|
|
1110
|
+
const vcsRes = await api(baseUrl, credentials, directory, "/vcs/status");
|
|
1111
|
+
if (vcsRes.res.ok) {
|
|
1112
|
+
const vcsStatus = vcsStatusSchema.parse(JSON.parse(vcsRes.bodyText));
|
|
1113
|
+
if (vcsStatus.length > 0) {
|
|
1114
|
+
return {
|
|
1115
|
+
diff: vcsStatus.map((v) => ({
|
|
1116
|
+
file: v.file,
|
|
1117
|
+
additions: v.additions,
|
|
1118
|
+
deletions: v.deletions,
|
|
1119
|
+
status: v.status
|
|
1120
|
+
})),
|
|
1121
|
+
diffSource: "working-tree"
|
|
1122
|
+
};
|
|
1409
1123
|
}
|
|
1410
1124
|
}
|
|
1411
|
-
|
|
1412
|
-
}
|
|
1413
|
-
return null;
|
|
1414
|
-
}
|
|
1415
|
-
async function pollAuthedEndpoint(baseUrl, password, child, pid, deadline) {
|
|
1416
|
-
while (Date.now() < deadline) {
|
|
1417
|
-
if (childDied(child, pid))
|
|
1418
|
-
return "died";
|
|
1419
|
-
const outcome = await probe(baseUrl, password);
|
|
1420
|
-
if (outcome === "ready")
|
|
1421
|
-
return "ready";
|
|
1422
|
-
if (outcome === "auth-failure")
|
|
1423
|
-
return "auth-failure";
|
|
1424
|
-
await sleep2(POLL_INTERVAL_MS);
|
|
1425
|
-
}
|
|
1426
|
-
return "timeout";
|
|
1125
|
+
} catch {}
|
|
1126
|
+
return { diff, diffSource: "session" };
|
|
1427
1127
|
}
|
|
1428
|
-
|
|
1429
|
-
const
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
const phase1Deadline = Math.max(Date.now(), deadline - phase2Reserve);
|
|
1433
|
-
const lineResult = await waitForReadinessLine(logPath, child, pid, phase1Deadline);
|
|
1434
|
-
if (lineResult === null) {
|
|
1435
|
-
const diedEarly = childDied(child, pid);
|
|
1436
|
-
killIdentifiedProcess(pid, identity);
|
|
1437
|
-
throw redactedReadinessError(rosterPath, password, diedEarly ? "exited before printing a readiness line" : `did not print a readiness line within ${budgetMs}ms`);
|
|
1128
|
+
function validateContext(context) {
|
|
1129
|
+
const parsed = busContextSchema.safeParse(context);
|
|
1130
|
+
if (!parsed.success) {
|
|
1131
|
+
return err(`space-bus: invalid context: ${parsed.error.message}`);
|
|
1438
1132
|
}
|
|
1439
|
-
const {
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
if (outcome === "died") {
|
|
1446
|
-
throw redactedReadinessError(rosterPath, password, "exited before becoming ready");
|
|
1133
|
+
const { roster, credentials } = parsed.data;
|
|
1134
|
+
let hostname;
|
|
1135
|
+
try {
|
|
1136
|
+
hostname = new URL(roster.server.baseUrl).hostname;
|
|
1137
|
+
} catch {
|
|
1138
|
+
return err("space-bus: context roster server.baseUrl is not a valid URL");
|
|
1447
1139
|
}
|
|
1448
|
-
if (
|
|
1449
|
-
|
|
1140
|
+
if (!LOOPBACK_HOSTS.has(hostname)) {
|
|
1141
|
+
return err(`space-bus: context roster server.baseUrl must point to localhost (got ${hostname}) — refusing to send credentials off-machine`);
|
|
1450
1142
|
}
|
|
1451
|
-
|
|
1143
|
+
return {
|
|
1144
|
+
ok: true,
|
|
1145
|
+
baseUrl: roster.server.baseUrl,
|
|
1146
|
+
projects: roster.projects,
|
|
1147
|
+
credentials: credentials ?? {}
|
|
1148
|
+
};
|
|
1452
1149
|
}
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
const provisional = readProvisional(rosterPath);
|
|
1456
|
-
if (!provisional)
|
|
1457
|
-
return;
|
|
1458
|
-
const discovery = readDiscovery(rosterPath);
|
|
1459
|
-
if (discovery && discovery.pid === provisional.pid && verifyIdentity(discovery.pid, discovery.identity)) {
|
|
1460
|
-
removeProvisional(rosterPath);
|
|
1461
|
-
return;
|
|
1462
|
-
}
|
|
1463
|
-
const hasIdentity = provisional.identity !== null && provisional.identity !== undefined && provisional.identity !== "";
|
|
1464
|
-
const isFresh = Date.now() - provisional.since < PROVISIONAL_FRESH_WINDOW_MS;
|
|
1465
|
-
if (hasIdentity || isFresh) {
|
|
1466
|
-
killIdentifiedProcess(provisional.pid, provisional.identity);
|
|
1467
|
-
}
|
|
1468
|
-
removeProvisional(rosterPath);
|
|
1150
|
+
function isStatusBusy(entry) {
|
|
1151
|
+
return entry?.type === "busy" || entry?.type === "retry" || false;
|
|
1469
1152
|
}
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
const requestedPort = managedConfig.port ?? 0;
|
|
1476
|
-
const logPath = logFilePath(rosterPath);
|
|
1477
|
-
const logFd = openSync2(logPath, "w", 384);
|
|
1478
|
-
let child;
|
|
1479
|
-
let pid;
|
|
1480
|
-
let spawnError;
|
|
1481
|
-
try {
|
|
1482
|
-
child = spawn(command[0], [...command.slice(1), "--port", String(requestedPort)], {
|
|
1483
|
-
cwd,
|
|
1484
|
-
detached: true,
|
|
1485
|
-
stdio: ["ignore", logFd, logFd],
|
|
1486
|
-
env: { ...process.env, OPENCODE_SERVER_PASSWORD: password }
|
|
1487
|
-
});
|
|
1488
|
-
child.on("error", (err2) => {
|
|
1489
|
-
spawnError = err2;
|
|
1490
|
-
});
|
|
1491
|
-
child.unref();
|
|
1492
|
-
pid = child.pid;
|
|
1493
|
-
} finally {
|
|
1494
|
-
closeQuietly(logFd);
|
|
1153
|
+
function resolveProjectOrErr(projects, name) {
|
|
1154
|
+
const project = findProject(projects, name);
|
|
1155
|
+
if (!project) {
|
|
1156
|
+
const valid = projects.map((p) => p.name).join(", ");
|
|
1157
|
+
return err(`space-bus: unknown project "${name}". Valid projects: ${valid}`);
|
|
1495
1158
|
}
|
|
1496
|
-
if (
|
|
1497
|
-
|
|
1159
|
+
if (!project.exists) {
|
|
1160
|
+
return err(`space-bus: project "${name}" path does not exist on disk: ${project.expandedPath}`);
|
|
1498
1161
|
}
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1162
|
+
return { ok: true, project };
|
|
1163
|
+
}
|
|
1164
|
+
async function roster(opts) {
|
|
1165
|
+
const ctx = validateContext(opts.context);
|
|
1166
|
+
if (!ctx.ok)
|
|
1167
|
+
return ctx;
|
|
1168
|
+
const { baseUrl, projects, credentials } = ctx;
|
|
1169
|
+
const results = await Promise.all(projects.map(async (p) => {
|
|
1170
|
+
if (!p.exists) {
|
|
1171
|
+
return {
|
|
1172
|
+
name: p.name,
|
|
1173
|
+
path: p.expandedPath,
|
|
1174
|
+
description: p.description,
|
|
1175
|
+
pathExists: false
|
|
1176
|
+
};
|
|
1177
|
+
}
|
|
1178
|
+
try {
|
|
1179
|
+
const [statusRes, listRes] = await Promise.all([
|
|
1180
|
+
api(baseUrl, credentials, p.expandedPath, "/session/status"),
|
|
1181
|
+
api(baseUrl, credentials, p.expandedPath, "/session?limit=101")
|
|
1182
|
+
]);
|
|
1183
|
+
if (!statusRes.res.ok || !listRes.res.ok) {
|
|
1184
|
+
return {
|
|
1185
|
+
name: p.name,
|
|
1186
|
+
path: p.expandedPath,
|
|
1187
|
+
description: p.description,
|
|
1188
|
+
pathExists: true,
|
|
1189
|
+
statusError: `status=${statusRes.res.status}/${listRes.res.status}`
|
|
1190
|
+
};
|
|
1191
|
+
}
|
|
1192
|
+
const statusMap = sessionStatusMapSchema.parse(JSON.parse(statusRes.bodyText));
|
|
1193
|
+
const sessions = sessionListSchema.parse(JSON.parse(listRes.bodyText));
|
|
1194
|
+
const busyCount = Object.values(statusMap).filter((s) => isStatusBusy(s)).length;
|
|
1195
|
+
const capped = sessions.length > 100;
|
|
1196
|
+
return {
|
|
1197
|
+
name: p.name,
|
|
1198
|
+
path: p.expandedPath,
|
|
1199
|
+
description: p.description,
|
|
1200
|
+
pathExists: true,
|
|
1201
|
+
busyCount,
|
|
1202
|
+
sessionCount: capped ? 100 : sessions.length,
|
|
1203
|
+
sessionCountCapped: capped
|
|
1204
|
+
};
|
|
1205
|
+
} catch (e) {
|
|
1206
|
+
return {
|
|
1207
|
+
name: p.name,
|
|
1208
|
+
path: p.expandedPath,
|
|
1209
|
+
description: p.description,
|
|
1210
|
+
pathExists: true,
|
|
1211
|
+
statusError: e.message
|
|
1212
|
+
};
|
|
1213
|
+
}
|
|
1214
|
+
}));
|
|
1215
|
+
return { ok: true, projects: results };
|
|
1216
|
+
}
|
|
1217
|
+
async function dispatchNew(baseUrl, credentials, projects, project, prompt, title) {
|
|
1218
|
+
const resolved = resolveProjectOrErr(projects, project);
|
|
1219
|
+
if (!resolved.ok)
|
|
1220
|
+
return resolved;
|
|
1221
|
+
const directory = resolved.project.expandedPath;
|
|
1222
|
+
const sessionTitle = title ?? `bus: ${prompt.slice(0, 60)}`;
|
|
1223
|
+
const createRes = await api(baseUrl, credentials, directory, "/session", {
|
|
1224
|
+
method: "POST",
|
|
1225
|
+
body: JSON.stringify({ title: sessionTitle })
|
|
1505
1226
|
});
|
|
1506
|
-
|
|
1507
|
-
|
|
1227
|
+
if (!createRes.res.ok) {
|
|
1228
|
+
return err(`space-bus: failed to create session in "${project}" (${createRes.res.status}): ${createRes.bodyText}`);
|
|
1229
|
+
}
|
|
1230
|
+
let session;
|
|
1508
1231
|
try {
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
if (spawnError) {
|
|
1513
|
-
clearInterval(check);
|
|
1514
|
-
reject(new Error(`space-bus: failed to spawn managed server (command: ${command.join(" ")}, cwd: ${cwd}, roster: ${rosterPath}, log: ${logPath}): ${spawnError.message}`));
|
|
1515
|
-
}
|
|
1516
|
-
}, POLL_INTERVAL_MS);
|
|
1517
|
-
readiness.finally(() => clearInterval(check)).catch(() => {});
|
|
1518
|
-
});
|
|
1519
|
-
const result2 = await Promise.race([readiness, spawnErrorWatch]);
|
|
1520
|
-
port = result2.port;
|
|
1521
|
-
baseUrl = result2.baseUrl;
|
|
1522
|
-
} finally {
|
|
1523
|
-
removeProvisional(rosterPath);
|
|
1232
|
+
session = sessionSchema.parse(JSON.parse(createRes.bodyText));
|
|
1233
|
+
} catch (e) {
|
|
1234
|
+
return err(`space-bus: unexpected /session response shape: ${e.message}`);
|
|
1524
1235
|
}
|
|
1525
|
-
const
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
pid,
|
|
1529
|
-
identity: finalIdentity,
|
|
1530
|
-
password,
|
|
1531
|
-
spawnConfig: { command, cwd, port: requestedPort },
|
|
1532
|
-
baseUrl
|
|
1236
|
+
const promptRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(session.id)}/prompt_async`, {
|
|
1237
|
+
method: "POST",
|
|
1238
|
+
body: JSON.stringify({ parts: [{ type: "text", text: prompt }] })
|
|
1533
1239
|
});
|
|
1240
|
+
if (promptRes.res.status !== 204) {
|
|
1241
|
+
return err(`space-bus: dispatch to "${project}" failed sending prompt (${promptRes.res.status}): ${promptRes.bodyText}`);
|
|
1242
|
+
}
|
|
1243
|
+
return { ok: true, sessionId: session.id, project, directory };
|
|
1244
|
+
}
|
|
1245
|
+
function toDispatchArgs(input) {
|
|
1246
|
+
if (input.sessionId !== undefined && input.sessionId === "") {
|
|
1247
|
+
return err("space-bus: sessionId must be a non-empty string");
|
|
1248
|
+
}
|
|
1249
|
+
if (!input.sessionId) {
|
|
1250
|
+
if (!input.project) {
|
|
1251
|
+
return err("space-bus: project is required when starting a new session");
|
|
1252
|
+
}
|
|
1253
|
+
return {
|
|
1254
|
+
ok: true,
|
|
1255
|
+
prompt: input.prompt,
|
|
1256
|
+
title: input.title,
|
|
1257
|
+
project: input.project
|
|
1258
|
+
};
|
|
1259
|
+
}
|
|
1534
1260
|
return {
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1261
|
+
ok: true,
|
|
1262
|
+
prompt: input.prompt,
|
|
1263
|
+
title: input.title,
|
|
1264
|
+
sessionId: input.sessionId,
|
|
1265
|
+
project: input.project
|
|
1539
1266
|
};
|
|
1540
1267
|
}
|
|
1541
|
-
async function
|
|
1542
|
-
const
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1268
|
+
async function dispatch(args, opts) {
|
|
1269
|
+
const ctx = validateContext(opts.context);
|
|
1270
|
+
if (!ctx.ok)
|
|
1271
|
+
return ctx;
|
|
1272
|
+
const { baseUrl, projects, credentials } = ctx;
|
|
1273
|
+
if (args.sessionId !== undefined && args.sessionId === "") {
|
|
1274
|
+
return err("space-bus: sessionId must be a non-empty string");
|
|
1275
|
+
}
|
|
1276
|
+
if (!args.sessionId) {
|
|
1277
|
+
if (!args.project) {
|
|
1278
|
+
return err("space-bus: project is required when starting a new session");
|
|
1279
|
+
}
|
|
1280
|
+
const r = await dispatchNew(baseUrl, credentials, projects, args.project, args.prompt, args.title);
|
|
1281
|
+
if (!r.ok)
|
|
1282
|
+
return r;
|
|
1283
|
+
return {
|
|
1284
|
+
ok: true,
|
|
1285
|
+
sessionId: r.sessionId,
|
|
1286
|
+
project: r.project,
|
|
1287
|
+
mode: "new",
|
|
1288
|
+
directory: r.directory
|
|
1289
|
+
};
|
|
1290
|
+
}
|
|
1291
|
+
const loc = await findSessionDirectory(baseUrl, credentials, projects, args.sessionId);
|
|
1292
|
+
if (!loc.ok)
|
|
1293
|
+
return loc;
|
|
1294
|
+
const { directory, project } = loc;
|
|
1295
|
+
if (args.project && args.project !== project) {
|
|
1296
|
+
return err(`space-bus: session ${args.sessionId} belongs to project "${project}", not "${args.project}" — refusing to steer the wrong session`);
|
|
1550
1297
|
}
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1298
|
+
return steerSession(baseUrl, credentials, args.sessionId, args.prompt, directory, project);
|
|
1299
|
+
}
|
|
1300
|
+
async function findSessionDirectory(baseUrl, credentials, projects, sessionId) {
|
|
1301
|
+
for (const p of projects) {
|
|
1302
|
+
if (!p.exists)
|
|
1303
|
+
continue;
|
|
1304
|
+
const { res, bodyText } = await api(baseUrl, credentials, p.expandedPath, `/session/${encodeURIComponent(sessionId)}`);
|
|
1305
|
+
if (!res.ok)
|
|
1306
|
+
continue;
|
|
1307
|
+
let session;
|
|
1308
|
+
try {
|
|
1309
|
+
session = sessionSchema.parse(JSON.parse(bodyText));
|
|
1310
|
+
} catch {
|
|
1311
|
+
continue;
|
|
1312
|
+
}
|
|
1313
|
+
const owner = session.directory ? projects.find((proj) => proj.expandedPath === session.directory) : undefined;
|
|
1314
|
+
if (owner) {
|
|
1315
|
+
return { ok: true, directory: owner.expandedPath, project: owner.name };
|
|
1316
|
+
}
|
|
1317
|
+
return err(`space-bus: session ${sessionId} belongs to ${session.directory ?? "an unknown directory"}, which is not a manifest project`);
|
|
1554
1318
|
}
|
|
1319
|
+
return err(`space-bus: no manifest project has a session with id ${sessionId}`);
|
|
1320
|
+
}
|
|
1321
|
+
function deriveSessionState(input) {
|
|
1322
|
+
if (!input.resolved)
|
|
1323
|
+
return "not_found";
|
|
1324
|
+
if (input.failed)
|
|
1325
|
+
return "failed";
|
|
1326
|
+
if (input.pendingQuestion)
|
|
1327
|
+
return "blocked";
|
|
1328
|
+
if (input.busy)
|
|
1329
|
+
return "running";
|
|
1330
|
+
return "complete";
|
|
1331
|
+
}
|
|
1332
|
+
function formatQuestionEntry(entry) {
|
|
1333
|
+
const firstQuestion = entry.questions?.[0];
|
|
1334
|
+
const text = firstQuestion?.question ?? "";
|
|
1335
|
+
const preview = text.length > 140 ? `${text.slice(0, 140)}…` : text;
|
|
1336
|
+
const options = (firstQuestion?.options ?? []).map((o) => o.label ?? "").filter((l) => l.length > 0);
|
|
1337
|
+
return { sessionId: entry.sessionID, preview, options };
|
|
1338
|
+
}
|
|
1339
|
+
async function fetchPendingQuestion(baseUrl, credentials, directory, sessionId) {
|
|
1555
1340
|
try {
|
|
1556
|
-
const
|
|
1557
|
-
if (
|
|
1558
|
-
return
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1341
|
+
const { res, bodyText } = await api(baseUrl, credentials, directory, "/question");
|
|
1342
|
+
if (!res.ok)
|
|
1343
|
+
return;
|
|
1344
|
+
const entries = pendingQuestionListSchema.parse(JSON.parse(bodyText));
|
|
1345
|
+
const entry = entries.find((e) => e.sessionID === sessionId);
|
|
1346
|
+
if (!entry)
|
|
1347
|
+
return;
|
|
1348
|
+
const { preview, options } = formatQuestionEntry(entry);
|
|
1349
|
+
return { preview, options };
|
|
1350
|
+
} catch {
|
|
1351
|
+
return;
|
|
1562
1352
|
}
|
|
1563
1353
|
}
|
|
1564
|
-
function
|
|
1565
|
-
const
|
|
1566
|
-
if (!
|
|
1567
|
-
return
|
|
1568
|
-
}
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1354
|
+
async function status(sessionId, opts) {
|
|
1355
|
+
const ctx = validateContext(opts.context);
|
|
1356
|
+
if (!ctx.ok)
|
|
1357
|
+
return ctx;
|
|
1358
|
+
const { baseUrl, projects, credentials } = ctx;
|
|
1359
|
+
const loc = await findSessionDirectory(baseUrl, credentials, projects, sessionId);
|
|
1360
|
+
if (!loc.ok)
|
|
1361
|
+
return loc;
|
|
1362
|
+
const { directory, project } = loc;
|
|
1363
|
+
const [sessionRes, statusMapRes, todoRes, diffResult, pendingQuestion] = await Promise.all([
|
|
1364
|
+
api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}`),
|
|
1365
|
+
api(baseUrl, credentials, directory, "/session/status"),
|
|
1366
|
+
api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/todo`),
|
|
1367
|
+
fetchDiffWithFallback(baseUrl, credentials, directory, sessionId),
|
|
1368
|
+
fetchPendingQuestion(baseUrl, credentials, directory, sessionId)
|
|
1369
|
+
]);
|
|
1370
|
+
if (!sessionRes.res.ok) {
|
|
1371
|
+
return err(`space-bus: failed to fetch session ${sessionId} (${sessionRes.res.status}): ${sessionRes.bodyText}`);
|
|
1575
1372
|
}
|
|
1576
|
-
let
|
|
1373
|
+
let session;
|
|
1374
|
+
let statusMap;
|
|
1375
|
+
let todos;
|
|
1577
1376
|
try {
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
configDrift = JSON.stringify(currentCommand) !== JSON.stringify(storedCommand) || currentCwd !== storedCwd || currentPort !== storedPort;
|
|
1591
|
-
}
|
|
1592
|
-
} catch {}
|
|
1377
|
+
session = sessionSchema.parse(JSON.parse(sessionRes.bodyText));
|
|
1378
|
+
statusMap = statusMapRes.res.ok ? sessionStatusMapSchema.parse(JSON.parse(statusMapRes.bodyText)) : {};
|
|
1379
|
+
todos = todoRes.res.ok ? todoSchema.parse(JSON.parse(todoRes.bodyText)) : [];
|
|
1380
|
+
} catch (e) {
|
|
1381
|
+
return err(`space-bus: unexpected response shape for session ${sessionId}: ${e.message}`);
|
|
1382
|
+
}
|
|
1383
|
+
const entry = statusMap[sessionId];
|
|
1384
|
+
const busy = isStatusBusy(entry);
|
|
1385
|
+
const { diff, diffSource } = diffResult;
|
|
1386
|
+
const additions = diff.reduce((sum, d) => sum + d.additions, 0);
|
|
1387
|
+
const deletions = diff.reduce((sum, d) => sum + d.deletions, 0);
|
|
1388
|
+
const state = deriveSessionState({ busy, pendingQuestion, resolved: true });
|
|
1593
1389
|
return {
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1390
|
+
ok: true,
|
|
1391
|
+
sessionId,
|
|
1392
|
+
project,
|
|
1393
|
+
busy,
|
|
1394
|
+
title: session.title,
|
|
1395
|
+
todos,
|
|
1396
|
+
diff: { files: diff.length, additions, deletions },
|
|
1397
|
+
diffSource,
|
|
1398
|
+
pendingQuestion,
|
|
1399
|
+
state,
|
|
1400
|
+
resultAvailable: state === "complete"
|
|
1598
1401
|
};
|
|
1599
1402
|
}
|
|
1600
|
-
async function
|
|
1601
|
-
const
|
|
1602
|
-
if (
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1403
|
+
async function steerSession(baseUrl, credentials, sessionId, message, directory, project) {
|
|
1404
|
+
const questionsRes = await api(baseUrl, credentials, directory, "/question");
|
|
1405
|
+
if (questionsRes.res.ok) {
|
|
1406
|
+
let questions;
|
|
1407
|
+
try {
|
|
1408
|
+
questions = questionListSchema.parse(JSON.parse(questionsRes.bodyText));
|
|
1409
|
+
} catch {
|
|
1410
|
+
questions = [];
|
|
1411
|
+
}
|
|
1412
|
+
const pending = questions.find((q) => q.sessionID === sessionId);
|
|
1413
|
+
if (pending) {
|
|
1414
|
+
const replyRes = await api(baseUrl, credentials, directory, `/question/${encodeURIComponent(pending.id)}/reply`, {
|
|
1415
|
+
method: "POST",
|
|
1416
|
+
body: JSON.stringify({ answers: [[message]] })
|
|
1417
|
+
});
|
|
1418
|
+
if (!replyRes.res.ok) {
|
|
1419
|
+
return err(`space-bus: failed to reply to question ${pending.id} for session ${sessionId} (${replyRes.res.status}): ${replyRes.bodyText}`);
|
|
1420
|
+
}
|
|
1421
|
+
return { ok: true, sessionId, project, mode: "question-reply" };
|
|
1617
1422
|
}
|
|
1618
|
-
removeDiscovery(rosterPath);
|
|
1619
|
-
return { stopped: true };
|
|
1620
1423
|
}
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1424
|
+
const promptRes = await api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/prompt_async`, {
|
|
1425
|
+
method: "POST",
|
|
1426
|
+
body: JSON.stringify({ parts: [{ type: "text", text: message }] })
|
|
1427
|
+
});
|
|
1428
|
+
if (promptRes.res.status !== 204) {
|
|
1429
|
+
return err(`space-bus: follow-up prompt to session ${sessionId} failed (${promptRes.res.status}): ${promptRes.bodyText}`);
|
|
1430
|
+
}
|
|
1431
|
+
return { ok: true, sessionId, project, mode: "follow-up" };
|
|
1432
|
+
}
|
|
1433
|
+
async function result(sessionId, opts) {
|
|
1434
|
+
const ctx = validateContext(opts.context);
|
|
1435
|
+
if (!ctx.ok)
|
|
1436
|
+
return ctx;
|
|
1437
|
+
const { baseUrl, projects, credentials } = ctx;
|
|
1438
|
+
const loc = await findSessionDirectory(baseUrl, credentials, projects, sessionId);
|
|
1439
|
+
if (!loc.ok)
|
|
1440
|
+
return loc;
|
|
1441
|
+
const { directory, project } = loc;
|
|
1442
|
+
const statusMapRes = await api(baseUrl, credentials, directory, "/session/status");
|
|
1443
|
+
if (statusMapRes.res.ok) {
|
|
1444
|
+
try {
|
|
1445
|
+
const statusMap = sessionStatusMapSchema.parse(JSON.parse(statusMapRes.bodyText));
|
|
1446
|
+
const entry = statusMap[sessionId];
|
|
1447
|
+
if (isStatusBusy(entry)) {
|
|
1448
|
+
return err(`space-bus: session ${sessionId} is still running, use bus_status`);
|
|
1449
|
+
}
|
|
1450
|
+
} catch {}
|
|
1451
|
+
}
|
|
1452
|
+
const [messageRes, diffResult] = await Promise.all([
|
|
1453
|
+
api(baseUrl, credentials, directory, `/session/${encodeURIComponent(sessionId)}/message?limit=50`),
|
|
1454
|
+
fetchDiffWithFallback(baseUrl, credentials, directory, sessionId)
|
|
1455
|
+
]);
|
|
1456
|
+
if (!messageRes.res.ok) {
|
|
1457
|
+
return err(`space-bus: failed to fetch messages for ${sessionId} (${messageRes.res.status}): ${messageRes.bodyText}`);
|
|
1624
1458
|
}
|
|
1459
|
+
let messages;
|
|
1625
1460
|
try {
|
|
1626
|
-
|
|
1627
|
-
} catch (
|
|
1628
|
-
|
|
1629
|
-
|
|
1461
|
+
messages = messageListSchema.parse(JSON.parse(messageRes.bodyText));
|
|
1462
|
+
} catch (e) {
|
|
1463
|
+
return err(`space-bus: unexpected response shape for session ${sessionId}: ${e.message}`);
|
|
1464
|
+
}
|
|
1465
|
+
const { diff, diffSource } = diffResult;
|
|
1466
|
+
const last = messages.filter((m) => m.info.role === "assistant").at(-1);
|
|
1467
|
+
const text = last ? last.parts.filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join(`
|
|
1468
|
+
`).trim() : "";
|
|
1469
|
+
return { ok: true, sessionId, project, text, diff, diffSource };
|
|
1470
|
+
}
|
|
1471
|
+
async function mapWithConcurrency(items, concurrency, fn) {
|
|
1472
|
+
const results = new Array(items.length);
|
|
1473
|
+
let next = 0;
|
|
1474
|
+
const limit = Math.max(1, Math.min(Number.isFinite(concurrency) ? Math.floor(concurrency) : 4, items.length));
|
|
1475
|
+
const workers = Array.from({ length: limit }, async () => {
|
|
1476
|
+
while (true) {
|
|
1477
|
+
const i = next++;
|
|
1478
|
+
if (i >= items.length)
|
|
1479
|
+
return;
|
|
1480
|
+
results[i] = await fn(items[i]);
|
|
1630
1481
|
}
|
|
1631
|
-
|
|
1632
|
-
|
|
1482
|
+
});
|
|
1483
|
+
await Promise.all(workers);
|
|
1484
|
+
return results;
|
|
1485
|
+
}
|
|
1486
|
+
var DEFAULT_WAIT_TIMEOUT_MS = 60000;
|
|
1487
|
+
var DEFAULT_WAIT_POLL_INTERVAL_MS = 1500;
|
|
1488
|
+
var DEFAULT_WAIT_CONCURRENCY = 4;
|
|
1489
|
+
var NEEDS_ATTENTION_STATES = [
|
|
1490
|
+
"complete",
|
|
1491
|
+
"blocked",
|
|
1492
|
+
"failed",
|
|
1493
|
+
"not_found"
|
|
1494
|
+
];
|
|
1495
|
+
function sleep2(ms) {
|
|
1496
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1497
|
+
}
|
|
1498
|
+
async function resolveWaitSessions(baseUrl, credentials, projects, sessionIds) {
|
|
1499
|
+
const locations = await mapWithConcurrency(sessionIds, DEFAULT_WAIT_CONCURRENCY, async (id) => {
|
|
1500
|
+
const loc = await findSessionDirectory(baseUrl, credentials, projects, id);
|
|
1501
|
+
return { id, loc };
|
|
1502
|
+
});
|
|
1503
|
+
const locationById = new Map;
|
|
1504
|
+
for (const { id, loc } of locations) {
|
|
1505
|
+
locationById.set(id, loc.ok ? { directory: loc.directory, project: loc.project } : null);
|
|
1633
1506
|
}
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1507
|
+
const groups = new Map;
|
|
1508
|
+
for (const id of sessionIds) {
|
|
1509
|
+
const loc = locationById.get(id);
|
|
1510
|
+
if (!loc)
|
|
1511
|
+
continue;
|
|
1512
|
+
const group = groups.get(loc.directory) ?? {
|
|
1513
|
+
directory: loc.directory,
|
|
1514
|
+
sessionIds: []
|
|
1515
|
+
};
|
|
1516
|
+
group.sessionIds.push(id);
|
|
1517
|
+
groups.set(loc.directory, group);
|
|
1637
1518
|
}
|
|
1638
|
-
|
|
1519
|
+
const lastKnown = new Map;
|
|
1520
|
+
for (const id of sessionIds) {
|
|
1521
|
+
const loc = locationById.get(id);
|
|
1522
|
+
lastKnown.set(id, {
|
|
1523
|
+
sessionId: id,
|
|
1524
|
+
project: loc?.project ?? "",
|
|
1525
|
+
state: loc ? "running" : "not_found",
|
|
1526
|
+
resultAvailable: false
|
|
1527
|
+
});
|
|
1528
|
+
}
|
|
1529
|
+
return { locationById, groupList: Array.from(groups.values()), lastKnown };
|
|
1639
1530
|
}
|
|
1640
|
-
async function
|
|
1641
|
-
|
|
1642
|
-
|
|
1531
|
+
async function wait(sessionIds, opts) {
|
|
1532
|
+
const ctx = validateContext(opts.context);
|
|
1533
|
+
if (!ctx.ok)
|
|
1534
|
+
return ctx;
|
|
1535
|
+
const { baseUrl, projects, credentials } = ctx;
|
|
1536
|
+
const uniqueIds = Array.from(new Set(sessionIds));
|
|
1537
|
+
if (uniqueIds.length === 0) {
|
|
1538
|
+
return { ok: true, sessions: [], waker: [], timedOut: true };
|
|
1539
|
+
}
|
|
1540
|
+
const timeoutMs = opts.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
|
|
1541
|
+
const pollIntervalMs = opts.pollIntervalMs ?? DEFAULT_WAIT_POLL_INTERVAL_MS;
|
|
1542
|
+
const deadline = Date.now() + timeoutMs;
|
|
1543
|
+
const { locationById, groupList, lastKnown } = await resolveWaitSessions(baseUrl, credentials, projects, uniqueIds);
|
|
1544
|
+
async function pollGroup(group) {
|
|
1545
|
+
const [statusRes, questionRes] = await Promise.all([
|
|
1546
|
+
api(baseUrl, credentials, group.directory, "/session/status"),
|
|
1547
|
+
api(baseUrl, credentials, group.directory, "/question")
|
|
1548
|
+
]);
|
|
1549
|
+
if (!statusRes.res.ok)
|
|
1643
1550
|
return;
|
|
1644
|
-
let
|
|
1551
|
+
let statusMap;
|
|
1645
1552
|
try {
|
|
1646
|
-
|
|
1647
|
-
groupAlive = true;
|
|
1553
|
+
statusMap = sessionStatusMapSchema.parse(JSON.parse(statusRes.bodyText));
|
|
1648
1554
|
} catch {
|
|
1649
|
-
groupAlive = false;
|
|
1650
|
-
}
|
|
1651
|
-
if (!groupAlive)
|
|
1652
|
-
return;
|
|
1653
|
-
if (!signalGroupOnly(pid, "SIGTERM"))
|
|
1654
|
-
return;
|
|
1655
|
-
if (await waitForGroupDeath(pid, STOP_GRACE_MS))
|
|
1656
1555
|
return;
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
if (failures >= tick.threshold) {
|
|
1677
|
-
return stopForHung(tick);
|
|
1556
|
+
}
|
|
1557
|
+
const pendingBySession = parsePendingQuestions(questionRes);
|
|
1558
|
+
for (const id of group.sessionIds) {
|
|
1559
|
+
const entry = statusMap[id];
|
|
1560
|
+
const busy = isStatusBusy(entry);
|
|
1561
|
+
const pendingQuestion = pendingBySession.get(id);
|
|
1562
|
+
const state = deriveSessionState({
|
|
1563
|
+
busy,
|
|
1564
|
+
pendingQuestion,
|
|
1565
|
+
resolved: true
|
|
1566
|
+
});
|
|
1567
|
+
lastKnown.set(id, {
|
|
1568
|
+
sessionId: id,
|
|
1569
|
+
project: locationById.get(id)?.project ?? "",
|
|
1570
|
+
state,
|
|
1571
|
+
resultAvailable: state === "complete",
|
|
1572
|
+
pendingQuestion
|
|
1573
|
+
});
|
|
1574
|
+
}
|
|
1678
1575
|
}
|
|
1679
|
-
|
|
1680
|
-
|
|
1576
|
+
while (true) {
|
|
1577
|
+
await mapWithConcurrency(groupList, DEFAULT_WAIT_CONCURRENCY, pollGroup);
|
|
1578
|
+
const sessions = uniqueIds.map((id) => lastKnown.get(id));
|
|
1579
|
+
const waker = sessions.filter((s) => NEEDS_ATTENTION_STATES.includes(s.state)).map((s) => s.sessionId);
|
|
1580
|
+
if (waker.length > 0) {
|
|
1581
|
+
return { ok: true, sessions, waker, timedOut: false };
|
|
1582
|
+
}
|
|
1583
|
+
if (Date.now() >= deadline) {
|
|
1584
|
+
return { ok: true, sessions, waker: [], timedOut: true };
|
|
1585
|
+
}
|
|
1586
|
+
const remaining = deadline - Date.now();
|
|
1587
|
+
await sleep2(Math.min(pollIntervalMs, Math.max(0, remaining)));
|
|
1681
1588
|
}
|
|
1682
|
-
return { kind: "tick", failures, lastReadyAt };
|
|
1683
|
-
}
|
|
1684
|
-
function makeSuperviseTick(rosterPath, handle, opts) {
|
|
1685
|
-
return {
|
|
1686
|
-
rosterPath,
|
|
1687
|
-
handle,
|
|
1688
|
-
password: handle.credentials.password ?? "",
|
|
1689
|
-
threshold: opts.threshold ?? SUPERVISE_FAILURE_THRESHOLD,
|
|
1690
|
-
unhealthyBudgetMs: opts.unhealthyBudgetMs ?? SUPERVISE_UNHEALTHY_BUDGET_MS,
|
|
1691
|
-
now: opts.now ?? Date.now,
|
|
1692
|
-
status: opts.status ?? serverStatus,
|
|
1693
|
-
probe: opts.probe ?? probe,
|
|
1694
|
-
stop: opts.stop ?? stopServer
|
|
1695
|
-
};
|
|
1696
1589
|
}
|
|
1697
|
-
|
|
1698
|
-
if (!
|
|
1699
|
-
|
|
1700
|
-
return;
|
|
1701
|
-
}
|
|
1702
|
-
let timer;
|
|
1703
|
-
const timed = new Promise((resolve) => {
|
|
1704
|
-
timer = setTimeout(resolve, intervalMs);
|
|
1705
|
-
});
|
|
1590
|
+
function parsePendingQuestions(questionRes) {
|
|
1591
|
+
if (!questionRes.res.ok)
|
|
1592
|
+
return new Map;
|
|
1706
1593
|
try {
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1594
|
+
const entries = pendingQuestionListSchema.parse(JSON.parse(questionRes.bodyText));
|
|
1595
|
+
return new Map(entries.map((e) => [e.sessionID, formatQuestionEntry(e)]));
|
|
1596
|
+
} catch {
|
|
1597
|
+
return new Map;
|
|
1711
1598
|
}
|
|
1712
1599
|
}
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
state = { failures: result2.failures, lastReadyAt: result2.lastReadyAt };
|
|
1726
|
-
if (shouldStop())
|
|
1727
|
-
return { reason: "signal" };
|
|
1728
|
-
await interruptibleSleep(doSleep, intervalMs, opts.interrupt);
|
|
1729
|
-
}
|
|
1600
|
+
|
|
1601
|
+
// src/format.ts
|
|
1602
|
+
function formatRoster(projects) {
|
|
1603
|
+
return projects.map((p) => {
|
|
1604
|
+
if (!p.pathExists)
|
|
1605
|
+
return `${p.name}: MISSING PATH (${p.path}) — ${p.description}`;
|
|
1606
|
+
if (p.statusError)
|
|
1607
|
+
return `${p.name}: status error (${p.statusError}) — ${p.description}`;
|
|
1608
|
+
const count = `${p.sessionCount ?? 0}${p.sessionCountCapped ? "+" : ""}`;
|
|
1609
|
+
return `${p.name}: ${p.busyCount ?? 0} busy / ${count} sessions — ${p.description} (${p.path})`;
|
|
1610
|
+
}).join(`
|
|
1611
|
+
`);
|
|
1730
1612
|
}
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1613
|
+
function formatDispatch(r) {
|
|
1614
|
+
switch (r.mode) {
|
|
1615
|
+
case "new":
|
|
1616
|
+
return `Dispatched. Session ${r.sessionId} in ${r.project} — report this ID.`;
|
|
1617
|
+
case "question-reply":
|
|
1618
|
+
return `Replied to pending question in session ${r.sessionId} (${r.project}).`;
|
|
1619
|
+
case "follow-up":
|
|
1620
|
+
return `Follow-up prompt sent to session ${r.sessionId} (${r.project}).`;
|
|
1737
1621
|
}
|
|
1738
|
-
return !isAlive(pid);
|
|
1739
1622
|
}
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1623
|
+
function dispatchMetadata(r) {
|
|
1624
|
+
return { sessionId: r.sessionId, project: r.project, mode: r.mode };
|
|
1625
|
+
}
|
|
1626
|
+
function formatStatus(r) {
|
|
1627
|
+
const todoLines = r.todos.length ? r.todos.map((t) => ` - [${t.status}] ${t.content} (${t.priority})`).join(`
|
|
1628
|
+
`) : " (none)";
|
|
1629
|
+
const lines = [
|
|
1630
|
+
`session: ${r.sessionId} (${r.project})`,
|
|
1631
|
+
`title: ${r.title ?? "(untitled)"}`,
|
|
1632
|
+
`busy: ${r.busy}`
|
|
1633
|
+
];
|
|
1634
|
+
if (r.pendingQuestion) {
|
|
1635
|
+
lines.push(`blocked: waiting on a question — "${r.pendingQuestion.preview}"`);
|
|
1636
|
+
if (r.pendingQuestion.options.length > 0) {
|
|
1637
|
+
lines.push(` options: ${r.pendingQuestion.options.join(" | ")}`);
|
|
1748
1638
|
}
|
|
1749
|
-
|
|
1750
|
-
while (Date.now() < deadline) {
|
|
1751
|
-
if (!groupAlive())
|
|
1752
|
-
return true;
|
|
1753
|
-
await sleep2(POLL_INTERVAL_MS);
|
|
1639
|
+
lines.push(` (answer with bus_task using sessionId)`);
|
|
1754
1640
|
}
|
|
1755
|
-
|
|
1641
|
+
lines.push(r.diffSource === "working-tree" ? `diff (working tree — repo-wide, may include changes from other sessions): ${r.diff.files} files, +${r.diff.additions}/-${r.diff.deletions}` : `diff: ${r.diff.files} files, +${r.diff.additions}/-${r.diff.deletions}`, `todos:`, todoLines);
|
|
1642
|
+
return lines.join(`
|
|
1643
|
+
`);
|
|
1644
|
+
}
|
|
1645
|
+
function formatWait(r) {
|
|
1646
|
+
const header = r.timedOut ? "timed out — no session reached a needs-attention state" : `woke on: ${r.waker.join(", ")}`;
|
|
1647
|
+
const sessionLines = r.sessions.map((s) => {
|
|
1648
|
+
const parts = [
|
|
1649
|
+
` - ${s.sessionId} (${s.project || "(unresolved)"}): ${s.state}`
|
|
1650
|
+
];
|
|
1651
|
+
if (s.pendingQuestion) {
|
|
1652
|
+
parts.push(` blocked: waiting on a question — "${s.pendingQuestion.preview}"`);
|
|
1653
|
+
if (s.pendingQuestion.options.length > 0) {
|
|
1654
|
+
parts.push(` options: ${s.pendingQuestion.options.join(" | ")}`);
|
|
1655
|
+
}
|
|
1656
|
+
parts.push(` (answer with bus_task using sessionId)`);
|
|
1657
|
+
}
|
|
1658
|
+
return parts.join(`
|
|
1659
|
+
`);
|
|
1660
|
+
});
|
|
1661
|
+
return [header, ...sessionLines].join(`
|
|
1662
|
+
`);
|
|
1663
|
+
}
|
|
1664
|
+
function formatResult(r) {
|
|
1665
|
+
const diffLines = r.diff.length ? r.diff.map((d) => ` - ${d.file ?? "(unknown)"} [${d.status ?? "?"}] +${d.additions}/-${d.deletions}`).join(`
|
|
1666
|
+
`) : " (no changes)";
|
|
1667
|
+
return [
|
|
1668
|
+
`session: ${r.sessionId} (${r.project})`,
|
|
1669
|
+
`--- reply ---`,
|
|
1670
|
+
r.text || "(empty)",
|
|
1671
|
+
r.diffSource === "working-tree" ? `--- diff (working tree — repo-wide, may include changes from other sessions) ---` : `--- diff ---`,
|
|
1672
|
+
diffLines
|
|
1673
|
+
].join(`
|
|
1674
|
+
`);
|
|
1756
1675
|
}
|
|
1757
|
-
|
|
1758
|
-
// src/mcp.ts
|
|
1759
|
-
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
1760
|
-
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
1761
|
-
import { z as z4 } from "zod";
|
|
1762
1676
|
|
|
1763
1677
|
// src/tools/bus_result.ts
|
|
1764
1678
|
import { tool } from "@opencode-ai/plugin";
|
|
@@ -1914,7 +1828,7 @@ async function mcpLoadContext() {
|
|
|
1914
1828
|
}
|
|
1915
1829
|
return loadContext();
|
|
1916
1830
|
}
|
|
1917
|
-
var version = "0.
|
|
1831
|
+
var version = "0.11.0";
|
|
1918
1832
|
var server = new McpServer({
|
|
1919
1833
|
name: "space-bus",
|
|
1920
1834
|
version
|