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