@akshar5/cohall 0.12.6 → 0.12.8
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 +7 -1
- package/bin/chunk-04a27ybz.js +460 -0
- package/bin/chunk-04a27ybz.js.map +10 -0
- package/bin/chunk-0nnvgtgx.js +665 -0
- package/bin/chunk-0nnvgtgx.js.map +10 -0
- package/bin/chunk-22xds47a.js +256 -0
- package/bin/chunk-22xds47a.js.map +10 -0
- package/bin/chunk-b3ba95j4.js +1867 -0
- package/bin/chunk-b3ba95j4.js.map +13 -0
- package/bin/chunk-c5qv9pg0.js +2160 -0
- package/bin/chunk-c5qv9pg0.js.map +15 -0
- package/bin/chunk-cgw59n50.js +267 -0
- package/bin/chunk-cgw59n50.js.map +11 -0
- package/bin/chunk-cy2pk1yf.js +269 -0
- package/bin/chunk-cy2pk1yf.js.map +10 -0
- package/bin/chunk-g6b3zmtw.js +268 -0
- package/bin/chunk-g6b3zmtw.js.map +10 -0
- package/bin/chunk-j574tp6f.js +40 -0
- package/bin/chunk-j574tp6f.js.map +9 -0
- package/bin/chunk-mqvp2676.js +415 -0
- package/bin/chunk-mqvp2676.js.map +11 -0
- package/bin/chunk-p493vm5f.js +21 -0
- package/bin/chunk-p493vm5f.js.map +10 -0
- package/bin/chunk-rsctgzxj.js +23 -0
- package/bin/chunk-rsctgzxj.js.map +10 -0
- package/bin/chunk-vkxze339.js +2826 -0
- package/bin/chunk-vkxze339.js.map +14 -0
- package/bin/chunk-wr5f7saj.js +50 -0
- package/bin/chunk-wr5f7saj.js.map +10 -0
- package/bin/cohall.js +18 -9100
- package/bin/cohall.js.map +5 -30
- package/deploy/windows/install-device.ps1 +2 -0
- package/docs/install.md +8 -1
- package/docs/integrations.md +6 -3
- package/docs/muse.md +13 -9
- package/package.json +1 -1
|
@@ -0,0 +1,665 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ProviderRunError,
|
|
3
|
+
availableProviders,
|
|
4
|
+
cleanupBotReply,
|
|
5
|
+
discoverGrokBots,
|
|
6
|
+
findExecutable,
|
|
7
|
+
run,
|
|
8
|
+
runGrokBot,
|
|
9
|
+
upgrade
|
|
10
|
+
} from "./chunk-b3ba95j4.js";
|
|
11
|
+
import {
|
|
12
|
+
prepareTaskFiles
|
|
13
|
+
} from "./chunk-mqvp2676.js";
|
|
14
|
+
import"./chunk-p493vm5f.js";
|
|
15
|
+
import"./chunk-g6b3zmtw.js";
|
|
16
|
+
import {
|
|
17
|
+
Device,
|
|
18
|
+
SocketEvent,
|
|
19
|
+
decodeSocketEvent,
|
|
20
|
+
maxSocketPayloadBytes,
|
|
21
|
+
now,
|
|
22
|
+
taskSlot
|
|
23
|
+
} from "./chunk-04a27ybz.js";
|
|
24
|
+
import {
|
|
25
|
+
version
|
|
26
|
+
} from "./chunk-rsctgzxj.js";
|
|
27
|
+
|
|
28
|
+
// apps/device/src/daemon.ts
|
|
29
|
+
import { Effect, Schedule, Schema } from "effect";
|
|
30
|
+
import { constants } from "node:fs";
|
|
31
|
+
import { open, realpath, stat } from "node:fs/promises";
|
|
32
|
+
import { arch, hostname, platform } from "node:os";
|
|
33
|
+
import { basename, isAbsolute, relative, sep } from "node:path";
|
|
34
|
+
import { WebSocket } from "ws";
|
|
35
|
+
var maxQueuedRelayMessages = 8;
|
|
36
|
+
|
|
37
|
+
class DeviceConnectionError extends Schema.TaggedErrorClass()("Device.ConnectionError", { message: Schema.String }) {
|
|
38
|
+
}
|
|
39
|
+
var socketUrl = (configuration) => {
|
|
40
|
+
const url = new URL(configuration.relayUrl);
|
|
41
|
+
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
42
|
+
url.pathname = "/ws/device";
|
|
43
|
+
return url.toString();
|
|
44
|
+
};
|
|
45
|
+
var providerLabel = (provider) => {
|
|
46
|
+
switch (provider) {
|
|
47
|
+
case "codex":
|
|
48
|
+
return "Codex";
|
|
49
|
+
case "claude-code":
|
|
50
|
+
return "Claude Code";
|
|
51
|
+
case "opencode":
|
|
52
|
+
return "OpenCode";
|
|
53
|
+
case "grok-bot":
|
|
54
|
+
return "Grok Bot";
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
var capabilities = (providers) => {
|
|
58
|
+
const values = providers.map((provider) => ({
|
|
59
|
+
id: provider,
|
|
60
|
+
label: providerLabel(provider),
|
|
61
|
+
detail: provider === "grok-bot" ? "Named bots through this computer's local Grok Bot gateway" : `${providerLabel(provider)} executable detected; authentication is checked when work starts`
|
|
62
|
+
}));
|
|
63
|
+
if (providers.some((provider) => provider !== "grok-bot")) {
|
|
64
|
+
values.push({ id: "task-attachments", label: "Task file attachments" });
|
|
65
|
+
}
|
|
66
|
+
values.push({ id: "task-clarification", label: "Task clarification and resume" });
|
|
67
|
+
values.push({ id: "task-deadlines", label: "Task deadlines" });
|
|
68
|
+
if (findExecutable("google-chrome") !== undefined || findExecutable("chromium") !== undefined || platform() === "darwin") {
|
|
69
|
+
values.push({ id: "browser-session", label: "Signed-in browser" });
|
|
70
|
+
}
|
|
71
|
+
if (findExecutable("xcodebuild") !== undefined) {
|
|
72
|
+
values.push({ id: "xcode", label: "Xcode" });
|
|
73
|
+
}
|
|
74
|
+
if (findExecutable("docker") !== undefined) {
|
|
75
|
+
values.push({ id: "docker", label: "Docker" });
|
|
76
|
+
}
|
|
77
|
+
return values;
|
|
78
|
+
};
|
|
79
|
+
var selectProviders = (installed, configured) => configured === undefined ? installed : configured.filter((provider) => installed.includes(provider));
|
|
80
|
+
var describeDevice = (configuration, status = "online", bots = []) => {
|
|
81
|
+
const operatingSystem = platform();
|
|
82
|
+
const platformName = operatingSystem === "darwin" || operatingSystem === "linux" ? operatingSystem : operatingSystem === "win32" ? "windows" : "unknown";
|
|
83
|
+
const installed = [
|
|
84
|
+
...availableProviders(),
|
|
85
|
+
...configuration.grokGateway === undefined ? [] : ["grok-bot"]
|
|
86
|
+
];
|
|
87
|
+
const providers = selectProviders(installed, configuration.providers);
|
|
88
|
+
return Device.make({
|
|
89
|
+
id: configuration.id,
|
|
90
|
+
name: configuration.name,
|
|
91
|
+
...configuration.description === undefined ? {} : { description: configuration.description },
|
|
92
|
+
hostname: hostname(),
|
|
93
|
+
platform: platformName,
|
|
94
|
+
architecture: arch(),
|
|
95
|
+
status,
|
|
96
|
+
providers,
|
|
97
|
+
...providers.includes("grok-bot") ? { bots } : {},
|
|
98
|
+
capabilities: capabilities(providers),
|
|
99
|
+
workspaces: configuration.workspaces.map((path) => ({
|
|
100
|
+
path,
|
|
101
|
+
label: basename(path) || path
|
|
102
|
+
})),
|
|
103
|
+
version,
|
|
104
|
+
lastSeenAt: now()
|
|
105
|
+
});
|
|
106
|
+
};
|
|
107
|
+
var allowedWorkspace = async (configuration, requested) => {
|
|
108
|
+
const selected = requested ?? configuration.workspaces[0];
|
|
109
|
+
if (selected === undefined) {
|
|
110
|
+
throw new Error("No workspace is configured on this device");
|
|
111
|
+
}
|
|
112
|
+
const candidate = await realpath(selected);
|
|
113
|
+
const allowed = configuration.workspaces.some((root) => {
|
|
114
|
+
const child = relative(root, candidate);
|
|
115
|
+
return child !== ".." && !child.startsWith(`..${sep}`) && !isAbsolute(child);
|
|
116
|
+
});
|
|
117
|
+
if (!allowed) {
|
|
118
|
+
throw new Error(`Workspace ${candidate} is outside this device's configured workspace roots`);
|
|
119
|
+
}
|
|
120
|
+
return candidate;
|
|
121
|
+
};
|
|
122
|
+
var openAllowedWorkspace = async (configuration, requested) => {
|
|
123
|
+
const path = await allowedWorkspace(configuration, requested);
|
|
124
|
+
const operatingSystem = platform();
|
|
125
|
+
const flags = constants.O_RDONLY | (operatingSystem === "win32" ? 0 : constants.O_DIRECTORY | constants.O_NOFOLLOW);
|
|
126
|
+
const handle = await open(path, flags);
|
|
127
|
+
try {
|
|
128
|
+
const identity = await handle.stat();
|
|
129
|
+
if (!identity.isDirectory()) {
|
|
130
|
+
throw new Error(`Workspace ${path} is not a directory`);
|
|
131
|
+
}
|
|
132
|
+
const cwd = operatingSystem === "linux" ? `/proc/self/fd/${handle.fd}` : path;
|
|
133
|
+
const validate = async () => {
|
|
134
|
+
const current = await handle.stat();
|
|
135
|
+
if (!current.isDirectory() || current.dev !== identity.dev || current.ino !== identity.ino) {
|
|
136
|
+
throw new Error(`Workspace ${path} changed before provider startup`);
|
|
137
|
+
}
|
|
138
|
+
const currentPath = await allowedWorkspace(configuration, cwd);
|
|
139
|
+
if (operatingSystem !== "linux") {
|
|
140
|
+
const currentPathIdentity = await stat(currentPath);
|
|
141
|
+
if (currentPathIdentity.dev !== identity.dev || currentPathIdentity.ino !== identity.ino) {
|
|
142
|
+
throw new Error(`Workspace ${path} changed before provider startup`);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
await validate();
|
|
147
|
+
return { cwd, validate, close: () => handle.close() };
|
|
148
|
+
} catch (cause) {
|
|
149
|
+
await handle.close().catch(() => {
|
|
150
|
+
return;
|
|
151
|
+
});
|
|
152
|
+
throw cause;
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
var promptFor = (task, deviceName, supportsClarification, files) => {
|
|
156
|
+
const context = task.context === undefined ? "" : `
|
|
157
|
+
|
|
158
|
+
Relevant context supplied by the sending agent:
|
|
159
|
+
${task.context}`;
|
|
160
|
+
return [
|
|
161
|
+
`You are the Cohall agent running on ${deviceName}.`,
|
|
162
|
+
"Complete the delegated task using this device's local workspace, tools, credentials, and signed-in services.",
|
|
163
|
+
"Never read, reveal, copy, or use Cohall configuration files or Cohall authentication tokens.",
|
|
164
|
+
"Return a concise, complete result with the evidence the sending agent needs.",
|
|
165
|
+
"For long tasks, optionally report a brief milestone with `cohall progress --message 'Running tests'`. Do not include logs or secrets in progress notes.",
|
|
166
|
+
...supportsClarification ? [
|
|
167
|
+
"If essential information is missing, run `cohall request-input --question 'Your question'` or the task_request_input MCP tool, then end this turn immediately. Cohall will pause the task and resume it when the sender answers. Do not guess, keep working, or report a final result after requesting input."
|
|
168
|
+
] : [],
|
|
169
|
+
...files === undefined ? [] : [
|
|
170
|
+
...files.inputNames.length === 0 ? [] : [
|
|
171
|
+
`Input directory: ${files.input}`,
|
|
172
|
+
`Input file names: ${files.inputNames.join(", ")}`
|
|
173
|
+
],
|
|
174
|
+
`Output directory: ${files.output}`,
|
|
175
|
+
"To return files, write at most 2 regular files of up to 256 KiB each in the output directory and mention them in your result."
|
|
176
|
+
],
|
|
177
|
+
`
|
|
178
|
+
Task:
|
|
179
|
+
${task.prompt}${context}`,
|
|
180
|
+
...(task.clarifications ?? []).flatMap((question) => question.answer === undefined ? [] : [
|
|
181
|
+
`Clarification question:
|
|
182
|
+
${question.question}
|
|
183
|
+
Sender's answer:
|
|
184
|
+
${question.answer.text}`
|
|
185
|
+
])
|
|
186
|
+
].join(`
|
|
187
|
+
`);
|
|
188
|
+
};
|
|
189
|
+
var send = (state, event) => {
|
|
190
|
+
if (state.socket?.readyState === WebSocket.OPEN) {
|
|
191
|
+
state.socket.send(JSON.stringify(event));
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
var taskRunKey = (taskId, runId) => `${taskId}:${runId ?? ""}`;
|
|
195
|
+
var omitOutputFiles = (event, note) => {
|
|
196
|
+
if (event._tag !== "TaskFinished" || (event.attachments?.length ?? 0) === 0) {
|
|
197
|
+
return event;
|
|
198
|
+
}
|
|
199
|
+
const message = `
|
|
200
|
+
|
|
201
|
+
[Output files omitted: ${note}]`;
|
|
202
|
+
return SocketEvent.cases.TaskFinished.make({
|
|
203
|
+
_tag: "TaskFinished",
|
|
204
|
+
taskId: event.taskId,
|
|
205
|
+
...event.runId === undefined ? {} : { runId: event.runId },
|
|
206
|
+
result: `${event.result.slice(0, 131072 - message.length)}${message}`,
|
|
207
|
+
...event.providerSessionId === undefined ? {} : { providerSessionId: event.providerSessionId }
|
|
208
|
+
});
|
|
209
|
+
};
|
|
210
|
+
var sendTerminal = (state, event) => {
|
|
211
|
+
const safeEvent = state.supportsAttachments ? event : omitOutputFiles(event, "the relay does not support attachments. Upgrade the relay and retry.");
|
|
212
|
+
state.terminal.set(taskRunKey(event.taskId, event.runId), safeEvent);
|
|
213
|
+
if (state.socket?.readyState === WebSocket.OPEN) {
|
|
214
|
+
state.socket.send(JSON.stringify(safeEvent));
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
var sendOperationTerminal = (state, operationId, event) => {
|
|
218
|
+
const payload = JSON.stringify(event);
|
|
219
|
+
state.operationTerminal.set(operationId, payload);
|
|
220
|
+
if (state.socket?.readyState === WebSocket.OPEN) {
|
|
221
|
+
state.socket.send(payload);
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
var remember = (state, task) => {
|
|
225
|
+
state.completed.add(taskRunKey(task.id, task.runId));
|
|
226
|
+
if (state.completed.size <= 1000) {
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
const oldest = state.completed.keys().next();
|
|
230
|
+
if (!oldest.done) {
|
|
231
|
+
state.completed.delete(oldest.value);
|
|
232
|
+
state.terminal.delete(oldest.value);
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
var rememberOperation = (state, operationId) => {
|
|
236
|
+
state.completedOperations.add(operationId);
|
|
237
|
+
if (state.completedOperations.size <= 100) {
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
const oldest = state.completedOperations.values().next();
|
|
241
|
+
if (!oldest.done) {
|
|
242
|
+
state.completedOperations.delete(oldest.value);
|
|
243
|
+
state.operationTerminal.delete(oldest.value);
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
var sessionKey = (task) => `${task.threadId}:${task.provider}`;
|
|
247
|
+
var hasCompletedRun = (state, task) => state.completed.has(taskRunKey(task.id, task.runId));
|
|
248
|
+
var drain = (configuration, state) => {
|
|
249
|
+
if (state.stopping || state.operation !== undefined) {
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
if (state.tasks.size === 0) {
|
|
253
|
+
const operation = state.operationQueue.shift();
|
|
254
|
+
if (operation !== undefined) {
|
|
255
|
+
executeOperation(configuration, state, operation);
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
const occupied = new Set([...state.tasks.values()].map(({ task }) => taskSlot(task)));
|
|
260
|
+
for (let index = 0;index < state.queue.length; ) {
|
|
261
|
+
const next = state.queue[index];
|
|
262
|
+
if (next === undefined || occupied.has(taskSlot(next))) {
|
|
263
|
+
index += 1;
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
state.queue.splice(index, 1);
|
|
267
|
+
occupied.add(taskSlot(next));
|
|
268
|
+
execute(configuration, state, next);
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
var execute = (configuration, state, task) => {
|
|
272
|
+
if (state.tasks.has(task.id) || hasCompletedRun(state, task)) {
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
const controller = new AbortController;
|
|
276
|
+
let deadlineTimer;
|
|
277
|
+
const enforceDeadline = () => {
|
|
278
|
+
if (task.expiresAt === undefined)
|
|
279
|
+
return;
|
|
280
|
+
const remaining = Date.parse(task.expiresAt) - Date.now();
|
|
281
|
+
if (remaining <= 0) {
|
|
282
|
+
controller.abort();
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
deadlineTimer = setTimeout(enforceDeadline, Math.min(remaining, 2147483647));
|
|
286
|
+
};
|
|
287
|
+
enforceDeadline();
|
|
288
|
+
send(state, SocketEvent.make({
|
|
289
|
+
_tag: "TaskAccepted",
|
|
290
|
+
taskId: task.id,
|
|
291
|
+
...task.runId === undefined ? {} : { runId: task.runId }
|
|
292
|
+
}));
|
|
293
|
+
const workflow = Effect.scoped(Effect.gen(function* () {
|
|
294
|
+
if (configuration.providers !== undefined && !configuration.providers.includes(task.provider)) {
|
|
295
|
+
return yield* new ProviderRunError({
|
|
296
|
+
provider: task.provider,
|
|
297
|
+
message: `${task.provider} is not enabled on this device. Update its configured providers and restart the worker before retrying.`
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
if (task.provider === "grok-bot") {
|
|
301
|
+
return yield* Effect.tryPromise({
|
|
302
|
+
try: (signal) => runGrokBot(configuration.grokGateway, task, signal, state.supportsClarification),
|
|
303
|
+
catch: (cause) => new ProviderRunError({
|
|
304
|
+
provider: task.provider,
|
|
305
|
+
message: cause instanceof Error ? cause.message : String(cause)
|
|
306
|
+
})
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
const provider = task.provider;
|
|
310
|
+
if (!state.supportsAttachments && (task.inputAttachmentNames?.length ?? 0) > 0) {
|
|
311
|
+
return yield* new ProviderRunError({
|
|
312
|
+
provider,
|
|
313
|
+
message: "The relay does not support task file attachments"
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
const workspace = yield* Effect.acquireRelease(Effect.tryPromise({
|
|
317
|
+
try: () => openAllowedWorkspace(configuration, task.workspace),
|
|
318
|
+
catch: (cause) => new ProviderRunError({
|
|
319
|
+
provider,
|
|
320
|
+
message: cause instanceof Error ? cause.message : String(cause)
|
|
321
|
+
})
|
|
322
|
+
}), (workspace2) => Effect.promise(() => workspace2.close().catch(() => {
|
|
323
|
+
return;
|
|
324
|
+
})));
|
|
325
|
+
const files = state.supportsAttachments ? yield* prepareTaskFiles(configuration, task.id, task.inputAttachmentNames ?? []).pipe(Effect.mapError((cause) => new ProviderRunError({
|
|
326
|
+
provider,
|
|
327
|
+
message: cause instanceof Error ? cause.message : String(cause)
|
|
328
|
+
}))) : undefined;
|
|
329
|
+
const sessionId = task.providerSessionId ?? state.sessions.get(sessionKey(task));
|
|
330
|
+
return yield* run({
|
|
331
|
+
provider,
|
|
332
|
+
threadId: task.threadId,
|
|
333
|
+
taskId: task.id,
|
|
334
|
+
prompt: promptFor(task, configuration.name, state.supportsClarification, files),
|
|
335
|
+
cwd: workspace.cwd,
|
|
336
|
+
beforeSpawn: workspace.validate,
|
|
337
|
+
...sessionId === undefined ? {} : { sessionId },
|
|
338
|
+
...task.runId === undefined ? {} : { runId: task.runId },
|
|
339
|
+
...configuration.model === undefined ? {} : { model: configuration.model },
|
|
340
|
+
...configuration.sandbox === undefined ? {} : { sandbox: configuration.sandbox }
|
|
341
|
+
}).pipe(Effect.flatMap((result) => files === undefined ? Effect.succeed(result) : Effect.tryPromise({
|
|
342
|
+
try: async () => ({ ...result, attachments: await files.collectOutputs() }),
|
|
343
|
+
catch: (cause) => new ProviderRunError({
|
|
344
|
+
provider,
|
|
345
|
+
message: cause instanceof Error ? cause.message : String(cause)
|
|
346
|
+
})
|
|
347
|
+
}).pipe(Effect.uninterruptible)));
|
|
348
|
+
}));
|
|
349
|
+
const done = Effect.runPromise(workflow, { signal: controller.signal }).then((result) => {
|
|
350
|
+
let finished;
|
|
351
|
+
if (result.question !== undefined) {
|
|
352
|
+
if (!state.supportsClarification || task.runId === undefined)
|
|
353
|
+
throw new Error("Upgrade the relay before requesting clarification");
|
|
354
|
+
finished = SocketEvent.cases.TaskInputRequested.make({
|
|
355
|
+
_tag: "TaskInputRequested",
|
|
356
|
+
taskId: task.id,
|
|
357
|
+
runId: task.runId,
|
|
358
|
+
question: result.question
|
|
359
|
+
});
|
|
360
|
+
} else {
|
|
361
|
+
finished = SocketEvent.cases.TaskFinished.make({
|
|
362
|
+
_tag: "TaskFinished",
|
|
363
|
+
taskId: task.id,
|
|
364
|
+
...task.runId === undefined ? {} : { runId: task.runId },
|
|
365
|
+
result: result.result,
|
|
366
|
+
...result.sessionId === undefined ? {} : { providerSessionId: result.sessionId },
|
|
367
|
+
...result.attachments === undefined || result.attachments.length === 0 ? {} : { attachments: result.attachments }
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
const bounded = Buffer.byteLength(JSON.stringify(finished)) > maxSocketPayloadBytes ? omitOutputFiles(finished, "the combined result exceeded the 1 MiB transfer limit. Shorten the result or files and retry.") : finished;
|
|
371
|
+
if (result.sessionId !== undefined) {
|
|
372
|
+
state.sessions.set(sessionKey(task), result.sessionId);
|
|
373
|
+
}
|
|
374
|
+
remember(state, task);
|
|
375
|
+
sendTerminal(state, bounded);
|
|
376
|
+
}).catch((cause) => {
|
|
377
|
+
remember(state, task);
|
|
378
|
+
sendTerminal(state, controller.signal.aborted ? SocketEvent.cases.TaskCancelled.make({
|
|
379
|
+
_tag: "TaskCancelled",
|
|
380
|
+
taskId: task.id,
|
|
381
|
+
...task.runId === undefined ? {} : { runId: task.runId }
|
|
382
|
+
}) : SocketEvent.cases.TaskFailed.make({
|
|
383
|
+
_tag: "TaskFailed",
|
|
384
|
+
taskId: task.id,
|
|
385
|
+
...task.runId === undefined ? {} : { runId: task.runId },
|
|
386
|
+
error: (cause instanceof Error ? cause.message : String(cause)).slice(0, 16384)
|
|
387
|
+
}));
|
|
388
|
+
}).finally(() => {
|
|
389
|
+
clearTimeout(deadlineTimer);
|
|
390
|
+
state.tasks.delete(task.id);
|
|
391
|
+
drain(configuration, state);
|
|
392
|
+
});
|
|
393
|
+
state.tasks.set(task.id, { task, controller, done });
|
|
394
|
+
};
|
|
395
|
+
var executeOperation = (configuration, state, operation) => {
|
|
396
|
+
if (state.operation !== undefined || state.completedOperations.has(operation.id)) {
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
state.operation = operation;
|
|
400
|
+
send(state, SocketEvent.make({ _tag: "OperationAccepted", operationId: operation.id }));
|
|
401
|
+
performDeviceOperation(operation, version).then((result) => {
|
|
402
|
+
rememberOperation(state, operation.id);
|
|
403
|
+
sendOperationTerminal(state, operation.id, SocketEvent.make({
|
|
404
|
+
_tag: "OperationFinished",
|
|
405
|
+
operationId: operation.id,
|
|
406
|
+
result
|
|
407
|
+
}));
|
|
408
|
+
}).catch((cause) => {
|
|
409
|
+
rememberOperation(state, operation.id);
|
|
410
|
+
sendOperationTerminal(state, operation.id, SocketEvent.make({
|
|
411
|
+
_tag: "OperationFailed",
|
|
412
|
+
operationId: operation.id,
|
|
413
|
+
error: (cause instanceof Error ? cause.message : String(cause)).slice(0, 16384)
|
|
414
|
+
}));
|
|
415
|
+
}).finally(() => {
|
|
416
|
+
state.operation = undefined;
|
|
417
|
+
drain(configuration, state);
|
|
418
|
+
});
|
|
419
|
+
};
|
|
420
|
+
var scheduleOperation = (configuration, state, operation) => {
|
|
421
|
+
if (state.stopping)
|
|
422
|
+
return;
|
|
423
|
+
if (state.completedOperations.has(operation.id) || state.operation?.id === operation.id || state.operationQueue.some((pending) => pending.id === operation.id)) {
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
if (state.tasks.size > 0 || state.operation !== undefined) {
|
|
427
|
+
if (state.operationQueue.length >= 10) {
|
|
428
|
+
state.socket?.close(4008, "Operation queue limit reached");
|
|
429
|
+
return;
|
|
430
|
+
}
|
|
431
|
+
state.operationQueue.push(operation);
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
434
|
+
executeOperation(configuration, state, operation);
|
|
435
|
+
};
|
|
436
|
+
var performDeviceOperation = (operation, currentVersion, runUpgrade = upgrade) => runUpgrade({
|
|
437
|
+
currentVersion,
|
|
438
|
+
target: operation.requestedVersion,
|
|
439
|
+
restart: operation.restart,
|
|
440
|
+
dryRun: false,
|
|
441
|
+
delegated: true
|
|
442
|
+
}).then((result) => JSON.stringify(result));
|
|
443
|
+
var schedule = (configuration, state, task) => {
|
|
444
|
+
if (state.stopping)
|
|
445
|
+
return;
|
|
446
|
+
if (hasCompletedRun(state, task) || state.queue.some((queued) => queued.id === task.id && queued.runId === task.runId)) {
|
|
447
|
+
return;
|
|
448
|
+
}
|
|
449
|
+
const running = state.tasks.get(task.id);
|
|
450
|
+
if (running !== undefined && running.task.runId === task.runId) {
|
|
451
|
+
send(state, SocketEvent.make({
|
|
452
|
+
_tag: "TaskAccepted",
|
|
453
|
+
taskId: task.id,
|
|
454
|
+
...task.runId === undefined ? {} : { runId: task.runId }
|
|
455
|
+
}));
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
458
|
+
if (task.providerSessionId !== undefined) {
|
|
459
|
+
state.sessions.set(sessionKey(task), task.providerSessionId);
|
|
460
|
+
}
|
|
461
|
+
if ([...state.tasks.values()].some(({ task: active }) => taskSlot(active) === taskSlot(task)) || state.operation !== undefined) {
|
|
462
|
+
if (state.queue.length >= 100) {
|
|
463
|
+
state.socket?.close(4008, "Task queue limit reached");
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
state.queue.push(task);
|
|
467
|
+
return;
|
|
468
|
+
}
|
|
469
|
+
execute(configuration, state, task);
|
|
470
|
+
};
|
|
471
|
+
var cancel = (state, taskId, runId) => {
|
|
472
|
+
const running = state.tasks.get(taskId);
|
|
473
|
+
if (running !== undefined && (runId === undefined || running.task.runId === runId)) {
|
|
474
|
+
if (running.task.provider !== "grok-bot") {
|
|
475
|
+
running.controller.abort();
|
|
476
|
+
}
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
const index = state.queue.findIndex((task) => task.id === taskId && (runId === undefined || task.runId === runId));
|
|
480
|
+
if (index !== -1) {
|
|
481
|
+
state.queue.splice(index, 1);
|
|
482
|
+
}
|
|
483
|
+
remember(state, { id: taskId, ...runId === undefined ? {} : { runId } });
|
|
484
|
+
sendTerminal(state, SocketEvent.cases.TaskCancelled.make({
|
|
485
|
+
_tag: "TaskCancelled",
|
|
486
|
+
taskId,
|
|
487
|
+
...runId === undefined ? {} : { runId }
|
|
488
|
+
}));
|
|
489
|
+
};
|
|
490
|
+
var connect = (configuration, state) => Effect.tryPromise({
|
|
491
|
+
try: (signal) => new Promise((complete) => {
|
|
492
|
+
const socket = new WebSocket(socketUrl(configuration), {
|
|
493
|
+
maxPayload: maxSocketPayloadBytes,
|
|
494
|
+
perMessageDeflate: false,
|
|
495
|
+
allowSynchronousEvents: false
|
|
496
|
+
});
|
|
497
|
+
let closed = false;
|
|
498
|
+
let connectionDeadline = setTimeout(() => socket.terminate(), 1e4);
|
|
499
|
+
const resetConnectionDeadline = () => {
|
|
500
|
+
if (closed || state.socket !== socket)
|
|
501
|
+
return;
|
|
502
|
+
clearTimeout(connectionDeadline);
|
|
503
|
+
connectionDeadline = setTimeout(() => socket.terminate(), 45000);
|
|
504
|
+
};
|
|
505
|
+
socket.on("ping", resetConnectionDeadline);
|
|
506
|
+
const discovery = new AbortController;
|
|
507
|
+
let bots = [];
|
|
508
|
+
let refreshing = false;
|
|
509
|
+
const refreshBots = async () => {
|
|
510
|
+
if (refreshing || configuration.grokGateway === undefined || configuration.providers !== undefined && !configuration.providers.includes("grok-bot")) {
|
|
511
|
+
return;
|
|
512
|
+
}
|
|
513
|
+
refreshing = true;
|
|
514
|
+
bots = await discoverGrokBots(configuration.grokGateway, discovery.signal).catch(() => []);
|
|
515
|
+
refreshing = false;
|
|
516
|
+
if (!closed) {
|
|
517
|
+
send(state, SocketEvent.make({
|
|
518
|
+
_tag: "DeviceHeartbeat",
|
|
519
|
+
deviceId: configuration.id,
|
|
520
|
+
status: state.tasks.size > 0 || state.operation !== undefined ? "busy" : "online",
|
|
521
|
+
bots
|
|
522
|
+
}));
|
|
523
|
+
}
|
|
524
|
+
};
|
|
525
|
+
const heartbeat = setInterval(() => {
|
|
526
|
+
send(state, SocketEvent.make({
|
|
527
|
+
_tag: "DeviceHeartbeat",
|
|
528
|
+
deviceId: configuration.id,
|
|
529
|
+
status: state.tasks.size > 0 || state.operation !== undefined ? "busy" : "online",
|
|
530
|
+
...configuration.grokGateway === undefined ? {} : { bots }
|
|
531
|
+
}));
|
|
532
|
+
refreshBots();
|
|
533
|
+
}, 15000);
|
|
534
|
+
let queuedMessages = 0;
|
|
535
|
+
const close = () => {
|
|
536
|
+
if (closed) {
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
closed = true;
|
|
540
|
+
discovery.abort();
|
|
541
|
+
clearTimeout(connectionDeadline);
|
|
542
|
+
clearInterval(heartbeat);
|
|
543
|
+
if (state.socket === socket) {
|
|
544
|
+
state.socket = undefined;
|
|
545
|
+
}
|
|
546
|
+
complete();
|
|
547
|
+
};
|
|
548
|
+
signal.addEventListener("abort", () => {
|
|
549
|
+
socket.terminate();
|
|
550
|
+
close();
|
|
551
|
+
}, { once: true });
|
|
552
|
+
socket.once("open", () => {
|
|
553
|
+
socket.send(JSON.stringify(SocketEvent.make({ _tag: "Authenticate", token: configuration.token })));
|
|
554
|
+
});
|
|
555
|
+
socket.on("message", (message) => {
|
|
556
|
+
if (queuedMessages >= maxQueuedRelayMessages) {
|
|
557
|
+
socket.close(4008, "Message queue limit reached");
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
queuedMessages += 1;
|
|
561
|
+
state.processing = state.processing.then(async () => {
|
|
562
|
+
if (closed) {
|
|
563
|
+
return;
|
|
564
|
+
}
|
|
565
|
+
const text = Buffer.isBuffer(message) ? message.toString("utf8") : message instanceof ArrayBuffer ? Buffer.from(message).toString("utf8") : Array.isArray(message) ? Buffer.concat(message).toString("utf8") : Buffer.from(message).toString("utf8");
|
|
566
|
+
const event = await Effect.runPromise(Effect.try({
|
|
567
|
+
try: () => JSON.parse(text),
|
|
568
|
+
catch: () => new DeviceConnectionError({ message: "Relay sent invalid JSON" })
|
|
569
|
+
}).pipe(Effect.flatMap(decodeSocketEvent)));
|
|
570
|
+
if (event._tag === "Connected") {
|
|
571
|
+
state.supportsAttachments = event.taskAttachments === true;
|
|
572
|
+
state.supportsClarification = event.taskClarification === true;
|
|
573
|
+
state.socket = socket;
|
|
574
|
+
resetConnectionDeadline();
|
|
575
|
+
socket.send(JSON.stringify(SocketEvent.make({
|
|
576
|
+
_tag: "DeviceHello",
|
|
577
|
+
device: describeDevice(configuration, state.tasks.size > 0 || state.operation !== undefined ? "busy" : "online", bots)
|
|
578
|
+
})));
|
|
579
|
+
for (const [key, pending] of state.terminal) {
|
|
580
|
+
const safeEvent = state.supportsAttachments ? pending : omitOutputFiles(pending, "the relay does not support attachments. Upgrade the relay and retry.");
|
|
581
|
+
state.terminal.set(key, safeEvent);
|
|
582
|
+
socket.send(JSON.stringify(safeEvent));
|
|
583
|
+
}
|
|
584
|
+
for (const payload of state.operationTerminal.values()) {
|
|
585
|
+
socket.send(payload);
|
|
586
|
+
}
|
|
587
|
+
refreshBots();
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
if (event._tag === "TaskAssigned") {
|
|
591
|
+
schedule(configuration, state, event.task);
|
|
592
|
+
return;
|
|
593
|
+
}
|
|
594
|
+
if (event._tag === "CancelTask") {
|
|
595
|
+
cancel(state, event.taskId, event.runId);
|
|
596
|
+
return;
|
|
597
|
+
}
|
|
598
|
+
if (event._tag === "TaskSettled") {
|
|
599
|
+
state.terminal.delete(taskRunKey(event.taskId, event.runId));
|
|
600
|
+
cleanupBotReply(event.taskId, event.runId).catch(() => {
|
|
601
|
+
console.error(`Could not remove local bot reply for settled task ${event.taskId}`);
|
|
602
|
+
});
|
|
603
|
+
return;
|
|
604
|
+
}
|
|
605
|
+
if (event._tag === "OperationAssigned") {
|
|
606
|
+
scheduleOperation(configuration, state, event.operation);
|
|
607
|
+
return;
|
|
608
|
+
}
|
|
609
|
+
if (event._tag === "OperationSettled") {
|
|
610
|
+
state.operationTerminal.delete(event.operationId);
|
|
611
|
+
return;
|
|
612
|
+
}
|
|
613
|
+
if (event._tag === "Error") {
|
|
614
|
+
console.error(`Relay error: ${event.message}`);
|
|
615
|
+
}
|
|
616
|
+
}).catch((cause) => {
|
|
617
|
+
console.error(`Invalid relay event: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
618
|
+
}).finally(() => {
|
|
619
|
+
queuedMessages = Math.max(0, queuedMessages - 1);
|
|
620
|
+
});
|
|
621
|
+
});
|
|
622
|
+
socket.once("close", close);
|
|
623
|
+
socket.once("error", () => socket.close());
|
|
624
|
+
}),
|
|
625
|
+
catch: (cause) => new DeviceConnectionError({
|
|
626
|
+
message: cause instanceof Error ? cause.message : String(cause)
|
|
627
|
+
})
|
|
628
|
+
});
|
|
629
|
+
var runDaemon = (configuration) => {
|
|
630
|
+
const state = {
|
|
631
|
+
socket: undefined,
|
|
632
|
+
stopping: false,
|
|
633
|
+
supportsAttachments: false,
|
|
634
|
+
supportsClarification: false,
|
|
635
|
+
processing: Promise.resolve(),
|
|
636
|
+
terminal: new Map,
|
|
637
|
+
queue: [],
|
|
638
|
+
sessions: new Map,
|
|
639
|
+
tasks: new Map,
|
|
640
|
+
completed: new Set,
|
|
641
|
+
operation: undefined,
|
|
642
|
+
operationQueue: [],
|
|
643
|
+
operationTerminal: new Map,
|
|
644
|
+
completedOperations: new Set
|
|
645
|
+
};
|
|
646
|
+
return connect(configuration, state).pipe(Effect.repeat({ schedule: Schedule.spaced("2 seconds") }), Effect.ensuring(Effect.promise(async () => {
|
|
647
|
+
state.stopping = true;
|
|
648
|
+
state.socket?.close();
|
|
649
|
+
const running = [...state.tasks.values()];
|
|
650
|
+
for (const { controller } of running) {
|
|
651
|
+
controller.abort();
|
|
652
|
+
}
|
|
653
|
+
await Promise.allSettled(running.map(({ done }) => done));
|
|
654
|
+
})));
|
|
655
|
+
};
|
|
656
|
+
export {
|
|
657
|
+
selectProviders,
|
|
658
|
+
runDaemon,
|
|
659
|
+
performDeviceOperation,
|
|
660
|
+
openAllowedWorkspace,
|
|
661
|
+
allowedWorkspace,
|
|
662
|
+
DeviceConnectionError
|
|
663
|
+
};
|
|
664
|
+
|
|
665
|
+
//# debugId=2A5B855EA0BC71EB64756E2164756E21
|