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