import * as Automerge from "@automerge/automerge";
import { HUB_RUN_TIMING_CUSTOM_TYPE, } from "./session-snapshot.js";
const MAX_AGENT_VIEW_ITEMS = 500;
export class HubViewDocument {
    doc;
    /**
     * Mutations applied since the last {@link compactHistory} or {@link resetSession}. Used as a cheap
     * proxy for "history size" so callers can decide when to compact without paying the O(n) cost of
     * Automerge.getAllChanges on every hot-path mutation.
     */
    mutationsSinceCompact = 0;
    constructor(initialState = createEmptyViewDocumentState()) {
        this.doc = Automerge.from(deepCloneJson(initialState));
    }
    getChangeCount() {
        return this.mutationsSinceCompact;
    }
    compactHistory() {
        this.doc = Automerge.from(deepCloneJson(Automerge.toJS(this.doc)));
        this.mutationsSinceCompact = 0;
    }
    createSyncState() {
        return { heads: undefined };
    }
    resetSession(snapshot, agentId = snapshot.header.id) {
        this.doc = Automerge.from(createViewDocumentStateFromSession(snapshot, agentId, this.doc.peers ?? []));
        this.mutationsSinceCompact = 0;
    }
    syncAgentList(agentIds) {
        this.doc = Automerge.change(this.doc, (doc) => {
            const uniqueAgentIds = Array.from(new Set(agentIds));
            for (const agentId of uniqueAgentIds) {
                ensureAgent(doc, agentId);
            }
            syncArray(doc.agentOrder, uniqueAgentIds);
            for (const agentId of Object.keys(doc.agentsById)) {
                if (!uniqueAgentIds.includes(agentId)) {
                    delete doc.agentsById[agentId];
                }
            }
        });
        this.mutationsSinceCompact += 1;
    }
    updateAgentMetadata(agentId, metadata) {
        this.doc = Automerge.change(this.doc, (doc) => {
            const agent = ensureAgent(doc, agentId);
            syncOptionalProperty(agent, "parentId", metadata.parentId);
            syncOptionalProperty(agent, "kind", metadata.kind);
            syncOptionalProperty(agent, "lifecycle", metadata.lifecycle);
            syncOptionalProperty(agent, "name", metadata.name);
            syncOptionalProperty(agent, "description", metadata.description);
        });
        this.mutationsSinceCompact += 1;
    }
    updateAgentSummary(agentId, summary) {
        this.doc = Automerge.change(this.doc, (doc) => {
            const agent = ensureAgent(doc, agentId);
            syncOptionalProperty(agent, "summary", summary);
        });
        this.mutationsSinceCompact += 1;
    }
    updateSession(snapshot, agentId = snapshot.header.id) {
        this.doc = Automerge.change(this.doc, (doc) => {
            const agent = ensureAgent(doc, agentId);
            if (agent.sessionId === undefined || agent.sessionId !== snapshot.header.id) {
                syncArray(agent.items, createItemsFromEntries(snapshot.entries));
                agent.live = createEmptyLiveState();
            }
            agent.sessionId = snapshot.header.id;
            agent.cwd = snapshot.header.cwd;
            agent.protocolVersion = snapshot.header.version;
            agent.sessionFile = snapshot.sessionFile;
            syncOptionalProperty(agent, "summary", snapshot.summary);
            agent.status.isRunning = snapshot.isRunning;
            syncOptionalProperty(agent.status, "runStartedAt", snapshot.runStartedAt);
            syncOptionalProperty(agent.status, "lastRunStartedAt", snapshot.lastRunStartedAt);
            syncOptionalProperty(agent.status, "lastRunEndedAt", snapshot.lastRunEndedAt);
            syncOptionalProperty(agent.status, "lastRunDurationMs", snapshot.lastRunDurationMs);
            syncOptionalProperty(agent.status, "lastRunEndReason", snapshot.lastRunEndReason);
            syncProperty(agent.queue, "messages", snapshot.queuedMessages ?? []);
            syncProperty(agent.queue, "steering", snapshot.steeringMessages ?? []);
            syncProperty(agent.queue, "followUp", snapshot.followUpMessages ?? []);
            agent.queue.size =
                (snapshot.queuedMessages?.length ?? 0) +
                    (snapshot.steeringMessages?.length ?? 0) +
                    (snapshot.followUpMessages?.length ?? 0);
            syncProperty(agent, "availableModels", snapshot.availableModels);
            syncProperty(agent, "availableThinkingLevels", snapshot.availableThinkingLevels);
            syncProperty(agent, "diagnostics", snapshot.diagnostics);
            syncOptionalProperty(agent, "lastError", snapshot.lastError);
            syncAgentPreview(agent, snapshot);
            agent.context.thinkingLevel = snapshot.context.thinkingLevel;
            syncProperty(agent.context, "autoCompactionEnabled", snapshot.autoCompactionEnabled);
            syncOptionalProperty(agent.context, "contextUsage", snapshot.contextUsage);
            syncProperty(agent.context, "pendingToolCallIds", snapshot.pendingToolCallIds);
            syncOptionalProperty(agent, "sessionName", snapshot.sessionName);
        });
        this.mutationsSinceCompact += 1;
    }
    updateAgentPreview(snapshot, agentId = snapshot.header.id) {
        this.doc = Automerge.change(this.doc, (doc) => {
            const agent = ensureAgent(doc, agentId);
            syncOptionalProperty(agent, "sessionId", snapshot.header.id);
            syncOptionalProperty(agent, "summary", snapshot.summary);
            syncAgentPreview(agent, snapshot);
        });
        this.mutationsSinceCompact += 1;
    }
    updateLiveEvent(event, agentId) {
        this.doc = Automerge.change(this.doc, (doc) => {
            const agent = ensureAgent(doc, agentId ?? getDefaultAgentId(doc));
            applyLiveEventToAgent(doc, agent.agentId, agent, event);
        });
        this.mutationsSinceCompact += 1;
    }
    updateSessionEvent(event, agentId) {
        this.doc = Automerge.change(this.doc, (doc) => {
            const agent = ensureAgent(doc, agentId ?? getDefaultAgentId(doc));
            applySessionEventToAgent(agent, event);
        });
        this.mutationsSinceCompact += 1;
    }
    updatePeers(peers) {
        this.doc = Automerge.change(this.doc, (doc) => {
            syncProperty(doc, "peers", toJsonCompatible(peers.map(createPeerView)));
        });
        this.mutationsSinceCompact += 1;
    }
    generateSyncMessage(syncState) {
        const heads = sortHeads(Automerge.getHeads(this.doc));
        if (syncState.heads && sameHeads(syncState.heads, heads)) {
            return { syncState, message: null, format: "incremental" };
        }
        if (!syncState.heads || !Automerge.hasHeads(this.doc, syncState.heads)) {
            return { syncState: { heads }, message: Automerge.save(this.doc), format: "snapshot" };
        }
        const message = Automerge.saveSince(this.doc, syncState.heads);
        return {
            syncState: { heads },
            message: message.byteLength > 0 ? message : null,
            format: "incremental",
        };
    }
    receiveSyncMessage(syncState, message) {
        this.validateReadOnlySyncMessage(message);
        return syncState;
    }
    validateReadOnlySyncMessage(message) {
        const decoded = Automerge.decodeSyncMessage(message);
        if (decoded.changes.length > 0) {
            throw new Error("Hub view document sync is read-only for peers.");
        }
    }
    getSnapshot() {
        return this.doc;
    }
}
export function createEmptyViewDocumentState() {
    return {
        version: 1,
        agentOrder: [],
        agentsById: {},
        peers: [],
    };
}
function sortHeads(heads) {
    return [...heads].sort();
}
function sameHeads(a, b) {
    return a.length === b.length && a.every((head, index) => head === b[index]);
}
function createViewDocumentStateFromSession(snapshot, agentId, peers) {
    return {
        version: 1,
        agentOrder: [agentId],
        agentsById: {
            [agentId]: createAgentFromSnapshot(agentId, snapshot),
        },
        peers: deepCloneJson(peers.map(createPeerView)),
    };
}
function createPeerView(peer) {
    return {
        ...peer,
        ...(peer.mcpSnapshot
            ? {
                mcpSnapshot: {
                    ...peer.mcpSnapshot,
                    servers: peer.mcpSnapshot.servers.map((server) => ({
                        ...server,
                        capabilities: {
                            tools: server.capabilities.tools.map(({ name, description }) => ({ name, description })),
                            resources: server.capabilities.resources.map((resource) => ({ ...resource })),
                            prompts: server.capabilities.prompts.map((prompt) => ({ ...prompt })),
                        },
                    })),
                },
            }
            : {}),
    };
}
function createAgentFromSnapshot(agentId, snapshot) {
    return {
        agentId,
        sessionId: snapshot.header.id,
        ...(snapshot.sessionName != null && { sessionName: snapshot.sessionName }),
        cwd: snapshot.header.cwd,
        protocolVersion: snapshot.header.version,
        sessionFile: snapshot.sessionFile,
        ...(snapshot.summary && { summary: snapshot.summary }),
        status: {
            isRunning: snapshot.isRunning,
            ...(snapshot.runStartedAt && { runStartedAt: snapshot.runStartedAt }),
            ...(snapshot.lastRunStartedAt && { lastRunStartedAt: snapshot.lastRunStartedAt }),
            ...(snapshot.lastRunEndedAt && { lastRunEndedAt: snapshot.lastRunEndedAt }),
            ...(snapshot.lastRunDurationMs && { lastRunDurationMs: snapshot.lastRunDurationMs }),
            ...(snapshot.lastRunEndReason && { lastRunEndReason: snapshot.lastRunEndReason }),
        },
        queue: {
            messages: deepCloneJson(snapshot.queuedMessages ?? []),
            steering: deepCloneJson(snapshot.steeringMessages ?? []),
            followUp: deepCloneJson(snapshot.followUpMessages ?? []),
            size: (snapshot.queuedMessages?.length ?? 0) +
                (snapshot.steeringMessages?.length ?? 0) +
                (snapshot.followUpMessages?.length ?? 0),
        },
        context: {
            model: deepCloneJson(snapshot.context.model),
            thinkingLevel: snapshot.context.thinkingLevel,
            ...(snapshot.autoCompactionEnabled != null && { autoCompactionEnabled: snapshot.autoCompactionEnabled }),
            pendingToolCallIds: deepCloneJson(snapshot.pendingToolCallIds),
            ...(snapshot.contextUsage && { contextUsage: deepCloneJson(snapshot.contextUsage) }),
        },
        messageCount: countMessagesFromEntries(snapshot.entries),
        items: createItemsFromEntries(snapshot.entries),
        live: createEmptyLiveState(),
        availableModels: deepCloneJson(snapshot.availableModels),
        availableThinkingLevels: deepCloneJson(snapshot.availableThinkingLevels),
        diagnostics: deepCloneJson(snapshot.diagnostics),
        ...(snapshot.lastError && { lastError: snapshot.lastError }),
    };
}
function deepCloneJson(value) {
    return JSON.parse(JSON.stringify(value));
}
function toJsonCompatible(value) {
    return JSON.parse(JSON.stringify(value));
}
function isPlainRecord(value) {
    if (value === null || typeof value !== "object" || Array.isArray(value)) {
        return false;
    }
    const proto = Object.getPrototypeOf(value);
    return proto === Object.prototype || proto === null;
}
function syncProperty(target, key, sourceValue) {
    const currentValue = target[key];
    if (Array.isArray(sourceValue)) {
        if (Array.isArray(currentValue)) {
            syncArray(currentValue, sourceValue);
            return;
        }
        target[key] = deepCloneJson(sourceValue);
        return;
    }
    if (isPlainRecord(sourceValue)) {
        if (isPlainRecord(currentValue)) {
            syncRecord(currentValue, sourceValue);
            return;
        }
        target[key] = deepCloneJson(sourceValue);
        return;
    }
    if (!Object.is(currentValue, sourceValue)) {
        target[key] = sourceValue;
    }
}
function syncRecord(target, source) {
    for (const key of Object.keys(target)) {
        if (!(key in source)) {
            delete target[key];
        }
    }
    for (const [key, value] of Object.entries(source)) {
        syncProperty(target, key, value);
    }
}
function syncArray(target, source) {
    while (target.length > source.length) {
        target.pop();
    }
    for (let i = 0; i < source.length; i += 1) {
        const sourceValue = source[i];
        if (i >= target.length) {
            target.push(deepCloneJson(sourceValue));
            continue;
        }
        syncArrayIndex(target, i, sourceValue);
    }
}
function syncArrayIndex(target, index, sourceValue) {
    const currentValue = target[index];
    if (Array.isArray(sourceValue)) {
        if (Array.isArray(currentValue)) {
            syncArray(currentValue, sourceValue);
            return;
        }
        target[index] = deepCloneJson(sourceValue);
        return;
    }
    if (isPlainRecord(sourceValue)) {
        if (isPlainRecord(currentValue)) {
            syncRecord(currentValue, sourceValue);
            return;
        }
        target[index] = deepCloneJson(sourceValue);
        return;
    }
    if (!Object.is(currentValue, sourceValue)) {
        target[index] = sourceValue;
    }
}
function ensureAgent(doc, agentId) {
    const existing = doc.agentsById[agentId];
    if (existing) {
        return existing;
    }
    const agent = createEmptyAgent(agentId);
    doc.agentsById[agentId] = agent;
    doc.agentOrder.push(agentId);
    return doc.agentsById[agentId];
}
function createEmptyAgent(agentId) {
    return {
        agentId,
        status: {
            isRunning: false,
        },
        queue: {
            messages: [],
            steering: [],
            followUp: [],
            size: 0,
        },
        context: {
            model: null,
            thinkingLevel: "off",
            pendingToolCallIds: [],
        },
        messageCount: 0,
        items: [],
        live: createEmptyLiveState(),
        availableModels: [],
        availableThinkingLevels: [],
        diagnostics: [],
    };
}
function createItemsFromEntries(entries) {
    return entries
        .flatMap((entry) => {
        if (entry.type === "message") {
            return [{ type: "message", message: deepCloneJson(entry.message) }];
        }
        if (entry.type === "custom" && entry.customType === HUB_RUN_TIMING_CUSTOM_TYPE) {
            const timing = parseHubRunTiming(entry.data);
            return timing ? [{ type: "run_timing", timing }] : [];
        }
        return [];
    })
        .slice(-MAX_AGENT_VIEW_ITEMS);
}
function countMessagesFromEntries(entries) {
    let count = 0;
    for (const entry of entries) {
        if (entry.type === "message") {
            count += 1;
        }
    }
    return count;
}
function syncAgentPreview(agent, snapshot) {
    agent.status.isRunning = snapshot.isRunning;
    syncProperty(agent.context, "model", snapshot.context.model);
    agent.messageCount = countMessagesFromEntries(snapshot.entries);
    syncOptionalProperty(agent, "lastError", snapshot.lastError);
    if (snapshot.lastError !== undefined) {
        syncOptionalProperty(agent.live, "statusMessage", snapshot.lastError);
    }
}
function parseHubRunTiming(value) {
    if (!value || typeof value !== "object" || Array.isArray(value)) {
        return undefined;
    }
    const candidate = value;
    if (!validIsoString(candidate.startedAt) ||
        !validIsoString(candidate.endedAt) ||
        typeof candidate.durationMs !== "number" ||
        !Number.isFinite(candidate.durationMs) ||
        !isHubRunEndReason(candidate.endReason)) {
        return undefined;
    }
    return {
        startedAt: candidate.startedAt,
        endedAt: candidate.endedAt,
        durationMs: candidate.durationMs,
        endReason: candidate.endReason,
    };
}
function validIsoString(value) {
    return typeof value === "string" && !Number.isNaN(Date.parse(value));
}
function isHubRunEndReason(value) {
    return value === "completed" || value === "interrupted" || value === "error";
}
function createEmptyLiveState() {
    return {
        itemIndicesById: {},
        toolOrder: [],
        toolsById: {},
    };
}
function syncOptionalProperty(target, key, value) {
    if (value === undefined) {
        delete target[key];
        return;
    }
    syncProperty(target, key, value);
}
function getDefaultAgentId(doc) {
    return doc.agentOrder[0] ?? "root";
}
function applyLiveEventToAgent(doc, agentId, agent, event) {
    switch (event.type) {
        case "message_start":
        case "message_update":
        case "message_end": {
            upsertLiveMessage(doc, agentId, agent, event.messageId, event.message);
            if (event.type === "message_end") {
                delete agent.live.itemIndicesById[event.messageId];
            }
            return;
        }
        case "assistant_message_start":
        case "assistant_message_update":
        case "assistant_message_end": {
            const messageId = event.type === "assistant_message_start"
                ? event.messageId
                : (agent.live.streamingMessageId ?? event.messageId);
            const index = upsertLiveMessage(doc, agentId, agent, messageId, event.message);
            if (event.type === "assistant_message_end") {
                delete agent.live.streamingMessageId;
                delete agent.live.streamingMessageIndex;
                delete agent.live.itemIndicesById[messageId];
            }
            else {
                agent.live.streamingMessageId = messageId;
                agent.live.streamingMessageIndex = index;
            }
            return;
        }
        case "tool_execution_start":
            agent.live.toolsById[event.toolCallId] = {
                toolCallId: event.toolCallId,
                toolName: event.toolName,
                args: deepCloneJson(event.args),
            };
            pushUnique(agent.live.toolOrder, event.toolCallId);
            return;
        case "tool_execution_update": {
            const tool = ensureLiveTool(agent, event.toolCallId, event.toolName);
            syncProperty(tool, "args", event.args);
            syncProperty(tool, "partialResult", event.partialResult);
            return;
        }
        case "tool_execution_end": {
            const tool = ensureLiveTool(agent, event.toolCallId, event.toolName);
            syncProperty(tool, "result", event.result);
            tool.isError = event.isError;
            return;
        }
        case "status":
            agent.live.statusMessage = event.message;
            return;
    }
}
function upsertLiveMessage(doc, agentId, agent, messageId, message) {
    const existingIndex = agent.live.itemIndicesById[messageId];
    if (existingIndex === undefined || agent.items[existingIndex]?.type !== "message") {
        const index = agent.items.length;
        agent.items.push({ type: "message", message: createMessageView(message) });
        agent.live.itemIndicesById[messageId] = index;
        pruneAgentViewItems(agent);
        const currentIndex = agent.live.itemIndicesById[messageId] ?? Math.max(0, agent.items.length - 1);
        if (message.role === "assistant") {
            syncAssistantMessageTextBlocks(doc, agentId, currentIndex, message);
        }
        return currentIndex;
    }
    syncMessageAt(doc, agentId, existingIndex, message);
    return existingIndex;
}
function createMessageView(message) {
    if (message.role !== "assistant") {
        return deepCloneJson(message);
    }
    return {
        ...deepCloneJson(message),
        content: message.content.map((block) => block.type === "text"
            ? { ...block, text: "" }
            : block.type === "thinking"
                ? { ...block, thinking: "" }
                : deepCloneJson(block)),
    };
}
function syncMessageAt(doc, agentId, index, message) {
    const existing = agentMessageAt(doc, agentId, index);
    if (!existing || existing.role !== "assistant" || message.role !== "assistant") {
        syncArrayIndex(doc.agentsById[agentId].items, index, { type: "message", message });
        return;
    }
    syncAssistantMessageMetadata(existing, message);
    syncAssistantMessageContentShape(existing, message);
    syncAssistantMessageTextBlocks(doc, agentId, index, message);
}
function agentMessageAt(doc, agentId, index) {
    const item = doc.agentsById[agentId]?.items[index];
    return item?.type === "message" ? item.message : undefined;
}
function applySessionEventToAgent(agent, event) {
    switch (event.type) {
        case "run_state_changed":
            agent.status.isRunning = event.isRunning;
            syncOptionalProperty(agent.status, "runStartedAt", event.runStartedAt);
            syncOptionalProperty(agent.status, "lastRunStartedAt", event.lastRunStartedAt);
            syncOptionalProperty(agent.status, "lastRunEndedAt", event.lastRunEndedAt);
            syncOptionalProperty(agent.status, "lastRunDurationMs", event.lastRunDurationMs);
            syncOptionalProperty(agent.status, "lastRunEndReason", event.lastRunEndReason);
            if (event.isRunning) {
                delete agent.live.statusMessage;
            }
            if (event.lastRunEndReason === "error") {
                syncOptionalProperty(agent, "lastError", event.lastError);
                syncOptionalProperty(agent.live, "statusMessage", event.lastError);
            }
            else if (event.lastError === undefined) {
                delete agent.lastError;
            }
            else if (!event.isRunning) {
                delete agent.lastError;
            }
            if (event.runTiming) {
                agent.items.push({ type: "run_timing", timing: deepCloneJson(event.runTiming) });
                pruneAgentViewItems(agent);
            }
            if (!event.isRunning) {
                clearLiveToolExecutions(agent);
            }
            return;
        case "queue_changed":
            agent.queue.size = event.messages.length + (event.steering?.length ?? 0) + (event.followUp?.length ?? 0);
            syncArray(agent.queue.messages, event.messages);
            syncProperty(agent.queue, "steering", event.steering ?? []);
            syncProperty(agent.queue, "followUp", event.followUp ?? []);
            return;
        case "summary_changed":
            syncOptionalProperty(agent, "summary", event.summary);
            return;
        case "error":
            if (event.endRun !== false) {
                agent.lastError = event.message;
                agent.live.statusMessage = event.message;
            }
            return;
        case "snapshot_updated":
            return;
    }
}
function clearLiveToolExecutions(agent) {
    agent.live.toolOrder.splice(0, agent.live.toolOrder.length);
    for (const toolCallId of Object.keys(agent.live.toolsById)) {
        delete agent.live.toolsById[toolCallId];
    }
}
function pruneAgentViewItems(agent) {
    const overflow = agent.items.length - MAX_AGENT_VIEW_ITEMS;
    if (overflow <= 0) {
        return;
    }
    agent.items.splice(0, overflow);
    for (const [messageId, index] of Object.entries(agent.live.itemIndicesById)) {
        if (index < overflow) {
            delete agent.live.itemIndicesById[messageId];
        }
        else {
            agent.live.itemIndicesById[messageId] = index - overflow;
        }
    }
    if (agent.live.streamingMessageIndex !== undefined) {
        if (agent.live.streamingMessageIndex < overflow) {
            delete agent.live.streamingMessageIndex;
            delete agent.live.streamingMessageId;
        }
        else {
            agent.live.streamingMessageIndex -= overflow;
        }
    }
}
function ensureLiveTool(agent, toolCallId, toolName) {
    const existing = agent.live.toolsById[toolCallId];
    if (existing) {
        existing.toolName = toolName;
        return existing;
    }
    const tool = {
        toolCallId,
        toolName,
    };
    agent.live.toolsById[toolCallId] = tool;
    pushUnique(agent.live.toolOrder, toolCallId);
    return agent.live.toolsById[toolCallId];
}
function syncAssistantMessageMetadata(target, source) {
    target.api = source.api;
    target.provider = source.provider;
    target.model = source.model;
    target.timestamp = source.timestamp;
    target.stopReason = source.stopReason;
    syncProperty(target, "usage", source.usage);
    syncOptionalProperty(target, "responseId", source.responseId);
    syncOptionalProperty(target, "errorMessage", source.errorMessage);
}
function syncAssistantMessageContentShape(target, source) {
    while (target.content.length > source.content.length) {
        target.content.pop();
    }
    for (let i = 0; i < source.content.length; i += 1) {
        const sourceBlock = source.content[i];
        const targetBlock = target.content[i];
        if (!targetBlock || targetBlock.type !== sourceBlock.type) {
            target.content[i] =
                sourceBlock.type === "text"
                    ? { ...sourceBlock, text: "" }
                    : sourceBlock.type === "thinking"
                        ? { ...sourceBlock, thinking: "" }
                        : deepCloneJson(sourceBlock);
            continue;
        }
        if (sourceBlock.type === "toolCall") {
            syncProperty(targetBlock, "id", sourceBlock.id);
            syncProperty(targetBlock, "name", sourceBlock.name);
            syncProperty(targetBlock, "arguments", sourceBlock.arguments);
            syncOptionalProperty(targetBlock, "thoughtSignature", sourceBlock.thoughtSignature);
        }
        else if (sourceBlock.type === "text") {
            syncOptionalProperty(targetBlock, "textSignature", sourceBlock.textSignature);
        }
        else {
            syncOptionalProperty(targetBlock, "thinkingSignature", sourceBlock.thinkingSignature);
            syncOptionalProperty(targetBlock, "redacted", sourceBlock.redacted);
        }
    }
}
function syncAssistantMessageTextBlocks(doc, agentId, messageIndex, message) {
    for (let i = 0; i < message.content.length; i += 1) {
        const block = message.content[i];
        if (block.type === "text") {
            Automerge.updateText(doc, ["agentsById", agentId, "items", messageIndex, "message", "content", i, "text"], block.text);
        }
        else if (block.type === "thinking") {
            Automerge.updateText(doc, ["agentsById", agentId, "items", messageIndex, "message", "content", i, "thinking"], block.thinking);
        }
    }
}
function pushUnique(items, item) {
    if (!items.includes(item)) {
        items.push(item);
    }
}
//# sourceMappingURL=hub-view-document.js.map