Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Merge remote-tracking branch 'gh/train/nov30-b1' into train/nov30-final
milind-soni1ea9b3cfe82d
diff --cc server/index.tsindex f7952e4db4,7a3e0a1a5b..04c90869be--- a/server/index.ts+++ b/server/index.ts@@@ -3845,7 -3845,7 +3845,7 @@@ const validateModelProposal = (selectio}return null;}; const engineHints = createEngineHints({ registry, access: (id) => providerConfigs()[id]?.access ?? registry.access(id), managed: (id) => managedDesktop.owns(id), policy: policyModelRefusal, ...(hostedModels ? { offered: (selection) => hostedModels!.allows(selection) } : {}) }); const ownThreads = createOwnThreads({ store, registry, node: (id) => coordinator.node(id), current: turnSelection, proposalRefusal: validateModelProposal, givesWay: modelGivesWay, modelName, hint: engineHints.hint, broken: engineHints.broken, localOnce: (engines) => localModelsOnce(engines, directLocalModels(providerConfigs(), (id, saved) => { const engine = registry.get(id), live = threadEngine(id); if (!engine || !live || !readyToRun(live, selectionContext)) return null; return { name: engine.displayName || id, models: [...saved, ...engine.models.options.map((option) => option.id)].filter((model) => !hostedModels || hostedModels.allows({ instanceId: id, model })) }; })), sourceLevel: sourceApprovalMode, mayRaise: (threadId) => !outsideLineage.handsNoLevel(threadId) && (!CLOUD_HOME || cloudOwnerPerson(threadPersonKey(threadId))) && (!HOSTED_WORKSPACE || sharedWorkspaceFullAccessEnabled()) });- const handedLines: HandedLineDeps | undefined = CLOUD_TEAM ? undefined : { store, mainThread: (botId) => handedMainThread(store.bot(botId), (threadId) => store.taskByThread(botId, threadId)?.archivedAt !== undefined, () => botMainThread(botId) ?? store.bot(botId)?.threadId) }; const automaticTitles = createAutomaticThreadTitles(); const titleHandedThread = createHandedThreadTitle({ store, gate: threadTitleGate, start: automaticTitles.start }); const botLink = createBotLinkHost({ roomLine: (threadId, key, params) => serverLine(threadLanguage(threadId), key, params), roomWindow: (threadId, reader) => roomTranscript.window(threadId, userNameFor(threadId), undefined, reader), roomOpener: (botId, threadId) => handoffOpener({ botId, threadId }, threadId), roomChanged: (groupId) => { const room = store.group(groupId); if (room) broadcast({ kind: "group", group: publicGroupState(room) }); }, roomFollow: followRoomMentions<GroupTurnOperation>({ members: (groupId) => (store.group(groupId)?.memberIds ?? []).map((id) => store.bot(id)).filter((bot): bot is BotRecord => Boolean(bot)), mentioned: (text, members) => roomResponders(text, members, { kind: "mentions" }), begin: (groupId, threadId, botIds) => Object.assign(beginGroupTurnOperation(groupId, threadId, botIds), { farSide: true }), finish: finishGroupTurnOperation, queue: groupQueues, wait: waitForChatRoomMember, run: (groupId, threadId, botId, hop, spoken, operation) => runGroupMemberTurn(groupId, threadId, botId, hop, spoken, undefined, undefined, () => operation.cancelled, undefined, undefined, undefined, undefined, operation) }), dataDir: DATA_DIR, environmentId: ENVIRONMENT_ID, store, coordinator: () => coordinator, kick: () => handoffTicks.kick(), level: (bot) => approvalModeForTurn(bot, true, bot.threadId), titleHanded: titleHandedThread, ...(handedLines ? { handedLine: (input) => { postHandedLine(handedLines, input); } } : {}), refusal: (bot) => botMoveRefusal(bot) ?? botHolds.handoff(bot.id) ?? starterCaps.pausedText(bot.id, undefined), paused: (botId) => starterAwake.isPaused(botId) || botHolds.held(botId), acceptRefusal: (bot) => linkLimits.acceptRefusal(bot), language: (threadId) => threadLanguage(threadId), personName: personNameIn, sessions, power: () => cloudPower, files: handoffFiles, storeFile: (path, name, root) => saveBotAttachment({ path, name, roots: [root], byContent: true }), log: (line) => console.error(line), local: (auth) => auth.kind === "loopback" && auth.trust !== "service" && !CLOUD_HOME && !HOSTED_WORKSPACE, owner: (auth) => !sharedMembership() && !HOSTED_WORKSPACE && (ownHome.owner(auth) || (CLOUD_PERSONAL && cloudOwnerSession(auth))) }); ROUTES.push(botLink.routes); const linkedRoster = createLinkedRoster({ link: botLink.link, bots: () => store.bots, active: () => coordinator.active() }); const handoffTicks = createHandoffTicks(), coordinator: Coordinator = createCoordinator({-const handedLines: HandedLineDeps | undefined = CLOUD_TEAM ? undefined : { store, mainThread: (botId) => handedMainThread(store.bot(botId), (threadId) => store.taskByThread(botId, threadId)?.archivedAt !== undefined, () => botMainThread(botId) ?? store.bot(botId)?.threadId) }; const titleHandedThread = createHandedThreadTitle({ store, gate: threadTitleGate, generate: generateThreadTitle }); const botLink = createBotLinkHost({ roomLine: (threadId, key, params) => serverLine(threadLanguage(threadId), key, params), roomWindow: (threadId, reader) => roomTranscript.window(threadId, userNameFor(threadId), undefined, reader), roomOpener: (botId, threadId) => handoffOpener({ botId, threadId }, threadId), roomChanged: (groupId) => { const room = store.group(groupId); if (room) broadcast({ kind: "group", group: publicGroupState(room) }); }, roomFollow: followRoomMentions<GroupTurnOperation>({ members: (groupId) => (store.group(groupId)?.memberIds ?? []).map((id) => store.bot(id)).filter((bot): bot is BotRecord => Boolean(bot)), mentioned: (text, members) => roomResponders(text, members, { kind: "mentions" }), begin: (groupId, threadId, botIds) => Object.assign(beginGroupTurnOperation(groupId, threadId, botIds), { farSide: true }), finish: finishGroupTurnOperation, queue: groupQueues, wait: waitForChatRoomMember, run: (groupId, threadId, botId, hop, spoken, operation) => runGroupMemberTurn(groupId, threadId, botId, hop, spoken, undefined, undefined, () => operation.cancelled, undefined, undefined, undefined, undefined, operation) }), dataDir: DATA_DIR, environmentId: ENVIRONMENT_ID, store, coordinator: () => coordinator, kick: () => handoffTicks.kick(), level: (bot) => approvalModeForTurn(bot, true, bot.threadId), titleHanded: titleHandedThread, ...(handedLines ? { handedLine: (input) => { postHandedLine(handedLines, input); } } : {}), refusal: (bot) => botMoveRefusal(bot) ?? botHolds.handoff(bot.id) ?? starterCaps.pausedText(bot.id, undefined), paused: (botId) => starterAwake.isPaused(botId) || botHolds.held(botId), acceptRefusal: (bot) => linkLimits.acceptRefusal(bot), language: (threadId) => threadLanguage(threadId), personName: personNameIn, sessions, power: () => cloudPower, files: handoffFiles, storeFile: (path, name, root) => saveBotAttachment({ path, name, roots: [root], byContent: true }), log: (line) => console.error(line), local: (auth) => auth.kind === "loopback" && auth.trust !== "service" && !CLOUD_HOME && !HOSTED_WORKSPACE, owner: (auth) => !sharedMembership() && !HOSTED_WORKSPACE && (ownHome.owner(auth) || (CLOUD_PERSONAL && cloudOwnerSession(auth))) }); ROUTES.push(botLink.routes); const linkedRoster = createLinkedRoster({ link: botLink.link, bots: () => store.bots, active: () => coordinator.active() }); const handedClose = createHandedClose({ store, working: (threadId) => coordinator.activeDirect(threadId), node: (id) => coordinator.node(id), waitArmed: (botId, threadId) => botWaits.all().some((wait) => wait.botId === botId && wait.threadId === threadId) }); const handoffTicks = createHandoffTicks(), coordinator: Coordinator = createCoordinator({++const handedLines: HandedLineDeps | undefined = CLOUD_TEAM ? undefined : { store, mainThread: (botId) => handedMainThread(store.bot(botId), (threadId) => store.taskByThread(botId, threadId)?.archivedAt !== undefined, () => botMainThread(botId) ?? store.bot(botId)?.threadId) }; const automaticTitles = createAutomaticThreadTitles(); const titleHandedThread = createHandedThreadTitle({ store, gate: threadTitleGate, start: automaticTitles.start }); const botLink = createBotLinkHost({ roomLine: (threadId, key, params) => serverLine(threadLanguage(threadId), key, params), roomWindow: (threadId, reader) => roomTranscript.window(threadId, userNameFor(threadId), undefined, reader), roomOpener: (botId, threadId) => handoffOpener({ botId, threadId }, threadId), roomChanged: (groupId) => { const room = store.group(groupId); if (room) broadcast({ kind: "group", group: publicGroupState(room) }); }, roomFollow: followRoomMentions<GroupTurnOperation>({ members: (groupId) => (store.group(groupId)?.memberIds ?? []).map((id) => store.bot(id)).filter((bot): bot is BotRecord => Boolean(bot)), mentioned: (text, members) => roomResponders(text, members, { kind: "mentions" }), begin: (groupId, threadId, botIds) => Object.assign(beginGroupTurnOperation(groupId, threadId, botIds), { farSide: true }), finish: finishGroupTurnOperation, queue: groupQueues, wait: waitForChatRoomMember, run: (groupId, threadId, botId, hop, spoken, operation) => runGroupMemberTurn(groupId, threadId, botId, hop, spoken, undefined, undefined, () => operation.cancelled, undefined, undefined, undefined, undefined, operation) }), dataDir: DATA_DIR, environmentId: ENVIRONMENT_ID, store, coordinator: () => coordinator, kick: () => handoffTicks.kick(), level: (bot) => approvalModeForTurn(bot, true, bot.threadId), titleHanded: titleHandedThread, ...(handedLines ? { handedLine: (input) => { postHandedLine(handedLines, input); } } : {}), refusal: (bot) => botMoveRefusal(bot) ?? botHolds.handoff(bot.id) ?? starterCaps.pausedText(bot.id, undefined), paused: (botId) => starterAwake.isPaused(botId) || botHolds.held(botId), acceptRefusal: (bot) => linkLimits.acceptRefusal(bot), language: (threadId) => threadLanguage(threadId), personName: personNameIn, sessions, power: () => cloudPower, files: handoffFiles, storeFile: (path, name, root) => saveBotAttachment({ path, name, roots: [root], byContent: true }), log: (line) => console.error(line), local: (auth) => auth.kind === "loopback" && auth.trust !== "service" && !CLOUD_HOME && !HOSTED_WORKSPACE, owner: (auth) => !sharedMembership() && !HOSTED_WORKSPACE && (ownHome.owner(auth) || (CLOUD_PERSONAL && cloudOwnerSession(auth))) }); ROUTES.push(botLink.routes); const linkedRoster = createLinkedRoster({ link: botLink.link, bots: () => store.bots, active: () => coordinator.active() }); const handedClose = createHandedClose({ store, working: (threadId) => coordinator.activeDirect(threadId), node: (id) => coordinator.node(id), waitArmed: (botId, threadId) => botWaits.all().some((wait) => wait.botId === botId && wait.threadId === threadId) }); const handoffTicks = createHandoffTicks(), coordinator: Coordinator = createCoordinator({dataDir: DATA_DIR, restartCut: restartCutStop({ dataDir: DATA_DIR, lines: (threadId) => store.activePath(threadId) }),now: Date.now, wrote: () => { handoffTicks.kick(); handoffStatus.changed(); }, handoffLimit: { refusal: (botId, open, origin) => botHolds.handoff(botId) ?? starterCaps.handoffs.refusal(botId, open) ?? usageCapGate.handoff(botId, origin) },log: line => console.error("coordinator:", line),@@@ -3931,9 -3927,10 +3931,9 @@@if (group) store.markGroupThreadUnread(group.id, child.threadId, true);else {if (!parent.parentId && parent.reply !== "poll") store.patchTask(parent.botId, parent.threadId, { unread: true });- const source = store.bot(parent.botId);if (source) markTaskContextExternallyUpdated(source, parent.threadId);}- if (!child.groupId && child.status === "completed" && !problem && !coordinator.activeDirect(child.threadId)) finishHandedThread(store, child.botId, child.threadId, parent.botId, (threadId) => botWaits.list(child.botId).some((wait) => wait.threadId === threadId));+ handedClose.ended(child, parent, Boolean(problem));},run: handoffFiles.around(async (node, resumed, signal, composed: ComposedTurn) => {const group = node.groupId ? store.group(node.groupId) : undefined;@@@ -7513,25 -7509,21 +7513,21 @@@ async function beginTurnelse { clearInternalTurn(threadId); doneNotice.personTurnStarted(threadId); }if (answer.quiet) quietTurnThreads.add(threadId);else quietTurnThreads.delete(threadId);+ const turnLineIds = new Set(opts?.excludeMessageIds ?? []);- const spoken = opts?.via === "call" || opts?.userMessage?.via === "call" ||- (turnLineIds.size > 0 && store.messagesFor(threadId).some((message) => turnLineIds.has(message.id) && message.via === "call"));++ const spoken = spokenTurn(opts?.via, opts?.userMessage?.via, turnLineIds, store.messagesFor(threadId));if (resolvedImages.text.trim() && !opts?.cardContinuation && !opts?.replyTo?.reactedWith) {const titled = store.titleTaskFromFirstMessage(bot.id, resolvedImages.text, threadId);- const snippet = titled?.title, titleGate = titled && snippet && !titled.openedBy?.botId ? threadTitleGate(bot) : null;- if (snippet && titleGate?.ok) {- void generateThreadTitle(titleGate.instance, resolvedImages.text)- .then((title) => {- if (title) store.retitleTask(bot.id, threadId, snippet, title);- })- .catch(() => undefined);+ const task = () => store.taskByThread(bot.id, threadId), current = task();+ if (current && !current.openedBy?.botId && !titleRegenerations.has(threadId) && (titled || (cfg.threadTitles?.followUp && current.titleMode === "automatic"))) {+ const title = current.title;+ automaticTitles.start(threadId, { request: resolvedImages.text, currentTitle: titled ? undefined : title,+ stillCurrent: () => task()?.title === title && task()?.titleMode === "automatic" && !titleRegenerations.has(threadId),+ model: () => threadTitleGate(store.projectBotForTask(bot.id, threadId) ?? bot, spoken || guestConfined || linkLimited),+ apply: (next) => { store.retitleTask(bot.id, threadId, title, next); } });}}- // Spoken words never reach the log.- console.log(turnStartLogLine({- botId, text: resolvedImages.text, images: turnImages.length, depth: commsDepth, card: Boolean(opts?.cardContinuation), spoken,- }));- const turnLineIds = new Set(opts?.excludeMessageIds ?? []);- const spoken = spokenTurn(opts?.via, opts?.userMessage?.via, turnLineIds, store.messagesFor(threadId));+ console.log(turnStartLogLine({ botId, text: resolvedImages.text, images: turnImages.length, depth: commsDepth, card: Boolean(opts?.cardContinuation), spoken }));const instanceId = instance.instanceId;const automated = commsDepth > 0 || opts?.automationSource !== undefined|| Boolean(opts?.unattended || opts?.cardContinuation || opts?.peerAsk || opts?.coordination || opts?.compactOnly || opts?.computerSelectionContinuation);@@@ -8809,7 -8797,7 +8798,7 @@@ ROUTES.push(createCalendarCallRoutes(roomView: (auth, group) => personRooms.groupForAuth(auth, publicGroupState(group)),messages: (threadId) => store.messagesFor(threadId),}));- const checkBacks = createCheckBacks({ dataDir: DATA_DIR, alive: (botId, threadId) => directChatOf(botId, threadId), busy: (botId, threadId) => threadBusy(botId, threadId), line: (record, line, messageId) => writeCheckBackLine(store, record, line, messageId, threadLanguage(record.threadId)), start: async (record, prompt) => { await startTurn(record.botId, prompt, { threadId: record.threadId, cardContinuation: true, ownRoot: true, origin: record.origin }); }, paused: (error) => [BOT_HELD_CODE, BOT_PAUSED_CODE].includes(String((error as { code?: unknown } | null)?.code)) }); const botWaits = new WaitManager(createWaitHost({ store, directChat: directChatOf, threadBusy, wrote: markTaskContextExternallyUpdated, notify, enqueue: (input) => routines!.enqueueWebhook(input), cloudHome: Boolean(CLOUD_HOME) })); store.onChange((change) => { if (change.type === "bot" && store.bot(change.botId)?.busy) botWaits.noteBotBusy(change.botId); });-const checkBacks = createCheckBacks({ dataDir: DATA_DIR, alive: (botId, threadId) => directChatOf(botId, threadId), busy: (botId, threadId) => threadBusy(botId, threadId), line: (record, line, messageId) => writeCheckBackLine(store, record, line, messageId, threadLanguage(record.threadId)), start: async (record, prompt) => { await startTurn(record.botId, prompt, { threadId: record.threadId, cardContinuation: true, origin: record.origin }); }, paused: (error) => [BOT_HELD_CODE, BOT_PAUSED_CODE].includes(String((error as { code?: unknown } | null)?.code)) }); const botWaits = new WaitManager({ ...createWaitHost({ store, directChat: directChatOf, threadBusy, wrote: markTaskContextExternallyUpdated, notify, enqueue: (input) => routines!.enqueueWebhook(input), cloudHome: Boolean(CLOUD_HOME) }), ended: (wait) => handedClose.look(wait.botId) }); store.onChange((change) => { if (change.type === "bot" && store.bot(change.botId)?.busy) botWaits.noteBotBusy(change.botId); });++const checkBacks = createCheckBacks({ dataDir: DATA_DIR, alive: (botId, threadId) => directChatOf(botId, threadId), busy: (botId, threadId) => threadBusy(botId, threadId), line: (record, line, messageId) => writeCheckBackLine(store, record, line, messageId, threadLanguage(record.threadId)), start: async (record, prompt) => { await startTurn(record.botId, prompt, { threadId: record.threadId, cardContinuation: true, ownRoot: true, origin: record.origin }); }, paused: (error) => [BOT_HELD_CODE, BOT_PAUSED_CODE].includes(String((error as { code?: unknown } | null)?.code)) }); const botWaits = new WaitManager({ ...createWaitHost({ store, directChat: directChatOf, threadBusy, wrote: markTaskContextExternallyUpdated, notify, enqueue: (input) => routines!.enqueueWebhook(input), cloudHome: Boolean(CLOUD_HOME) }), ended: (wait) => handedClose.look(wait.botId) }); store.onChange((change) => { if (change.type === "bot" && store.bot(change.botId)?.busy) botWaits.noteBotBusy(change.botId); });const recoveryOwners = routines.routineRequestReceiptOwners();if (recoveryOwners.length > 0) {const recoveryThreads = [...new Set(recoveryOwners.map((owner) => owner.threadId))];diff --cc server/waits.tsindex 6203a86cfc,7fb02e5fb6..90cf3228d5--- a/server/waits.ts+++ b/server/waits.ts@@@ -418,13 -397,10 +422,14 @@@ export class WaitManagertry { posted = this.options.post(wait, wait.ending); } catch (error) { console.error(`wait ${wait.id}: could not post`, error); }if (!posted) continue;const status = wait.ending.status;+ if (status === "fired" && wait.followUp) {+ const outcome = this.startFollowUp(wait, now);+ if (outcome === "retry") continue;+ if (outcome === "gaveup") { this.followUpLost(wait); continue; }+ }this.commit(() => { this.waits = this.waits.filter((w) => w !== wait); });- if (status === "fired" && wait.followUp) this.safely(() => this.options.followUp(wait as WaitRecord & { followUp: string }));if (wait.cardMessageId) this.safely(() => this.options.settleCard(wait, status === "fired" ? "fired" : "expired"));+ this.ended(wait);}} finally {this.ticking = false;@@@ -479,32 -455,9 +484,38 @@@try { run(); } catch (error) { console.error("wait: callback failed", error); }}+ /** Starts a fired wait's follow-up. A refused enqueue is not the end of the work: the wait stays with its decided+ * result and the next attempt is scheduled, so the retry does not depend on the condition still holding. */+ private startFollowUp(wait: WaitRecord, now: number): "started" | "retry" | "gaveup" {+ try {+ this.options.followUp(wait as WaitRecord & { followUp: string });+ return "started";+ } catch (error) {+ console.error(`wait ${wait.id}: could not start the follow-up`, error);+ wait.followUpTries = (wait.followUpTries ?? 0) + 1;+ if (wait.followUpTries >= FOLLOW_UP_TRIES) return "gaveup";+ wait.followUpRetryAt = now + FOLLOW_UP_RETRY_MS;+ try { this.commit(() => {}); } catch (saveError) { console.error(`wait ${wait.id}: could not store its retry`, saveError); }+ return "retry";+ }+ }++ /** The follow-up never started: say so once, in a notice of its own, then let the wait go. The "fired" notice already+ * went out under that status, and the host posts one notice per wait id and status, so this one needs another. */+ private followUpLost(wait: WaitRecord): void {+ try {+ this.options.post(wait, { status: "stopped", text: chatNotice("chat.notice.waitFollowUpLost", { label: wait.label }) });+ } catch (error) {+ console.error(`wait ${wait.id}: could not post`, error);+ }+ this.commit(() => { this.waits = this.waits.filter((w) => w !== wait); });+ if (wait.cardMessageId) this.safely(() => this.options.settleCard(wait, "expired"));++ this.ended(wait);++ }+++ private ended(wait: WaitRecord): void {+ const ended = this.options.ended;+ if (ended) this.safely(() => ended(cloneWait(wait)));}private commit(mutate: () => void): void {