justconnect 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +2045 -0
- package/package.json +47 -4
- package/README.md +0 -3
package/dist/cli.js
ADDED
|
@@ -0,0 +1,2045 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/index.ts
|
|
4
|
+
import { resolve } from "node:path";
|
|
5
|
+
import { pathToFileURL } from "node:url";
|
|
6
|
+
|
|
7
|
+
// ../protocol/dist/envelope.js
|
|
8
|
+
function isObject(value) {
|
|
9
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
10
|
+
}
|
|
11
|
+
function parseEnvelope(raw) {
|
|
12
|
+
let parsed;
|
|
13
|
+
try {
|
|
14
|
+
parsed = JSON.parse(raw);
|
|
15
|
+
} catch {
|
|
16
|
+
return void 0;
|
|
17
|
+
}
|
|
18
|
+
if (!isObject(parsed) || typeof parsed.t !== "string")
|
|
19
|
+
return void 0;
|
|
20
|
+
return parsed;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// ../core/dist/state.js
|
|
24
|
+
var emptySessionState = () => ({
|
|
25
|
+
messages: [],
|
|
26
|
+
hasMore: false,
|
|
27
|
+
status: "idle",
|
|
28
|
+
permissions: [],
|
|
29
|
+
questions: [],
|
|
30
|
+
localSendStatus: {},
|
|
31
|
+
pendingSends: {}
|
|
32
|
+
});
|
|
33
|
+
var emptyClientState = () => ({
|
|
34
|
+
agent: null,
|
|
35
|
+
models: [],
|
|
36
|
+
sessions: [],
|
|
37
|
+
selectedSessionID: null,
|
|
38
|
+
sessionStates: {},
|
|
39
|
+
lastSeq: 0
|
|
40
|
+
});
|
|
41
|
+
function stateForSession(state, sessionID) {
|
|
42
|
+
return state.sessionStates[sessionID] ?? emptySessionState();
|
|
43
|
+
}
|
|
44
|
+
function toSnapshot(state) {
|
|
45
|
+
const messages = {};
|
|
46
|
+
const statuses = {};
|
|
47
|
+
for (const [id, sessionState] of Object.entries(state.sessionStates)) {
|
|
48
|
+
messages[id] = sessionState.messages;
|
|
49
|
+
statuses[id] = sessionState.status;
|
|
50
|
+
}
|
|
51
|
+
return {
|
|
52
|
+
seq: state.lastSeq,
|
|
53
|
+
agent: state.agent,
|
|
54
|
+
models: state.models,
|
|
55
|
+
sessions: state.sessions,
|
|
56
|
+
messages,
|
|
57
|
+
permissions: Object.values(state.sessionStates).flatMap((s) => s.permissions),
|
|
58
|
+
questions: Object.values(state.sessionStates).flatMap((s) => s.questions),
|
|
59
|
+
statuses,
|
|
60
|
+
...state.selectedSessionID ? { selectedSessionID: state.selectedSessionID } : {}
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// ../core/dist/reducer.js
|
|
65
|
+
function updateSession(state, sessionID, update) {
|
|
66
|
+
return {
|
|
67
|
+
...state,
|
|
68
|
+
sessionStates: {
|
|
69
|
+
...state.sessionStates,
|
|
70
|
+
[sessionID]: update(stateForSession(state, sessionID))
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
function upsertSessionList(sessions, session) {
|
|
75
|
+
const rest = sessions.filter((s) => s.id !== session.id);
|
|
76
|
+
return [session, ...rest];
|
|
77
|
+
}
|
|
78
|
+
function upsertMessageInto(view, message) {
|
|
79
|
+
const index = view.messages.findIndex((m) => m.id === message.id);
|
|
80
|
+
const localIndex = message.role === "user" ? view.messages.findIndex((m) => m.id.startsWith("local-") && m.role === "user" && view.localSendStatus[m.id]?.kind !== "failed") : -1;
|
|
81
|
+
const parts = message.parts.length > 0 ? message.parts : index >= 0 ? view.messages[index]?.parts ?? [] : [];
|
|
82
|
+
const messages = [...view.messages];
|
|
83
|
+
const target = index >= 0 ? index : localIndex;
|
|
84
|
+
if (target >= 0) {
|
|
85
|
+
const old = messages[target];
|
|
86
|
+
messages[target] = { ...message, parts };
|
|
87
|
+
const { [old.id]: _dropStatus, ...localSendStatus } = view.localSendStatus;
|
|
88
|
+
const { [old.id]: _dropPending, ...pendingSends } = view.pendingSends;
|
|
89
|
+
return { ...view, messages, localSendStatus, pendingSends };
|
|
90
|
+
}
|
|
91
|
+
messages.push({ ...message, parts });
|
|
92
|
+
return { ...view, messages };
|
|
93
|
+
}
|
|
94
|
+
function upsertPartInto(view, messageID, part) {
|
|
95
|
+
const index = view.messages.findIndex((m) => m.id === messageID);
|
|
96
|
+
if (index < 0)
|
|
97
|
+
return view;
|
|
98
|
+
const message = view.messages[index];
|
|
99
|
+
const partIndex = message.parts.findIndex((p) => p.id === part.id);
|
|
100
|
+
const parts = [...message.parts];
|
|
101
|
+
if (partIndex >= 0)
|
|
102
|
+
parts[partIndex] = part;
|
|
103
|
+
else
|
|
104
|
+
parts.push(part);
|
|
105
|
+
const messages = [...view.messages];
|
|
106
|
+
messages[index] = { ...message, parts };
|
|
107
|
+
return { ...view, messages };
|
|
108
|
+
}
|
|
109
|
+
function applyDeltaInto(view, messageID, partID2, field, delta) {
|
|
110
|
+
const index = view.messages.findIndex((m) => m.id === messageID);
|
|
111
|
+
if (index < 0)
|
|
112
|
+
return view;
|
|
113
|
+
const message = view.messages[index];
|
|
114
|
+
const partIndex = message.parts.findIndex((p) => p.id === partID2);
|
|
115
|
+
if (partIndex < 0)
|
|
116
|
+
return view;
|
|
117
|
+
const part = message.parts[partIndex];
|
|
118
|
+
if (part.type !== field)
|
|
119
|
+
return view;
|
|
120
|
+
const parts = [...message.parts];
|
|
121
|
+
parts[partIndex] = { ...part, text: part.text + delta };
|
|
122
|
+
const messages = [...view.messages];
|
|
123
|
+
messages[index] = { ...message, parts };
|
|
124
|
+
return { ...view, messages };
|
|
125
|
+
}
|
|
126
|
+
function applyEvent(state, event) {
|
|
127
|
+
const next = { ...state, lastSeq: Math.max(state.lastSeq, event.seq) };
|
|
128
|
+
switch (event.type) {
|
|
129
|
+
case "hello":
|
|
130
|
+
return {
|
|
131
|
+
...next,
|
|
132
|
+
agent: event.properties.agent,
|
|
133
|
+
models: event.properties.models ?? []
|
|
134
|
+
};
|
|
135
|
+
case "session.upsert": {
|
|
136
|
+
const session = event.properties.session;
|
|
137
|
+
const withStatus = updateSession(next, session.id, (view) => ({
|
|
138
|
+
...view,
|
|
139
|
+
status: session.status
|
|
140
|
+
}));
|
|
141
|
+
return { ...withStatus, sessions: upsertSessionList(withStatus.sessions, session) };
|
|
142
|
+
}
|
|
143
|
+
case "session.remove": {
|
|
144
|
+
const { sessionID } = event.properties;
|
|
145
|
+
const sessionStates = { ...next.sessionStates };
|
|
146
|
+
delete sessionStates[sessionID];
|
|
147
|
+
return {
|
|
148
|
+
...next,
|
|
149
|
+
sessionStates,
|
|
150
|
+
sessions: next.sessions.filter((s) => s.id !== sessionID),
|
|
151
|
+
selectedSessionID: next.selectedSessionID === sessionID ? null : next.selectedSessionID
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
case "message.upsert": {
|
|
155
|
+
const message = event.properties.message;
|
|
156
|
+
return updateSession(next, message.sessionID, (view) => upsertMessageInto(view, message));
|
|
157
|
+
}
|
|
158
|
+
case "message.remove":
|
|
159
|
+
return updateSession(next, event.properties.sessionID, (view) => {
|
|
160
|
+
const { sessionID: _sid, messageID } = event.properties;
|
|
161
|
+
const { [messageID]: _s, ...localSendStatus } = view.localSendStatus;
|
|
162
|
+
const { [messageID]: _p, ...pendingSends } = view.pendingSends;
|
|
163
|
+
return {
|
|
164
|
+
...view,
|
|
165
|
+
messages: view.messages.filter((m) => m.id !== messageID),
|
|
166
|
+
localSendStatus,
|
|
167
|
+
pendingSends
|
|
168
|
+
};
|
|
169
|
+
});
|
|
170
|
+
case "part.upsert":
|
|
171
|
+
return updateSession(next, event.properties.sessionID, (view) => upsertPartInto(view, event.properties.messageID, event.properties.part));
|
|
172
|
+
case "part.remove":
|
|
173
|
+
return updateSession(next, event.properties.sessionID, (view) => {
|
|
174
|
+
const messages = view.messages.map((m) => m.id === event.properties.messageID ? { ...m, parts: m.parts.filter((p) => p.id !== event.properties.partID) } : m);
|
|
175
|
+
return { ...view, messages };
|
|
176
|
+
});
|
|
177
|
+
case "part.delta":
|
|
178
|
+
return updateSession(next, event.properties.sessionID, (view) => {
|
|
179
|
+
const p = event.properties;
|
|
180
|
+
return applyDeltaInto(view, p.messageID, p.partID, p.field, p.delta);
|
|
181
|
+
});
|
|
182
|
+
case "permission.ask":
|
|
183
|
+
return updateSession(next, event.properties.request.sessionID, (view) => ({
|
|
184
|
+
...view,
|
|
185
|
+
permissions: view.permissions.some((p) => p.id === event.properties.request.id) ? view.permissions : [...view.permissions, event.properties.request]
|
|
186
|
+
}));
|
|
187
|
+
case "permission.reply":
|
|
188
|
+
return updateSession(next, event.properties.sessionID, (view) => ({
|
|
189
|
+
...view,
|
|
190
|
+
permissions: view.permissions.filter((p) => p.id !== event.properties.requestID)
|
|
191
|
+
}));
|
|
192
|
+
case "question.ask":
|
|
193
|
+
return updateSession(next, event.properties.request.sessionID, (view) => ({
|
|
194
|
+
...view,
|
|
195
|
+
questions: view.questions.some((q) => q.id === event.properties.request.id) ? view.questions : [...view.questions, event.properties.request]
|
|
196
|
+
}));
|
|
197
|
+
case "question.reply":
|
|
198
|
+
case "question.reject":
|
|
199
|
+
return updateSession(next, event.properties.sessionID, (view) => ({
|
|
200
|
+
...view,
|
|
201
|
+
questions: view.questions.filter((q) => q.id !== event.properties.requestID)
|
|
202
|
+
}));
|
|
203
|
+
case "status.change": {
|
|
204
|
+
const { sessionID, status, message } = event.properties;
|
|
205
|
+
return updateSession(next, sessionID, (view) => ({
|
|
206
|
+
...view,
|
|
207
|
+
status,
|
|
208
|
+
statusMessage: message,
|
|
209
|
+
error: status === "busy" || status === "idle" ? void 0 : view.error
|
|
210
|
+
}));
|
|
211
|
+
}
|
|
212
|
+
case "error": {
|
|
213
|
+
const { sessionID, message, fatal } = event.properties;
|
|
214
|
+
const withGlobal = fatal ? { ...next, globalError: message } : next;
|
|
215
|
+
if (!sessionID)
|
|
216
|
+
return withGlobal;
|
|
217
|
+
return updateSession(withGlobal, sessionID, (view) => ({
|
|
218
|
+
...view,
|
|
219
|
+
error: message,
|
|
220
|
+
status: "error"
|
|
221
|
+
}));
|
|
222
|
+
}
|
|
223
|
+
case "log":
|
|
224
|
+
return next;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
function findPermission(state, requestID) {
|
|
228
|
+
for (const [sessionID, view] of Object.entries(state.sessionStates)) {
|
|
229
|
+
const request = view.permissions.find((p) => p.id === requestID);
|
|
230
|
+
if (request)
|
|
231
|
+
return { sessionID, request };
|
|
232
|
+
}
|
|
233
|
+
return void 0;
|
|
234
|
+
}
|
|
235
|
+
function findQuestion(state, requestID) {
|
|
236
|
+
for (const [sessionID, view] of Object.entries(state.sessionStates)) {
|
|
237
|
+
const request = view.questions.find((q) => q.id === requestID);
|
|
238
|
+
if (request)
|
|
239
|
+
return { sessionID, request };
|
|
240
|
+
}
|
|
241
|
+
return void 0;
|
|
242
|
+
}
|
|
243
|
+
function selectSession(state, sessionID) {
|
|
244
|
+
return { ...state, selectedSessionID: sessionID };
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// ../core/dist/backoff.js
|
|
248
|
+
function createBackoff(options = {}) {
|
|
249
|
+
const baseMs = options.baseMs ?? 1e3;
|
|
250
|
+
const maxMs = options.maxMs ?? 3e4;
|
|
251
|
+
const jitter = options.jitter ?? 0.2;
|
|
252
|
+
let attempt = 0;
|
|
253
|
+
return {
|
|
254
|
+
get attempt() {
|
|
255
|
+
return attempt;
|
|
256
|
+
},
|
|
257
|
+
next() {
|
|
258
|
+
attempt = Math.min(attempt + 1, 20);
|
|
259
|
+
const raw = Math.min(baseMs * 2 ** (attempt - 1), maxMs);
|
|
260
|
+
return Math.round(raw * (1 - jitter + Math.random() * jitter * 2));
|
|
261
|
+
},
|
|
262
|
+
reset() {
|
|
263
|
+
attempt = 0;
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
var sleep = (ms, signal) => new Promise((resolve2, reject) => {
|
|
268
|
+
if (signal?.aborted) {
|
|
269
|
+
reject(new Error("aborted"));
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
const timer = setTimeout(() => {
|
|
273
|
+
signal?.removeEventListener("abort", onAbort);
|
|
274
|
+
resolve2();
|
|
275
|
+
}, ms);
|
|
276
|
+
function onAbort() {
|
|
277
|
+
clearTimeout(timer);
|
|
278
|
+
reject(new Error("aborted"));
|
|
279
|
+
}
|
|
280
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
// ../adapter-opencode/dist/wire.js
|
|
284
|
+
var text = (value, fallback = "") => typeof value === "string" ? value : fallback;
|
|
285
|
+
var num = (value, fallback = 0) => typeof value === "number" ? value : fallback;
|
|
286
|
+
var obj = (value) => typeof value === "object" && value !== null ? value : {};
|
|
287
|
+
var arr = (value) => Array.isArray(value) ? value : [];
|
|
288
|
+
function toSession(info) {
|
|
289
|
+
const time = obj(info.time);
|
|
290
|
+
return {
|
|
291
|
+
id: text(info.id),
|
|
292
|
+
title: text(info.title) || "Untitled",
|
|
293
|
+
...text(info.directory) ? { directory: text(info.directory) } : {},
|
|
294
|
+
status: "idle",
|
|
295
|
+
createdAt: num(time.created, Date.now()),
|
|
296
|
+
updatedAt: num(time.updated, num(time.created, Date.now())),
|
|
297
|
+
...text(info.parentID) ? { parentID: text(info.parentID) } : {}
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
function toStatus(wire) {
|
|
301
|
+
const kind = text(wire.type, "idle");
|
|
302
|
+
if (kind === "busy")
|
|
303
|
+
return { status: "busy" };
|
|
304
|
+
if (kind === "retry") {
|
|
305
|
+
return {
|
|
306
|
+
status: "retry",
|
|
307
|
+
message: text(wire.message, "Retrying\u2026"),
|
|
308
|
+
attempt: num(wire.attempt, 1),
|
|
309
|
+
next: num(wire.next)
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
return { status: "idle" };
|
|
313
|
+
}
|
|
314
|
+
function toolStatus(value) {
|
|
315
|
+
const status = text(value, "pending");
|
|
316
|
+
if (status === "completed" || status === "error" || status === "running")
|
|
317
|
+
return status;
|
|
318
|
+
return "pending";
|
|
319
|
+
}
|
|
320
|
+
function toPart(part) {
|
|
321
|
+
const id = text(part.id);
|
|
322
|
+
switch (text(part.type)) {
|
|
323
|
+
case "file":
|
|
324
|
+
return {
|
|
325
|
+
id,
|
|
326
|
+
type: "file",
|
|
327
|
+
mime: text(part.mime, "application/octet-stream"),
|
|
328
|
+
...text(part.filename) ? { filename: text(part.filename) } : {},
|
|
329
|
+
url: text(part.url)
|
|
330
|
+
};
|
|
331
|
+
case "tool": {
|
|
332
|
+
const state = obj(part.state);
|
|
333
|
+
return {
|
|
334
|
+
id,
|
|
335
|
+
type: "tool",
|
|
336
|
+
tool: text(part.tool, "tool"),
|
|
337
|
+
...text(part.callID) ? { callID: text(part.callID) } : {},
|
|
338
|
+
status: toolStatus(state.status ?? part.status),
|
|
339
|
+
...text(state.title) ? { title: text(state.title) } : {},
|
|
340
|
+
...state.input ?? part.input ? { input: state.input ?? part.input } : {},
|
|
341
|
+
...text(state.output) ? { output: text(state.output) } : {},
|
|
342
|
+
...text(state.error) ? { error: text(state.error) } : {}
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
case "reasoning":
|
|
346
|
+
return { id, type: "reasoning", text: text(part.text) };
|
|
347
|
+
case "error":
|
|
348
|
+
return { id, type: "error", message: text(part.state?.error ?? part.error, "Unknown error") };
|
|
349
|
+
default:
|
|
350
|
+
return { id, type: "text", text: text(part.text) };
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
function toMessage(envelope) {
|
|
354
|
+
const info = obj(envelope.info);
|
|
355
|
+
const model = obj(info.model);
|
|
356
|
+
const time = obj(info.time);
|
|
357
|
+
return {
|
|
358
|
+
id: text(info.id),
|
|
359
|
+
sessionID: text(info.sessionID),
|
|
360
|
+
role: ["user", "assistant", "system"].includes(text(info.role)) ? text(info.role) : "assistant",
|
|
361
|
+
parts: arr(envelope.parts).map(toPart),
|
|
362
|
+
createdAt: num(time.created, Date.now()),
|
|
363
|
+
...text(model.modelID ?? info.modelID) ? { model: text(model.modelID ?? info.modelID) } : {},
|
|
364
|
+
...text(model.providerID ?? info.providerID) ? { provider: text(model.providerID ?? info.providerID) } : {},
|
|
365
|
+
...text(info.agent) ? { agent: text(info.agent) } : {}
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
function toPermission(request) {
|
|
369
|
+
const tool = obj(request.tool);
|
|
370
|
+
return {
|
|
371
|
+
id: text(request.id),
|
|
372
|
+
sessionID: text(request.sessionID),
|
|
373
|
+
kind: text(request.permission, "other"),
|
|
374
|
+
title: `Allow ${text(request.permission, "action")}?`,
|
|
375
|
+
patterns: arr(request.patterns).map((p) => text(p)),
|
|
376
|
+
metadata: obj(request.metadata),
|
|
377
|
+
...text(tool.messageID) ? { messageID: text(tool.messageID) } : {},
|
|
378
|
+
...text(tool.callID) ? { callID: text(tool.callID) } : {},
|
|
379
|
+
createdAt: Date.now()
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
function toQuestion(request) {
|
|
383
|
+
return {
|
|
384
|
+
id: text(request.id),
|
|
385
|
+
sessionID: text(request.sessionID),
|
|
386
|
+
questions: arr(request.questions).map((q) => ({
|
|
387
|
+
question: text(q.question),
|
|
388
|
+
header: text(q.header, "Question"),
|
|
389
|
+
options: arr(q.options).map((o) => ({
|
|
390
|
+
label: text(o.label),
|
|
391
|
+
description: text(o.description) || void 0
|
|
392
|
+
})),
|
|
393
|
+
...typeof q.multiple === "boolean" ? { multiple: q.multiple } : {},
|
|
394
|
+
...typeof q.custom === "boolean" ? { custom: q.custom } : {}
|
|
395
|
+
})),
|
|
396
|
+
...obj(request.tool).messageID ? { tool: "question" } : {},
|
|
397
|
+
createdAt: Date.now()
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
function toModels(providers) {
|
|
401
|
+
const connected = Array.isArray(providers.connected) ? providers.connected.map((id) => text(id)) : [];
|
|
402
|
+
return arr(providers.all).flatMap((provider) => {
|
|
403
|
+
const providerID = text(provider.id);
|
|
404
|
+
if (connected.length > 0 && !connected.includes(providerID))
|
|
405
|
+
return [];
|
|
406
|
+
return Object.entries(obj(provider.models)).map(([id, model]) => ({
|
|
407
|
+
id: text(model.id, id),
|
|
408
|
+
name: text(model.name, id),
|
|
409
|
+
provider: providerID
|
|
410
|
+
}));
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
function unwrapEvent(payload) {
|
|
414
|
+
if (payload.payload && typeof payload.payload === "object") {
|
|
415
|
+
return obj(payload.payload);
|
|
416
|
+
}
|
|
417
|
+
return payload;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
// ../adapter-opencode/dist/wire-v2.js
|
|
421
|
+
var text2 = (value, fallback = "") => typeof value === "string" ? value : fallback;
|
|
422
|
+
var num2 = (value, fallback = 0) => typeof value === "number" ? value : fallback;
|
|
423
|
+
var obj2 = (value) => typeof value === "object" && value !== null ? value : {};
|
|
424
|
+
var arr2 = (value) => Array.isArray(value) ? value : [];
|
|
425
|
+
function toSession2(info) {
|
|
426
|
+
const time = obj2(info.time);
|
|
427
|
+
const location = obj2(info.location);
|
|
428
|
+
const created = num2(time.created, Date.now());
|
|
429
|
+
return {
|
|
430
|
+
id: text2(info.id),
|
|
431
|
+
title: text2(info.title) || "Untitled",
|
|
432
|
+
...text2(location.directory) ? { directory: text2(location.directory) } : {},
|
|
433
|
+
status: "idle",
|
|
434
|
+
createdAt: created,
|
|
435
|
+
updatedAt: num2(time.updated, created),
|
|
436
|
+
...text2(info.parentID) ? { parentID: text2(info.parentID) } : {},
|
|
437
|
+
...text2(obj2(info.model).id) ? { model: text2(obj2(info.model).id) } : {},
|
|
438
|
+
...text2(obj2(info.model).providerID) ? { provider: text2(obj2(info.model).providerID) } : {}
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
function toStatus2(wire) {
|
|
442
|
+
const kind = text2(wire.type, "idle");
|
|
443
|
+
if (kind === "busy")
|
|
444
|
+
return { status: "busy" };
|
|
445
|
+
if (kind === "retry") {
|
|
446
|
+
return {
|
|
447
|
+
status: "retry",
|
|
448
|
+
message: text2(wire.message, "Retrying\u2026"),
|
|
449
|
+
attempt: num2(wire.attempt, 1),
|
|
450
|
+
next: num2(wire.next)
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
return { status: "idle" };
|
|
454
|
+
}
|
|
455
|
+
function toolStatus2(value) {
|
|
456
|
+
const status = text2(value, "pending");
|
|
457
|
+
if (status === "completed" || status === "error" || status === "running")
|
|
458
|
+
return status;
|
|
459
|
+
return "pending";
|
|
460
|
+
}
|
|
461
|
+
function toolOutput(state) {
|
|
462
|
+
const parts = arr2(state.content).filter((part) => text2(part.type) === "text");
|
|
463
|
+
if (parts.length === 0)
|
|
464
|
+
return void 0;
|
|
465
|
+
return parts.map((part) => text2(part.text)).join("\n");
|
|
466
|
+
}
|
|
467
|
+
var partID = (messageID, kind, ordinal) => `${messageID}:${kind}:${ordinal}`;
|
|
468
|
+
function toPart2(block, messageID, ordinal) {
|
|
469
|
+
switch (text2(block.type)) {
|
|
470
|
+
case "reasoning":
|
|
471
|
+
return { id: partID(messageID, "reasoning", ordinal), type: "reasoning", text: text2(block.text) };
|
|
472
|
+
case "tool": {
|
|
473
|
+
const state = obj2(block.state);
|
|
474
|
+
const input = state.input;
|
|
475
|
+
const output = toolOutput(state);
|
|
476
|
+
const error = text2(obj2(state.error).message);
|
|
477
|
+
return {
|
|
478
|
+
id: text2(block.id, partID(messageID, "tool", ordinal)),
|
|
479
|
+
type: "tool",
|
|
480
|
+
tool: text2(block.name, "tool"),
|
|
481
|
+
...text2(block.id) ? { callID: text2(block.id) } : {},
|
|
482
|
+
status: toolStatus2(state.status),
|
|
483
|
+
...input !== void 0 ? { input } : {},
|
|
484
|
+
...output ? { output } : {},
|
|
485
|
+
...error ? { error } : {}
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
default:
|
|
489
|
+
return { id: partID(messageID, "text", ordinal), type: "text", text: text2(block.text) };
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
function userParts(raw) {
|
|
493
|
+
const id = text2(raw.id);
|
|
494
|
+
const parts = [];
|
|
495
|
+
if (text2(raw.text))
|
|
496
|
+
parts.push({ id: partID(id, "text", 0), type: "text", text: text2(raw.text) });
|
|
497
|
+
arr2(raw.files).forEach((file, index) => {
|
|
498
|
+
const source = obj2(file.source);
|
|
499
|
+
const url = text2(source.uri) || `data:${text2(file.mime, "application/octet-stream")};base64,${text2(file.data)}`;
|
|
500
|
+
parts.push({
|
|
501
|
+
id: partID(id, "file", index),
|
|
502
|
+
type: "file",
|
|
503
|
+
mime: text2(file.mime, "application/octet-stream"),
|
|
504
|
+
...text2(file.name) ? { filename: text2(file.name) } : {},
|
|
505
|
+
url
|
|
506
|
+
});
|
|
507
|
+
});
|
|
508
|
+
return parts;
|
|
509
|
+
}
|
|
510
|
+
function toMessage2(raw, sessionIDHint = "") {
|
|
511
|
+
const id = text2(raw.id);
|
|
512
|
+
const sessionID = text2(raw.sessionID) || sessionIDHint;
|
|
513
|
+
if (!id || !sessionID)
|
|
514
|
+
return null;
|
|
515
|
+
const time = obj2(raw.time);
|
|
516
|
+
const createdAt = num2(time.created, Date.now());
|
|
517
|
+
switch (text2(raw.type)) {
|
|
518
|
+
case "user":
|
|
519
|
+
return { id, sessionID, role: "user", parts: userParts(raw), createdAt };
|
|
520
|
+
case "system":
|
|
521
|
+
return { id, sessionID, role: "system", parts: [{ id: partID(id, "text", 0), type: "text", text: text2(raw.text) }], createdAt };
|
|
522
|
+
case "assistant": {
|
|
523
|
+
const model = obj2(raw.model);
|
|
524
|
+
const ordinals = { text: 0, reasoning: 0, tool: 0 };
|
|
525
|
+
return {
|
|
526
|
+
id,
|
|
527
|
+
sessionID,
|
|
528
|
+
role: "assistant",
|
|
529
|
+
parts: arr2(raw.content).map((block) => {
|
|
530
|
+
const kind = text2(block.type);
|
|
531
|
+
const key = kind === "reasoning" ? "reasoning" : kind === "tool" ? "tool" : "text";
|
|
532
|
+
return toPart2(block, id, ordinals[key]++);
|
|
533
|
+
}),
|
|
534
|
+
createdAt,
|
|
535
|
+
...text2(model.id) ? { model: text2(model.id) } : {},
|
|
536
|
+
...text2(model.providerID) ? { provider: text2(model.providerID) } : {},
|
|
537
|
+
...text2(raw.agent) ? { agent: text2(raw.agent) } : {}
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
default:
|
|
541
|
+
return null;
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
function toPermission2(request) {
|
|
545
|
+
const source = obj2(request.source);
|
|
546
|
+
const action = text2(request.action, "action");
|
|
547
|
+
return {
|
|
548
|
+
id: text2(request.id),
|
|
549
|
+
sessionID: text2(request.sessionID),
|
|
550
|
+
kind: action,
|
|
551
|
+
title: text2(request.message) || `Allow ${action}?`,
|
|
552
|
+
patterns: arr2(request.resources).map((resource) => text2(resource)),
|
|
553
|
+
metadata: obj2(request.metadata),
|
|
554
|
+
...text2(source.type) === "tool" && text2(source.messageID) ? { messageID: text2(source.messageID) } : {},
|
|
555
|
+
...text2(source.type) === "tool" && text2(source.id) ? { callID: text2(source.id) } : {},
|
|
556
|
+
createdAt: Date.now()
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
function toModels2(models) {
|
|
560
|
+
return models.filter((model) => obj2(model).enabled !== false).map((model) => {
|
|
561
|
+
const id = text2(model.modelID) || text2(model.id);
|
|
562
|
+
return { id, name: text2(model.name, id), provider: text2(model.providerID) };
|
|
563
|
+
}).filter((model) => model.id.length > 0);
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
// ../adapter-opencode/dist/service.js
|
|
567
|
+
import { readFileSync } from "node:fs";
|
|
568
|
+
import { homedir } from "node:os";
|
|
569
|
+
import { join } from "node:path";
|
|
570
|
+
var readJSON = (path) => {
|
|
571
|
+
try {
|
|
572
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
573
|
+
} catch {
|
|
574
|
+
return void 0;
|
|
575
|
+
}
|
|
576
|
+
};
|
|
577
|
+
var str = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
|
|
578
|
+
function servicePaths(env = process.env, home = homedir()) {
|
|
579
|
+
const stateBase = str(env.XDG_STATE_HOME) ?? join(home, ".local", "state");
|
|
580
|
+
const configBase = str(env.XDG_CONFIG_HOME) ?? join(home, ".config");
|
|
581
|
+
return {
|
|
582
|
+
state: join(stateBase, "opencode", "service.json"),
|
|
583
|
+
config: join(configBase, "opencode", "service.json")
|
|
584
|
+
};
|
|
585
|
+
}
|
|
586
|
+
function discoverOpenCodeServer(env = process.env, home = homedir()) {
|
|
587
|
+
const paths = servicePaths(env, home);
|
|
588
|
+
const state = readJSON(paths.state);
|
|
589
|
+
const config2 = readJSON(paths.config);
|
|
590
|
+
const password = str(state?.password) ?? str(config2?.password);
|
|
591
|
+
const url = str(state?.url);
|
|
592
|
+
if (url)
|
|
593
|
+
return { url: url.replace(/\/+$/, ""), ...password ? { password } : {}, source: "service.json" };
|
|
594
|
+
if (password) {
|
|
595
|
+
return { url: "http://127.0.0.1:4096", password, source: "service.json" };
|
|
596
|
+
}
|
|
597
|
+
return void 0;
|
|
598
|
+
}
|
|
599
|
+
function resolveServers(options = {}, env = process.env, home = homedir()) {
|
|
600
|
+
const discovered = discoverOpenCodeServer(env, home);
|
|
601
|
+
const explicitURL = options.serverURL ?? str(env.OPENCODE_SERVER);
|
|
602
|
+
const explicitPassword = options.password ?? str(env.OPENCODE_SERVER_PASSWORD);
|
|
603
|
+
const candidates = [];
|
|
604
|
+
const push = (url, source, password) => {
|
|
605
|
+
const normalized = url.replace(/\/+$/, "");
|
|
606
|
+
if (candidates.some((candidate) => candidate.url === normalized))
|
|
607
|
+
return;
|
|
608
|
+
candidates.push({ url: normalized, ...password ? { password } : {}, source });
|
|
609
|
+
};
|
|
610
|
+
if (explicitURL)
|
|
611
|
+
push(explicitURL, "flag", explicitPassword);
|
|
612
|
+
if (discovered)
|
|
613
|
+
push(discovered.url, discovered.source, explicitPassword ?? discovered.password);
|
|
614
|
+
push("http://127.0.0.1:4096", "default port", explicitPassword ?? discovered?.password);
|
|
615
|
+
return candidates;
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
// ../adapter-opencode/dist/index.js
|
|
619
|
+
var text3 = (value, fallback = "") => typeof value === "string" ? value : fallback;
|
|
620
|
+
var obj3 = (value) => typeof value === "object" && value !== null ? value : {};
|
|
621
|
+
var arr3 = (value) => Array.isArray(value) ? value : [];
|
|
622
|
+
var parseJSON = (value) => {
|
|
623
|
+
try {
|
|
624
|
+
return JSON.parse(value);
|
|
625
|
+
} catch {
|
|
626
|
+
return value;
|
|
627
|
+
}
|
|
628
|
+
};
|
|
629
|
+
var OpenCodeAdapter = class {
|
|
630
|
+
platform = "opencode";
|
|
631
|
+
name = "OpenCode";
|
|
632
|
+
capabilities = {
|
|
633
|
+
sessions: true,
|
|
634
|
+
history: true,
|
|
635
|
+
permissions: true,
|
|
636
|
+
questions: true,
|
|
637
|
+
attachments: true,
|
|
638
|
+
abort: true,
|
|
639
|
+
models: true
|
|
640
|
+
};
|
|
641
|
+
baseURL;
|
|
642
|
+
directory;
|
|
643
|
+
password;
|
|
644
|
+
candidates;
|
|
645
|
+
shutdown = new AbortController();
|
|
646
|
+
api = "v1";
|
|
647
|
+
ctx;
|
|
648
|
+
assistantMessages = /* @__PURE__ */ new Set();
|
|
649
|
+
userMessages = /* @__PURE__ */ new Set();
|
|
650
|
+
toolNames = /* @__PURE__ */ new Map();
|
|
651
|
+
constructor(options = {}) {
|
|
652
|
+
this.candidates = resolveServers(options);
|
|
653
|
+
this.baseURL = this.candidates[0].url;
|
|
654
|
+
this.password = options.password ?? process.env.OPENCODE_SERVER_PASSWORD ?? this.candidates[0].password;
|
|
655
|
+
this.directory = options.directory;
|
|
656
|
+
}
|
|
657
|
+
get prefix() {
|
|
658
|
+
return this.api === "v2" ? "/api" : "";
|
|
659
|
+
}
|
|
660
|
+
info() {
|
|
661
|
+
return {
|
|
662
|
+
platform: this.platform,
|
|
663
|
+
name: this.name,
|
|
664
|
+
capabilities: this.capabilities,
|
|
665
|
+
...this.directory ? { workspace: this.directory } : {}
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
async start(ctx) {
|
|
669
|
+
this.ctx = ctx;
|
|
670
|
+
this.api = await this.detectAPI(ctx);
|
|
671
|
+
if (this.api === "v2") {
|
|
672
|
+
this.capabilities = { ...this.capabilities, questions: false };
|
|
673
|
+
}
|
|
674
|
+
void this.stream(ctx);
|
|
675
|
+
}
|
|
676
|
+
async stop() {
|
|
677
|
+
this.shutdown.abort();
|
|
678
|
+
}
|
|
679
|
+
async detectAPI(ctx) {
|
|
680
|
+
const problems = [];
|
|
681
|
+
for (const candidate of this.candidates) {
|
|
682
|
+
const headers = { Accept: "application/json" };
|
|
683
|
+
if (candidate.password) {
|
|
684
|
+
headers.Authorization = `Basic ${Buffer.from(`opencode:${candidate.password}`).toString("base64")}`;
|
|
685
|
+
}
|
|
686
|
+
try {
|
|
687
|
+
const info = await fetch(`${candidate.url}/api/info`, {
|
|
688
|
+
headers,
|
|
689
|
+
signal: AbortSignal.timeout(4e3)
|
|
690
|
+
});
|
|
691
|
+
if (info.ok) {
|
|
692
|
+
const payload = obj3(await info.json());
|
|
693
|
+
this.use(candidate);
|
|
694
|
+
ctx.log("info", `OpenCode ${text3(payload.version, "2")} at ${candidate.url}`);
|
|
695
|
+
return "v2";
|
|
696
|
+
}
|
|
697
|
+
if (info.status === 401) {
|
|
698
|
+
problems.push(`${candidate.url} needs a password`);
|
|
699
|
+
continue;
|
|
700
|
+
}
|
|
701
|
+
const legacy = await fetch(`${candidate.url}/session`, {
|
|
702
|
+
headers,
|
|
703
|
+
signal: AbortSignal.timeout(4e3)
|
|
704
|
+
});
|
|
705
|
+
const contentType = legacy.headers.get("content-type") ?? "";
|
|
706
|
+
if (legacy.ok && contentType.includes("application/json")) {
|
|
707
|
+
this.use(candidate);
|
|
708
|
+
ctx.log("info", `OpenCode v1 at ${candidate.url}`);
|
|
709
|
+
return "v1";
|
|
710
|
+
}
|
|
711
|
+
problems.push(`${candidate.url} is not an OpenCode API`);
|
|
712
|
+
} catch {
|
|
713
|
+
problems.push(`${candidate.url} unreachable`);
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
throw new Error(`No OpenCode server found. Start OpenCode first, then run justconnect again.
|
|
717
|
+
tried: ${problems.join(", ")}`);
|
|
718
|
+
}
|
|
719
|
+
use(candidate) {
|
|
720
|
+
this.baseURL = candidate.url;
|
|
721
|
+
if (candidate.password)
|
|
722
|
+
this.password = candidate.password;
|
|
723
|
+
}
|
|
724
|
+
headers(directory) {
|
|
725
|
+
const dir = directory ?? this.directory;
|
|
726
|
+
const headers = { Accept: "application/json" };
|
|
727
|
+
if (dir)
|
|
728
|
+
headers["x-opencode-directory"] = dir;
|
|
729
|
+
if (this.password) {
|
|
730
|
+
headers.Authorization = `Basic ${Buffer.from(`opencode:${this.password}`).toString("base64")}`;
|
|
731
|
+
}
|
|
732
|
+
return headers;
|
|
733
|
+
}
|
|
734
|
+
async request(path, options = {}) {
|
|
735
|
+
const url = new URL(`${this.baseURL}${this.prefix}${path}`);
|
|
736
|
+
for (const [key, value] of Object.entries(options.query ?? {})) {
|
|
737
|
+
url.searchParams.set(key, value);
|
|
738
|
+
}
|
|
739
|
+
const headers = this.headers(options.directory);
|
|
740
|
+
if (options.accept)
|
|
741
|
+
headers.Accept = options.accept;
|
|
742
|
+
const response = await fetch(url, {
|
|
743
|
+
method: options.method ?? "GET",
|
|
744
|
+
headers,
|
|
745
|
+
...options.body !== void 0 ? { body: JSON.stringify(options.body), headers: { ...headers, "Content-Type": "application/json" } } : {},
|
|
746
|
+
signal: this.shutdown.signal
|
|
747
|
+
});
|
|
748
|
+
if (!response.ok) {
|
|
749
|
+
throw new Error(`OpenCode ${options.method ?? "GET"} ${path} \u2192 HTTP ${response.status}`);
|
|
750
|
+
}
|
|
751
|
+
if (options.accept === "text/event-stream")
|
|
752
|
+
return void 0;
|
|
753
|
+
if (response.status === 204)
|
|
754
|
+
return void 0;
|
|
755
|
+
const payload = await response.text();
|
|
756
|
+
return payload ? JSON.parse(payload) : void 0;
|
|
757
|
+
}
|
|
758
|
+
async stream(ctx) {
|
|
759
|
+
const backoff = createBackoff({ baseMs: 1e3, maxMs: 3e4 });
|
|
760
|
+
const path = this.api === "v2" ? "/api/event" : "/global/event";
|
|
761
|
+
while (!this.shutdown.signal.aborted) {
|
|
762
|
+
try {
|
|
763
|
+
const response = await fetch(`${this.baseURL}${path}`, {
|
|
764
|
+
headers: { ...this.headers(), Accept: "text/event-stream" },
|
|
765
|
+
signal: this.shutdown.signal
|
|
766
|
+
});
|
|
767
|
+
if (!response.ok)
|
|
768
|
+
throw new Error(`SSE HTTP ${response.status}`);
|
|
769
|
+
if (!response.body)
|
|
770
|
+
throw new Error("SSE response had no body");
|
|
771
|
+
backoff.reset();
|
|
772
|
+
ctx.log("info", "OpenCode event stream connected");
|
|
773
|
+
const reader = response.body.getReader();
|
|
774
|
+
const decoder = new TextDecoder();
|
|
775
|
+
let buffer = "";
|
|
776
|
+
while (!this.shutdown.signal.aborted) {
|
|
777
|
+
const { value, done } = await reader.read();
|
|
778
|
+
if (done)
|
|
779
|
+
break;
|
|
780
|
+
buffer += decoder.decode(value, { stream: true });
|
|
781
|
+
let newline;
|
|
782
|
+
while ((newline = buffer.indexOf("\n")) >= 0) {
|
|
783
|
+
const line = buffer.slice(0, newline).trim();
|
|
784
|
+
buffer = buffer.slice(newline + 1);
|
|
785
|
+
if (!line.startsWith("data:"))
|
|
786
|
+
continue;
|
|
787
|
+
const payload = line.slice(5).trim();
|
|
788
|
+
if (!payload || payload === "{}")
|
|
789
|
+
continue;
|
|
790
|
+
try {
|
|
791
|
+
const parsed = JSON.parse(payload);
|
|
792
|
+
if (this.api === "v2")
|
|
793
|
+
this.handleV2(ctx, parsed);
|
|
794
|
+
else
|
|
795
|
+
this.handle(ctx, unwrapEvent(parsed));
|
|
796
|
+
} catch (cause) {
|
|
797
|
+
ctx.log("warn", "Could not decode OpenCode event", String(cause));
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
} catch (cause) {
|
|
802
|
+
if (this.shutdown.signal.aborted)
|
|
803
|
+
break;
|
|
804
|
+
ctx.log("warn", "OpenCode event stream dropped", String(cause));
|
|
805
|
+
}
|
|
806
|
+
if (this.shutdown.signal.aborted)
|
|
807
|
+
break;
|
|
808
|
+
await sleep(backoff.next(), this.shutdown.signal).catch(() => void 0);
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
handle(ctx, event) {
|
|
812
|
+
const type = text3(event.type);
|
|
813
|
+
const p = obj3(event.properties);
|
|
814
|
+
switch (type) {
|
|
815
|
+
case "server.connected":
|
|
816
|
+
ctx.log("info", "OpenCode server connected");
|
|
817
|
+
break;
|
|
818
|
+
case "message.updated":
|
|
819
|
+
ctx.emit("message.upsert", {
|
|
820
|
+
message: toMessage({ info: p.info, parts: [] })
|
|
821
|
+
});
|
|
822
|
+
break;
|
|
823
|
+
case "message.removed":
|
|
824
|
+
ctx.emit("message.remove", {
|
|
825
|
+
sessionID: text3(p.sessionID),
|
|
826
|
+
messageID: text3(p.messageID)
|
|
827
|
+
});
|
|
828
|
+
break;
|
|
829
|
+
case "message.part.updated": {
|
|
830
|
+
const part = obj3(p.part);
|
|
831
|
+
ctx.emit("part.upsert", {
|
|
832
|
+
sessionID: text3(p.sessionID ?? part.sessionID),
|
|
833
|
+
messageID: text3(part.messageID),
|
|
834
|
+
part: toPart(part)
|
|
835
|
+
});
|
|
836
|
+
break;
|
|
837
|
+
}
|
|
838
|
+
case "message.part.removed":
|
|
839
|
+
ctx.emit("part.remove", {
|
|
840
|
+
sessionID: text3(p.sessionID),
|
|
841
|
+
messageID: text3(p.messageID),
|
|
842
|
+
partID: text3(p.partID)
|
|
843
|
+
});
|
|
844
|
+
break;
|
|
845
|
+
case "message.part.delta":
|
|
846
|
+
ctx.emit("part.delta", {
|
|
847
|
+
sessionID: text3(p.sessionID),
|
|
848
|
+
messageID: text3(p.messageID),
|
|
849
|
+
partID: text3(p.partID),
|
|
850
|
+
field: text3(p.field) === "reasoning" ? "reasoning" : "text",
|
|
851
|
+
delta: text3(p.delta)
|
|
852
|
+
});
|
|
853
|
+
break;
|
|
854
|
+
case "permission.asked":
|
|
855
|
+
ctx.emit("permission.ask", { request: toPermission(p) });
|
|
856
|
+
break;
|
|
857
|
+
case "permission.replied":
|
|
858
|
+
ctx.emit("permission.reply", {
|
|
859
|
+
sessionID: text3(p.sessionID),
|
|
860
|
+
requestID: text3(p.requestID),
|
|
861
|
+
reply: text3(p.reply)
|
|
862
|
+
});
|
|
863
|
+
break;
|
|
864
|
+
case "question.asked":
|
|
865
|
+
ctx.emit("question.ask", { request: toQuestion(p) });
|
|
866
|
+
break;
|
|
867
|
+
case "question.replied":
|
|
868
|
+
ctx.emit("question.reply", {
|
|
869
|
+
sessionID: text3(p.sessionID),
|
|
870
|
+
requestID: text3(p.requestID),
|
|
871
|
+
answers: Array.isArray(p.answers) ? p.answers : []
|
|
872
|
+
});
|
|
873
|
+
break;
|
|
874
|
+
case "question.rejected":
|
|
875
|
+
ctx.emit("question.reject", {
|
|
876
|
+
sessionID: text3(p.sessionID),
|
|
877
|
+
requestID: text3(p.requestID)
|
|
878
|
+
});
|
|
879
|
+
break;
|
|
880
|
+
case "session.created":
|
|
881
|
+
case "session.updated":
|
|
882
|
+
ctx.emit("session.upsert", { session: toSession(obj3(p.info)) });
|
|
883
|
+
break;
|
|
884
|
+
case "session.deleted":
|
|
885
|
+
ctx.emit("session.remove", { sessionID: text3(obj3(p.info).id ?? p.sessionID) });
|
|
886
|
+
break;
|
|
887
|
+
case "session.status": {
|
|
888
|
+
const status = toStatus(obj3(p.status));
|
|
889
|
+
ctx.emit("status.change", {
|
|
890
|
+
sessionID: text3(p.sessionID),
|
|
891
|
+
...status
|
|
892
|
+
});
|
|
893
|
+
break;
|
|
894
|
+
}
|
|
895
|
+
case "session.idle":
|
|
896
|
+
ctx.emit("status.change", { sessionID: text3(p.sessionID), status: "idle" });
|
|
897
|
+
break;
|
|
898
|
+
case "session.error":
|
|
899
|
+
ctx.emit("error", {
|
|
900
|
+
...p.sessionID ? { sessionID: text3(p.sessionID) } : {},
|
|
901
|
+
message: text3(obj3(p.error).data?.message ?? obj3(p.error).name, "Session error")
|
|
902
|
+
});
|
|
903
|
+
break;
|
|
904
|
+
default:
|
|
905
|
+
ctx.log("debug", `Ignored OpenCode event: ${type || "(unknown)"}`);
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
/** Announce an assistant message once, so clients can attach parts to it. */
|
|
909
|
+
assistant(sessionID, messageID) {
|
|
910
|
+
if (!sessionID || !messageID || this.assistantMessages.has(messageID))
|
|
911
|
+
return;
|
|
912
|
+
this.assistantMessages.add(messageID);
|
|
913
|
+
this.ctx?.emit("message.upsert", {
|
|
914
|
+
message: {
|
|
915
|
+
id: messageID,
|
|
916
|
+
sessionID,
|
|
917
|
+
role: "assistant",
|
|
918
|
+
parts: [],
|
|
919
|
+
createdAt: Date.now()
|
|
920
|
+
}
|
|
921
|
+
});
|
|
922
|
+
}
|
|
923
|
+
async refreshSession(ctx, sessionID) {
|
|
924
|
+
if (!sessionID)
|
|
925
|
+
return;
|
|
926
|
+
try {
|
|
927
|
+
const response = await this.request(`/session/${encodeURIComponent(sessionID)}`);
|
|
928
|
+
ctx.emit("session.upsert", { session: toSession2(obj3(response.data)) });
|
|
929
|
+
} catch (cause) {
|
|
930
|
+
ctx.log("debug", `Could not refresh session ${sessionID}`, String(cause));
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
handleV2(ctx, event) {
|
|
934
|
+
const type = text3(event.type);
|
|
935
|
+
const d = obj3(event.data);
|
|
936
|
+
const sessionID = text3(d.sessionID);
|
|
937
|
+
const messageID = text3(d.assistantMessageID);
|
|
938
|
+
const ordinal = typeof d.ordinal === "number" ? d.ordinal : 0;
|
|
939
|
+
switch (type) {
|
|
940
|
+
case "server.connected":
|
|
941
|
+
ctx.log("info", "OpenCode server connected");
|
|
942
|
+
break;
|
|
943
|
+
case "session.created":
|
|
944
|
+
void this.refreshSession(ctx, text3(d.sessionID));
|
|
945
|
+
break;
|
|
946
|
+
case "session.renamed":
|
|
947
|
+
void this.refreshSession(ctx, text3(d.sessionID));
|
|
948
|
+
break;
|
|
949
|
+
case "session.archived":
|
|
950
|
+
case "session.deleted":
|
|
951
|
+
ctx.emit("session.remove", { sessionID });
|
|
952
|
+
break;
|
|
953
|
+
case "session.status":
|
|
954
|
+
ctx.emit("status.change", { sessionID, ...toStatus2(obj3(d.status)) });
|
|
955
|
+
break;
|
|
956
|
+
case "session.idle":
|
|
957
|
+
ctx.emit("status.change", { sessionID, status: "idle" });
|
|
958
|
+
break;
|
|
959
|
+
case "session.execution.started":
|
|
960
|
+
ctx.emit("status.change", { sessionID, status: "busy" });
|
|
961
|
+
break;
|
|
962
|
+
// A turn ends with execution.succeeded/interrupted/failed; session.idle
|
|
963
|
+
// exists too, but the v2 server only emits it on some transitions.
|
|
964
|
+
case "session.execution.succeeded":
|
|
965
|
+
case "session.execution.interrupted":
|
|
966
|
+
ctx.emit("status.change", { sessionID, status: "idle" });
|
|
967
|
+
break;
|
|
968
|
+
case "session.execution.failed":
|
|
969
|
+
ctx.emit("status.change", { sessionID, status: "idle" });
|
|
970
|
+
ctx.emit("error", {
|
|
971
|
+
...sessionID ? { sessionID } : {},
|
|
972
|
+
message: text3(obj3(d.error).message, "Session error")
|
|
973
|
+
});
|
|
974
|
+
break;
|
|
975
|
+
case "session.text.started":
|
|
976
|
+
this.assistant(sessionID, messageID);
|
|
977
|
+
ctx.emit("part.upsert", {
|
|
978
|
+
sessionID,
|
|
979
|
+
messageID,
|
|
980
|
+
part: { id: partID(messageID, "text", ordinal), type: "text", text: "" }
|
|
981
|
+
});
|
|
982
|
+
break;
|
|
983
|
+
case "session.text.delta":
|
|
984
|
+
this.assistant(sessionID, messageID);
|
|
985
|
+
ctx.emit("part.delta", {
|
|
986
|
+
sessionID,
|
|
987
|
+
messageID,
|
|
988
|
+
partID: partID(messageID, "text", ordinal),
|
|
989
|
+
field: "text",
|
|
990
|
+
delta: text3(d.delta)
|
|
991
|
+
});
|
|
992
|
+
break;
|
|
993
|
+
case "session.text.ended":
|
|
994
|
+
this.assistant(sessionID, messageID);
|
|
995
|
+
ctx.emit("part.upsert", {
|
|
996
|
+
sessionID,
|
|
997
|
+
messageID,
|
|
998
|
+
part: { id: partID(messageID, "text", ordinal), type: "text", text: text3(d.text) }
|
|
999
|
+
});
|
|
1000
|
+
break;
|
|
1001
|
+
case "session.reasoning.started":
|
|
1002
|
+
this.assistant(sessionID, messageID);
|
|
1003
|
+
ctx.emit("part.upsert", {
|
|
1004
|
+
sessionID,
|
|
1005
|
+
messageID,
|
|
1006
|
+
part: { id: partID(messageID, "reasoning", ordinal), type: "reasoning", text: "" }
|
|
1007
|
+
});
|
|
1008
|
+
break;
|
|
1009
|
+
case "session.reasoning.delta":
|
|
1010
|
+
this.assistant(sessionID, messageID);
|
|
1011
|
+
ctx.emit("part.delta", {
|
|
1012
|
+
sessionID,
|
|
1013
|
+
messageID,
|
|
1014
|
+
partID: partID(messageID, "reasoning", ordinal),
|
|
1015
|
+
field: "reasoning",
|
|
1016
|
+
delta: text3(d.delta)
|
|
1017
|
+
});
|
|
1018
|
+
break;
|
|
1019
|
+
case "session.reasoning.ended":
|
|
1020
|
+
this.assistant(sessionID, messageID);
|
|
1021
|
+
ctx.emit("part.upsert", {
|
|
1022
|
+
sessionID,
|
|
1023
|
+
messageID,
|
|
1024
|
+
part: { id: partID(messageID, "reasoning", ordinal), type: "reasoning", text: text3(d.text) }
|
|
1025
|
+
});
|
|
1026
|
+
break;
|
|
1027
|
+
case "session.tool.input.started":
|
|
1028
|
+
this.assistant(sessionID, messageID);
|
|
1029
|
+
ctx.emit("part.upsert", {
|
|
1030
|
+
sessionID,
|
|
1031
|
+
messageID,
|
|
1032
|
+
part: {
|
|
1033
|
+
id: text3(d.id),
|
|
1034
|
+
type: "tool",
|
|
1035
|
+
tool: text3(d.name, "tool"),
|
|
1036
|
+
callID: text3(d.id),
|
|
1037
|
+
status: "pending"
|
|
1038
|
+
}
|
|
1039
|
+
});
|
|
1040
|
+
break;
|
|
1041
|
+
case "session.tool.input.ended": {
|
|
1042
|
+
this.assistant(sessionID, messageID);
|
|
1043
|
+
ctx.emit("part.upsert", {
|
|
1044
|
+
sessionID,
|
|
1045
|
+
messageID,
|
|
1046
|
+
part: {
|
|
1047
|
+
id: text3(d.id),
|
|
1048
|
+
type: "tool",
|
|
1049
|
+
tool: this.toolNames.get(text3(d.id)) ?? "tool",
|
|
1050
|
+
callID: text3(d.id),
|
|
1051
|
+
status: "pending",
|
|
1052
|
+
input: parseJSON(text3(d.text))
|
|
1053
|
+
}
|
|
1054
|
+
});
|
|
1055
|
+
break;
|
|
1056
|
+
}
|
|
1057
|
+
case "session.tool.called":
|
|
1058
|
+
this.assistant(sessionID, messageID);
|
|
1059
|
+
ctx.emit("part.upsert", {
|
|
1060
|
+
sessionID,
|
|
1061
|
+
messageID,
|
|
1062
|
+
part: {
|
|
1063
|
+
id: text3(d.id),
|
|
1064
|
+
type: "tool",
|
|
1065
|
+
tool: this.toolNames.get(text3(d.id)) ?? "tool",
|
|
1066
|
+
callID: text3(d.id),
|
|
1067
|
+
status: "running",
|
|
1068
|
+
input: d.input
|
|
1069
|
+
}
|
|
1070
|
+
});
|
|
1071
|
+
break;
|
|
1072
|
+
case "session.tool.success": {
|
|
1073
|
+
this.assistant(sessionID, messageID);
|
|
1074
|
+
const output = arr3(d.content).filter((part) => text3(part.type) === "text").map((part) => text3(part.text)).join("\n");
|
|
1075
|
+
ctx.emit("part.upsert", {
|
|
1076
|
+
sessionID,
|
|
1077
|
+
messageID,
|
|
1078
|
+
part: {
|
|
1079
|
+
id: text3(d.id),
|
|
1080
|
+
type: "tool",
|
|
1081
|
+
tool: this.toolNames.get(text3(d.id)) ?? "tool",
|
|
1082
|
+
callID: text3(d.id),
|
|
1083
|
+
status: "completed",
|
|
1084
|
+
...output ? { output } : {}
|
|
1085
|
+
}
|
|
1086
|
+
});
|
|
1087
|
+
break;
|
|
1088
|
+
}
|
|
1089
|
+
case "session.tool.failed":
|
|
1090
|
+
this.assistant(sessionID, messageID);
|
|
1091
|
+
ctx.emit("part.upsert", {
|
|
1092
|
+
sessionID,
|
|
1093
|
+
messageID,
|
|
1094
|
+
part: {
|
|
1095
|
+
id: text3(d.id),
|
|
1096
|
+
type: "tool",
|
|
1097
|
+
tool: this.toolNames.get(text3(d.id)) ?? "tool",
|
|
1098
|
+
callID: text3(d.id),
|
|
1099
|
+
status: "error",
|
|
1100
|
+
error: text3(obj3(d.error).message, "Tool failed")
|
|
1101
|
+
}
|
|
1102
|
+
});
|
|
1103
|
+
break;
|
|
1104
|
+
case "session.message.content.updated": {
|
|
1105
|
+
if (this.userMessages.has(text3(d.messageID)))
|
|
1106
|
+
break;
|
|
1107
|
+
if (arr3(d.content).length === 0)
|
|
1108
|
+
break;
|
|
1109
|
+
const message = toMessage2({ ...d, id: text3(d.messageID), sessionID, type: "assistant" });
|
|
1110
|
+
if (message) {
|
|
1111
|
+
this.assistantMessages.add(message.id);
|
|
1112
|
+
ctx.emit("message.upsert", { message });
|
|
1113
|
+
}
|
|
1114
|
+
break;
|
|
1115
|
+
}
|
|
1116
|
+
case "session.inbox.enqueued": {
|
|
1117
|
+
const item = obj3(d.item);
|
|
1118
|
+
if (text3(item.type) !== "user")
|
|
1119
|
+
break;
|
|
1120
|
+
const payload = obj3(item.payload);
|
|
1121
|
+
const inboxMessageID = text3(d.inboxID);
|
|
1122
|
+
this.userMessages.add(inboxMessageID);
|
|
1123
|
+
const files = arr3(payload.files).map((file, index) => {
|
|
1124
|
+
const source = obj3(file.source);
|
|
1125
|
+
return {
|
|
1126
|
+
id: partID(inboxMessageID, "file", index),
|
|
1127
|
+
type: "file",
|
|
1128
|
+
mime: text3(file.mime, "application/octet-stream"),
|
|
1129
|
+
...text3(file.name) ? { filename: text3(file.name) } : {},
|
|
1130
|
+
url: text3(source.uri) || `data:${text3(file.mime, "application/octet-stream")};base64,${text3(file.data)}`
|
|
1131
|
+
};
|
|
1132
|
+
});
|
|
1133
|
+
this.ctx?.emit("message.upsert", {
|
|
1134
|
+
message: {
|
|
1135
|
+
id: inboxMessageID,
|
|
1136
|
+
sessionID,
|
|
1137
|
+
role: "user",
|
|
1138
|
+
parts: [
|
|
1139
|
+
...files,
|
|
1140
|
+
...text3(payload.text) ? [{ id: partID(inboxMessageID, "text", 0), type: "text", text: text3(payload.text) }] : []
|
|
1141
|
+
],
|
|
1142
|
+
createdAt: Date.now()
|
|
1143
|
+
}
|
|
1144
|
+
});
|
|
1145
|
+
break;
|
|
1146
|
+
}
|
|
1147
|
+
case "permission.asked":
|
|
1148
|
+
ctx.emit("permission.ask", { request: toPermission2(d) });
|
|
1149
|
+
break;
|
|
1150
|
+
case "permission.replied":
|
|
1151
|
+
ctx.emit("permission.reply", {
|
|
1152
|
+
sessionID,
|
|
1153
|
+
requestID: text3(d.requestID),
|
|
1154
|
+
reply: text3(d.reply)
|
|
1155
|
+
});
|
|
1156
|
+
break;
|
|
1157
|
+
case "form.created":
|
|
1158
|
+
case "form.replied":
|
|
1159
|
+
case "form.cancelled":
|
|
1160
|
+
ctx.log("debug", `Ignored OpenCode form event: ${type}`);
|
|
1161
|
+
break;
|
|
1162
|
+
default:
|
|
1163
|
+
ctx.log("debug", `Ignored OpenCode event: ${type || "(unknown)"}`);
|
|
1164
|
+
}
|
|
1165
|
+
if (type === "session.tool.input.started")
|
|
1166
|
+
this.toolNames.set(text3(d.id), text3(d.name, "tool"));
|
|
1167
|
+
}
|
|
1168
|
+
query(directory) {
|
|
1169
|
+
const dir = directory ?? this.directory;
|
|
1170
|
+
return this.api === "v2" && dir ? { directory: dir } : {};
|
|
1171
|
+
}
|
|
1172
|
+
async listSessions() {
|
|
1173
|
+
if (this.api === "v2") {
|
|
1174
|
+
const response = await this.request("/session", { query: this.query() });
|
|
1175
|
+
return arr3(response.data).map(toSession2);
|
|
1176
|
+
}
|
|
1177
|
+
const sessions = await this.request("/session");
|
|
1178
|
+
return sessions.map(toSession);
|
|
1179
|
+
}
|
|
1180
|
+
async createSession(input) {
|
|
1181
|
+
if (this.api === "v2") {
|
|
1182
|
+
const directory = input.directory ?? this.directory;
|
|
1183
|
+
const response = await this.request("/session", {
|
|
1184
|
+
method: "POST",
|
|
1185
|
+
body: {
|
|
1186
|
+
...input.title ? { title: input.title } : {},
|
|
1187
|
+
...directory ? { location: { directory } } : {}
|
|
1188
|
+
}
|
|
1189
|
+
});
|
|
1190
|
+
return toSession2(obj3(response.data));
|
|
1191
|
+
}
|
|
1192
|
+
const created = await this.request("/session", {
|
|
1193
|
+
method: "POST",
|
|
1194
|
+
body: { ...input.title ? { title: input.title } : {} },
|
|
1195
|
+
...input.directory ? { directory: input.directory } : {}
|
|
1196
|
+
});
|
|
1197
|
+
return toSession(created);
|
|
1198
|
+
}
|
|
1199
|
+
async archiveSession(sessionID) {
|
|
1200
|
+
if (this.api === "v2") {
|
|
1201
|
+
await this.request(`/session/${encodeURIComponent(sessionID)}`, {
|
|
1202
|
+
method: "PATCH",
|
|
1203
|
+
body: { archived: true }
|
|
1204
|
+
});
|
|
1205
|
+
return;
|
|
1206
|
+
}
|
|
1207
|
+
await this.request(`/session/${encodeURIComponent(sessionID)}`, {
|
|
1208
|
+
method: "PATCH",
|
|
1209
|
+
body: { time: { archived: Date.now() } }
|
|
1210
|
+
});
|
|
1211
|
+
}
|
|
1212
|
+
async listMessages(sessionID) {
|
|
1213
|
+
if (this.api === "v2") {
|
|
1214
|
+
const response = await this.request(`/session/${encodeURIComponent(sessionID)}/message`);
|
|
1215
|
+
return arr3(response.data).reverse().map((message) => toMessage2(message, sessionID)).filter((message) => message !== null);
|
|
1216
|
+
}
|
|
1217
|
+
const envelopes = await this.request(`/session/${encodeURIComponent(sessionID)}/message`);
|
|
1218
|
+
return envelopes.map(toMessage);
|
|
1219
|
+
}
|
|
1220
|
+
async listModels() {
|
|
1221
|
+
if (this.api === "v2") {
|
|
1222
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
1223
|
+
const response = await this.request("/model", { query: this.query() });
|
|
1224
|
+
const models = toModels2(arr3(response.data));
|
|
1225
|
+
if (models.length > 0 || attempt > 0)
|
|
1226
|
+
return models;
|
|
1227
|
+
await new Promise((resolve2) => setTimeout(resolve2, 500));
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
return toModels(await this.request("/provider"));
|
|
1231
|
+
}
|
|
1232
|
+
async sendMessage(input) {
|
|
1233
|
+
if (this.api === "v2") {
|
|
1234
|
+
if (input.model && input.provider) {
|
|
1235
|
+
await this.request(`/session/${encodeURIComponent(input.sessionID)}/model`, {
|
|
1236
|
+
method: "POST",
|
|
1237
|
+
body: { model: { id: input.model, providerID: input.provider } }
|
|
1238
|
+
});
|
|
1239
|
+
}
|
|
1240
|
+
const files = input.attachments.map((attachment) => ({
|
|
1241
|
+
uri: attachment.url,
|
|
1242
|
+
...attachment.filename ? { name: attachment.filename } : {},
|
|
1243
|
+
...attachment.mime ? { mime: attachment.mime } : {}
|
|
1244
|
+
}));
|
|
1245
|
+
const result2 = await this.request(`/session/${encodeURIComponent(input.sessionID)}/prompt`, {
|
|
1246
|
+
method: "POST",
|
|
1247
|
+
body: { text: input.text, ...files.length > 0 ? { files } : {} }
|
|
1248
|
+
});
|
|
1249
|
+
const inbox = obj3(result2.data);
|
|
1250
|
+
const id = text3(inbox.id) || `local-${Date.now().toString(36)}`;
|
|
1251
|
+
this.userMessages.add(id);
|
|
1252
|
+
const createdAt = typeof obj3(inbox.time).created === "number" ? obj3(inbox.time).created : Date.now();
|
|
1253
|
+
const parts2 = [
|
|
1254
|
+
...input.attachments,
|
|
1255
|
+
...input.text ? [{ id: partID(id, "text", 0), type: "text", text: input.text }] : []
|
|
1256
|
+
];
|
|
1257
|
+
return {
|
|
1258
|
+
id,
|
|
1259
|
+
sessionID: text3(inbox.sessionID) || input.sessionID,
|
|
1260
|
+
role: "user",
|
|
1261
|
+
parts: parts2,
|
|
1262
|
+
createdAt,
|
|
1263
|
+
...input.model ? { model: input.model } : {},
|
|
1264
|
+
...input.provider ? { provider: input.provider } : {}
|
|
1265
|
+
};
|
|
1266
|
+
}
|
|
1267
|
+
const parts = input.attachments.map((attachment) => ({
|
|
1268
|
+
type: "file",
|
|
1269
|
+
mime: attachment.mime,
|
|
1270
|
+
...attachment.filename ? { filename: attachment.filename } : {},
|
|
1271
|
+
url: attachment.url
|
|
1272
|
+
}));
|
|
1273
|
+
if (input.text)
|
|
1274
|
+
parts.push({ type: "text", text: input.text });
|
|
1275
|
+
const model = input.model && input.provider ? { providerID: input.provider, modelID: input.model } : void 0;
|
|
1276
|
+
const result = await this.request(`/session/${encodeURIComponent(input.sessionID)}/message`, {
|
|
1277
|
+
method: "POST",
|
|
1278
|
+
body: { parts, ...model ? { model } : {} },
|
|
1279
|
+
...input.directory ? { directory: input.directory } : {}
|
|
1280
|
+
});
|
|
1281
|
+
return toMessage(result);
|
|
1282
|
+
}
|
|
1283
|
+
async abort(sessionID) {
|
|
1284
|
+
const path = this.api === "v2" ? "interrupt" : "abort";
|
|
1285
|
+
await this.request(`/session/${encodeURIComponent(sessionID)}/${path}`, { method: "POST" });
|
|
1286
|
+
}
|
|
1287
|
+
async replyPermission(request, reply) {
|
|
1288
|
+
if (this.api === "v2") {
|
|
1289
|
+
await this.request(`/session/${encodeURIComponent(request.sessionID)}/permission/${encodeURIComponent(request.id)}/reply`, { method: "POST", body: { decision: reply } });
|
|
1290
|
+
return;
|
|
1291
|
+
}
|
|
1292
|
+
await this.request(`/permission/${encodeURIComponent(request.id)}/reply`, {
|
|
1293
|
+
method: "POST",
|
|
1294
|
+
body: { reply }
|
|
1295
|
+
});
|
|
1296
|
+
}
|
|
1297
|
+
async replyQuestion(request, answers) {
|
|
1298
|
+
if (this.api === "v2")
|
|
1299
|
+
throw new Error("OpenCode v2 forms are not supported yet.");
|
|
1300
|
+
await this.request(`/question/${encodeURIComponent(request.id)}/reply`, {
|
|
1301
|
+
method: "POST",
|
|
1302
|
+
body: { answers }
|
|
1303
|
+
});
|
|
1304
|
+
}
|
|
1305
|
+
async rejectQuestion(request) {
|
|
1306
|
+
if (this.api === "v2")
|
|
1307
|
+
throw new Error("OpenCode v2 forms are not supported yet.");
|
|
1308
|
+
await this.request(`/question/${encodeURIComponent(request.id)}/reject`, {
|
|
1309
|
+
method: "POST",
|
|
1310
|
+
body: {}
|
|
1311
|
+
});
|
|
1312
|
+
}
|
|
1313
|
+
};
|
|
1314
|
+
var dist_default = OpenCodeAdapter;
|
|
1315
|
+
|
|
1316
|
+
// ../adapter-cli/dist/index.js
|
|
1317
|
+
import { spawn } from "node:child_process";
|
|
1318
|
+
import { randomUUID } from "node:crypto";
|
|
1319
|
+
|
|
1320
|
+
// ../adapter-cli/dist/presets.js
|
|
1321
|
+
var str2 = (value, fallback = "") => typeof value === "string" ? value : fallback;
|
|
1322
|
+
var obj4 = (value) => typeof value === "object" && value !== null ? value : {};
|
|
1323
|
+
function toolDelta(item) {
|
|
1324
|
+
const id = str2(item.id ?? item.callID ?? item.tool_call_id);
|
|
1325
|
+
if (!id)
|
|
1326
|
+
return [];
|
|
1327
|
+
const rawStatus = str2(item.status, "in_progress");
|
|
1328
|
+
const status = rawStatus === "completed" || rawStatus === "ok" ? "completed" : rawStatus === "failed" || rawStatus === "error" ? "error" : "running";
|
|
1329
|
+
const delta = {
|
|
1330
|
+
kind: "tool",
|
|
1331
|
+
id,
|
|
1332
|
+
tool: str2(item.type ?? item.name ?? item.command, "tool"),
|
|
1333
|
+
status
|
|
1334
|
+
};
|
|
1335
|
+
const title = str2(item.title ?? item.command ?? item.description);
|
|
1336
|
+
if (title)
|
|
1337
|
+
delta.title = title;
|
|
1338
|
+
const output = str2(item.output ?? item.result ?? item.message);
|
|
1339
|
+
if (output)
|
|
1340
|
+
delta.output = output;
|
|
1341
|
+
return [delta];
|
|
1342
|
+
}
|
|
1343
|
+
var codexPreset = {
|
|
1344
|
+
name: "Codex CLI",
|
|
1345
|
+
command: "codex",
|
|
1346
|
+
args: (prompt) => ["exec", "--json", "--skip-git-repo-check", prompt],
|
|
1347
|
+
parseMode: "jsonl",
|
|
1348
|
+
inputMode: "arg",
|
|
1349
|
+
mapJson: (value) => {
|
|
1350
|
+
const type = str2(value.type);
|
|
1351
|
+
const item = obj4(value.item);
|
|
1352
|
+
if (type === "item.completed" || type === "item.updated") {
|
|
1353
|
+
const itemType = str2(item.type);
|
|
1354
|
+
if (itemType === "agent_message" || itemType === "assistant") {
|
|
1355
|
+
const content = str2(item.text ?? item.content);
|
|
1356
|
+
return content ? [{ kind: "text", text: `${content}
|
|
1357
|
+
` }] : [];
|
|
1358
|
+
}
|
|
1359
|
+
if (itemType === "command_execution" || itemType === "tool_call")
|
|
1360
|
+
return toolDelta(item);
|
|
1361
|
+
}
|
|
1362
|
+
if (type === "turn.failed") {
|
|
1363
|
+
return [{ kind: "text", text: `
|
|
1364
|
+
[error] ${str2(obj4(value.error).message, "Codex turn failed")}
|
|
1365
|
+
` }];
|
|
1366
|
+
}
|
|
1367
|
+
return [];
|
|
1368
|
+
}
|
|
1369
|
+
};
|
|
1370
|
+
var aiderPreset = {
|
|
1371
|
+
name: "Aider",
|
|
1372
|
+
command: "aider",
|
|
1373
|
+
args: (prompt) => ["--no-auto-commits", "--message", prompt],
|
|
1374
|
+
parseMode: "text",
|
|
1375
|
+
inputMode: "arg"
|
|
1376
|
+
};
|
|
1377
|
+
var geminiPreset = {
|
|
1378
|
+
name: "Gemini CLI",
|
|
1379
|
+
command: "gemini",
|
|
1380
|
+
args: (prompt) => ["--prompt", prompt, "--output-format", "stream-json"],
|
|
1381
|
+
parseMode: "jsonl",
|
|
1382
|
+
inputMode: "arg",
|
|
1383
|
+
mapJson: (value) => {
|
|
1384
|
+
const type = str2(value.type);
|
|
1385
|
+
if (type === "content" || type === "assistant" || type === "text") {
|
|
1386
|
+
const content = str2(value.text ?? value.content ?? value.delta);
|
|
1387
|
+
return content ? [{ kind: "text", text: content }] : [];
|
|
1388
|
+
}
|
|
1389
|
+
if (type === "tool_call" || type === "tool_result")
|
|
1390
|
+
return toolDelta(obj4(value.tool ?? value));
|
|
1391
|
+
return [];
|
|
1392
|
+
}
|
|
1393
|
+
};
|
|
1394
|
+
var genericPreset = {
|
|
1395
|
+
name: "Generic CLI",
|
|
1396
|
+
command: "cat",
|
|
1397
|
+
args: () => [],
|
|
1398
|
+
parseMode: "text",
|
|
1399
|
+
inputMode: "stdin"
|
|
1400
|
+
};
|
|
1401
|
+
var presets = {
|
|
1402
|
+
codex: codexPreset,
|
|
1403
|
+
aider: aiderPreset,
|
|
1404
|
+
gemini: geminiPreset,
|
|
1405
|
+
generic: genericPreset
|
|
1406
|
+
};
|
|
1407
|
+
function resolvePreset(options) {
|
|
1408
|
+
const base = presets[options.preset ?? "generic"] ?? genericPreset;
|
|
1409
|
+
return {
|
|
1410
|
+
...base,
|
|
1411
|
+
...options.command ? { command: options.command } : {},
|
|
1412
|
+
...options.args ? { args: (prompt) => options.args.map((arg) => arg.replace("{prompt}", prompt)) } : {},
|
|
1413
|
+
...options.parseMode ? { parseMode: options.parseMode } : {},
|
|
1414
|
+
...options.inputMode ? { inputMode: options.inputMode } : {}
|
|
1415
|
+
};
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1418
|
+
// ../adapter-cli/dist/index.js
|
|
1419
|
+
var newID = (prefix) => `${prefix}-${randomUUID()}`;
|
|
1420
|
+
var CliAdapter = class {
|
|
1421
|
+
platform;
|
|
1422
|
+
name;
|
|
1423
|
+
capabilities = {
|
|
1424
|
+
sessions: true,
|
|
1425
|
+
history: false,
|
|
1426
|
+
permissions: false,
|
|
1427
|
+
questions: false,
|
|
1428
|
+
attachments: false,
|
|
1429
|
+
abort: true,
|
|
1430
|
+
models: false
|
|
1431
|
+
};
|
|
1432
|
+
preset;
|
|
1433
|
+
cwd;
|
|
1434
|
+
sessions = /* @__PURE__ */ new Map();
|
|
1435
|
+
children = /* @__PURE__ */ new Map();
|
|
1436
|
+
ctx;
|
|
1437
|
+
constructor(options = {}) {
|
|
1438
|
+
this.preset = resolvePreset(options);
|
|
1439
|
+
this.cwd = options.cwd;
|
|
1440
|
+
this.platform = options.preset ?? "cli";
|
|
1441
|
+
this.name = this.preset.name;
|
|
1442
|
+
}
|
|
1443
|
+
info() {
|
|
1444
|
+
return {
|
|
1445
|
+
platform: this.platform,
|
|
1446
|
+
name: this.name,
|
|
1447
|
+
capabilities: this.capabilities,
|
|
1448
|
+
...this.cwd ? { workspace: this.cwd } : {}
|
|
1449
|
+
};
|
|
1450
|
+
}
|
|
1451
|
+
async start(ctx) {
|
|
1452
|
+
this.ctx = ctx;
|
|
1453
|
+
ctx.log("info", `CLI adapter ready: ${this.preset.command} (${this.preset.parseMode})`);
|
|
1454
|
+
}
|
|
1455
|
+
async stop() {
|
|
1456
|
+
for (const child of this.children.values())
|
|
1457
|
+
child.kill("SIGTERM");
|
|
1458
|
+
this.children.clear();
|
|
1459
|
+
}
|
|
1460
|
+
makeSession(id, directory) {
|
|
1461
|
+
const now = Date.now();
|
|
1462
|
+
return {
|
|
1463
|
+
id,
|
|
1464
|
+
title: directory ? `${directory.split("/").pop()}` : "New session",
|
|
1465
|
+
status: "idle",
|
|
1466
|
+
createdAt: now,
|
|
1467
|
+
updatedAt: now,
|
|
1468
|
+
...directory ? { directory } : {}
|
|
1469
|
+
};
|
|
1470
|
+
}
|
|
1471
|
+
async listSessions() {
|
|
1472
|
+
return [...this.sessions.values()].sort((a, b) => b.updatedAt - a.updatedAt);
|
|
1473
|
+
}
|
|
1474
|
+
async createSession(input) {
|
|
1475
|
+
const session = this.makeSession(newID("cli"), input.directory);
|
|
1476
|
+
if (input.title)
|
|
1477
|
+
session.title = input.title;
|
|
1478
|
+
this.sessions.set(session.id, session);
|
|
1479
|
+
this.ctx?.emit("session.upsert", { session });
|
|
1480
|
+
return session;
|
|
1481
|
+
}
|
|
1482
|
+
async archiveSession(sessionID) {
|
|
1483
|
+
this.sessions.delete(sessionID);
|
|
1484
|
+
this.ctx?.emit("session.remove", { sessionID });
|
|
1485
|
+
}
|
|
1486
|
+
async listMessages(_sessionID) {
|
|
1487
|
+
return [];
|
|
1488
|
+
}
|
|
1489
|
+
async listModels() {
|
|
1490
|
+
return [];
|
|
1491
|
+
}
|
|
1492
|
+
async abort(sessionID) {
|
|
1493
|
+
const child = this.children.get(sessionID);
|
|
1494
|
+
if (child)
|
|
1495
|
+
child.kill("SIGTERM");
|
|
1496
|
+
this.children.delete(sessionID);
|
|
1497
|
+
this.ctx?.emit("status.change", { sessionID, status: "idle" });
|
|
1498
|
+
}
|
|
1499
|
+
async replyPermission(_request, _reply) {
|
|
1500
|
+
throw new Error("This CLI adapter does not support interactive permissions.");
|
|
1501
|
+
}
|
|
1502
|
+
async replyQuestion(_request, _answers) {
|
|
1503
|
+
throw new Error("This CLI adapter does not support interactive questions.");
|
|
1504
|
+
}
|
|
1505
|
+
async rejectQuestion(_request) {
|
|
1506
|
+
throw new Error("This CLI adapter does not support interactive questions.");
|
|
1507
|
+
}
|
|
1508
|
+
async sendMessage(input) {
|
|
1509
|
+
if (input.attachments.length > 0) {
|
|
1510
|
+
this.ctx?.log("warn", "This CLI adapter ignores attachments.");
|
|
1511
|
+
}
|
|
1512
|
+
let sessionID = input.sessionID;
|
|
1513
|
+
if (!sessionID) {
|
|
1514
|
+
const session = await this.createSession({ directory: input.directory });
|
|
1515
|
+
sessionID = session.id;
|
|
1516
|
+
} else if (!this.sessions.has(sessionID)) {
|
|
1517
|
+
const session = this.makeSession(sessionID, input.directory);
|
|
1518
|
+
this.sessions.set(sessionID, session);
|
|
1519
|
+
this.ctx?.emit("session.upsert", { session });
|
|
1520
|
+
}
|
|
1521
|
+
const message = {
|
|
1522
|
+
id: newID("msg"),
|
|
1523
|
+
sessionID,
|
|
1524
|
+
role: "user",
|
|
1525
|
+
parts: input.text ? [{ id: newID("part"), type: "text", text: input.text }] : [],
|
|
1526
|
+
createdAt: Date.now()
|
|
1527
|
+
};
|
|
1528
|
+
this.ctx?.emit("message.upsert", { message });
|
|
1529
|
+
await this.run(sessionID, input.text);
|
|
1530
|
+
return message;
|
|
1531
|
+
}
|
|
1532
|
+
run(sessionID, prompt) {
|
|
1533
|
+
const ctx = this.ctx;
|
|
1534
|
+
if (!ctx)
|
|
1535
|
+
throw new Error("Adapter has not been started.");
|
|
1536
|
+
const messageID = newID("msg");
|
|
1537
|
+
const textPartID = newID("part");
|
|
1538
|
+
let fullText = "";
|
|
1539
|
+
const toolParts = /* @__PURE__ */ new Map();
|
|
1540
|
+
const parts = () => [
|
|
1541
|
+
...fullText ? [{ id: textPartID, type: "text", text: fullText }] : [],
|
|
1542
|
+
...toolParts.values()
|
|
1543
|
+
];
|
|
1544
|
+
const emitMessage = () => ctx.emit("message.upsert", {
|
|
1545
|
+
message: {
|
|
1546
|
+
id: messageID,
|
|
1547
|
+
sessionID,
|
|
1548
|
+
role: "assistant",
|
|
1549
|
+
parts: parts(),
|
|
1550
|
+
createdAt: Date.now()
|
|
1551
|
+
}
|
|
1552
|
+
});
|
|
1553
|
+
emitMessage();
|
|
1554
|
+
ctx.emit("status.change", { sessionID, status: "busy" });
|
|
1555
|
+
const child = spawn(this.preset.command, this.preset.args(prompt), {
|
|
1556
|
+
cwd: this.cwd,
|
|
1557
|
+
env: process.env,
|
|
1558
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
1559
|
+
});
|
|
1560
|
+
this.children.set(sessionID, child);
|
|
1561
|
+
const applyDelta = (delta) => {
|
|
1562
|
+
if (delta.kind === "text") {
|
|
1563
|
+
fullText += delta.text;
|
|
1564
|
+
ctx.emit("part.delta", {
|
|
1565
|
+
sessionID,
|
|
1566
|
+
messageID,
|
|
1567
|
+
partID: textPartID,
|
|
1568
|
+
field: "text",
|
|
1569
|
+
delta: delta.text
|
|
1570
|
+
});
|
|
1571
|
+
return;
|
|
1572
|
+
}
|
|
1573
|
+
const existing = toolParts.get(delta.id);
|
|
1574
|
+
toolParts.set(delta.id, {
|
|
1575
|
+
id: delta.id,
|
|
1576
|
+
type: "tool",
|
|
1577
|
+
tool: delta.tool,
|
|
1578
|
+
status: delta.status,
|
|
1579
|
+
...delta.title ?? existing?.title ? { title: delta.title ?? existing?.title } : {},
|
|
1580
|
+
...delta.output ?? existing?.output ? { output: delta.output ?? existing?.output } : {},
|
|
1581
|
+
...delta.error ?? existing?.error ? { error: delta.error ?? existing?.error } : {}
|
|
1582
|
+
});
|
|
1583
|
+
ctx.emit("part.upsert", { sessionID, messageID, part: toolParts.get(delta.id) });
|
|
1584
|
+
};
|
|
1585
|
+
let buffer = "";
|
|
1586
|
+
child.stdout.setEncoding("utf8");
|
|
1587
|
+
child.stdout.on("data", (chunk) => {
|
|
1588
|
+
buffer += chunk;
|
|
1589
|
+
let newline;
|
|
1590
|
+
while ((newline = buffer.indexOf("\n")) >= 0) {
|
|
1591
|
+
const line = buffer.slice(0, newline).trim();
|
|
1592
|
+
buffer = buffer.slice(newline + 1);
|
|
1593
|
+
if (!line)
|
|
1594
|
+
continue;
|
|
1595
|
+
if (this.preset.parseMode === "jsonl") {
|
|
1596
|
+
try {
|
|
1597
|
+
const value = JSON.parse(line);
|
|
1598
|
+
for (const delta of this.preset.mapJson?.(value) ?? [])
|
|
1599
|
+
applyDelta(delta);
|
|
1600
|
+
} catch {
|
|
1601
|
+
ctx.log("debug", "Non-JSON CLI line", line.slice(0, 200));
|
|
1602
|
+
}
|
|
1603
|
+
} else {
|
|
1604
|
+
applyDelta({ kind: "text", text: `${line}
|
|
1605
|
+
` });
|
|
1606
|
+
}
|
|
1607
|
+
}
|
|
1608
|
+
});
|
|
1609
|
+
child.stderr.setEncoding("utf8");
|
|
1610
|
+
child.stderr.on("data", (chunk) => {
|
|
1611
|
+
ctx.log("debug", `${this.preset.name} stderr`, chunk.slice(0, 500));
|
|
1612
|
+
});
|
|
1613
|
+
if (this.preset.inputMode === "stdin")
|
|
1614
|
+
child.stdin.write(prompt);
|
|
1615
|
+
child.stdin.end();
|
|
1616
|
+
return new Promise((resolve2, reject) => {
|
|
1617
|
+
child.once("error", (cause) => reject(cause));
|
|
1618
|
+
child.once("close", (code, signal) => {
|
|
1619
|
+
if (this.children.get(sessionID) === child)
|
|
1620
|
+
this.children.delete(sessionID);
|
|
1621
|
+
if (buffer.trim()) {
|
|
1622
|
+
if (this.preset.parseMode === "jsonl") {
|
|
1623
|
+
try {
|
|
1624
|
+
const value = JSON.parse(buffer.trim());
|
|
1625
|
+
for (const delta of this.preset.mapJson?.(value) ?? [])
|
|
1626
|
+
applyDelta(delta);
|
|
1627
|
+
} catch {
|
|
1628
|
+
ctx.log("debug", "Non-JSON CLI tail", buffer.slice(0, 200));
|
|
1629
|
+
}
|
|
1630
|
+
} else {
|
|
1631
|
+
applyDelta({ kind: "text", text: `${buffer.trim()}
|
|
1632
|
+
` });
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
emitMessage();
|
|
1636
|
+
ctx.emit("status.change", { sessionID, status: "idle" });
|
|
1637
|
+
if (code === 0 || signal === "SIGTERM") {
|
|
1638
|
+
resolve2({
|
|
1639
|
+
id: messageID,
|
|
1640
|
+
sessionID,
|
|
1641
|
+
role: "assistant",
|
|
1642
|
+
parts: parts(),
|
|
1643
|
+
createdAt: Date.now()
|
|
1644
|
+
});
|
|
1645
|
+
} else {
|
|
1646
|
+
reject(new Error(`${this.preset.command} exited with code ${code ?? "unknown"}`));
|
|
1647
|
+
}
|
|
1648
|
+
});
|
|
1649
|
+
});
|
|
1650
|
+
}
|
|
1651
|
+
};
|
|
1652
|
+
|
|
1653
|
+
// src/config.ts
|
|
1654
|
+
import { randomBytes, randomInt } from "node:crypto";
|
|
1655
|
+
import { mkdirSync, readFileSync as readFileSync2, writeFileSync } from "node:fs";
|
|
1656
|
+
import { dirname, join as join2 } from "node:path";
|
|
1657
|
+
import { homedir as homedir2 } from "node:os";
|
|
1658
|
+
var configPath = () => process.env.JUSTCONNECT_CONFIG ?? join2(homedir2(), ".config", "justconnect", "bridge.json");
|
|
1659
|
+
function parseArgs(argv) {
|
|
1660
|
+
const result = {};
|
|
1661
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
1662
|
+
const arg = argv[i];
|
|
1663
|
+
if (!arg.startsWith("--")) continue;
|
|
1664
|
+
const key = arg.slice(2);
|
|
1665
|
+
const next = argv[i + 1];
|
|
1666
|
+
if (next !== void 0 && !next.startsWith("--")) {
|
|
1667
|
+
result[key] = next;
|
|
1668
|
+
i += 1;
|
|
1669
|
+
} else {
|
|
1670
|
+
result[key] = true;
|
|
1671
|
+
}
|
|
1672
|
+
}
|
|
1673
|
+
return result;
|
|
1674
|
+
}
|
|
1675
|
+
var stringValue = (value) => typeof value === "string" ? value : void 0;
|
|
1676
|
+
function loadOrCreateConfig(args2) {
|
|
1677
|
+
let saved = {};
|
|
1678
|
+
try {
|
|
1679
|
+
saved = JSON.parse(readFileSync2(configPath(), "utf8"));
|
|
1680
|
+
} catch {
|
|
1681
|
+
}
|
|
1682
|
+
const savedOptions = saved.options ?? {};
|
|
1683
|
+
const optionKeys = ["server", "dir", "command", "name", "model", "cwd", "timeout", "extra-args", "password"];
|
|
1684
|
+
const options = { ...savedOptions };
|
|
1685
|
+
for (const key of optionKeys) {
|
|
1686
|
+
const value = stringValue(args2[key]);
|
|
1687
|
+
if (value !== void 0) options[key] = value;
|
|
1688
|
+
}
|
|
1689
|
+
const config2 = {
|
|
1690
|
+
relay: stringValue(args2.relay) ?? saved.relay ?? process.env.JUSTCONNECT_RELAY ?? "wss://jc-relay.utachi.website/ws",
|
|
1691
|
+
code: stringValue(args2.code) ?? saved.code ?? randomInt(0, 1e6).toString().padStart(6, "0"),
|
|
1692
|
+
token: saved.token ?? randomBytes(24).toString("hex"),
|
|
1693
|
+
adapter: stringValue(args2.adapter) ?? saved.adapter ?? "opencode",
|
|
1694
|
+
options
|
|
1695
|
+
};
|
|
1696
|
+
const path = configPath();
|
|
1697
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
1698
|
+
writeFileSync(path, `${JSON.stringify(config2, null, 2)}
|
|
1699
|
+
`, { mode: 384 });
|
|
1700
|
+
return config2;
|
|
1701
|
+
}
|
|
1702
|
+
|
|
1703
|
+
// src/engine.ts
|
|
1704
|
+
import WebSocket from "ws";
|
|
1705
|
+
var BridgeEngine = class {
|
|
1706
|
+
constructor(options) {
|
|
1707
|
+
this.options = options;
|
|
1708
|
+
}
|
|
1709
|
+
options;
|
|
1710
|
+
state = emptyClientState();
|
|
1711
|
+
seq = 0;
|
|
1712
|
+
ws;
|
|
1713
|
+
stopped = false;
|
|
1714
|
+
backoff = createBackoff({ baseMs: 1e3, maxMs: 3e4 });
|
|
1715
|
+
hydratedSessions = /* @__PURE__ */ new Set();
|
|
1716
|
+
codeRefresh;
|
|
1717
|
+
refreshWatchdog;
|
|
1718
|
+
get snapshot() {
|
|
1719
|
+
return toSnapshot(this.state);
|
|
1720
|
+
}
|
|
1721
|
+
async start() {
|
|
1722
|
+
const { adapter: adapter2 } = this.options;
|
|
1723
|
+
await adapter2.start({
|
|
1724
|
+
emit: (type, properties) => this.emit(type, properties),
|
|
1725
|
+
log: (level, message, detail) => this.emit("log", { level, message, ...detail ? { detail } : {} }),
|
|
1726
|
+
selectedSessionID: () => this.state.selectedSessionID
|
|
1727
|
+
});
|
|
1728
|
+
await this.hydrate();
|
|
1729
|
+
await this.connectLoop();
|
|
1730
|
+
}
|
|
1731
|
+
async stop() {
|
|
1732
|
+
this.stopped = true;
|
|
1733
|
+
if (this.codeRefresh) clearTimeout(this.codeRefresh);
|
|
1734
|
+
if (this.refreshWatchdog) clearTimeout(this.refreshWatchdog);
|
|
1735
|
+
this.ws?.close();
|
|
1736
|
+
await this.options.adapter.stop();
|
|
1737
|
+
}
|
|
1738
|
+
emit(type, properties) {
|
|
1739
|
+
const event = { seq: ++this.seq, at: Date.now(), type, properties };
|
|
1740
|
+
this.state = applyEvent(this.state, event);
|
|
1741
|
+
this.send({ t: "event", event });
|
|
1742
|
+
}
|
|
1743
|
+
send(envelope) {
|
|
1744
|
+
if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify(envelope));
|
|
1745
|
+
}
|
|
1746
|
+
async hydrate() {
|
|
1747
|
+
const { adapter: adapter2 } = this.options;
|
|
1748
|
+
const sessions = await adapter2.listSessions();
|
|
1749
|
+
for (const session of sessions) this.emit("session.upsert", { session });
|
|
1750
|
+
const models = await adapter2.listModels();
|
|
1751
|
+
this.emit("hello", { agent: adapter2.info(), models });
|
|
1752
|
+
const selected = sessions.find((session) => session.id === this.options.config.options.sessionID);
|
|
1753
|
+
if (selected) this.state = selectSession(this.state, selected.id);
|
|
1754
|
+
else if (sessions[0]) this.state = selectSession(this.state, sessions[0].id);
|
|
1755
|
+
await this.loadHistory(this.state.selectedSessionID);
|
|
1756
|
+
}
|
|
1757
|
+
/** Replay a session's transcript once; later updates arrive as events. */
|
|
1758
|
+
async loadHistory(sessionID) {
|
|
1759
|
+
const { adapter: adapter2 } = this.options;
|
|
1760
|
+
if (!sessionID || this.hydratedSessions.has(sessionID)) return;
|
|
1761
|
+
if (!adapter2.capabilities.history) return;
|
|
1762
|
+
this.hydratedSessions.add(sessionID);
|
|
1763
|
+
try {
|
|
1764
|
+
for (const message of await adapter2.listMessages(sessionID)) {
|
|
1765
|
+
this.emit("message.upsert", { message });
|
|
1766
|
+
}
|
|
1767
|
+
} catch (cause) {
|
|
1768
|
+
this.hydratedSessions.delete(sessionID);
|
|
1769
|
+
this.log("warn", `Could not load history for ${sessionID}`, String(cause));
|
|
1770
|
+
}
|
|
1771
|
+
}
|
|
1772
|
+
async connectLoop() {
|
|
1773
|
+
while (!this.stopped) {
|
|
1774
|
+
try {
|
|
1775
|
+
await this.connectOnce();
|
|
1776
|
+
this.backoff.reset();
|
|
1777
|
+
this.log("info", "Relay connection closed; reconnecting");
|
|
1778
|
+
} catch (cause) {
|
|
1779
|
+
if (this.stopped) return;
|
|
1780
|
+
this.log("warn", "Relay connection failed", String(cause));
|
|
1781
|
+
}
|
|
1782
|
+
if (this.stopped) return;
|
|
1783
|
+
await sleep(this.backoff.next()).catch(() => void 0);
|
|
1784
|
+
}
|
|
1785
|
+
}
|
|
1786
|
+
log(level, message, detail) {
|
|
1787
|
+
const prefix = `[justconnect] ${level.toUpperCase()}`;
|
|
1788
|
+
if (detail) console.error(prefix, message, detail);
|
|
1789
|
+
else console.error(prefix, message);
|
|
1790
|
+
}
|
|
1791
|
+
connectOnce() {
|
|
1792
|
+
const { config: config2 } = this.options;
|
|
1793
|
+
const ws = new WebSocket(config2.relay);
|
|
1794
|
+
this.ws = ws;
|
|
1795
|
+
let lastPong = Date.now();
|
|
1796
|
+
return new Promise((resolve2) => {
|
|
1797
|
+
const handshake = setTimeout(() => {
|
|
1798
|
+
this.log("warn", "Relay handshake timed out");
|
|
1799
|
+
ws.terminate();
|
|
1800
|
+
}, 1e4);
|
|
1801
|
+
ws.on("open", () => {
|
|
1802
|
+
ws.send(
|
|
1803
|
+
JSON.stringify({
|
|
1804
|
+
t: "bridge.hello",
|
|
1805
|
+
code: config2.code,
|
|
1806
|
+
token: config2.token,
|
|
1807
|
+
agent: this.options.adapter.info()
|
|
1808
|
+
})
|
|
1809
|
+
);
|
|
1810
|
+
});
|
|
1811
|
+
ws.on("message", (data) => {
|
|
1812
|
+
const envelope = parseEnvelope(data.toString());
|
|
1813
|
+
if (!envelope) return;
|
|
1814
|
+
switch (envelope.t) {
|
|
1815
|
+
case "bridge.ack":
|
|
1816
|
+
clearTimeout(handshake);
|
|
1817
|
+
if (this.refreshWatchdog) clearTimeout(this.refreshWatchdog);
|
|
1818
|
+
this.backoff.reset();
|
|
1819
|
+
this.send({ t: "snapshot", snapshot: toSnapshot(this.state) });
|
|
1820
|
+
this.scheduleCodeRefresh(envelope.codeExpiresAt);
|
|
1821
|
+
console.log(`[justconnect] connected \xB7 code ${config2.code}`);
|
|
1822
|
+
break;
|
|
1823
|
+
case "command":
|
|
1824
|
+
void this.handleCommand(envelope.command);
|
|
1825
|
+
break;
|
|
1826
|
+
case "bridge.pong":
|
|
1827
|
+
lastPong = Date.now();
|
|
1828
|
+
break;
|
|
1829
|
+
case "error":
|
|
1830
|
+
this.log("warn", "Relay error", envelope.message);
|
|
1831
|
+
break;
|
|
1832
|
+
default:
|
|
1833
|
+
break;
|
|
1834
|
+
}
|
|
1835
|
+
});
|
|
1836
|
+
const heartbeat = setInterval(() => {
|
|
1837
|
+
if (Date.now() - lastPong > 6e4) ws.terminate();
|
|
1838
|
+
else if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ t: "ping", at: Date.now() }));
|
|
1839
|
+
}, 25e3);
|
|
1840
|
+
const finish = () => {
|
|
1841
|
+
clearTimeout(handshake);
|
|
1842
|
+
clearInterval(heartbeat);
|
|
1843
|
+
if (this.codeRefresh) clearTimeout(this.codeRefresh);
|
|
1844
|
+
if (this.refreshWatchdog) clearTimeout(this.refreshWatchdog);
|
|
1845
|
+
if (this.ws === ws) this.ws = void 0;
|
|
1846
|
+
resolve2();
|
|
1847
|
+
};
|
|
1848
|
+
ws.on("close", finish);
|
|
1849
|
+
ws.on("error", () => void 0);
|
|
1850
|
+
});
|
|
1851
|
+
}
|
|
1852
|
+
/**
|
|
1853
|
+
* Pairing codes expire after 15 minutes, which is useless for a bridge that
|
|
1854
|
+
* runs all day. Re-announce shortly before expiry so the printed code stays
|
|
1855
|
+
* valid for as long as the process is alive.
|
|
1856
|
+
*/
|
|
1857
|
+
scheduleCodeRefresh(expiresAt) {
|
|
1858
|
+
if (this.codeRefresh) clearTimeout(this.codeRefresh);
|
|
1859
|
+
const delay = Math.max(15e3, expiresAt - Date.now() - 6e4);
|
|
1860
|
+
this.codeRefresh = setTimeout(() => {
|
|
1861
|
+
const { config: config2 } = this.options;
|
|
1862
|
+
this.send({
|
|
1863
|
+
t: "bridge.hello",
|
|
1864
|
+
code: config2.code,
|
|
1865
|
+
token: config2.token,
|
|
1866
|
+
agent: this.options.adapter.info()
|
|
1867
|
+
});
|
|
1868
|
+
if (this.refreshWatchdog) clearTimeout(this.refreshWatchdog);
|
|
1869
|
+
this.refreshWatchdog = setTimeout(() => this.ws?.terminate(), 1e4);
|
|
1870
|
+
this.refreshWatchdog.unref?.();
|
|
1871
|
+
}, delay);
|
|
1872
|
+
this.codeRefresh.unref?.();
|
|
1873
|
+
}
|
|
1874
|
+
async handleCommand(command) {
|
|
1875
|
+
try {
|
|
1876
|
+
const result = await this.dispatch(command);
|
|
1877
|
+
this.send({ t: "result", result: { id: command.id, ok: true, result } });
|
|
1878
|
+
} catch (cause) {
|
|
1879
|
+
const message = cause instanceof Error ? cause.message : String(cause);
|
|
1880
|
+
this.log("error", `Command ${command.type} failed`, message);
|
|
1881
|
+
this.send({ t: "result", result: { id: command.id, ok: false, error: message } });
|
|
1882
|
+
}
|
|
1883
|
+
}
|
|
1884
|
+
async dispatch(command) {
|
|
1885
|
+
const { adapter: adapter2 } = this.options;
|
|
1886
|
+
const p = command.properties;
|
|
1887
|
+
switch (command.type) {
|
|
1888
|
+
case "session.list": {
|
|
1889
|
+
const sessions = await adapter2.listSessions();
|
|
1890
|
+
for (const session of sessions) this.emit("session.upsert", { session });
|
|
1891
|
+
return sessions;
|
|
1892
|
+
}
|
|
1893
|
+
case "session.create": {
|
|
1894
|
+
const session = await adapter2.createSession(p);
|
|
1895
|
+
this.emit("session.upsert", { session });
|
|
1896
|
+
this.state = selectSession(this.state, session.id);
|
|
1897
|
+
return session;
|
|
1898
|
+
}
|
|
1899
|
+
case "session.archive": {
|
|
1900
|
+
await adapter2.archiveSession(p.sessionID);
|
|
1901
|
+
this.emit("session.remove", { sessionID: p.sessionID });
|
|
1902
|
+
if (this.state.selectedSessionID === p.sessionID) {
|
|
1903
|
+
const next = this.state.sessions.find((s) => s.id !== p.sessionID);
|
|
1904
|
+
this.state = selectSession(this.state, next?.id ?? null);
|
|
1905
|
+
}
|
|
1906
|
+
return { ok: true };
|
|
1907
|
+
}
|
|
1908
|
+
case "session.select":
|
|
1909
|
+
this.state = selectSession(this.state, p.sessionID);
|
|
1910
|
+
await this.loadHistory(p.sessionID);
|
|
1911
|
+
return { ok: true };
|
|
1912
|
+
case "message.send": {
|
|
1913
|
+
let sessionID = p.sessionID ?? this.state.selectedSessionID ?? void 0;
|
|
1914
|
+
if (!sessionID) {
|
|
1915
|
+
const session = await adapter2.createSession({ directory: p.directory });
|
|
1916
|
+
sessionID = session.id;
|
|
1917
|
+
this.emit("session.upsert", { session });
|
|
1918
|
+
this.state = selectSession(this.state, session.id);
|
|
1919
|
+
}
|
|
1920
|
+
const message = await adapter2.sendMessage({
|
|
1921
|
+
sessionID,
|
|
1922
|
+
text: p.text,
|
|
1923
|
+
attachments: p.attachments ?? [],
|
|
1924
|
+
...p.model ? { model: p.model } : {},
|
|
1925
|
+
...p.provider ? { provider: p.provider } : {},
|
|
1926
|
+
...p.directory ? { directory: p.directory } : {}
|
|
1927
|
+
});
|
|
1928
|
+
this.emit("message.upsert", { message });
|
|
1929
|
+
return message;
|
|
1930
|
+
}
|
|
1931
|
+
case "message.abort":
|
|
1932
|
+
await adapter2.abort(p.sessionID);
|
|
1933
|
+
this.emit("status.change", { sessionID: p.sessionID, status: "idle" });
|
|
1934
|
+
return { ok: true };
|
|
1935
|
+
case "permission.reply": {
|
|
1936
|
+
const found = findPermission(this.state, p.requestID);
|
|
1937
|
+
if (!found) throw new Error("Permission request not found.");
|
|
1938
|
+
await adapter2.replyPermission(found.request, p.reply);
|
|
1939
|
+
this.emit("permission.reply", {
|
|
1940
|
+
sessionID: found.sessionID,
|
|
1941
|
+
requestID: p.requestID,
|
|
1942
|
+
reply: p.reply
|
|
1943
|
+
});
|
|
1944
|
+
return { ok: true };
|
|
1945
|
+
}
|
|
1946
|
+
case "question.reply": {
|
|
1947
|
+
const found = findQuestion(this.state, p.requestID);
|
|
1948
|
+
if (!found) throw new Error("Question request not found.");
|
|
1949
|
+
await adapter2.replyQuestion(found.request, p.answers);
|
|
1950
|
+
this.emit("question.reply", {
|
|
1951
|
+
sessionID: found.sessionID,
|
|
1952
|
+
requestID: p.requestID,
|
|
1953
|
+
answers: p.answers
|
|
1954
|
+
});
|
|
1955
|
+
return { ok: true };
|
|
1956
|
+
}
|
|
1957
|
+
case "question.reject": {
|
|
1958
|
+
const found = findQuestion(this.state, p.requestID);
|
|
1959
|
+
if (!found) throw new Error("Question request not found.");
|
|
1960
|
+
await adapter2.rejectQuestion(found.request);
|
|
1961
|
+
this.emit("question.reject", { sessionID: found.sessionID, requestID: p.requestID });
|
|
1962
|
+
return { ok: true };
|
|
1963
|
+
}
|
|
1964
|
+
case "models.list":
|
|
1965
|
+
return this.state.models;
|
|
1966
|
+
case "ping":
|
|
1967
|
+
return { pong: true };
|
|
1968
|
+
}
|
|
1969
|
+
}
|
|
1970
|
+
};
|
|
1971
|
+
|
|
1972
|
+
// src/index.ts
|
|
1973
|
+
var args = parseArgs(process.argv.slice(2));
|
|
1974
|
+
if (args.help || args.h) {
|
|
1975
|
+
console.log(`justconnect \u2014 reach your local coding agent from any device
|
|
1976
|
+
|
|
1977
|
+
Usage:
|
|
1978
|
+
justconnect
|
|
1979
|
+
|
|
1980
|
+
That is it. The bridge finds your running OpenCode, dials the public relay,
|
|
1981
|
+
and prints a code to type at https://justconnect.utachi.website.
|
|
1982
|
+
|
|
1983
|
+
Options:
|
|
1984
|
+
--relay <url> Relay WebSocket URL (or JUSTCONNECT_RELAY)
|
|
1985
|
+
--adapter <name> opencode (default) | codex | aider | gemini | generic | /path/to/module
|
|
1986
|
+
--dir <path> Project directory the agent works in (default: current directory)
|
|
1987
|
+
--code <6digits> Reuse a specific pairing code
|
|
1988
|
+
--server <url> OpenCode server URL (auto-detected by default)
|
|
1989
|
+
--password <pw> OpenCode password (auto-detected by default)
|
|
1990
|
+
--command <cmd> Command for the generic CLI adapter
|
|
1991
|
+
--name <name> Label shown for the agent
|
|
1992
|
+
--help Show this help
|
|
1993
|
+
|
|
1994
|
+
Config is saved to ~/.config/justconnect/bridge.json (or JUSTCONNECT_CONFIG).`);
|
|
1995
|
+
process.exit(0);
|
|
1996
|
+
}
|
|
1997
|
+
var config = loadOrCreateConfig(args);
|
|
1998
|
+
function webURL(relay) {
|
|
1999
|
+
if (process.env.JUSTCONNECT_WEB) return process.env.JUSTCONNECT_WEB;
|
|
2000
|
+
return /(^|\.)utachi\.website/.test(relay) ? "https://justconnect.utachi.website" : "http://localhost:5173";
|
|
2001
|
+
}
|
|
2002
|
+
async function makeAdapter() {
|
|
2003
|
+
const name = config.adapter;
|
|
2004
|
+
const cwd = config.options.dir ?? config.options.cwd;
|
|
2005
|
+
if (name === "opencode") {
|
|
2006
|
+
return new dist_default({
|
|
2007
|
+
...config.options.server ? { serverURL: config.options.server } : {},
|
|
2008
|
+
...config.options.password ? { password: config.options.password } : {},
|
|
2009
|
+
// Scope to the project the bridge was started in, like `opencode` does.
|
|
2010
|
+
directory: cwd ?? process.cwd()
|
|
2011
|
+
});
|
|
2012
|
+
}
|
|
2013
|
+
if (["codex", "aider", "gemini", "generic"].includes(name)) {
|
|
2014
|
+
return new CliAdapter({
|
|
2015
|
+
preset: name,
|
|
2016
|
+
...cwd ? { cwd } : {},
|
|
2017
|
+
...config.options.command ? { command: config.options.command } : {}
|
|
2018
|
+
});
|
|
2019
|
+
}
|
|
2020
|
+
const modulePath = pathToFileURL(resolve(name)).href;
|
|
2021
|
+
const loaded = await import(modulePath);
|
|
2022
|
+
if (!loaded.default) throw new Error(`Custom adapter ${name} has no default export.`);
|
|
2023
|
+
return new loaded.default(config.options);
|
|
2024
|
+
}
|
|
2025
|
+
var adapter = await makeAdapter();
|
|
2026
|
+
var engine = new BridgeEngine({ config, adapter });
|
|
2027
|
+
console.log("");
|
|
2028
|
+
console.log(` justconnect \xB7 ${adapter.info().name} \xB7 code ${config.code}`);
|
|
2029
|
+
console.log("");
|
|
2030
|
+
console.log(` Open ${webURL(config.relay)} and enter the code above.`);
|
|
2031
|
+
console.log(" Leave this running. Codes refresh automatically. Ctrl-C to stop.");
|
|
2032
|
+
console.log("");
|
|
2033
|
+
try {
|
|
2034
|
+
await engine.start();
|
|
2035
|
+
} catch (cause) {
|
|
2036
|
+
console.error(`
|
|
2037
|
+
${cause instanceof Error ? cause.message : String(cause)}
|
|
2038
|
+
`);
|
|
2039
|
+
process.exit(1);
|
|
2040
|
+
}
|
|
2041
|
+
for (const signal of ["SIGINT", "SIGTERM"]) {
|
|
2042
|
+
process.on(signal, () => {
|
|
2043
|
+
void engine.stop().then(() => process.exit(0));
|
|
2044
|
+
});
|
|
2045
|
+
}
|