@akshar5/cohall 0.12.5 → 0.12.7
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/CHANGELOG.md +31 -0
- package/README.md +1 -1
- package/bin/chunk-04a27ybz.js +460 -0
- package/bin/chunk-04a27ybz.js.map +10 -0
- package/bin/chunk-27xa296w.js +40 -0
- package/bin/chunk-27xa296w.js.map +9 -0
- package/bin/chunk-39by7csf.js +267 -0
- package/bin/chunk-39by7csf.js.map +11 -0
- package/bin/chunk-61m7z93m.js +256 -0
- package/bin/chunk-61m7z93m.js.map +10 -0
- package/bin/chunk-7dgeftrk.js +23 -0
- package/bin/chunk-7dgeftrk.js.map +10 -0
- package/bin/chunk-7ss2d5n4.js +50 -0
- package/bin/chunk-7ss2d5n4.js.map +10 -0
- package/bin/chunk-89ga9j8t.js +269 -0
- package/bin/chunk-89ga9j8t.js.map +10 -0
- package/bin/chunk-90k4bw6t.js +2801 -0
- package/bin/chunk-90k4bw6t.js.map +14 -0
- package/bin/chunk-akct7v1q.js +2160 -0
- package/bin/chunk-akct7v1q.js.map +15 -0
- package/bin/chunk-b3ba95j4.js +1867 -0
- package/bin/chunk-b3ba95j4.js.map +13 -0
- package/bin/chunk-d2sykjmx.js +665 -0
- package/bin/chunk-d2sykjmx.js.map +10 -0
- package/bin/chunk-g6b3zmtw.js +268 -0
- package/bin/chunk-g6b3zmtw.js.map +10 -0
- package/bin/chunk-p493vm5f.js +21 -0
- package/bin/chunk-p493vm5f.js.map +10 -0
- package/bin/chunk-zxrjgp9k.js +415 -0
- package/bin/chunk-zxrjgp9k.js.map +11 -0
- package/bin/cohall.js +18 -9103
- package/bin/cohall.js.map +5 -30
- package/deploy/windows/install-device.ps1 +2 -0
- package/docs/install.md +6 -2
- package/docs/integrations.md +6 -3
- package/package.json +1 -1
|
@@ -0,0 +1,1867 @@
|
|
|
1
|
+
import {
|
|
2
|
+
readBoundedFile
|
|
3
|
+
} from "./chunk-p493vm5f.js";
|
|
4
|
+
import {
|
|
5
|
+
configurationPath
|
|
6
|
+
} from "./chunk-g6b3zmtw.js";
|
|
7
|
+
import {
|
|
8
|
+
Bot,
|
|
9
|
+
BotId,
|
|
10
|
+
Provider,
|
|
11
|
+
RequestTaskInput,
|
|
12
|
+
TaskId,
|
|
13
|
+
TaskRunId,
|
|
14
|
+
ThreadId
|
|
15
|
+
} from "./chunk-04a27ybz.js";
|
|
16
|
+
|
|
17
|
+
// packages/providers/src/index.ts
|
|
18
|
+
import { Effect, Schema } from "effect";
|
|
19
|
+
import { execa } from "execa";
|
|
20
|
+
import { accessSync, constants, statSync } from "node:fs";
|
|
21
|
+
import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
22
|
+
import { homedir, platform, tmpdir } from "node:os";
|
|
23
|
+
import { delimiter, extname, isAbsolute, join, resolve } from "node:path";
|
|
24
|
+
import { execFile } from "node:child_process";
|
|
25
|
+
|
|
26
|
+
class ProviderUnavailableError extends Schema.TaggedErrorClass()("CohallProvider.Unavailable", { provider: Provider, message: Schema.String }) {
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
class ProviderRunError extends Schema.TaggedErrorClass()("CohallProvider.RunError", {
|
|
30
|
+
provider: Provider,
|
|
31
|
+
message: Schema.String,
|
|
32
|
+
exitCode: Schema.optionalKey(Schema.Number)
|
|
33
|
+
}) {
|
|
34
|
+
}
|
|
35
|
+
var maxResultBytes = 131072;
|
|
36
|
+
var maxJsonBytes = 1024 * 1024;
|
|
37
|
+
var executables = {
|
|
38
|
+
codex: "codex",
|
|
39
|
+
"claude-code": "claude",
|
|
40
|
+
opencode: "opencode"
|
|
41
|
+
};
|
|
42
|
+
var providerEnvironment = () => ({
|
|
43
|
+
...Object.fromEntries(Object.entries(process.env).filter(([name]) => {
|
|
44
|
+
const key = platform() === "win32" ? name.toUpperCase() : name;
|
|
45
|
+
return !key.startsWith("COHALL_") || key === "COHALL_CONFIG";
|
|
46
|
+
})),
|
|
47
|
+
...process.env.COHALL_CONFIG === undefined ? {} : { COHALL_CONFIG: resolve(process.env.COHALL_CONFIG) },
|
|
48
|
+
PATH: executableDirectories().join(delimiter)
|
|
49
|
+
});
|
|
50
|
+
var record = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? Object.fromEntries(Object.entries(value)) : undefined;
|
|
51
|
+
var text = (value) => typeof value === "string" ? value : undefined;
|
|
52
|
+
var executableCandidates = (command) => {
|
|
53
|
+
if (platform() !== "win32" || extname(command).length > 0) {
|
|
54
|
+
return [command];
|
|
55
|
+
}
|
|
56
|
+
return (process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter((extension) => extension.length > 0).map((extension) => `${command}${extension.toLowerCase()}`);
|
|
57
|
+
};
|
|
58
|
+
var executableDirectories = () => {
|
|
59
|
+
const home = homedir();
|
|
60
|
+
const configured = (process.env.PATH ?? "").split(delimiter).filter(Boolean);
|
|
61
|
+
const common = platform() === "win32" ? [
|
|
62
|
+
process.env.APPDATA === undefined ? undefined : join(process.env.APPDATA, "npm"),
|
|
63
|
+
process.env.LOCALAPPDATA === undefined ? undefined : join(process.env.LOCALAPPDATA, "pnpm"),
|
|
64
|
+
join(home, ".bun", "bin")
|
|
65
|
+
] : [
|
|
66
|
+
join(home, ".local", "bin"),
|
|
67
|
+
join(home, ".npm-global", "bin"),
|
|
68
|
+
join(home, ".bun", "bin"),
|
|
69
|
+
join(home, ".local", "share", "pnpm"),
|
|
70
|
+
"/opt/homebrew/bin",
|
|
71
|
+
"/usr/local/bin"
|
|
72
|
+
];
|
|
73
|
+
return [
|
|
74
|
+
...new Set([...configured, ...common.filter((path) => path !== undefined)].map((path) => resolve(path)))
|
|
75
|
+
];
|
|
76
|
+
};
|
|
77
|
+
var findExecutable = (command) => {
|
|
78
|
+
const paths = isAbsolute(command) || command.includes("/") || command.includes("\\") ? [""] : executableDirectories();
|
|
79
|
+
for (const directory of paths) {
|
|
80
|
+
for (const candidate of executableCandidates(command)) {
|
|
81
|
+
const path = resolve(directory.length === 0 ? candidate : join(directory, candidate));
|
|
82
|
+
try {
|
|
83
|
+
if (!statSync(path).isFile())
|
|
84
|
+
continue;
|
|
85
|
+
accessSync(path, platform() === "win32" ? constants.F_OK : constants.X_OK);
|
|
86
|
+
return path;
|
|
87
|
+
} catch {
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return;
|
|
93
|
+
};
|
|
94
|
+
var available = (provider) => provider !== "grok-bot" && findExecutable(executables[provider]) !== undefined;
|
|
95
|
+
var availableProviders = () => Provider.literals.filter((provider) => provider !== "grok-bot").filter(available);
|
|
96
|
+
var boundedText = (stream, limit, onOverflow) => new Promise((resolve2, reject) => {
|
|
97
|
+
const chunks = [];
|
|
98
|
+
let size = 0;
|
|
99
|
+
const cleanup = () => {
|
|
100
|
+
stream.off("data", onData);
|
|
101
|
+
stream.off("end", onEnd);
|
|
102
|
+
stream.off("error", onError);
|
|
103
|
+
};
|
|
104
|
+
const onData = (chunk) => {
|
|
105
|
+
const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
|
|
106
|
+
size += bytes.byteLength;
|
|
107
|
+
if (size <= limit) {
|
|
108
|
+
chunks.push(bytes);
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
cleanup();
|
|
112
|
+
onOverflow();
|
|
113
|
+
reject(new Error(`Provider output exceeded ${Math.floor(limit / 1024)} KiB`));
|
|
114
|
+
};
|
|
115
|
+
const onEnd = () => {
|
|
116
|
+
cleanup();
|
|
117
|
+
resolve2(Buffer.concat(chunks, size).toString("utf8"));
|
|
118
|
+
};
|
|
119
|
+
const onError = (cause) => {
|
|
120
|
+
cleanup();
|
|
121
|
+
reject(cause);
|
|
122
|
+
};
|
|
123
|
+
stream.on("data", onData);
|
|
124
|
+
stream.once("end", onEnd);
|
|
125
|
+
stream.once("error", onError);
|
|
126
|
+
});
|
|
127
|
+
var captureText = (stream, limit) => new Promise((resolve2, reject) => {
|
|
128
|
+
const chunks = [];
|
|
129
|
+
let captured = 0;
|
|
130
|
+
let truncated = false;
|
|
131
|
+
const onData = (chunk) => {
|
|
132
|
+
const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
|
|
133
|
+
const remaining = limit - captured;
|
|
134
|
+
if (remaining > 0) {
|
|
135
|
+
const selected = bytes.byteLength <= remaining ? bytes : bytes.subarray(0, remaining);
|
|
136
|
+
chunks.push(selected);
|
|
137
|
+
captured += selected.byteLength;
|
|
138
|
+
}
|
|
139
|
+
truncated ||= bytes.byteLength > remaining;
|
|
140
|
+
};
|
|
141
|
+
const onEnd = () => resolve2({ text: Buffer.concat(chunks, captured).toString("utf8"), truncated });
|
|
142
|
+
stream.on("data", onData);
|
|
143
|
+
stream.once("end", onEnd);
|
|
144
|
+
stream.once("error", reject);
|
|
145
|
+
});
|
|
146
|
+
var failureMessage = (command, stderr, exitCode) => {
|
|
147
|
+
const fallback = exitCode === undefined ? `${command} failed` : `${command} exited with status ${exitCode}`;
|
|
148
|
+
const suffix = stderr.truncated ? `
|
|
149
|
+
[stderr truncated after 64 KiB]` : "";
|
|
150
|
+
const available2 = 16384 - suffix.length;
|
|
151
|
+
return `${(stderr.text.trim() || fallback).slice(0, available2)}${suffix}`;
|
|
152
|
+
};
|
|
153
|
+
var codexCommand = (options) => {
|
|
154
|
+
const common = [
|
|
155
|
+
"--json",
|
|
156
|
+
"--skip-git-repo-check",
|
|
157
|
+
"-c",
|
|
158
|
+
'approval_policy="never"',
|
|
159
|
+
...options.model === undefined ? [] : ["--model", options.model],
|
|
160
|
+
...options.sandbox === undefined ? [] : ["-c", `sandbox_mode=${JSON.stringify(options.sandbox)}`]
|
|
161
|
+
];
|
|
162
|
+
return options.sessionId === undefined ? ["codex", "exec", ...common, "-"] : ["codex", "exec", "resume", ...common, options.sessionId, "-"];
|
|
163
|
+
};
|
|
164
|
+
var claudeCommand = (options) => [
|
|
165
|
+
"claude",
|
|
166
|
+
"-p",
|
|
167
|
+
"--output-format",
|
|
168
|
+
"json",
|
|
169
|
+
...options.model === undefined ? [] : ["--model", options.model],
|
|
170
|
+
...options.sessionId === undefined ? [] : ["--resume", options.sessionId]
|
|
171
|
+
];
|
|
172
|
+
var opencodeCommand = (options, promptPath) => [
|
|
173
|
+
"opencode",
|
|
174
|
+
"run",
|
|
175
|
+
"--format",
|
|
176
|
+
"json",
|
|
177
|
+
...options.model === undefined ? [] : ["--model", options.model],
|
|
178
|
+
...options.sessionId === undefined ? [] : ["--session", options.sessionId],
|
|
179
|
+
"Complete the task described in the attached Cohall prompt file.",
|
|
180
|
+
`--file=${promptPath}`
|
|
181
|
+
];
|
|
182
|
+
var prepareCommand = async (options) => {
|
|
183
|
+
switch (options.provider) {
|
|
184
|
+
case "codex":
|
|
185
|
+
return {
|
|
186
|
+
command: codexCommand(options),
|
|
187
|
+
input: options.prompt,
|
|
188
|
+
cleanup: () => Promise.resolve()
|
|
189
|
+
};
|
|
190
|
+
case "claude-code":
|
|
191
|
+
return {
|
|
192
|
+
command: claudeCommand(options),
|
|
193
|
+
input: options.prompt,
|
|
194
|
+
cleanup: () => Promise.resolve()
|
|
195
|
+
};
|
|
196
|
+
case "opencode": {
|
|
197
|
+
const directory = await mkdtemp(join(tmpdir(), "cohall-opencode-"));
|
|
198
|
+
const promptPath = join(directory, "prompt.md");
|
|
199
|
+
try {
|
|
200
|
+
if (platform() !== "win32") {
|
|
201
|
+
await chmod(directory, 448);
|
|
202
|
+
}
|
|
203
|
+
await writeFile(promptPath, options.prompt, { mode: 384 });
|
|
204
|
+
return {
|
|
205
|
+
command: opencodeCommand(options, promptPath),
|
|
206
|
+
cleanup: () => rm(directory, { recursive: true, force: true })
|
|
207
|
+
};
|
|
208
|
+
} catch (cause) {
|
|
209
|
+
await rm(directory, { recursive: true, force: true }).catch(() => {
|
|
210
|
+
return;
|
|
211
|
+
});
|
|
212
|
+
throw cause;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
var forEachJsonEvent = async (stdout, onEvent, onOversized) => {
|
|
218
|
+
let chunks = [];
|
|
219
|
+
let size = 0;
|
|
220
|
+
let oversized = false;
|
|
221
|
+
const append = (chunk) => {
|
|
222
|
+
if (oversized) {
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
if (size + chunk.byteLength > maxJsonBytes) {
|
|
226
|
+
chunks = [];
|
|
227
|
+
size = 0;
|
|
228
|
+
oversized = true;
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
if (chunk.byteLength > 0) {
|
|
232
|
+
chunks.push(chunk);
|
|
233
|
+
size += chunk.byteLength;
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
const emit = () => {
|
|
237
|
+
if (oversized) {
|
|
238
|
+
oversized = false;
|
|
239
|
+
onOversized();
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
const line = Buffer.concat(chunks, size).toString("utf8");
|
|
243
|
+
chunks = [];
|
|
244
|
+
size = 0;
|
|
245
|
+
if (line.trim().length === 0) {
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
const event = record(JSON.parse(line));
|
|
249
|
+
if (event !== undefined) {
|
|
250
|
+
onEvent(event);
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
for await (const chunk of stdout) {
|
|
254
|
+
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
|
|
255
|
+
let start = 0;
|
|
256
|
+
for (let newline = bytes.indexOf(10, start);newline !== -1; ) {
|
|
257
|
+
append(bytes.subarray(start, newline));
|
|
258
|
+
emit();
|
|
259
|
+
start = newline + 1;
|
|
260
|
+
newline = bytes.indexOf(10, start);
|
|
261
|
+
}
|
|
262
|
+
append(bytes.subarray(start));
|
|
263
|
+
}
|
|
264
|
+
if (size > 0 || oversized) {
|
|
265
|
+
emit();
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
var parseCodex = async (stdout, existingSession) => {
|
|
269
|
+
let result = "";
|
|
270
|
+
let sessionId = existingSession;
|
|
271
|
+
let discardedEvent = false;
|
|
272
|
+
await forEachJsonEvent(stdout, (event) => {
|
|
273
|
+
if (text(event.type) === "turn.failed") {
|
|
274
|
+
throw new ProviderRunError({
|
|
275
|
+
provider: "codex",
|
|
276
|
+
message: (text(record(event.error)?.message) || "Codex turn failed").slice(0, 16384)
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
if (text(event.type) === "thread.started") {
|
|
280
|
+
sessionId = text(event.thread_id) ?? sessionId;
|
|
281
|
+
}
|
|
282
|
+
if (text(event.type) !== "item.completed") {
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
const item = record(event.item);
|
|
286
|
+
if (text(item?.type) === "agent_message") {
|
|
287
|
+
const content = text(item?.text) ?? text(item?.content);
|
|
288
|
+
result = content ?? result;
|
|
289
|
+
if (content !== undefined && content.length > 0)
|
|
290
|
+
discardedEvent = false;
|
|
291
|
+
}
|
|
292
|
+
}, () => {
|
|
293
|
+
discardedEvent = true;
|
|
294
|
+
});
|
|
295
|
+
if (discardedEvent) {
|
|
296
|
+
throw new Error("Provider JSON event exceeded 1 MiB without a later text response");
|
|
297
|
+
}
|
|
298
|
+
return {
|
|
299
|
+
result: result || "Codex completed the task without a text response.",
|
|
300
|
+
...sessionId === undefined ? {} : { sessionId }
|
|
301
|
+
};
|
|
302
|
+
};
|
|
303
|
+
var parseClaude = (stdout, existingSession) => {
|
|
304
|
+
const value = record(JSON.parse(stdout));
|
|
305
|
+
const result = text(value?.result) ?? text(value?.content);
|
|
306
|
+
if (result === undefined) {
|
|
307
|
+
throw new Error("Claude Code returned JSON without a result");
|
|
308
|
+
}
|
|
309
|
+
const sessionId = text(value?.session_id) ?? text(value?.sessionId) ?? existingSession;
|
|
310
|
+
return { result, ...sessionId === undefined ? {} : { sessionId } };
|
|
311
|
+
};
|
|
312
|
+
var claudeFailureMessage = (stdout) => {
|
|
313
|
+
try {
|
|
314
|
+
const value = record(JSON.parse(stdout));
|
|
315
|
+
const result = text(value?.result) ?? text(value?.content);
|
|
316
|
+
if (result?.trim())
|
|
317
|
+
return result;
|
|
318
|
+
const errors = value?.errors;
|
|
319
|
+
return Array.isArray(errors) ? errors.map(text).filter((error) => error !== undefined).join(`
|
|
320
|
+
`) || undefined : text(errors);
|
|
321
|
+
} catch {
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
var textFromPart = (value) => {
|
|
326
|
+
const part = record(value);
|
|
327
|
+
if (part === undefined) {
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
return text(part.text) ?? text(part.content) ?? text(record(part.part)?.text);
|
|
331
|
+
};
|
|
332
|
+
var openCodeError = (event) => {
|
|
333
|
+
if (text(event.type) !== "error") {
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
const error = record(event.error);
|
|
337
|
+
const name = text(error?.name);
|
|
338
|
+
const message = text(record(error?.data)?.message) ?? text(error?.message) ?? text(event.message) ?? text(event.error);
|
|
339
|
+
if (name !== undefined && message !== undefined) {
|
|
340
|
+
return `OpenCode ${name}: ${message}`;
|
|
341
|
+
}
|
|
342
|
+
return message === undefined ? "OpenCode reported an error" : `OpenCode: ${message}`;
|
|
343
|
+
};
|
|
344
|
+
var parseOpenCode = async (stdout, existingSession) => {
|
|
345
|
+
let result = "";
|
|
346
|
+
let sessionId = existingSession;
|
|
347
|
+
let discardedEvent = false;
|
|
348
|
+
let messageId;
|
|
349
|
+
const parts = new Map;
|
|
350
|
+
let partBytes = 0;
|
|
351
|
+
let oversizedMessage = false;
|
|
352
|
+
const selectMessage = (id) => {
|
|
353
|
+
messageId = id;
|
|
354
|
+
parts.clear();
|
|
355
|
+
partBytes = 0;
|
|
356
|
+
oversizedMessage = false;
|
|
357
|
+
result = "";
|
|
358
|
+
};
|
|
359
|
+
await forEachJsonEvent(stdout, (event) => {
|
|
360
|
+
const failure = openCodeError(event);
|
|
361
|
+
if (failure !== undefined) {
|
|
362
|
+
throw new ProviderRunError({ provider: "opencode", message: failure });
|
|
363
|
+
}
|
|
364
|
+
sessionId = text(event.sessionID) ?? text(event.sessionId) ?? text(event.session_id) ?? text(record(event.info)?.sessionID) ?? sessionId;
|
|
365
|
+
const part = record(event.part);
|
|
366
|
+
const nextMessageId = text(part?.messageID);
|
|
367
|
+
if (text(event.type) === "step_start" && nextMessageId !== undefined && nextMessageId !== messageId) {
|
|
368
|
+
selectMessage(nextMessageId);
|
|
369
|
+
discardedEvent = false;
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
if (text(event.type) !== "text")
|
|
373
|
+
return;
|
|
374
|
+
const content = textFromPart(part) ?? textFromPart(event) ?? text(event.result);
|
|
375
|
+
if (content === undefined)
|
|
376
|
+
return;
|
|
377
|
+
const partId = text(part?.id);
|
|
378
|
+
if (nextMessageId !== undefined && partId !== undefined) {
|
|
379
|
+
if (nextMessageId !== messageId)
|
|
380
|
+
selectMessage(nextMessageId);
|
|
381
|
+
if (oversizedMessage)
|
|
382
|
+
return;
|
|
383
|
+
const previous = parts.get(partId);
|
|
384
|
+
if (content.length === 0 && previous === undefined)
|
|
385
|
+
return;
|
|
386
|
+
partBytes += byteLength(content) - byteLength(previous ?? "") + (previous === undefined ? byteLength(partId) : 0);
|
|
387
|
+
if (partBytes > maxJsonBytes) {
|
|
388
|
+
oversizedMessage = true;
|
|
389
|
+
parts.clear();
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
parts.set(partId, content);
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
if (content.length === 0)
|
|
396
|
+
return;
|
|
397
|
+
selectMessage(undefined);
|
|
398
|
+
result = content;
|
|
399
|
+
discardedEvent = false;
|
|
400
|
+
}, () => {
|
|
401
|
+
discardedEvent = true;
|
|
402
|
+
});
|
|
403
|
+
if (discardedEvent) {
|
|
404
|
+
throw new Error("Provider JSON event exceeded 1 MiB without a later text response");
|
|
405
|
+
}
|
|
406
|
+
if (oversizedMessage)
|
|
407
|
+
throw new Error("OpenCode message exceeded 1 MiB");
|
|
408
|
+
if (parts.size > 0)
|
|
409
|
+
result = [...parts.values()].filter((content) => content.length > 0).join(`
|
|
410
|
+
`);
|
|
411
|
+
if (result.length === 0) {
|
|
412
|
+
throw new Error("OpenCode produced no result; verify its authentication and use a supported project workspace");
|
|
413
|
+
}
|
|
414
|
+
return { result, ...sessionId === undefined ? {} : { sessionId } };
|
|
415
|
+
};
|
|
416
|
+
var readOutput = async (options, stdout, onFailure) => {
|
|
417
|
+
try {
|
|
418
|
+
switch (options.provider) {
|
|
419
|
+
case "codex":
|
|
420
|
+
return await parseCodex(stdout, options.sessionId);
|
|
421
|
+
case "claude-code":
|
|
422
|
+
return await boundedText(stdout, maxJsonBytes, onFailure);
|
|
423
|
+
case "opencode":
|
|
424
|
+
return await parseOpenCode(stdout, options.sessionId);
|
|
425
|
+
}
|
|
426
|
+
} catch (cause) {
|
|
427
|
+
onFailure();
|
|
428
|
+
throw cause;
|
|
429
|
+
}
|
|
430
|
+
};
|
|
431
|
+
var byteLength = (value) => new TextEncoder().encode(value).byteLength;
|
|
432
|
+
var processExists = (pid) => {
|
|
433
|
+
try {
|
|
434
|
+
process.kill(-pid, 0);
|
|
435
|
+
return true;
|
|
436
|
+
} catch (cause) {
|
|
437
|
+
if (typeof cause === "object" && cause !== null && "code" in cause && cause.code === "ESRCH") {
|
|
438
|
+
return false;
|
|
439
|
+
}
|
|
440
|
+
throw cause;
|
|
441
|
+
}
|
|
442
|
+
};
|
|
443
|
+
var waitForProcessGroup = async (pid, timeoutMs) => {
|
|
444
|
+
const deadline = Date.now() + timeoutMs;
|
|
445
|
+
while (processExists(pid)) {
|
|
446
|
+
if (Date.now() >= deadline) {
|
|
447
|
+
return false;
|
|
448
|
+
}
|
|
449
|
+
await new Promise((resolve2) => setTimeout(resolve2, 25));
|
|
450
|
+
}
|
|
451
|
+
return true;
|
|
452
|
+
};
|
|
453
|
+
var terminateWindowsTree = (pid) => new Promise((resolve2) => {
|
|
454
|
+
const systemRoot = process.env.SystemRoot ?? "C:\\Windows";
|
|
455
|
+
execFile(join(systemRoot, "System32", "taskkill.exe"), ["/PID", String(pid), "/T", "/F"], { windowsHide: true }, () => resolve2());
|
|
456
|
+
});
|
|
457
|
+
var terminateProcessTree = async (pid) => {
|
|
458
|
+
if (platform() === "win32") {
|
|
459
|
+
await terminateWindowsTree(pid);
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
try {
|
|
463
|
+
process.kill(-pid, "SIGTERM");
|
|
464
|
+
} catch (cause) {
|
|
465
|
+
if (typeof cause === "object" && cause !== null && "code" in cause && cause.code === "ESRCH") {
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
throw cause;
|
|
469
|
+
}
|
|
470
|
+
if (await waitForProcessGroup(pid, 5000)) {
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
process.kill(-pid, "SIGKILL");
|
|
474
|
+
await waitForProcessGroup(pid, 1000);
|
|
475
|
+
};
|
|
476
|
+
var settlePromise = (promise) => promise.then((value) => ({ _tag: "Success", value }), (error) => ({ _tag: "Failure", error }));
|
|
477
|
+
var run = (options) => Effect.callback((resume, signal) => {
|
|
478
|
+
const running = (async () => {
|
|
479
|
+
const executable = findExecutable(executables[options.provider]);
|
|
480
|
+
if (executable === undefined) {
|
|
481
|
+
throw new ProviderUnavailableError({
|
|
482
|
+
provider: options.provider,
|
|
483
|
+
message: `${executables[options.provider]} is not available on this device`
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
const prepared = await prepareCommand(options);
|
|
487
|
+
try {
|
|
488
|
+
await options.beforeSpawn?.();
|
|
489
|
+
signal.throwIfAborted();
|
|
490
|
+
const [, ...arguments_] = prepared.command;
|
|
491
|
+
const child = execa(executable, arguments_, {
|
|
492
|
+
cwd: options.cwd,
|
|
493
|
+
env: {
|
|
494
|
+
...providerEnvironment(),
|
|
495
|
+
COHALL_PROVIDER: options.provider,
|
|
496
|
+
COHALL_THREAD_ID: options.threadId,
|
|
497
|
+
...options.taskId === undefined ? {} : { COHALL_TASK_ID: options.taskId },
|
|
498
|
+
...options.runId === undefined ? {} : { COHALL_TASK_RUN_ID: options.runId }
|
|
499
|
+
},
|
|
500
|
+
extendEnv: false,
|
|
501
|
+
detached: platform() !== "win32",
|
|
502
|
+
stdin: "pipe",
|
|
503
|
+
stdout: "pipe",
|
|
504
|
+
stderr: "pipe",
|
|
505
|
+
buffer: false,
|
|
506
|
+
reject: false,
|
|
507
|
+
cleanup: false
|
|
508
|
+
});
|
|
509
|
+
let finished = false;
|
|
510
|
+
const exited = child.then(({ exitCode, failed, originalMessage, shortMessage }) => {
|
|
511
|
+
finished = true;
|
|
512
|
+
if (failed && exitCode === undefined) {
|
|
513
|
+
throw new Error(originalMessage ?? shortMessage ?? "Provider failed to start");
|
|
514
|
+
}
|
|
515
|
+
return exitCode ?? 1;
|
|
516
|
+
});
|
|
517
|
+
let termination;
|
|
518
|
+
const terminate = () => {
|
|
519
|
+
if (child.pid === undefined || termination !== undefined) {
|
|
520
|
+
return;
|
|
521
|
+
}
|
|
522
|
+
termination = terminateProcessTree(child.pid).catch(() => {
|
|
523
|
+
return;
|
|
524
|
+
});
|
|
525
|
+
};
|
|
526
|
+
signal.addEventListener("abort", terminate, { once: true });
|
|
527
|
+
if (signal.aborted) {
|
|
528
|
+
terminate();
|
|
529
|
+
}
|
|
530
|
+
try {
|
|
531
|
+
const written = new Promise((resolve2, reject) => {
|
|
532
|
+
child.stdin.once("error", reject);
|
|
533
|
+
child.stdin.end(prepared.input, (cause) => cause === undefined || cause === null ? resolve2() : reject(cause));
|
|
534
|
+
});
|
|
535
|
+
const [output, stderr, exit, input] = await Promise.all([
|
|
536
|
+
settlePromise(readOutput(options, child.stdout, terminate)),
|
|
537
|
+
captureText(child.stderr, 64 * 1024),
|
|
538
|
+
settlePromise(exited),
|
|
539
|
+
settlePromise(written.catch((cause) => {
|
|
540
|
+
terminate();
|
|
541
|
+
throw cause;
|
|
542
|
+
}))
|
|
543
|
+
]);
|
|
544
|
+
if (output._tag === "Failure" && output.error instanceof ProviderRunError)
|
|
545
|
+
throw output.error;
|
|
546
|
+
if (exit._tag === "Failure" && (child.pid === undefined || output._tag === "Success" && input._tag === "Success")) {
|
|
547
|
+
throw exit.error;
|
|
548
|
+
}
|
|
549
|
+
const exitCode = exit._tag === "Success" ? exit.value : undefined;
|
|
550
|
+
if (exitCode !== 0 || input._tag === "Failure") {
|
|
551
|
+
let diagnostic = stderr;
|
|
552
|
+
if (stderr.text.trim().length === 0) {
|
|
553
|
+
let message = output._tag === "Failure" ? output.error instanceof Error ? output.error.message : String(output.error) : typeof output.value === "string" ? claudeFailureMessage(output.value) : undefined;
|
|
554
|
+
if (message === undefined && input._tag === "Failure") {
|
|
555
|
+
message = input.error instanceof Error ? input.error.message : String(input.error);
|
|
556
|
+
}
|
|
557
|
+
if (message !== undefined)
|
|
558
|
+
diagnostic = { text: message, truncated: false };
|
|
559
|
+
}
|
|
560
|
+
throw new ProviderRunError({
|
|
561
|
+
provider: options.provider,
|
|
562
|
+
message: failureMessage(executables[options.provider], diagnostic, exitCode),
|
|
563
|
+
...exitCode === undefined ? {} : { exitCode }
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
if (output._tag === "Failure")
|
|
567
|
+
throw output.error;
|
|
568
|
+
const result = typeof output.value === "string" ? parseClaude(output.value, options.sessionId) : output.value;
|
|
569
|
+
if (byteLength(result.result) > maxResultBytes) {
|
|
570
|
+
throw new ProviderRunError({
|
|
571
|
+
provider: options.provider,
|
|
572
|
+
message: "Provider result exceeded 128 KiB"
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
if (result.sessionId !== undefined && byteLength(result.sessionId) > 4096) {
|
|
576
|
+
throw new ProviderRunError({
|
|
577
|
+
provider: options.provider,
|
|
578
|
+
message: "Provider session ID exceeded 4 KiB"
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
return result;
|
|
582
|
+
} finally {
|
|
583
|
+
signal.removeEventListener("abort", terminate);
|
|
584
|
+
if (!finished) {
|
|
585
|
+
terminate();
|
|
586
|
+
await exited.catch(() => {
|
|
587
|
+
return;
|
|
588
|
+
});
|
|
589
|
+
}
|
|
590
|
+
await termination;
|
|
591
|
+
}
|
|
592
|
+
} finally {
|
|
593
|
+
await prepared.cleanup();
|
|
594
|
+
}
|
|
595
|
+
})();
|
|
596
|
+
running.then((result) => resume(Effect.succeed(result)), (cause) => resume(Effect.fail(cause instanceof ProviderUnavailableError || cause instanceof ProviderRunError ? cause : new ProviderRunError({
|
|
597
|
+
provider: options.provider,
|
|
598
|
+
message: (cause instanceof Error ? cause.message : String(cause)).slice(0, 16384)
|
|
599
|
+
}))));
|
|
600
|
+
return Effect.promise(() => running.then(() => {
|
|
601
|
+
return;
|
|
602
|
+
}, () => {
|
|
603
|
+
return;
|
|
604
|
+
}));
|
|
605
|
+
});
|
|
606
|
+
|
|
607
|
+
// apps/device/src/bot-replies.ts
|
|
608
|
+
import { Schema as Schema2 } from "effect";
|
|
609
|
+
import { randomUUID } from "node:crypto";
|
|
610
|
+
import { chmod as chmod2, link, mkdir, open, unlink } from "node:fs/promises";
|
|
611
|
+
import { dirname, join as join2 } from "node:path";
|
|
612
|
+
import { platform as platform2 } from "node:os";
|
|
613
|
+
var replyLifetimeMs = 6 * 60 * 60 * 1000;
|
|
614
|
+
var Pending = Schema2.Struct({
|
|
615
|
+
taskId: TaskId,
|
|
616
|
+
botId: BotId,
|
|
617
|
+
threadId: ThreadId,
|
|
618
|
+
deadline: Schema2.Int.check(Schema2.isGreaterThanOrEqualTo(0))
|
|
619
|
+
});
|
|
620
|
+
var Dispatch = Schema2.Struct({ taskId: TaskId });
|
|
621
|
+
var Reply = Schema2.Union([
|
|
622
|
+
Schema2.Struct({
|
|
623
|
+
result: Schema2.String.check(Schema2.isMaxLength(131072)),
|
|
624
|
+
error: Schema2.optionalKey(Schema2.Never),
|
|
625
|
+
question: Schema2.optionalKey(Schema2.Never)
|
|
626
|
+
}),
|
|
627
|
+
Schema2.Struct({
|
|
628
|
+
error: Schema2.NonEmptyString.check(Schema2.isMaxLength(16384)),
|
|
629
|
+
result: Schema2.optionalKey(Schema2.Never),
|
|
630
|
+
question: Schema2.optionalKey(Schema2.Never)
|
|
631
|
+
}),
|
|
632
|
+
Schema2.Struct({
|
|
633
|
+
question: RequestTaskInput.fields.question,
|
|
634
|
+
result: Schema2.optionalKey(Schema2.Never),
|
|
635
|
+
error: Schema2.optionalKey(Schema2.Never)
|
|
636
|
+
})
|
|
637
|
+
]);
|
|
638
|
+
var Receipt = Schema2.Struct({
|
|
639
|
+
taskId: TaskId,
|
|
640
|
+
submittedAt: Schema2.Int.check(Schema2.isGreaterThanOrEqualTo(0)),
|
|
641
|
+
reply: Reply
|
|
642
|
+
});
|
|
643
|
+
var isMissing = (cause) => cause instanceof Error && ("code" in cause) && cause.code === "ENOENT";
|
|
644
|
+
var alreadyExists = (cause) => cause instanceof Error && ("code" in cause) && cause.code === "EEXIST";
|
|
645
|
+
var paths = (taskId, runId) => {
|
|
646
|
+
const id = Schema2.decodeUnknownSync(TaskId)(taskId);
|
|
647
|
+
const directory = join2(dirname(configurationPath()), "bot-replies");
|
|
648
|
+
const key = runId === undefined ? id : `${id}.${Schema2.decodeUnknownSync(TaskRunId)(runId)}`;
|
|
649
|
+
return {
|
|
650
|
+
directory,
|
|
651
|
+
pending: join2(directory, `${key}.pending.json`),
|
|
652
|
+
receipt: join2(directory, `${key}.reply.json`),
|
|
653
|
+
dispatch: join2(directory, `${key}.dispatch.json`)
|
|
654
|
+
};
|
|
655
|
+
};
|
|
656
|
+
var readJson = async (path, limit) => {
|
|
657
|
+
const file = await open(path, "r").catch((cause) => {
|
|
658
|
+
if (isMissing(cause))
|
|
659
|
+
return;
|
|
660
|
+
throw cause;
|
|
661
|
+
});
|
|
662
|
+
if (file === undefined)
|
|
663
|
+
return;
|
|
664
|
+
try {
|
|
665
|
+
const buffer = Buffer.alloc(limit + 1);
|
|
666
|
+
let size = 0;
|
|
667
|
+
while (size < buffer.length) {
|
|
668
|
+
const { bytesRead } = await file.read(buffer, size, buffer.length - size, size);
|
|
669
|
+
if (bytesRead === 0)
|
|
670
|
+
break;
|
|
671
|
+
size += bytesRead;
|
|
672
|
+
}
|
|
673
|
+
if (size > limit)
|
|
674
|
+
throw new Error("Bot reply record exceeds its size limit");
|
|
675
|
+
return JSON.parse(buffer.subarray(0, size).toString("utf8"));
|
|
676
|
+
} catch {
|
|
677
|
+
throw new Error("Invalid local bot reply record");
|
|
678
|
+
} finally {
|
|
679
|
+
await file.close();
|
|
680
|
+
}
|
|
681
|
+
};
|
|
682
|
+
var pendingReply = async (taskId, runId) => {
|
|
683
|
+
const value = await readJson(paths(taskId, runId).pending, 4096);
|
|
684
|
+
if (value === undefined)
|
|
685
|
+
return;
|
|
686
|
+
const decoded = Schema2.decodeUnknownResult(Pending)(value);
|
|
687
|
+
if (decoded._tag === "Failure" || decoded.success.taskId !== taskId) {
|
|
688
|
+
throw new Error("Invalid local bot reply manifest");
|
|
689
|
+
}
|
|
690
|
+
return decoded.success;
|
|
691
|
+
};
|
|
692
|
+
var publish = async (path, value) => {
|
|
693
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
694
|
+
const file = await open(temporary, "wx", 384);
|
|
695
|
+
try {
|
|
696
|
+
try {
|
|
697
|
+
await file.writeFile(`${JSON.stringify(value)}
|
|
698
|
+
`, "utf8");
|
|
699
|
+
await file.sync();
|
|
700
|
+
} finally {
|
|
701
|
+
await file.close();
|
|
702
|
+
}
|
|
703
|
+
await link(temporary, path);
|
|
704
|
+
if (platform2() !== "win32") {
|
|
705
|
+
const directory = await open(dirname(path), "r");
|
|
706
|
+
try {
|
|
707
|
+
await directory.sync();
|
|
708
|
+
} finally {
|
|
709
|
+
await directory.close();
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
return true;
|
|
713
|
+
} catch (cause) {
|
|
714
|
+
if (alreadyExists(cause))
|
|
715
|
+
return false;
|
|
716
|
+
throw cause;
|
|
717
|
+
} finally {
|
|
718
|
+
await unlink(temporary);
|
|
719
|
+
}
|
|
720
|
+
};
|
|
721
|
+
var shellQuote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
|
|
722
|
+
var prepareBotReply = async (task) => {
|
|
723
|
+
if (task.provider !== "grok-bot" || task.botId === undefined) {
|
|
724
|
+
throw new Error("Only a named Grok Bot task can receive a bot reply");
|
|
725
|
+
}
|
|
726
|
+
const files = paths(task.id, task.runId);
|
|
727
|
+
await mkdir(files.directory, { recursive: true, mode: 448 });
|
|
728
|
+
await chmod2(files.directory, 448);
|
|
729
|
+
const record2 = Pending.make({
|
|
730
|
+
taskId: task.id,
|
|
731
|
+
botId: task.botId,
|
|
732
|
+
threadId: task.threadId,
|
|
733
|
+
deadline: Date.now() + replyLifetimeMs
|
|
734
|
+
});
|
|
735
|
+
await publish(files.pending, record2);
|
|
736
|
+
const pending = await pendingReply(task.id, task.runId);
|
|
737
|
+
if (pending === undefined || pending.botId !== task.botId || pending.threadId !== task.threadId) {
|
|
738
|
+
throw new Error("Bot reply manifest does not match this task");
|
|
739
|
+
}
|
|
740
|
+
const dispatch = await readJson(files.dispatch, 4096);
|
|
741
|
+
if (dispatch !== undefined) {
|
|
742
|
+
const decoded = Schema2.decodeUnknownResult(Dispatch)(dispatch);
|
|
743
|
+
if (decoded._tag === "Failure" || decoded.success.taskId !== task.id) {
|
|
744
|
+
throw new Error("Invalid local bot dispatch record");
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
return {
|
|
748
|
+
deadline: pending.deadline,
|
|
749
|
+
command: `COHALL_CONFIG=${shellQuote(configurationPath())} cohall`,
|
|
750
|
+
dispatched: dispatch !== undefined
|
|
751
|
+
};
|
|
752
|
+
};
|
|
753
|
+
var claimBotDispatch = async (taskId, runId) => {
|
|
754
|
+
const pending = await pendingReply(taskId, runId);
|
|
755
|
+
if (pending === undefined)
|
|
756
|
+
throw new Error("No pending bot reply for this task");
|
|
757
|
+
if (Date.now() >= pending.deadline)
|
|
758
|
+
throw new Error("Bot reply deadline has expired");
|
|
759
|
+
return publish(paths(taskId, runId).dispatch, { taskId });
|
|
760
|
+
};
|
|
761
|
+
var readBotReply = async (taskId, runId) => {
|
|
762
|
+
const pending = await pendingReply(taskId, runId);
|
|
763
|
+
if (pending === undefined)
|
|
764
|
+
return;
|
|
765
|
+
const value = await readJson(paths(taskId, runId).receipt, 1024 * 1024);
|
|
766
|
+
if (value === undefined)
|
|
767
|
+
return;
|
|
768
|
+
const decoded = Schema2.decodeUnknownResult(Receipt)(value);
|
|
769
|
+
if (decoded._tag === "Failure" || decoded.success.taskId !== taskId) {
|
|
770
|
+
throw new Error("Invalid local bot reply receipt");
|
|
771
|
+
}
|
|
772
|
+
if (decoded.success.submittedAt >= pending.deadline) {
|
|
773
|
+
throw new Error("Bot reply was submitted after its deadline");
|
|
774
|
+
}
|
|
775
|
+
return decoded.success.reply;
|
|
776
|
+
};
|
|
777
|
+
var writeBotReply = async (taskId, reply, runId) => {
|
|
778
|
+
const decoded = Schema2.decodeUnknownResult(Reply)(reply);
|
|
779
|
+
if (decoded._tag === "Failure") {
|
|
780
|
+
throw new Error("Provide a result of at most 131072 characters, a nonempty error of at most 16384 characters, or a clarification question of at most 4096 UTF-8 bytes");
|
|
781
|
+
}
|
|
782
|
+
const pending = await pendingReply(taskId, runId);
|
|
783
|
+
if (pending === undefined)
|
|
784
|
+
throw new Error("No pending bot reply for this task");
|
|
785
|
+
const existing = await readBotReply(taskId, runId);
|
|
786
|
+
if (existing !== undefined) {
|
|
787
|
+
if (JSON.stringify(existing) === JSON.stringify(decoded.success))
|
|
788
|
+
return;
|
|
789
|
+
throw new Error("A different reply has already been submitted for this task");
|
|
790
|
+
}
|
|
791
|
+
const submittedAt = Date.now();
|
|
792
|
+
if (submittedAt >= pending.deadline)
|
|
793
|
+
throw new Error("Bot reply deadline has expired");
|
|
794
|
+
if (await publish(paths(taskId, runId).receipt, { taskId, submittedAt, reply: decoded.success }))
|
|
795
|
+
return;
|
|
796
|
+
const winner = await readBotReply(taskId, runId);
|
|
797
|
+
if (JSON.stringify(winner) !== JSON.stringify(decoded.success)) {
|
|
798
|
+
throw new Error("A different reply has already been submitted for this task");
|
|
799
|
+
}
|
|
800
|
+
};
|
|
801
|
+
var cleanupBotReply = async (taskId, runId) => {
|
|
802
|
+
const files = paths(taskId, runId);
|
|
803
|
+
for (const path of [files.pending, files.receipt, files.dispatch]) {
|
|
804
|
+
await unlink(path).catch((cause) => {
|
|
805
|
+
if (!isMissing(cause))
|
|
806
|
+
throw cause;
|
|
807
|
+
});
|
|
808
|
+
}
|
|
809
|
+
};
|
|
810
|
+
|
|
811
|
+
// apps/device/src/grok-bot.ts
|
|
812
|
+
import { Effect as Effect2, Schedule, Schema as Schema3 } from "effect";
|
|
813
|
+
import { constants as constants2 } from "node:fs";
|
|
814
|
+
import { open as open2 } from "node:fs/promises";
|
|
815
|
+
import { isIP } from "node:net";
|
|
816
|
+
var maxResponseBytes = 4 * 1024 * 1024;
|
|
817
|
+
var maxDiscoveryBytes = 64 * 1024;
|
|
818
|
+
var text2 = Schema3.NonEmptyString;
|
|
819
|
+
var Discovery = Schema3.Struct({
|
|
820
|
+
port: Schema3.Int.check(Schema3.isBetween({ minimum: 1, maximum: 65535 })),
|
|
821
|
+
host: Schema3.optionalKey(text2),
|
|
822
|
+
scheme: Schema3.optionalKey(Schema3.Literals(["http", "https"])),
|
|
823
|
+
token: Schema3.optionalKey(Schema3.String.check(Schema3.isMaxLength(16384)))
|
|
824
|
+
});
|
|
825
|
+
var Agent = Schema3.Struct({
|
|
826
|
+
id: Bot.fields.id,
|
|
827
|
+
name: Bot.fields.name,
|
|
828
|
+
description: Schema3.optionalKey(Schema3.String),
|
|
829
|
+
isGroup: Schema3.optionalKey(Schema3.Boolean)
|
|
830
|
+
});
|
|
831
|
+
var Roster = Schema3.Array(Agent).check(Schema3.isMaxLength(1024));
|
|
832
|
+
var Acceptance = Schema3.Union([
|
|
833
|
+
Schema3.Struct({ outcome: Schema3.Literals(["not-found", "unknown-durability"]) }),
|
|
834
|
+
Schema3.Struct({
|
|
835
|
+
outcome: Schema3.Literal("found"),
|
|
836
|
+
record: Schema3.Struct({
|
|
837
|
+
status: Schema3.Literals(["accepted", "pending", "rejected"])
|
|
838
|
+
})
|
|
839
|
+
})
|
|
840
|
+
]);
|
|
841
|
+
var SendResult = Schema3.Struct({ accepted: Schema3.Literal(true) });
|
|
842
|
+
|
|
843
|
+
class GatewayError extends Error {
|
|
844
|
+
}
|
|
845
|
+
var decode = (schema, value, label) => {
|
|
846
|
+
const result = Schema3.decodeUnknownResult(schema)(value);
|
|
847
|
+
if (result._tag === "Failure")
|
|
848
|
+
throw new GatewayError(`Grok Bot returned an invalid ${label}`);
|
|
849
|
+
return result.success;
|
|
850
|
+
};
|
|
851
|
+
var readConnection = async (path) => {
|
|
852
|
+
const value = await (async () => {
|
|
853
|
+
const file = await open2(path, constants2.O_RDONLY | (process.platform === "win32" ? 0 : constants2.O_NONBLOCK));
|
|
854
|
+
try {
|
|
855
|
+
const metadata = await file.stat();
|
|
856
|
+
if (!metadata.isFile())
|
|
857
|
+
throw new Error("Discovery must be a regular file");
|
|
858
|
+
const buffer = await readBoundedFile(file, maxDiscoveryBytes);
|
|
859
|
+
if (buffer.length > maxDiscoveryBytes)
|
|
860
|
+
throw new Error("Discovery file exceeds its size limit");
|
|
861
|
+
return decode(Discovery, JSON.parse(buffer.toString("utf8")), "discovery file");
|
|
862
|
+
} finally {
|
|
863
|
+
await file.close();
|
|
864
|
+
}
|
|
865
|
+
})().catch(() => {
|
|
866
|
+
throw new Error("Cannot read Grok Bot gateway discovery; check its configured file and running gateway");
|
|
867
|
+
});
|
|
868
|
+
const host = value.host ?? "127.0.0.1";
|
|
869
|
+
const normalized = host === "0.0.0.0" || host === "localhost" ? "127.0.0.1" : host === "::" || host === "::1" || host === "[::1]" ? "[::1]" : host;
|
|
870
|
+
if (!(normalized === "[::1]" || isIP(normalized) === 4 && normalized.startsWith("127."))) {
|
|
871
|
+
throw new Error("Grok Bot gateway must use a loopback address on this device");
|
|
872
|
+
}
|
|
873
|
+
return { url: `${value.scheme ?? "http"}://${normalized}:${value.port}`, token: value.token };
|
|
874
|
+
};
|
|
875
|
+
var rpc = async (connection, method, args, schema, signal) => {
|
|
876
|
+
const controller = new AbortController;
|
|
877
|
+
const deadline = setTimeout(() => controller.abort(), 20000);
|
|
878
|
+
const combined = signal === undefined ? controller.signal : AbortSignal.any([signal, controller.signal]);
|
|
879
|
+
try {
|
|
880
|
+
const response = await fetch(`${connection.url}/api/${method}`, {
|
|
881
|
+
method: "POST",
|
|
882
|
+
redirect: "error",
|
|
883
|
+
headers: {
|
|
884
|
+
"content-type": "application/json",
|
|
885
|
+
"x-sand-slim-avatars": "1",
|
|
886
|
+
...connection.token === undefined || connection.token.length === 0 ? {} : { authorization: `Bearer ${connection.token}` }
|
|
887
|
+
},
|
|
888
|
+
body: JSON.stringify(args),
|
|
889
|
+
signal: combined
|
|
890
|
+
});
|
|
891
|
+
if (!response.ok) {
|
|
892
|
+
await response.body?.cancel();
|
|
893
|
+
throw new GatewayError(`Grok Bot ${method} failed (HTTP ${response.status})`);
|
|
894
|
+
}
|
|
895
|
+
if (response.body === null)
|
|
896
|
+
throw new GatewayError("Grok Bot returned an empty response");
|
|
897
|
+
const reader = response.body.getReader();
|
|
898
|
+
const chunks = [];
|
|
899
|
+
let size = 0;
|
|
900
|
+
try {
|
|
901
|
+
for (;; ) {
|
|
902
|
+
const chunk = await reader.read();
|
|
903
|
+
if (chunk.done)
|
|
904
|
+
break;
|
|
905
|
+
size += chunk.value.byteLength;
|
|
906
|
+
if (size > maxResponseBytes)
|
|
907
|
+
throw new GatewayError("Grok Bot response exceeded 4 MiB");
|
|
908
|
+
chunks.push(chunk.value);
|
|
909
|
+
}
|
|
910
|
+
} finally {
|
|
911
|
+
await reader.cancel().catch(() => {
|
|
912
|
+
return;
|
|
913
|
+
});
|
|
914
|
+
reader.releaseLock();
|
|
915
|
+
}
|
|
916
|
+
let json;
|
|
917
|
+
try {
|
|
918
|
+
json = JSON.parse(Buffer.concat(chunks, size).toString("utf8"));
|
|
919
|
+
} catch {
|
|
920
|
+
throw new GatewayError(`Grok Bot ${method} returned invalid JSON`);
|
|
921
|
+
}
|
|
922
|
+
return decode(schema, json, `${method} response`);
|
|
923
|
+
} catch (cause) {
|
|
924
|
+
if (signal?.aborted)
|
|
925
|
+
throw new Error("Stopped waiting for Grok Bot; its run may still be active");
|
|
926
|
+
if (cause instanceof GatewayError)
|
|
927
|
+
throw cause;
|
|
928
|
+
throw new Error(`Grok Bot ${method} failed; check gateway availability and compatibility`);
|
|
929
|
+
} finally {
|
|
930
|
+
clearTimeout(deadline);
|
|
931
|
+
}
|
|
932
|
+
};
|
|
933
|
+
var discoverGrokBots = async (path, signal) => {
|
|
934
|
+
const connection = await readConnection(path);
|
|
935
|
+
const roster = await rpc(connection, "listAgents", {}, Roster, signal);
|
|
936
|
+
const bots = roster.filter((agent) => agent.isGroup !== true);
|
|
937
|
+
if (bots.length > 256)
|
|
938
|
+
throw new Error("Grok Bot discovery exceeds Cohall's limit of 256 bots");
|
|
939
|
+
if (new Set(bots.map((bot) => bot.id)).size !== bots.length) {
|
|
940
|
+
throw new Error("Grok Bot returned duplicate bot identities");
|
|
941
|
+
}
|
|
942
|
+
return bots.map(({ id, name, description }) => ({
|
|
943
|
+
id,
|
|
944
|
+
name,
|
|
945
|
+
...description === undefined ? {} : { description: description.slice(0, 512) }
|
|
946
|
+
}));
|
|
947
|
+
};
|
|
948
|
+
var poll = (pass, intervalMs = 1000) => Effect2.tryPromise({ try: pass, catch: (cause) => cause }).pipe(Effect2.repeat({
|
|
949
|
+
schedule: Schedule.spaced(intervalMs),
|
|
950
|
+
until: (value) => value !== undefined
|
|
951
|
+
}));
|
|
952
|
+
var timeoutMessage = "Timed out waiting for the bot to reply through Cohall; the bot may still be running.";
|
|
953
|
+
var requireTime = (deadline) => {
|
|
954
|
+
if (Date.now() >= deadline)
|
|
955
|
+
throw new Error(timeoutMessage);
|
|
956
|
+
};
|
|
957
|
+
var finishReply = (reply) => {
|
|
958
|
+
if (reply.question !== undefined)
|
|
959
|
+
return { result: "", question: reply.question };
|
|
960
|
+
if (reply.error !== undefined)
|
|
961
|
+
throw new Error(reply.error);
|
|
962
|
+
if (reply.result === undefined)
|
|
963
|
+
throw new Error("Grok Bot returned an invalid Cohall reply");
|
|
964
|
+
return { result: reply.result };
|
|
965
|
+
};
|
|
966
|
+
var taskPrompt = (task, command, supportsClarification) => {
|
|
967
|
+
const reply = `${command} reply ${task.id}${task.runId === undefined ? "" : ` --run-id ${task.runId}`}`;
|
|
968
|
+
return [
|
|
969
|
+
task.prompt,
|
|
970
|
+
task.context === undefined ? "" : `Context:
|
|
971
|
+
${task.context}`,
|
|
972
|
+
`This request came through Cohall. Thread: ${task.threadId}. Task: ${task.id}.`,
|
|
973
|
+
`You may use your own tools and delegate work to another Cohall device when the request calls for it. Discover devices with: ${command} devices`,
|
|
974
|
+
`Delegation example: ${command} delegate --thread ${task.threadId} --parent ${task.id} --target @device --provider codex --prompt 'Concrete task' --context 'Relevant context'`,
|
|
975
|
+
"When finished, hand the final answer back to Cohall so it reaches the requesting device. Write it to a UTF-8 file on this computer, then run:",
|
|
976
|
+
`${reply} --message-file /absolute/path/to/your-answer.txt`,
|
|
977
|
+
`Alternatively pipe your answer into: ${reply} --message -`,
|
|
978
|
+
`If you cannot complete this task, report the reason with: ${reply} --error 'Reason'`,
|
|
979
|
+
...supportsClarification && task.runId !== undefined ? [
|
|
980
|
+
`If essential information is missing, run ${reply} --question 'Your question' and end this turn. Cohall will pause the task and send a new turn with the answer. Do not send a final reply after asking.`,
|
|
981
|
+
...(task.clarifications ?? []).flatMap((question) => question.answer === undefined ? [] : [
|
|
982
|
+
`Clarification question:
|
|
983
|
+
${question.question}
|
|
984
|
+
Sender's answer:
|
|
985
|
+
${question.answer.text}`
|
|
986
|
+
])
|
|
987
|
+
] : [],
|
|
988
|
+
"The callback command must succeed. After submitting a final result, send the same answer in this chat. After submitting a question, end the turn. A normal chat message alone does not complete the Cohall task."
|
|
989
|
+
].filter(Boolean).join(`
|
|
990
|
+
|
|
991
|
+
`);
|
|
992
|
+
};
|
|
993
|
+
var runGrokBot = async (path, task, signal, supportsClarification = false) => {
|
|
994
|
+
const existing = await readBotReply(task.id, task.runId);
|
|
995
|
+
if (existing !== undefined)
|
|
996
|
+
return finishReply(existing);
|
|
997
|
+
const { deadline, command, dispatched } = await prepareBotReply(task);
|
|
998
|
+
requireTime(deadline);
|
|
999
|
+
const agentId = task.botId;
|
|
1000
|
+
if (agentId === undefined)
|
|
1001
|
+
throw new Error("Select a Grok Bot for this task");
|
|
1002
|
+
const lookup = async (lookupSignal = signal) => {
|
|
1003
|
+
if (path === undefined)
|
|
1004
|
+
throw new Error("Configure this device's Grok Bot gateway discovery file first");
|
|
1005
|
+
return rpc(await readConnection(path), "promptAcceptanceStatus", { accountSlot: "host", agentId, clientNonce: task.runId ?? task.id }, Acceptance, lookupSignal);
|
|
1006
|
+
};
|
|
1007
|
+
const waitForReply = (reconcile = false) => {
|
|
1008
|
+
const receipt = poll(async () => {
|
|
1009
|
+
const receipt2 = await readBotReply(task.id, task.runId);
|
|
1010
|
+
if (receipt2 !== undefined)
|
|
1011
|
+
return finishReply(receipt2);
|
|
1012
|
+
requireTime(deadline);
|
|
1013
|
+
return;
|
|
1014
|
+
});
|
|
1015
|
+
if (!reconcile || path === undefined)
|
|
1016
|
+
return Effect2.runPromise(receipt, { signal });
|
|
1017
|
+
const acceptance2 = poll(async (lookupSignal) => {
|
|
1018
|
+
const current = await lookup(lookupSignal).catch(() => {
|
|
1019
|
+
return;
|
|
1020
|
+
});
|
|
1021
|
+
if (current?.outcome !== "found")
|
|
1022
|
+
return;
|
|
1023
|
+
if (current.record.status === "rejected")
|
|
1024
|
+
throw new Error("Grok Bot rejected this task; check its conversation");
|
|
1025
|
+
return current.record.status === "accepted" ? true : undefined;
|
|
1026
|
+
}, 5000).pipe(Effect2.andThen(Effect2.never));
|
|
1027
|
+
return Effect2.runPromise(Effect2.raceFirst(receipt, acceptance2), { signal });
|
|
1028
|
+
};
|
|
1029
|
+
if (dispatched)
|
|
1030
|
+
return waitForReply(true);
|
|
1031
|
+
if (path === undefined)
|
|
1032
|
+
throw new Error("Configure this device's Grok Bot gateway discovery file first");
|
|
1033
|
+
const connection = await readConnection(path);
|
|
1034
|
+
let acceptance = await lookup();
|
|
1035
|
+
if (acceptance.outcome === "unknown-durability")
|
|
1036
|
+
throw new Error("Grok Bot cannot confirm whether this task was accepted; check its conversation before retrying");
|
|
1037
|
+
if (acceptance.outcome === "not-found") {
|
|
1038
|
+
const receipt = await readBotReply(task.id, task.runId);
|
|
1039
|
+
if (receipt !== undefined)
|
|
1040
|
+
return finishReply(receipt);
|
|
1041
|
+
requireTime(deadline);
|
|
1042
|
+
const roster = await rpc(connection, "listAgents", {}, Roster, signal);
|
|
1043
|
+
if (!roster.some((row) => row.id === agentId && row.isGroup !== true)) {
|
|
1044
|
+
throw new Error("The selected Grok Bot no longer exists on this device");
|
|
1045
|
+
}
|
|
1046
|
+
requireTime(deadline);
|
|
1047
|
+
acceptance = await lookup();
|
|
1048
|
+
if (acceptance.outcome === "not-found") {
|
|
1049
|
+
requireTime(deadline);
|
|
1050
|
+
if (!await claimBotDispatch(task.id, task.runId)) {
|
|
1051
|
+
return waitForReply(true);
|
|
1052
|
+
}
|
|
1053
|
+
try {
|
|
1054
|
+
await rpc(connection, "sendPrompt", {
|
|
1055
|
+
agentId,
|
|
1056
|
+
prompt: taskPrompt(task, command, supportsClarification),
|
|
1057
|
+
clientNonce: task.runId ?? task.id,
|
|
1058
|
+
directAddressedAcceptance: true
|
|
1059
|
+
}, SendResult, signal);
|
|
1060
|
+
} catch {
|
|
1061
|
+
if (signal.aborted)
|
|
1062
|
+
throw new Error("Stopped waiting for Grok Bot; its run may still be active");
|
|
1063
|
+
const receipt2 = await readBotReply(task.id, task.runId);
|
|
1064
|
+
if (receipt2 !== undefined)
|
|
1065
|
+
return finishReply(receipt2);
|
|
1066
|
+
return waitForReply(true);
|
|
1067
|
+
}
|
|
1068
|
+
return waitForReply();
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
if (acceptance.outcome === "unknown-durability")
|
|
1072
|
+
throw new Error("Grok Bot cannot confirm task acceptance; the prompt was not resent");
|
|
1073
|
+
if (acceptance.outcome === "found" && acceptance.record.status === "rejected")
|
|
1074
|
+
throw new Error("Grok Bot rejected this task; check its conversation");
|
|
1075
|
+
return waitForReply(acceptance.outcome === "found" && acceptance.record.status === "pending");
|
|
1076
|
+
};
|
|
1077
|
+
|
|
1078
|
+
// apps/device/src/upgrade.ts
|
|
1079
|
+
import { Schema as Schema4 } from "effect";
|
|
1080
|
+
import { execa as execa2 } from "execa";
|
|
1081
|
+
import { constants as constants3 } from "node:fs";
|
|
1082
|
+
import {
|
|
1083
|
+
access,
|
|
1084
|
+
chmod as chmod3,
|
|
1085
|
+
mkdir as mkdir2,
|
|
1086
|
+
readFile,
|
|
1087
|
+
readdir,
|
|
1088
|
+
realpath,
|
|
1089
|
+
rename,
|
|
1090
|
+
rm as rm2,
|
|
1091
|
+
stat,
|
|
1092
|
+
writeFile as writeFile2
|
|
1093
|
+
} from "node:fs/promises";
|
|
1094
|
+
import { delimiter as delimiter2, dirname as dirname2, extname as extname2, isAbsolute as isAbsolute2, join as join3, relative, resolve as resolve2, sep } from "node:path";
|
|
1095
|
+
import { platform as operatingSystem } from "node:os";
|
|
1096
|
+
var packageName = "@akshar5/cohall";
|
|
1097
|
+
var minimumBunLookupVersion = "1.2.15";
|
|
1098
|
+
var semanticVersion = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
|
|
1099
|
+
var parseVersion = (value) => {
|
|
1100
|
+
const [, major, minor, patch, prerelease] = semanticVersion.exec(value) ?? [];
|
|
1101
|
+
if (major === undefined || minor === undefined || patch === undefined)
|
|
1102
|
+
return;
|
|
1103
|
+
const identifiers = prerelease?.split(".") ?? [];
|
|
1104
|
+
if (identifiers.some((part) => /^0\d+$/.test(part)))
|
|
1105
|
+
return;
|
|
1106
|
+
return {
|
|
1107
|
+
core: [BigInt(major), BigInt(minor), BigInt(patch)],
|
|
1108
|
+
prerelease: identifiers
|
|
1109
|
+
};
|
|
1110
|
+
};
|
|
1111
|
+
var compareVersions = (left, right) => {
|
|
1112
|
+
const a = parseVersion(left);
|
|
1113
|
+
const b = parseVersion(right);
|
|
1114
|
+
if (a === undefined || b === undefined) {
|
|
1115
|
+
throw new Error(`Could not safely compare Cohall versions ${left} and ${right}`);
|
|
1116
|
+
}
|
|
1117
|
+
for (const [index, part] of a.core.entries()) {
|
|
1118
|
+
const other = b.core[index];
|
|
1119
|
+
if (other !== undefined && part !== other)
|
|
1120
|
+
return part > other ? 1 : -1;
|
|
1121
|
+
}
|
|
1122
|
+
if (a.prerelease.length === 0 || b.prerelease.length === 0) {
|
|
1123
|
+
return Number(b.prerelease.length > 0) - Number(a.prerelease.length > 0);
|
|
1124
|
+
}
|
|
1125
|
+
for (let index = 0;index < Math.max(a.prerelease.length, b.prerelease.length); index += 1) {
|
|
1126
|
+
const part = a.prerelease[index];
|
|
1127
|
+
const other = b.prerelease[index];
|
|
1128
|
+
if (part === undefined)
|
|
1129
|
+
return -1;
|
|
1130
|
+
if (other === undefined)
|
|
1131
|
+
return 1;
|
|
1132
|
+
if (part === other)
|
|
1133
|
+
continue;
|
|
1134
|
+
const numeric = /^\d+$/.test(part);
|
|
1135
|
+
const otherNumeric = /^\d+$/.test(other);
|
|
1136
|
+
if (numeric !== otherNumeric)
|
|
1137
|
+
return numeric ? -1 : 1;
|
|
1138
|
+
return numeric ? BigInt(part) > BigInt(other) ? 1 : -1 : part > other ? 1 : -1;
|
|
1139
|
+
}
|
|
1140
|
+
return 0;
|
|
1141
|
+
};
|
|
1142
|
+
var PackageManager = Schema4.Literals(["npm", "bun", "pnpm"]);
|
|
1143
|
+
var RestartReceipt = Schema4.Struct({
|
|
1144
|
+
version: Schema4.String,
|
|
1145
|
+
fromVersion: Schema4.String,
|
|
1146
|
+
packageManager: PackageManager,
|
|
1147
|
+
pendingServices: Schema4.Array(Schema4.String),
|
|
1148
|
+
restartedServices: Schema4.Array(Schema4.String),
|
|
1149
|
+
restartingService: Schema4.optionalKey(Schema4.String)
|
|
1150
|
+
});
|
|
1151
|
+
var pnpmEnvironment = () => Object.fromEntries([
|
|
1152
|
+
["COREPACK_ENABLE_PROJECT_SPEC", "0"],
|
|
1153
|
+
...["GLOBAL_DIR", "GLOBAL_BIN_DIR", "STORE_DIR"].flatMap((name) => {
|
|
1154
|
+
const value = process.env[`COHALL_PNPM_${name}`];
|
|
1155
|
+
return value === undefined ? [] : [
|
|
1156
|
+
[`npm_config_${name.toLowerCase()}`, value],
|
|
1157
|
+
[`pnpm_config_${name.toLowerCase()}`, value]
|
|
1158
|
+
];
|
|
1159
|
+
})
|
|
1160
|
+
]);
|
|
1161
|
+
var normalizePath = (path) => path.replaceAll("\\", "/");
|
|
1162
|
+
var pnpmGlobalDirectory = /^(.*\/global\/v?\d+)\//;
|
|
1163
|
+
var normalizeUpgradeTarget = (target) => {
|
|
1164
|
+
if (target === undefined || target === "latest") {
|
|
1165
|
+
return "latest";
|
|
1166
|
+
}
|
|
1167
|
+
const normalized = target.startsWith("v") ? target.slice(1) : target;
|
|
1168
|
+
if (parseVersion(normalized) === undefined) {
|
|
1169
|
+
throw new Error("--to must be latest or an exact semantic version");
|
|
1170
|
+
}
|
|
1171
|
+
return normalized;
|
|
1172
|
+
};
|
|
1173
|
+
var deviceVersionWarning = (cliVersion, deviceVersion) => deviceVersion === undefined || deviceVersion === cliVersion ? undefined : `Running device daemon uses Cohall ${deviceVersion}, while this CLI is ${cliVersion}. Run upgrade through the executable configured by the device service.`;
|
|
1174
|
+
var packageInstallation = (canonicalEntrypoint, entrypoint = canonicalEntrypoint, runtimePlatform = process.platform) => {
|
|
1175
|
+
const path = normalizePath(canonicalEntrypoint);
|
|
1176
|
+
const marker = `/node_modules/${packageName}/`;
|
|
1177
|
+
const packageIndex = path.lastIndexOf(marker);
|
|
1178
|
+
if (packageIndex === -1) {
|
|
1179
|
+
throw new Error("cohall upgrade requires a global npm, Bun, or pnpm installation; package-runner and source-checkout executions cannot upgrade themselves");
|
|
1180
|
+
}
|
|
1181
|
+
if ([path, normalizePath(entrypoint)].some((candidate) => candidate.includes("/.npm/_npx/") || candidate.includes("/.bunx/") || candidate.includes("/dlx/"))) {
|
|
1182
|
+
throw new Error("This Cohall process is running from a temporary package-runner cache; install it globally before using cohall upgrade");
|
|
1183
|
+
}
|
|
1184
|
+
if (path.includes("/.bun/install/global/node_modules/")) {
|
|
1185
|
+
return { manager: "bun", entrypoint };
|
|
1186
|
+
}
|
|
1187
|
+
if (pnpmGlobalDirectory.test(path) || /\/v\d+\/links\//.test(path) || path.includes("/node_modules/.pnpm/") || pnpmGlobalDirectory.test(normalizePath(entrypoint))) {
|
|
1188
|
+
return { manager: "pnpm", entrypoint };
|
|
1189
|
+
}
|
|
1190
|
+
const nodeModulesParent = path.slice(0, packageIndex);
|
|
1191
|
+
const prefix = runtimePlatform !== "win32" && nodeModulesParent.endsWith("/lib") ? nodeModulesParent.slice(0, -"/lib".length) || "/" : runtimePlatform === "win32" && nodeModulesParent.endsWith(":") ? `${nodeModulesParent}/` : nodeModulesParent;
|
|
1192
|
+
return { manager: "npm", prefix, entrypoint };
|
|
1193
|
+
};
|
|
1194
|
+
var resolvePackageInstallation = async (entrypoint, options = {}) => {
|
|
1195
|
+
const canonicalEntrypoint = await realpath(entrypoint);
|
|
1196
|
+
const runtimePlatform = options.platform ?? process.platform;
|
|
1197
|
+
const installation = packageInstallation(canonicalEntrypoint, resolve2(entrypoint), runtimePlatform);
|
|
1198
|
+
if (installation.manager !== "pnpm") {
|
|
1199
|
+
const prefix = installation.prefix;
|
|
1200
|
+
if (installation.manager === "npm" && prefix !== undefined) {
|
|
1201
|
+
const packageEntry2 = join3(prefix, ...runtimePlatform === "win32" ? [] : ["lib"], "node_modules", packageName, "bin", "cohall.js");
|
|
1202
|
+
const command = join3(prefix, ...runtimePlatform === "win32" ? [] : ["bin"], "cohall");
|
|
1203
|
+
const globalCommand = runtimePlatform === "win32" ? await readFile(`${command}.cmd`, "utf8").then((shim) => /"%dp0%\\node_modules\\@akshar5\\cohall\\bin\\cohall\.js"\s+%\*/i.test(shim)).catch(() => false) : await realpath(command).catch(() => {
|
|
1204
|
+
return;
|
|
1205
|
+
}) === canonicalEntrypoint;
|
|
1206
|
+
if (globalCommand && await realpath(packageEntry2).catch(() => {
|
|
1207
|
+
return;
|
|
1208
|
+
}) === canonicalEntrypoint)
|
|
1209
|
+
return {
|
|
1210
|
+
...installation,
|
|
1211
|
+
canonicalEntrypoint,
|
|
1212
|
+
pnpmExecutable: undefined,
|
|
1213
|
+
globalRoot: undefined
|
|
1214
|
+
};
|
|
1215
|
+
}
|
|
1216
|
+
const bun = await (options.resolveExecutable ?? trustedExecutable)("bun").catch(() => {
|
|
1217
|
+
return;
|
|
1218
|
+
});
|
|
1219
|
+
if (bun !== undefined) {
|
|
1220
|
+
const result2 = await (options.runner ?? defaultRunner).run(bun, ["pm", "ls", "--global"], 1e4);
|
|
1221
|
+
const root2 = result2.stdout.split(/\r?\n/, 1)[0]?.match(/^(.*?) node_modules \(\d+(?: installed)?\)$/)?.[1];
|
|
1222
|
+
if (result2.exitCode === 0 && root2 !== undefined && isAbsolute2(root2) && await realpath(join3(root2, "node_modules", packageName, "bin", "cohall.js")).catch(() => {
|
|
1223
|
+
return;
|
|
1224
|
+
}) === canonicalEntrypoint)
|
|
1225
|
+
return {
|
|
1226
|
+
manager: "bun",
|
|
1227
|
+
entrypoint: resolve2(entrypoint),
|
|
1228
|
+
canonicalEntrypoint,
|
|
1229
|
+
globalDir: root2,
|
|
1230
|
+
pnpmExecutable: undefined,
|
|
1231
|
+
globalRoot: undefined
|
|
1232
|
+
};
|
|
1233
|
+
}
|
|
1234
|
+
throw new Error("This operation requires a verified global npm, Bun, or pnpm installation. Project-local packages cannot upgrade or install a service; run the global cohall command with its package manager's configuration.");
|
|
1235
|
+
}
|
|
1236
|
+
const lexicalPath = normalizePath(installation.entrypoint);
|
|
1237
|
+
const globalRoot = lexicalPath.match(pnpmGlobalDirectory)?.[1] ?? lexicalPath.match(/^(.*\/v?\d+)\//)?.[1];
|
|
1238
|
+
const globalEntrypointError = () => new Error("This operation requires a global pnpm entrypoint; project-local and shared-store executions cannot select a global installation. Run the global cohall command.");
|
|
1239
|
+
if (globalRoot === undefined)
|
|
1240
|
+
throw globalEntrypointError();
|
|
1241
|
+
const selectedManager = process.env.COHALL_PNPM_EXECUTABLE ?? "pnpm";
|
|
1242
|
+
const pnpmExecutable = options.resolveExecutable === undefined ? await trustedExecutable(selectedManager, { preserveSymlink: true }) : await options.resolveExecutable(selectedManager);
|
|
1243
|
+
const result = await checked(options.runner ?? defaultRunner, {
|
|
1244
|
+
command: pnpmExecutable,
|
|
1245
|
+
arguments: ["root", "--global"],
|
|
1246
|
+
environment: pnpmEnvironment()
|
|
1247
|
+
}, 1e4);
|
|
1248
|
+
const reported = normalizePath(result.stdout.trim().split(/\r?\n/).at(-1)?.trim() ?? "");
|
|
1249
|
+
const root = reported.endsWith("/node_modules") ? dirname2(reported) : reported;
|
|
1250
|
+
const selected = resolve2(globalRoot);
|
|
1251
|
+
const configured = isAbsolute2(root) ? resolve2(root) : undefined;
|
|
1252
|
+
if (configured === undefined || (process.platform === "win32" ? selected.toLowerCase() !== configured.toLowerCase() : selected !== configured))
|
|
1253
|
+
throw globalEntrypointError();
|
|
1254
|
+
const packageEntry = (root2) => join3(root2, "node_modules", packageName, "bin", "cohall.js");
|
|
1255
|
+
const entries = await readdir(globalRoot, { withFileTypes: true });
|
|
1256
|
+
const candidates = [
|
|
1257
|
+
packageEntry(globalRoot),
|
|
1258
|
+
...entries.filter((entry) => entry.isSymbolicLink()).map((entry) => packageEntry(join3(globalRoot, entry.name)))
|
|
1259
|
+
];
|
|
1260
|
+
for (const candidate of candidates) {
|
|
1261
|
+
if (await realpath(candidate).catch(() => {
|
|
1262
|
+
return;
|
|
1263
|
+
}) === canonicalEntrypoint)
|
|
1264
|
+
return {
|
|
1265
|
+
...installation,
|
|
1266
|
+
entrypoint: candidate,
|
|
1267
|
+
canonicalEntrypoint,
|
|
1268
|
+
globalDir: dirname2(globalRoot),
|
|
1269
|
+
globalRoot,
|
|
1270
|
+
pnpmExecutable
|
|
1271
|
+
};
|
|
1272
|
+
}
|
|
1273
|
+
throw new Error("Could not find a stable pnpm global executable for this installation. Run the global cohall command, then use cohall service install before upgrading.");
|
|
1274
|
+
};
|
|
1275
|
+
var pnpmServiceDirectories = async (executable, globalRoot, runner = defaultRunner) => {
|
|
1276
|
+
const query = async (arguments_) => {
|
|
1277
|
+
const result = await checked(runner, { command: executable, arguments: arguments_, environment: pnpmEnvironment() }, 1e4);
|
|
1278
|
+
const directory = result.stdout.trim().split(/\r?\n/).at(-1)?.trim() ?? "";
|
|
1279
|
+
if (!isAbsolute2(directory))
|
|
1280
|
+
throw new Error(`pnpm ${arguments_.join(" ")} did not report an absolute directory`);
|
|
1281
|
+
return directory;
|
|
1282
|
+
};
|
|
1283
|
+
const [bin, store] = await Promise.all([
|
|
1284
|
+
query(["bin", "--global"]),
|
|
1285
|
+
query(["--dir", globalRoot, "--ignore-workspace", "store", "path"])
|
|
1286
|
+
]);
|
|
1287
|
+
return { bin, store };
|
|
1288
|
+
};
|
|
1289
|
+
var packageInstallCommand = (installation, target) => {
|
|
1290
|
+
const specification = `${packageName}@${target}`;
|
|
1291
|
+
switch (installation.manager) {
|
|
1292
|
+
case "bun":
|
|
1293
|
+
return {
|
|
1294
|
+
command: "bun",
|
|
1295
|
+
arguments: ["add", "--global", specification],
|
|
1296
|
+
...installation.globalDir === undefined ? {} : { environment: { BUN_INSTALL_GLOBAL_DIR: installation.globalDir } }
|
|
1297
|
+
};
|
|
1298
|
+
case "pnpm":
|
|
1299
|
+
return {
|
|
1300
|
+
command: "pnpm",
|
|
1301
|
+
arguments: [
|
|
1302
|
+
"add",
|
|
1303
|
+
"--global",
|
|
1304
|
+
...installation.globalDir === undefined ? [] : ["--global-dir", installation.globalDir],
|
|
1305
|
+
...process.env.COHALL_PNPM_GLOBAL_BIN_DIR === undefined ? [] : ["--global-bin-dir", process.env.COHALL_PNPM_GLOBAL_BIN_DIR],
|
|
1306
|
+
specification
|
|
1307
|
+
],
|
|
1308
|
+
environment: pnpmEnvironment()
|
|
1309
|
+
};
|
|
1310
|
+
case "npm":
|
|
1311
|
+
return {
|
|
1312
|
+
command: "npm",
|
|
1313
|
+
arguments: [
|
|
1314
|
+
"install",
|
|
1315
|
+
"--global",
|
|
1316
|
+
...installation.prefix === undefined ? [] : ["--prefix", installation.prefix],
|
|
1317
|
+
specification
|
|
1318
|
+
]
|
|
1319
|
+
};
|
|
1320
|
+
}
|
|
1321
|
+
};
|
|
1322
|
+
var executableNames = (command) => {
|
|
1323
|
+
if (operatingSystem() !== "win32" || extname2(command).length > 0) {
|
|
1324
|
+
return [command];
|
|
1325
|
+
}
|
|
1326
|
+
return (process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map((extension) => `${command}${extension.toLowerCase()}`);
|
|
1327
|
+
};
|
|
1328
|
+
var containsPath = (root, path) => {
|
|
1329
|
+
const child = relative(root, path);
|
|
1330
|
+
return child !== ".." && !child.startsWith(`..${sep}`) && !isAbsolute2(child);
|
|
1331
|
+
};
|
|
1332
|
+
var linuxSystemExecutableRoots = [
|
|
1333
|
+
"/bin",
|
|
1334
|
+
"/sbin",
|
|
1335
|
+
"/usr/bin",
|
|
1336
|
+
"/usr/sbin",
|
|
1337
|
+
"/usr/lib/node_modules",
|
|
1338
|
+
"/usr/share/nodejs",
|
|
1339
|
+
"/nix/store"
|
|
1340
|
+
];
|
|
1341
|
+
var macosHomebrewRoots = ["/opt/homebrew", "/usr/local"];
|
|
1342
|
+
var macosAdminGroup = 80;
|
|
1343
|
+
var isTrustedSystemPath = (platform3, path) => platform3 === "linux" && (path === "/home" || linuxSystemExecutableRoots.some((root) => containsPath(root, path) || containsPath(path, root)));
|
|
1344
|
+
var isTrustedGroupWritablePath = (options) => {
|
|
1345
|
+
return options.platform === "darwin" && options.uid !== undefined && options.ownerUid === options.uid && options.ownerGid === macosAdminGroup && macosHomebrewRoots.some((root) => containsPath(root, options.canonical) && containsPath(root, options.path));
|
|
1346
|
+
};
|
|
1347
|
+
var validateExecutable = async (candidate, preserveSymlink = false) => {
|
|
1348
|
+
const canonical = await realpath(candidate);
|
|
1349
|
+
if (operatingSystem() === "win32") {
|
|
1350
|
+
return preserveSymlink ? resolve2(candidate) : canonical;
|
|
1351
|
+
}
|
|
1352
|
+
const uid = process.getuid?.();
|
|
1353
|
+
for (const executablePath of preserveSymlink ? [canonical, resolve2(candidate)] : [canonical]) {
|
|
1354
|
+
for (let path = executablePath;; path = dirname2(path)) {
|
|
1355
|
+
const metadata = await stat(path);
|
|
1356
|
+
const trustedGroupWritablePath = isTrustedGroupWritablePath({
|
|
1357
|
+
platform: operatingSystem(),
|
|
1358
|
+
canonical,
|
|
1359
|
+
path,
|
|
1360
|
+
uid,
|
|
1361
|
+
ownerUid: metadata.uid,
|
|
1362
|
+
ownerGid: metadata.gid
|
|
1363
|
+
});
|
|
1364
|
+
if ((metadata.mode & 2) !== 0 || (metadata.mode & 16) !== 0 && !trustedGroupWritablePath) {
|
|
1365
|
+
throw new Error(`Refusing executable beneath group- or world-writable path ${path}`);
|
|
1366
|
+
}
|
|
1367
|
+
if (uid !== undefined && metadata.uid !== 0 && metadata.uid !== uid && !isTrustedSystemPath(operatingSystem(), path)) {
|
|
1368
|
+
throw new Error(`Refusing executable owned by another user at ${path}`);
|
|
1369
|
+
}
|
|
1370
|
+
const parent = dirname2(path);
|
|
1371
|
+
if (parent === path) {
|
|
1372
|
+
break;
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
return preserveSymlink ? resolve2(candidate) : canonical;
|
|
1377
|
+
};
|
|
1378
|
+
var trustedExecutable = async (command, options = {}) => {
|
|
1379
|
+
const candidates = isAbsolute2(command) ? [command] : (process.env.PATH ?? "").split(delimiter2).filter(Boolean).flatMap((directory) => executableNames(command).map((name) => join3(directory, name)));
|
|
1380
|
+
let failure;
|
|
1381
|
+
for (const path of candidates) {
|
|
1382
|
+
const available2 = await access(path, operatingSystem() === "win32" ? constants3.F_OK : constants3.X_OK).then(() => true).catch(() => false);
|
|
1383
|
+
if (!available2)
|
|
1384
|
+
continue;
|
|
1385
|
+
try {
|
|
1386
|
+
if (!(await stat(path)).isFile())
|
|
1387
|
+
continue;
|
|
1388
|
+
return await validateExecutable(path, options.preserveSymlink);
|
|
1389
|
+
} catch (cause) {
|
|
1390
|
+
failure ??= cause;
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
throw failure ?? new Error(`Could not find ${command} on PATH`);
|
|
1394
|
+
};
|
|
1395
|
+
var trustedServices = async (services, resolveExecutable) => {
|
|
1396
|
+
const resolved = new Map;
|
|
1397
|
+
const invocation = async (value) => {
|
|
1398
|
+
let command = resolved.get(value.command);
|
|
1399
|
+
if (command === undefined) {
|
|
1400
|
+
command = resolveExecutable(value.command);
|
|
1401
|
+
resolved.set(value.command, command);
|
|
1402
|
+
}
|
|
1403
|
+
return { ...value, command: await command };
|
|
1404
|
+
};
|
|
1405
|
+
const secured = [];
|
|
1406
|
+
for (const service of services) {
|
|
1407
|
+
let check;
|
|
1408
|
+
try {
|
|
1409
|
+
check = await invocation(service.check);
|
|
1410
|
+
} catch (cause) {
|
|
1411
|
+
if (cause instanceof Error && cause.message.startsWith("Could not find ")) {
|
|
1412
|
+
continue;
|
|
1413
|
+
}
|
|
1414
|
+
throw cause;
|
|
1415
|
+
}
|
|
1416
|
+
secured.push({
|
|
1417
|
+
...service,
|
|
1418
|
+
check,
|
|
1419
|
+
...service.entrypoint === undefined ? {} : {
|
|
1420
|
+
entrypoint: {
|
|
1421
|
+
...service.entrypoint,
|
|
1422
|
+
inspect: await invocation(service.entrypoint.inspect)
|
|
1423
|
+
}
|
|
1424
|
+
},
|
|
1425
|
+
restart: await Promise.all(service.restart.map(invocation))
|
|
1426
|
+
});
|
|
1427
|
+
}
|
|
1428
|
+
return secured;
|
|
1429
|
+
};
|
|
1430
|
+
var ScheduledTaskAction = Schema4.Struct({
|
|
1431
|
+
Execute: Schema4.NonEmptyString,
|
|
1432
|
+
Arguments: Schema4.NonEmptyString
|
|
1433
|
+
});
|
|
1434
|
+
var powershellLiteral = "(?:[^'\\r\\n]|'')+";
|
|
1435
|
+
var scheduledTaskBootstrap = new RegExp([
|
|
1436
|
+
"^\\$ErrorActionPreference = 'Stop'",
|
|
1437
|
+
`\\$env:COHALL_CONFIG = '${powershellLiteral}'`,
|
|
1438
|
+
`(?:\\$env:PNPM_HOME = '${powershellLiteral}'\\r?\\n\\$env:PATH = '${powershellLiteral}' \\+ ';' \\+ \\$env:PATH\\r?\\n)?(?:\\$env:COHALL_PNPM_EXECUTABLE = '${powershellLiteral}'\\r?\\n)?(?:\\$env:COHALL_PNPM_STORE_DIR = '${powershellLiteral}'\\r?\\n)?(?:\\$env:COHALL_PNPM_GLOBAL_DIR = '${powershellLiteral}'\\r?\\n)?(?:\\$env:COHALL_PNPM_GLOBAL_BIN_DIR = '${powershellLiteral}'\\r?\\n\\$env:PATH = '${powershellLiteral}' \\+ ';' \\+ \\$env:PATH\\r?\\n)?\\$env:PATH = '${powershellLiteral}' \\+ ';' \\+ \\$env:PATH`,
|
|
1439
|
+
`& '(${powershellLiteral})' '(${powershellLiteral})' device`,
|
|
1440
|
+
"exit \\$LASTEXITCODE(?:\\r?\\n)?$"
|
|
1441
|
+
].join("\\r?\\n"));
|
|
1442
|
+
var scheduledTaskEntrypoint = (output) => {
|
|
1443
|
+
let value;
|
|
1444
|
+
try {
|
|
1445
|
+
value = JSON.parse(output);
|
|
1446
|
+
} catch {
|
|
1447
|
+
return;
|
|
1448
|
+
}
|
|
1449
|
+
const decoded = Schema4.decodeUnknownOption(ScheduledTaskAction)(value);
|
|
1450
|
+
if (decoded._tag === "None")
|
|
1451
|
+
return;
|
|
1452
|
+
const action = decoded.value;
|
|
1453
|
+
if (!/(?:^|[/\\])(?:powershell|pwsh)\.exe$/i.test(action.Execute))
|
|
1454
|
+
return;
|
|
1455
|
+
const encoded = /^-NoLogo\s+-NoProfile\s+-NonInteractive\s+-EncodedCommand\s+([A-Za-z0-9+/]+={0,2})\s*$/i.exec(action.Arguments)?.[1];
|
|
1456
|
+
if (encoded === undefined)
|
|
1457
|
+
return;
|
|
1458
|
+
const bytes = Buffer.from(encoded, "base64");
|
|
1459
|
+
if (bytes.length % 2 !== 0 || bytes.toString("base64") !== encoded)
|
|
1460
|
+
return;
|
|
1461
|
+
const bootstrap = scheduledTaskBootstrap.exec(bytes.toString("utf16le"));
|
|
1462
|
+
const node = bootstrap?.[1]?.replaceAll("''", "'");
|
|
1463
|
+
if (node === undefined || !/(?:^|[/\\])node\.exe$/i.test(node))
|
|
1464
|
+
return;
|
|
1465
|
+
return bootstrap?.[2]?.replaceAll("''", "'");
|
|
1466
|
+
};
|
|
1467
|
+
var serviceCandidates = (runtimePlatform, uid) => {
|
|
1468
|
+
if (runtimePlatform === "linux") {
|
|
1469
|
+
const systemd = (manager, unit, device) => {
|
|
1470
|
+
const user = manager === "systemd-user" ? ["--user"] : [];
|
|
1471
|
+
return {
|
|
1472
|
+
id: `${manager}:${unit}`,
|
|
1473
|
+
label: unit,
|
|
1474
|
+
manager,
|
|
1475
|
+
device,
|
|
1476
|
+
check: { command: "systemctl", arguments: [...user, "is-active", "--quiet", unit] },
|
|
1477
|
+
entrypoint: {
|
|
1478
|
+
inspect: {
|
|
1479
|
+
command: "systemctl",
|
|
1480
|
+
arguments: [...user, "show", "--property=ExecStart", "--value", unit]
|
|
1481
|
+
},
|
|
1482
|
+
parse: (output) => output.match(/\bpath=(.*?)\s*;/)?.[1]?.trim()
|
|
1483
|
+
},
|
|
1484
|
+
restart: [{ command: "systemctl", arguments: [...user, "restart", unit] }]
|
|
1485
|
+
};
|
|
1486
|
+
};
|
|
1487
|
+
return [
|
|
1488
|
+
systemd("systemd-user", "cohall-relay.service", false),
|
|
1489
|
+
systemd("systemd-system", "cohall-relay.service", false),
|
|
1490
|
+
systemd("systemd-user", "cohall-device.service", true)
|
|
1491
|
+
];
|
|
1492
|
+
}
|
|
1493
|
+
if (runtimePlatform === "darwin") {
|
|
1494
|
+
const domain = `gui/${uid ?? 0}`;
|
|
1495
|
+
const launchd = (label, device) => ({
|
|
1496
|
+
id: `launchd:${label}`,
|
|
1497
|
+
label,
|
|
1498
|
+
manager: "launchd",
|
|
1499
|
+
device,
|
|
1500
|
+
check: { command: "launchctl", arguments: ["print", `${domain}/${label}`] },
|
|
1501
|
+
activeOutput: /\bstate\s*=\s*running\b/,
|
|
1502
|
+
entrypoint: {
|
|
1503
|
+
inspect: { command: "launchctl", arguments: ["print", `${domain}/${label}`] },
|
|
1504
|
+
parse: (output) => output.match(/^\s*program\s*=\s*(.+)$/m)?.[1]?.trim()
|
|
1505
|
+
},
|
|
1506
|
+
restart: [{ command: "launchctl", arguments: ["kickstart", "-k", `${domain}/${label}`] }]
|
|
1507
|
+
});
|
|
1508
|
+
return [launchd("com.cohall.relay", false), launchd("com.cohall.device", true)];
|
|
1509
|
+
}
|
|
1510
|
+
if (runtimePlatform === "win32") {
|
|
1511
|
+
return [
|
|
1512
|
+
{
|
|
1513
|
+
id: "scheduled-task:Cohall Device",
|
|
1514
|
+
label: "Cohall Device",
|
|
1515
|
+
manager: "scheduled-task",
|
|
1516
|
+
device: true,
|
|
1517
|
+
check: {
|
|
1518
|
+
command: "powershell.exe",
|
|
1519
|
+
arguments: [
|
|
1520
|
+
"-NoProfile",
|
|
1521
|
+
"-NonInteractive",
|
|
1522
|
+
"-Command",
|
|
1523
|
+
"if ((Get-ScheduledTask -TaskName 'Cohall Device' -ErrorAction SilentlyContinue).State -eq 'Running') { exit 0 } else { exit 1 }"
|
|
1524
|
+
]
|
|
1525
|
+
},
|
|
1526
|
+
entrypoint: {
|
|
1527
|
+
inspect: {
|
|
1528
|
+
command: "powershell.exe",
|
|
1529
|
+
arguments: [
|
|
1530
|
+
"-NoProfile",
|
|
1531
|
+
"-NonInteractive",
|
|
1532
|
+
"-Command",
|
|
1533
|
+
"@((Get-ScheduledTask -TaskName 'Cohall Device' -TaskPath '\\' -ErrorAction Stop).Actions) | Select-Object Execute, Arguments | ConvertTo-Json -Compress"
|
|
1534
|
+
]
|
|
1535
|
+
},
|
|
1536
|
+
parse: scheduledTaskEntrypoint
|
|
1537
|
+
},
|
|
1538
|
+
restart: [
|
|
1539
|
+
{
|
|
1540
|
+
command: "schtasks.exe",
|
|
1541
|
+
arguments: ["/End", "/TN", "Cohall Device"],
|
|
1542
|
+
allowFailure: true
|
|
1543
|
+
},
|
|
1544
|
+
{ command: "schtasks.exe", arguments: ["/Run", "/TN", "Cohall Device"] }
|
|
1545
|
+
]
|
|
1546
|
+
}
|
|
1547
|
+
];
|
|
1548
|
+
}
|
|
1549
|
+
return [];
|
|
1550
|
+
};
|
|
1551
|
+
var defaultRunner = {
|
|
1552
|
+
run: async (command, arguments_, timeoutMs = 300000, environment, cwd) => {
|
|
1553
|
+
const result = await execa2(command, arguments_, {
|
|
1554
|
+
...cwd === undefined ? {} : { cwd },
|
|
1555
|
+
encoding: "utf8",
|
|
1556
|
+
maxBuffer: 1024 * 1024,
|
|
1557
|
+
timeout: timeoutMs,
|
|
1558
|
+
windowsHide: true,
|
|
1559
|
+
stdin: "ignore",
|
|
1560
|
+
...environment === undefined ? {} : { env: environment },
|
|
1561
|
+
reject: false,
|
|
1562
|
+
stripFinalNewline: false
|
|
1563
|
+
});
|
|
1564
|
+
return {
|
|
1565
|
+
exitCode: result.failed ? result.exitCode || 1 : 0,
|
|
1566
|
+
stdout: result.stdout,
|
|
1567
|
+
stderr: result.stderr,
|
|
1568
|
+
...result.shortMessage === undefined ? {} : { error: result.shortMessage.slice(0, 16384) }
|
|
1569
|
+
};
|
|
1570
|
+
}
|
|
1571
|
+
};
|
|
1572
|
+
var checked = async (runner, invocation, timeoutMs) => {
|
|
1573
|
+
const result = await runner.run(invocation.command, invocation.arguments, timeoutMs, invocation.environment, invocation.cwd);
|
|
1574
|
+
if (result.exitCode === 0 || invocation.allowFailure === true) {
|
|
1575
|
+
return result;
|
|
1576
|
+
}
|
|
1577
|
+
const detail = (result.stderr.trim() || result.stdout.trim() || result.error || "unknown error").slice(0, 16384);
|
|
1578
|
+
throw new Error(`${invocation.command} ${invocation.arguments.join(" ")} failed with status ${result.exitCode}: ${detail}`);
|
|
1579
|
+
};
|
|
1580
|
+
var activeServices = async (runner, candidates) => {
|
|
1581
|
+
const active = [];
|
|
1582
|
+
for (const service of candidates) {
|
|
1583
|
+
const result = await runner.run(service.check.command, service.check.arguments, 1e4);
|
|
1584
|
+
if (result.exitCode === 0 && (service.activeOutput === undefined || service.activeOutput.test(`${result.stdout}
|
|
1585
|
+
${result.stderr}`))) {
|
|
1586
|
+
active.push(service);
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
return active;
|
|
1590
|
+
};
|
|
1591
|
+
var assertServiceInstallations = async (runner, services, installation) => {
|
|
1592
|
+
for (const service of services) {
|
|
1593
|
+
if (service.entrypoint === undefined) {
|
|
1594
|
+
continue;
|
|
1595
|
+
}
|
|
1596
|
+
const result = await checked(runner, service.entrypoint.inspect, 1e4);
|
|
1597
|
+
const serviceEntrypoint = service.entrypoint.parse(`${result.stdout}
|
|
1598
|
+
${result.stderr}`);
|
|
1599
|
+
if (serviceEntrypoint === undefined) {
|
|
1600
|
+
throw new Error(`Could not determine the executable used by active ${service.label}${service.manager === "scheduled-task" ? ". Reinstall the task with cohall service install." : ""}`);
|
|
1601
|
+
}
|
|
1602
|
+
const canonicalServiceEntrypoint = await realpath(serviceEntrypoint).catch((cause) => {
|
|
1603
|
+
throw new Error(`Could not resolve the executable used by active ${service.label}: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
1604
|
+
});
|
|
1605
|
+
if (canonicalServiceEntrypoint === installation.canonicalEntrypoint) {
|
|
1606
|
+
const servicePath = resolve2(serviceEntrypoint);
|
|
1607
|
+
const sameEntrypoint = service.manager === "scheduled-task" ? servicePath.toLowerCase() === installation.entrypoint.toLowerCase() : servicePath === installation.entrypoint;
|
|
1608
|
+
if (installation.manager === "pnpm" && !sameEntrypoint)
|
|
1609
|
+
throw new Error(`Active ${service.label} is pinned to a pnpm package directory that changes during upgrades. ${service.device ? "Run cohall service install through the global cohall command before upgrading." : `Update the relay service executable to ${installation.entrypoint} before upgrading.`}`);
|
|
1610
|
+
continue;
|
|
1611
|
+
}
|
|
1612
|
+
throw new Error(`Active ${service.label} uses ${serviceEntrypoint}, but this Cohall CLI uses ${installation.entrypoint}. Run the service executable's upgrade command so its installation is updated before restart.`);
|
|
1613
|
+
}
|
|
1614
|
+
};
|
|
1615
|
+
var readReceipt = async (path) => readFile(path, "utf8").then((content) => Schema4.decodeUnknownOption(RestartReceipt)(JSON.parse(content))).then((decoded) => decoded._tag === "Some" ? decoded.value : undefined).catch(() => {
|
|
1616
|
+
return;
|
|
1617
|
+
});
|
|
1618
|
+
var writeReceipt = async (path, value) => {
|
|
1619
|
+
const directory = dirname2(path);
|
|
1620
|
+
const temporary = `${path}.${process.pid}.tmp`;
|
|
1621
|
+
await mkdir2(directory, { recursive: true, mode: 448 });
|
|
1622
|
+
if (operatingSystem() !== "win32") {
|
|
1623
|
+
await chmod3(directory, 448);
|
|
1624
|
+
}
|
|
1625
|
+
await writeFile2(temporary, `${JSON.stringify(value, null, 2)}
|
|
1626
|
+
`, { mode: 384 });
|
|
1627
|
+
await rename(temporary, path);
|
|
1628
|
+
};
|
|
1629
|
+
var installedVersion = async (entrypoint) => {
|
|
1630
|
+
const canonicalEntrypoint = await realpath(entrypoint);
|
|
1631
|
+
const metadata = JSON.parse(await readFile(join3(dirname2(dirname2(canonicalEntrypoint)), "package.json"), "utf8"));
|
|
1632
|
+
if (typeof metadata !== "object" || metadata === null || !("name" in metadata) || metadata.name !== packageName || !("version" in metadata) || typeof metadata.version !== "string") {
|
|
1633
|
+
throw new Error(`Could not verify the installed ${packageName} version`);
|
|
1634
|
+
}
|
|
1635
|
+
return metadata.version;
|
|
1636
|
+
};
|
|
1637
|
+
var restartReceiptPath = () => join3(dirname2(configurationPath()), "upgrade-restart.json");
|
|
1638
|
+
var restartServices = async (runner, services, statePath, state, preserveDeviceReceipt) => {
|
|
1639
|
+
let current = state;
|
|
1640
|
+
for (const service of services) {
|
|
1641
|
+
current = { ...current, restartingService: service.id };
|
|
1642
|
+
await writeReceipt(statePath, current);
|
|
1643
|
+
try {
|
|
1644
|
+
for (const invocation of service.restart) {
|
|
1645
|
+
await checked(runner, invocation, 60000);
|
|
1646
|
+
}
|
|
1647
|
+
} catch (cause) {
|
|
1648
|
+
current = {
|
|
1649
|
+
version: current.version,
|
|
1650
|
+
fromVersion: current.fromVersion,
|
|
1651
|
+
packageManager: current.packageManager,
|
|
1652
|
+
pendingServices: current.pendingServices,
|
|
1653
|
+
restartedServices: current.restartedServices
|
|
1654
|
+
};
|
|
1655
|
+
await writeReceipt(statePath, current);
|
|
1656
|
+
throw cause;
|
|
1657
|
+
}
|
|
1658
|
+
if (service.device && preserveDeviceReceipt) {
|
|
1659
|
+
return current;
|
|
1660
|
+
}
|
|
1661
|
+
current = {
|
|
1662
|
+
version: current.version,
|
|
1663
|
+
fromVersion: current.fromVersion,
|
|
1664
|
+
packageManager: current.packageManager,
|
|
1665
|
+
pendingServices: current.pendingServices.filter((id) => id !== service.id),
|
|
1666
|
+
restartedServices: [...current.restartedServices, service.id]
|
|
1667
|
+
};
|
|
1668
|
+
await writeReceipt(statePath, current);
|
|
1669
|
+
}
|
|
1670
|
+
return current;
|
|
1671
|
+
};
|
|
1672
|
+
var reportedRestartServices = (receipt) => receipt.restartingService === undefined || receipt.restartedServices.includes(receipt.restartingService) ? receipt.restartedServices : [...receipt.restartedServices, receipt.restartingService];
|
|
1673
|
+
var upgrade = async (options) => {
|
|
1674
|
+
const target = normalizeUpgradeTarget(options.target);
|
|
1675
|
+
const runner = options.runner ?? defaultRunner;
|
|
1676
|
+
const resolveExecutable = options.resolveExecutable ?? trustedExecutable;
|
|
1677
|
+
const runtimePlatform = options.platform ?? process.platform;
|
|
1678
|
+
const uid = options.uid ?? process.getuid?.();
|
|
1679
|
+
const candidates = await trustedServices(serviceCandidates(runtimePlatform, uid), resolveExecutable);
|
|
1680
|
+
const statePath = options.statePath ?? restartReceiptPath();
|
|
1681
|
+
const previous = await readReceipt(statePath);
|
|
1682
|
+
const entrypoint = options.entrypoint ?? process.argv[1];
|
|
1683
|
+
if (entrypoint === undefined) {
|
|
1684
|
+
throw new Error("Could not resolve the Cohall executable path");
|
|
1685
|
+
}
|
|
1686
|
+
const installation = await resolvePackageInstallation(entrypoint, {
|
|
1687
|
+
runner,
|
|
1688
|
+
platform: runtimePlatform,
|
|
1689
|
+
...options.resolveExecutable === undefined ? {} : { resolveExecutable }
|
|
1690
|
+
});
|
|
1691
|
+
if (previous?.version === options.currentVersion && (target === previous.version || target === "latest" && options.restart) && await installedVersion(installation.entrypoint).catch(() => {
|
|
1692
|
+
return;
|
|
1693
|
+
}) === previous.version) {
|
|
1694
|
+
const pending = candidates.filter((service) => previous.pendingServices.includes(service.id));
|
|
1695
|
+
const active = await activeServices(runner, pending);
|
|
1696
|
+
await assertServiceInstallations(runner, active, installation);
|
|
1697
|
+
if (options.dryRun || !options.restart) {
|
|
1698
|
+
return {
|
|
1699
|
+
upgraded: previous.fromVersion !== previous.version,
|
|
1700
|
+
from_version: previous.fromVersion,
|
|
1701
|
+
installed_version: previous.version,
|
|
1702
|
+
requested_version: previous.version,
|
|
1703
|
+
package_manager: previous.packageManager,
|
|
1704
|
+
services_restarted: previous.restartedServices,
|
|
1705
|
+
services_pending_restart: previous.pendingServices,
|
|
1706
|
+
resumed_after_restart: false,
|
|
1707
|
+
dry_run: options.dryRun
|
|
1708
|
+
};
|
|
1709
|
+
}
|
|
1710
|
+
const activeIds = new Set(active.map((service) => service.id));
|
|
1711
|
+
const completedByRestart = pending.filter((service) => options.delegated === true && service.device && service.id === previous.restartingService && activeIds.has(service.id));
|
|
1712
|
+
const completedIds = new Set(completedByRestart.map((service) => service.id));
|
|
1713
|
+
const remaining = active.filter((service) => !completedIds.has(service.id));
|
|
1714
|
+
let resumed = {
|
|
1715
|
+
version: previous.version,
|
|
1716
|
+
fromVersion: previous.fromVersion,
|
|
1717
|
+
packageManager: previous.packageManager,
|
|
1718
|
+
pendingServices: previous.pendingServices.filter((id) => !completedIds.has(id)),
|
|
1719
|
+
restartedServices: [
|
|
1720
|
+
...previous.restartedServices,
|
|
1721
|
+
...completedByRestart.map((service) => service.id)
|
|
1722
|
+
]
|
|
1723
|
+
};
|
|
1724
|
+
if (remaining.length > 0) {
|
|
1725
|
+
await writeReceipt(statePath, resumed);
|
|
1726
|
+
resumed = await restartServices(runner, remaining, statePath, resumed, options.delegated === true);
|
|
1727
|
+
} else if (completedIds.size > 0) {
|
|
1728
|
+
await writeReceipt(statePath, resumed);
|
|
1729
|
+
}
|
|
1730
|
+
if (resumed.pendingServices.length === 0) {
|
|
1731
|
+
await rm2(statePath, { force: true });
|
|
1732
|
+
}
|
|
1733
|
+
return {
|
|
1734
|
+
upgraded: previous.fromVersion !== previous.version,
|
|
1735
|
+
from_version: previous.fromVersion,
|
|
1736
|
+
installed_version: previous.version,
|
|
1737
|
+
requested_version: previous.version,
|
|
1738
|
+
package_manager: previous.packageManager,
|
|
1739
|
+
services_restarted: reportedRestartServices(resumed),
|
|
1740
|
+
services_pending_restart: resumed.pendingServices.filter((id) => id !== resumed.restartingService),
|
|
1741
|
+
resumed_after_restart: true,
|
|
1742
|
+
dry_run: false
|
|
1743
|
+
};
|
|
1744
|
+
}
|
|
1745
|
+
const services = await activeServices(runner, candidates);
|
|
1746
|
+
await assertServiceInstallations(runner, services, installation);
|
|
1747
|
+
const pendingServices = [
|
|
1748
|
+
...new Set([...previous?.pendingServices ?? [], ...services.map((service) => service.id)])
|
|
1749
|
+
];
|
|
1750
|
+
const resolvePackageManager = () => {
|
|
1751
|
+
if (installation.pnpmExecutable !== undefined)
|
|
1752
|
+
return Promise.resolve(installation.pnpmExecutable);
|
|
1753
|
+
return options.resolveExecutable === undefined ? trustedExecutable(installation.manager) : resolveExecutable(installation.manager);
|
|
1754
|
+
};
|
|
1755
|
+
let packageManagerExecutable;
|
|
1756
|
+
let resolvedTarget = target;
|
|
1757
|
+
if (target === "latest") {
|
|
1758
|
+
packageManagerExecutable = await resolvePackageManager();
|
|
1759
|
+
let lookupFlags = ["--global"];
|
|
1760
|
+
if (installation.manager === "bun") {
|
|
1761
|
+
const information = await checked(runner, { command: packageManagerExecutable, arguments: ["--version"] }, 1e4);
|
|
1762
|
+
if (compareVersions(information.stdout.trim(), minimumBunLookupVersion) < 0) {
|
|
1763
|
+
throw new Error(`Latest upgrades require Bun ${minimumBunLookupVersion} or newer; upgrade Bun or use --to <exact-version>`);
|
|
1764
|
+
}
|
|
1765
|
+
}
|
|
1766
|
+
if (installation.manager === "pnpm") {
|
|
1767
|
+
const information = await checked(runner, {
|
|
1768
|
+
command: packageManagerExecutable,
|
|
1769
|
+
arguments: ["--ignore-workspace", "--version"],
|
|
1770
|
+
environment: pnpmEnvironment(),
|
|
1771
|
+
...installation.globalRoot === undefined ? {} : { cwd: installation.globalRoot }
|
|
1772
|
+
}, 1e4);
|
|
1773
|
+
lookupFlags = compareVersions(information.stdout.trim(), "11.0.0") < 0 ? [] : ["--ignore-workspace"];
|
|
1774
|
+
}
|
|
1775
|
+
const lookup = await checked(runner, {
|
|
1776
|
+
command: packageManagerExecutable,
|
|
1777
|
+
arguments: [
|
|
1778
|
+
...installation.manager === "bun" ? ["pm"] : [],
|
|
1779
|
+
"view",
|
|
1780
|
+
...lookupFlags,
|
|
1781
|
+
...installation.prefix === undefined ? [] : ["--prefix", installation.prefix],
|
|
1782
|
+
`${packageName}@latest`,
|
|
1783
|
+
"version",
|
|
1784
|
+
"--json"
|
|
1785
|
+
],
|
|
1786
|
+
...installation.manager === "pnpm" ? { environment: pnpmEnvironment() } : {},
|
|
1787
|
+
...installation.globalRoot === undefined ? {} : { cwd: installation.globalRoot }
|
|
1788
|
+
}, 30000);
|
|
1789
|
+
const response = JSON.parse(lookup.stdout);
|
|
1790
|
+
const latest = Array.isArray(response) && response.length === 1 ? response[0] : response;
|
|
1791
|
+
if (typeof latest !== "string" || parseVersion(latest) === undefined) {
|
|
1792
|
+
throw new Error(`Could not resolve ${packageName}@latest to an exact semantic version`);
|
|
1793
|
+
}
|
|
1794
|
+
resolvedTarget = latest;
|
|
1795
|
+
}
|
|
1796
|
+
let nextVersion = await installedVersion(installation.entrypoint).catch((cause) => {
|
|
1797
|
+
if (target === "latest") {
|
|
1798
|
+
throw new Error("Could not verify the installed version before upgrading latest; use --to <version> to repair this installation", { cause });
|
|
1799
|
+
}
|
|
1800
|
+
return;
|
|
1801
|
+
});
|
|
1802
|
+
if (target === "latest" && (compareVersions(resolvedTarget, options.currentVersion) < 0 || compareVersions(resolvedTarget, nextVersion ?? options.currentVersion) < 0)) {
|
|
1803
|
+
return {
|
|
1804
|
+
upgraded: false,
|
|
1805
|
+
from_version: options.currentVersion,
|
|
1806
|
+
installed_version: nextVersion ?? options.currentVersion,
|
|
1807
|
+
requested_version: target,
|
|
1808
|
+
package_manager: installation.manager,
|
|
1809
|
+
services_restarted: [],
|
|
1810
|
+
services_pending_restart: previous?.pendingServices ?? [],
|
|
1811
|
+
resumed_after_restart: false,
|
|
1812
|
+
dry_run: options.dryRun
|
|
1813
|
+
};
|
|
1814
|
+
}
|
|
1815
|
+
if (options.dryRun) {
|
|
1816
|
+
return {
|
|
1817
|
+
upgraded: false,
|
|
1818
|
+
from_version: options.currentVersion,
|
|
1819
|
+
installed_version: options.currentVersion,
|
|
1820
|
+
requested_version: target,
|
|
1821
|
+
package_manager: installation.manager,
|
|
1822
|
+
services_restarted: [],
|
|
1823
|
+
services_pending_restart: pendingServices,
|
|
1824
|
+
resumed_after_restart: false,
|
|
1825
|
+
dry_run: true
|
|
1826
|
+
};
|
|
1827
|
+
}
|
|
1828
|
+
if (nextVersion === undefined || resolvedTarget !== nextVersion) {
|
|
1829
|
+
const install = packageInstallCommand(installation, resolvedTarget);
|
|
1830
|
+
const installExecutable = packageManagerExecutable ?? await resolvePackageManager();
|
|
1831
|
+
await checked(runner, { ...install, command: installExecutable });
|
|
1832
|
+
nextVersion = await installedVersion(installation.entrypoint);
|
|
1833
|
+
}
|
|
1834
|
+
if (nextVersion !== resolvedTarget) {
|
|
1835
|
+
throw new Error(`Installed Cohall ${nextVersion}, expected ${resolvedTarget}`);
|
|
1836
|
+
}
|
|
1837
|
+
const upgraded = nextVersion !== options.currentVersion;
|
|
1838
|
+
const initial = {
|
|
1839
|
+
version: nextVersion,
|
|
1840
|
+
fromVersion: options.currentVersion,
|
|
1841
|
+
packageManager: installation.manager,
|
|
1842
|
+
pendingServices,
|
|
1843
|
+
restartedServices: []
|
|
1844
|
+
};
|
|
1845
|
+
if (initial.pendingServices.length > 0) {
|
|
1846
|
+
await writeReceipt(statePath, initial);
|
|
1847
|
+
}
|
|
1848
|
+
const completed = options.restart ? await restartServices(runner, services, statePath, initial, options.delegated === true) : initial;
|
|
1849
|
+
if (completed.pendingServices.length === 0) {
|
|
1850
|
+
await rm2(statePath, { force: true });
|
|
1851
|
+
}
|
|
1852
|
+
return {
|
|
1853
|
+
upgraded,
|
|
1854
|
+
from_version: options.currentVersion,
|
|
1855
|
+
installed_version: nextVersion,
|
|
1856
|
+
requested_version: target,
|
|
1857
|
+
package_manager: installation.manager,
|
|
1858
|
+
services_restarted: reportedRestartServices(completed),
|
|
1859
|
+
services_pending_restart: completed.pendingServices.filter((id) => id !== completed.restartingService),
|
|
1860
|
+
resumed_after_restart: false,
|
|
1861
|
+
dry_run: false
|
|
1862
|
+
};
|
|
1863
|
+
};
|
|
1864
|
+
|
|
1865
|
+
export { ProviderRunError, findExecutable, availableProviders, run, writeBotReply, cleanupBotReply, discoverGrokBots, runGrokBot, normalizeUpgradeTarget, deviceVersionWarning, resolvePackageInstallation, pnpmServiceDirectories, trustedExecutable, serviceCandidates, upgrade };
|
|
1866
|
+
|
|
1867
|
+
//# debugId=B09927D33D29CFB764756E2164756E21
|