import {
  resolveWorkspaceAgentSessionSortTimeUnixMs,
  workspaceAgentProviderLabel
} from "./chunk-3D5VTIKP.js";
import {
  normalizeAgentTitleText
} from "./chunk-GCBDIQDX.js";
import {
  translate,
  translateInUiLanguage
} from "./chunk-ZAVQMGAX.js";

// shared/workspaceAgentStatusNormalizer.ts
var FAILED_STATUS_TOKENS = /* @__PURE__ */ new Set(["failed", "error"]);
var CANCELED_STATUS_TOKENS = /* @__PURE__ */ new Set(["canceled"]);
var COMPLETED_STATUS_TOKENS = /* @__PURE__ */ new Set(["completed", "ended", "end"]);
var WAITING_APPROVAL_TOKENS = /* @__PURE__ */ new Set([
  "waiting_approval",
  "awaiting_approval"
]);
var WAITING_INPUT_TOKENS = /* @__PURE__ */ new Set(["waiting_input"]);
var WAITING_STATUS_TOKENS = /* @__PURE__ */ new Set(["waiting"]);
var WORKING_STATUS_TOKENS = /* @__PURE__ */ new Set(["working", "running", "streaming"]);
var READY_STATUS_TOKENS = /* @__PURE__ */ new Set(["ready", "idle"]);
function normalizeWorkspaceAgentStatus(input) {
  return normalizeOptionalWorkspaceAgentStatus(input) ?? { kind: "ready" };
}
function normalizeOptionalWorkspaceAgentStatus(input) {
  const lifecycleStatus = normalizeStatusToken(input.lifecycleStatus);
  const effectiveStatus = normalizeStatusToken(input.effectiveStatus);
  const sessionStatus = normalizeStatusToken(input.status);
  const turnPhase = normalizeStatusToken(input.turnPhase);
  const currentPhase = normalizeStatusToken(input.currentPhase);
  const tokens = [
    lifecycleStatus,
    effectiveStatus,
    sessionStatus,
    turnPhase,
    currentPhase
  ].filter(Boolean);
  if (tokens.length === 0) {
    return null;
  }
  if ([lifecycleStatus, effectiveStatus, sessionStatus, currentPhase].some(
    (token) => FAILED_STATUS_TOKENS.has(token)
  )) {
    return { kind: "failed" };
  }
  if ([lifecycleStatus, effectiveStatus, sessionStatus].some(
    (token) => CANCELED_STATUS_TOKENS.has(token)
  )) {
    return { kind: "canceled" };
  }
  if ([lifecycleStatus, effectiveStatus, sessionStatus].some(
    (token) => COMPLETED_STATUS_TOKENS.has(token)
  )) {
    return { kind: "completed" };
  }
  const waitKind = waitingKindFromTokens([
    currentPhase,
    turnPhase,
    effectiveStatus,
    sessionStatus
  ]);
  if (waitKind) {
    return { kind: "waiting", waitKind };
  }
  if ([currentPhase, turnPhase, effectiveStatus, sessionStatus].some(
    (token) => WAITING_STATUS_TOKENS.has(token)
  )) {
    return { kind: "waiting" };
  }
  if ([currentPhase, turnPhase, effectiveStatus, sessionStatus].some(
    (token) => WORKING_STATUS_TOKENS.has(token)
  )) {
    return { kind: "working" };
  }
  if (lifecycleStatus === "active" || lifecycleStatus === "ready" || [currentPhase, turnPhase, effectiveStatus, sessionStatus].some(
    (token) => READY_STATUS_TOKENS.has(token)
  )) {
    return { kind: "ready" };
  }
  return null;
}
function waitingKindFromTokens(tokens) {
  if (tokens.some((token) => WAITING_APPROVAL_TOKENS.has(token))) {
    return "approval";
  }
  if (tokens.some((token) => WAITING_INPUT_TOKENS.has(token))) {
    return "input";
  }
  return void 0;
}
function normalizeStatusToken(status) {
  return status?.trim().toLowerCase() ?? "";
}

// shared/workspaceAgentSyntheticMessages.ts
function isWorkspaceAgentSyntheticControlMessage(text) {
  const normalized = text?.trim().toLowerCase() ?? "";
  switch (normalized) {
    case "[request interrupted by user]":
    case "request interrupted by user":
    case "[request interrupted by user for tool use]":
    case "request interrupted by user for tool use":
      return true;
    default:
      return false;
  }
}

// shared/workspaceAgentLatestActivitySummary.ts
function fallbackSummary(status) {
  switch (status) {
    case "working":
      return translate("agentHost.workspaceAgentActivityStatusWorking");
    case "waiting":
      return translate("agentHost.workspaceAgentActivityStatusWaiting");
    case "idle":
      return translate("agentHost.workspaceAgentActivityStatusIdle");
    case "canceled":
    case "completed":
      return translate("agentHost.workspaceAgentActivityStatusEnd");
    case "failed":
      return translate("agentHost.workspaceAgentActivityStatusFailed");
  }
}
function isWorkspaceAgentUntitledTask(title) {
  return localizedWorkspaceAgentLabelSet(
    "agentHost.workspaceAgentsUntitledTask"
  ).has(compactText(title));
}
function compactText(value) {
  return value.trim().replace(/\s+/g, " ");
}
function localizedWorkspaceAgentLabelSet(key) {
  return new Set(
    ["en", "zh-CN"].map((language) => compactText(translateInUiLanguage(language, key))).filter(Boolean)
  );
}

// shared/workspaceAgentSessionTitle.ts
function resolveDisplayableWorkspaceAgentSessionTitle(session) {
  const title = normalizeAgentTitleText(session.title);
  if (!title || isWorkspaceAgentUntitledTask(title) || isWorkspaceAgentSyntheticControlMessage(title)) {
    return "";
  }
  const provider = session.provider?.trim();
  if (provider && workspaceAgentProviderLabel(provider).toLowerCase() === title.toLowerCase()) {
    return "";
  }
  return title;
}

// shared/workspaceAgentActivityTypes.ts
import {
  mergeAgentActivityMessages
} from "@tutti-os/agent-activity-core";
var WORKSPACE_AGENT_ACTIVITY_RUNTIME_SESSION_ORIGIN = "WORKSPACE_AGENT_SESSION_ORIGIN_RUNTIME";
function isWorkspaceAgentActivityRuntimeSessionOrigin(sessionOrigin) {
  const normalized = sessionOrigin?.trim().toUpperCase() ?? "";
  return normalized === "" || normalized === WORKSPACE_AGENT_ACTIVITY_RUNTIME_SESSION_ORIGIN;
}
function isWorkspaceAgentActivityOptimisticMessage(message) {
  return message.payload?.__agentGuiOptimisticPrompt === true;
}
function selectWorkspaceAgentActivityOverlayMessages(input) {
  const durableMessages = input.durableMessages ?? [];
  const localMessages = input.localMessages ?? [];
  if (localMessages.length === 0) {
    return [];
  }
  const durableIdentities = new Set(
    durableMessages.map(workspaceAgentActivityMessageIdentity).filter((identity) => identity !== null)
  );
  return localMessages.filter((message) => {
    if (isWorkspaceAgentActivityOptimisticMessage(message)) {
      return true;
    }
    const identity = workspaceAgentActivityMessageIdentity(message);
    return identity === null || !durableIdentities.has(identity);
  });
}
function mergeWorkspaceAgentActivityDurableAndOverlayMessages(input) {
  const durableMessages = input.durableMessages ?? [];
  const overlayMessages = selectWorkspaceAgentActivityOverlayMessages(input);
  return overlayMessages.length === 0 ? [...durableMessages] : mergeAgentActivityMessages(durableMessages, overlayMessages);
}
function workspaceAgentActivityMessageIdentity(message) {
  const messageId = message.messageId?.trim() ?? "";
  if (messageId) {
    return `message:${messageId}`;
  }
  if (typeof message.version === "number" && Number.isFinite(message.version)) {
    return `version:${message.version}`;
  }
  return null;
}

// shared/workspaceAgentActivityListViewModel.ts
function collectWorkspaceAgentGeneratedFiles(snapshot, options = {}) {
  const workspaceRoot = options.workspaceRoot?.trim().replace(/\/+$/, "") || resolveWorkspaceRootFromSessions(snapshot.sessions);
  const filesByPath = /* @__PURE__ */ new Map();
  for (const session of snapshot.sessions) {
    const sessionCwd = session.cwd?.trim().replace(/\/+$/, "") || workspaceRoot;
    const normalizePath = createAgentGeneratedFilePathNormalizer({
      sessionCwd,
      workspaceRoot
    });
    const messages = resolveWorkspaceAgentSessionMessages(
      snapshot.sessionMessagesById,
      session
    );
    if (messages.length === 0) {
      continue;
    }
    for (const file of changedFilesForSession(messages, normalizePath)) {
      filesByPath.set(file.path, file);
    }
    for (const path of imageGenerationPathsFromMessages(
      messages,
      normalizePath
    )) {
      if (filesByPath.has(path)) {
        continue;
      }
      filesByPath.set(path, {
        path,
        label: path.split("/").filter(Boolean).at(-1) ?? path
      });
    }
  }
  return applyShortestUniqueFileLabels([...filesByPath.values()]);
}
function buildWorkspaceAgentActivityListViewModel(snapshot, options = {}) {
  const presencesById = new Map(
    snapshot.presences.map((presence) => [presence.id, presence])
  );
  const activities = snapshot.sessions.map((session) => {
    const presence = session.presenceId === void 0 ? null : presencesById.get(session.presenceId) ?? null;
    const messages = resolveWorkspaceAgentSessionMessages(
      options.sessionMessagesById,
      session
    );
    const status = resolveWorkspaceAgentActivityStatus(session);
    if (shouldHideEmptyRuntimePlaceholderSession(
      session,
      messages,
      status,
      options
    )) {
      return null;
    }
    const user = resolveActivityUser(session, presence, options);
    const agentProvider = resolveProvider(session, presence);
    const agentName = workspaceAgentProviderLabel(agentProvider);
    const resolvedSortTimeUnixMs = resolveWorkspaceAgentSessionSortTimeUnixMs(
      session,
      {
        messages
      }
    );
    const latestActivity = resolveLatestActivity(messages, status, {
      agentName,
      userName: user.userName
    });
    const activity = {
      id: `activity-${session.agentSessionId}`,
      sessionId: session.agentSessionId,
      userId: user.userId,
      userName: user.userName,
      ...user.userAvatarUrl ? { userAvatarUrl: user.userAvatarUrl } : {},
      agentProvider,
      agentName,
      title: resolveWorkspaceAgentActivityTitle(session, messages),
      status,
      latestActivitySummary: latestActivity.summary,
      latestActivityActorName: latestActivity.actorName,
      changedFiles: changedFilesForSession(messages),
      sortTimeUnixMs: resolvedSortTimeUnixMs,
      readTimeUnixMs: readTimeUnixMs(session, status, resolvedSortTimeUnixMs)
    };
    return activity;
  }).filter(
    (activity) => activity !== null
  ).sort(compareActivities);
  return { activities };
}
function reuseWorkspaceAgentActivityListViewModelIfUnchanged(previous, next) {
  if (!previous) {
    return next;
  }
  if (next.activities.length === 0) {
    return previous.activities.length === 0 ? previous : next;
  }
  const previousActivitiesById = new Map(
    previous.activities.map((activity) => [activity.id, activity])
  );
  const activities = next.activities.map((activity) => {
    const previousActivity = previousActivitiesById.get(activity.id);
    if (!previousActivity || !workspaceAgentActivityCardEquals(previousActivity, activity)) {
      return activity;
    }
    return previousActivity;
  });
  const reusedEveryActivityInPlace = previous.activities.length === activities.length && previous.activities.every(
    (activity, index) => activity === activities[index]
  );
  return reusedEveryActivityInPlace ? previous : { activities };
}
function shouldHideEmptyRuntimePlaceholderSession(session, messages, status, options) {
  if (!isWorkspaceAgentActivityRuntimeSessionOrigin(session.sessionOrigin)) {
    return false;
  }
  if (messages.length > 0) {
    return false;
  }
  if (!hasLoadedSessionMessageRecord(session, options.sessionMessagesById)) {
    return false;
  }
  if (!isRuntimePlaceholderTerminalStatus(status)) {
    return false;
  }
  return resolveDisplayableWorkspaceAgentSessionTitle(session) === "";
}
function hasLoadedSessionMessageRecord(session, sessionMessagesById) {
  if (!sessionMessagesById) {
    return false;
  }
  return workspaceAgentSessionMessageAliases(session).some(
    (alias) => alias in sessionMessagesById
  );
}
function isRuntimePlaceholderTerminalStatus(status) {
  return status === "idle" || status === "completed" || status === "canceled";
}
function workspaceAgentActivityCardEquals(left, right) {
  return left.id === right.id && left.sessionId === right.sessionId && left.userId === right.userId && left.userName === right.userName && left.userAvatarUrl === right.userAvatarUrl && left.agentProvider === right.agentProvider && left.agentName === right.agentName && left.title === right.title && left.status === right.status && left.latestActivitySummary === right.latestActivitySummary && left.latestActivityActorName === right.latestActivityActorName && left.sortTimeUnixMs === right.sortTimeUnixMs && JSON.stringify(left.conversationPreview ?? []) === JSON.stringify(right.conversationPreview ?? []) && JSON.stringify(left.toolCalls ?? []) === JSON.stringify(right.toolCalls ?? []) && JSON.stringify(left.changedFiles) === JSON.stringify(right.changedFiles);
}
function resolveWorkspaceAgentSessionMessages(sessionMessagesById, session) {
  if (!sessionMessagesById) {
    return [];
  }
  for (const alias of workspaceAgentSessionMessageAliases(session)) {
    const messages = sessionMessagesById[alias];
    if (messages) {
      return messages;
    }
  }
  return [];
}
function resolveActivityUser(session, presence, options) {
  if (presence) {
    return resolveUserFromId(presence.userId ?? "", options);
  }
  const sessionUserId = session.userId?.trim() ?? "";
  if (sessionUserId) {
    return resolveUserFromId(sessionUserId, options);
  }
  const fallbackMember = selectFallbackMember(options.fallbackMembers ?? []);
  if (fallbackMember) {
    return {
      userId: fallbackMember.userId,
      userName: fallbackMember.label || "Unknown member",
      ...fallbackMember.avatarUrl ? { userAvatarUrl: fallbackMember.avatarUrl } : {}
    };
  }
  return {
    userId: null,
    userName: "Unknown member"
  };
}
function resolveUserFromId(rawUserId, options) {
  const userId = rawUserId.trim();
  const profile = options.userProfilesById?.[userId];
  const profileName = compactText2(profile?.name ?? "");
  const profileAvatar = profile?.avatar?.trim();
  const rawName = profileName || userId || "Unknown member";
  return {
    userId,
    userName: stripTrailingParentheticalEmailFromLabel(rawName) || rawName,
    ...profileAvatar ? { userAvatarUrl: profileAvatar } : {}
  };
}
function selectFallbackMember(members) {
  return members.find((member) => member.role === "owner") ?? members[0] ?? null;
}
function resolveProvider(session, presence) {
  const sessionProvider = normalizeProvider(session.provider);
  if (sessionProvider) {
    return sessionProvider;
  }
  const presenceProvider = normalizeProvider(presence?.provider);
  if (presenceProvider) {
    return presenceProvider;
  }
  return "unknown";
}
function normalizeProvider(provider) {
  const trimmed = provider?.trim();
  return trimmed ? trimmed.toLowerCase() : null;
}
function resolveWorkspaceAgentActivityStatus(session) {
  const normalized = normalizeWorkspaceAgentStatus(session).kind;
  switch (normalized) {
    case "failed":
      return "failed";
    case "canceled":
      return "canceled";
    case "completed":
      return "completed";
    case "waiting":
      return "waiting";
    case "working":
      return "working";
    case "ready":
    default:
      return "idle";
  }
}
function resolveWorkspaceAgentActivityTitle(session, messages = []) {
  const sessionTitle = resolveDisplayableWorkspaceAgentSessionTitle(session);
  const userMessageTitle = firstUserMessageText(messages);
  if (sessionTitle && !isProviderPlaceholderTitleForSession(sessionTitle, session)) {
    return sessionTitle;
  }
  return userMessageTitle || sessionTitle || workspaceAgentUntitledTaskLabel();
}
function isProviderPlaceholderTitleForSession(title, session) {
  const provider = normalizeProvider(session.provider);
  if (!provider) {
    return false;
  }
  const normalizedTitle = title.trim().toLowerCase();
  return workspaceAgentProviderLabel(provider).toLowerCase() === normalizedTitle;
}
function resolveLatestActivity(messages, status, actors) {
  const latestMessage = latestDisplayableMessage(messages);
  if (latestMessage) {
    return {
      actorName: messageRole(latestMessage.message) === "user" ? actors.userName : actors.agentName,
      summary: latestMessage.text
    };
  }
  return {
    actorName: actors.agentName,
    summary: fallbackSummary(status)
  };
}
function changedFilesForSession(messages, normalizePath = defaultChangedFilePathNormalizer) {
  const changedFilesByPath = /* @__PURE__ */ new Map();
  const appendPath = (path) => {
    if (!path || changedFilesByPath.has(path)) {
      return;
    }
    changedFilesByPath.set(path, {
      path,
      label: path
    });
  };
  for (const message of messages) {
    for (const path of changedFilePathsFromMessage(message, normalizePath)) {
      appendPath(path);
    }
  }
  return applyShortestUniqueFileLabels(Array.from(changedFilesByPath.values()));
}
function changedFilePathsFromMessage(message, normalizePath = defaultChangedFilePathNormalizer) {
  const payload = objectValue(message.payload);
  const explicitFileChanges = fileChangePaths(
    arrayValue(objectValue(payload?.fileChanges)?.files),
    normalizePath
  );
  if (explicitFileChanges.length > 0) {
    return explicitFileChanges;
  }
  if (!isSuccessfulFileChangeToolMessage(message)) {
    return [];
  }
  const toolState = objectValue(payload?.tool_state);
  const input = objectValue(payload?.input) ?? objectValue(toolState?.input) ?? null;
  const output = objectValue(payload?.output);
  const paths = dedupeStrings([
    ...pathsValue(payload?.paths, normalizePath),
    ...pathsValue(output?.paths, normalizePath),
    ...pathsValue(input?.paths, normalizePath),
    ...changeMapPaths(payload?.changes, normalizePath),
    ...changeMapPaths(output?.changes, normalizePath),
    ...changeMapPaths(input?.changes, normalizePath),
    ...contentDiffPaths(payload?.content, normalizePath),
    ...contentDiffPaths(output?.content, normalizePath),
    ...contentDiffPaths(input?.content, normalizePath),
    stringValue(payload?.path),
    stringValue(payload?.filePath),
    stringValue(payload?.file_path),
    stringValue(input?.path),
    stringValue(input?.filePath),
    stringValue(input?.file_path),
    stringValue(output?.path),
    stringValue(output?.filePath),
    stringValue(output?.file_path)
  ]);
  return paths.map((path) => normalizePath(path)).filter((path) => path !== null);
}
function defaultChangedFilePathNormalizer(value) {
  return normalizedChangedFilePath(value);
}
function resolveWorkspaceRootFromSessions(sessions) {
  for (const session of sessions) {
    const cwd = session.cwd?.trim().replace(/\/+$/, "") ?? "";
    if (cwd) {
      return cwd;
    }
  }
  return "";
}
function createAgentGeneratedFilePathNormalizer(input) {
  const workspaceRoot = input.workspaceRoot?.trim().replace(/\/+$/, "") ?? "";
  const sessionCwd = input.sessionCwd?.trim().replace(/\/+$/, "") || workspaceRoot;
  return (value) => {
    if (typeof value !== "string") {
      return null;
    }
    return resolveAgentGeneratedFilePath(value, workspaceRoot, sessionCwd);
  };
}
function resolveAgentGeneratedFilePath(rawPath, workspaceRoot, sessionCwd) {
  const path = rawPath.trim();
  if (!path || isStructuredPayloadPath(path)) {
    return null;
  }
  if (path.startsWith("/workspace/")) {
    return path;
  }
  if (isAgentStateGeneratedImagePath(path)) {
    return path;
  }
  if (isAbsoluteAgentGeneratedFilePath(path)) {
    if (workspaceRoot && !isPathInsideOrEqual(path, workspaceRoot) && !isAgentStateGeneratedImagePath(path)) {
      return null;
    }
    return path.replace(/\\/g, "/");
  }
  const base = sessionCwd || workspaceRoot;
  if (!base) {
    return null;
  }
  const resolved = joinAgentGeneratedFilePath(base, path.replace(/^\.?\//, ""));
  if (workspaceRoot && !isPathInsideOrEqual(resolved, workspaceRoot) && !isAgentStateGeneratedImagePath(resolved)) {
    return null;
  }
  return resolved;
}
function isAbsoluteAgentGeneratedFilePath(path) {
  return path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path);
}
function isPathInsideOrEqual(path, root) {
  const normalizedPath = path.replace(/\\/g, "/").replace(/\/+$/, "");
  const normalizedRoot = root.replace(/\\/g, "/").replace(/\/+$/, "");
  if (!normalizedRoot) {
    return false;
  }
  return normalizedPath === normalizedRoot || normalizedPath.startsWith(`${normalizedRoot}/`);
}
function joinAgentGeneratedFilePath(base, relativePath) {
  const normalizedBase = base.replace(/\\/g, "/").replace(/\/+$/, "");
  const normalizedRelative = relativePath.replace(/\\/g, "/");
  return `${normalizedBase}/${normalizedRelative}`;
}
function imageGenerationPathsFromMessages(messages, normalizePath) {
  const paths = [];
  for (const message of messages) {
    const payload = objectValue(message.payload);
    if (!payload) {
      continue;
    }
    const output = objectValue(payload.output);
    for (const uri of [
      ...imageGenerationUris(payload.content),
      ...imageGenerationUris(output?.content)
    ]) {
      const normalized = normalizePath(uri);
      if (normalized) {
        paths.push(normalized);
      }
    }
  }
  return dedupeStrings(paths);
}
function imageGenerationUris(value) {
  if (!Array.isArray(value)) {
    return [];
  }
  const uris = [];
  for (const item of value) {
    const record = objectValue(item);
    if (!record) {
      continue;
    }
    const type = stringValue(record.type)?.toLowerCase();
    const uri = stringValue(record.uri) ?? stringValue(record.path);
    if (!uri) {
      continue;
    }
    if (type === "image" || uri.toLowerCase().includes("generated_images") || /\.(?:png|jpe?g|gif|webp|bmp|svg)$/i.test(uri)) {
      uris.push(uri);
    }
  }
  return uris;
}
function isAgentStateGeneratedImagePath(path) {
  const segments = path.split("/").filter(Boolean);
  const stateRootIndex = segments.findIndex(
    (segment) => segment === ".nextop" || segment === ".nextop-dev"
  );
  if (stateRootIndex < 0) {
    return false;
  }
  const statePath = segments.slice(stateRootIndex);
  return statePath[1] === "agent" && statePath[2] === "runs" && statePath.includes("generated_images");
}
function normalizedChangedFilePath(value, options = {}) {
  if (typeof value !== "string") {
    return null;
  }
  const path = value.trim();
  if (!path || isStructuredPayloadPath(path)) {
    return null;
  }
  if (!options.allowRelative && !path.startsWith("/workspace/")) {
    return null;
  }
  return path;
}
function applyShortestUniqueFileLabels(files) {
  const suffixByPath = shortestUniquePathSuffixByPath(
    files.map((file) => file.path)
  );
  return files.map((file) => ({
    ...file,
    label: suffixByPath.get(file.path) ?? file.label
  }));
}
function shortestUniquePathSuffixByPath(paths) {
  const partsByPath = new Map(
    paths.map((path) => [path, splitPathSegments(path)])
  );
  const labels = /* @__PURE__ */ new Map();
  const unresolved = new Set(paths);
  for (let depth = 1; unresolved.size > 0; depth += 1) {
    const grouped = /* @__PURE__ */ new Map();
    for (const path of unresolved) {
      const parts = partsByPath.get(path) ?? [];
      const suffix = parts.slice(-Math.min(depth, parts.length)).join("/");
      const fallback = parts.at(-1) ?? path;
      const label = suffix || fallback;
      const group = grouped.get(label);
      if (group) {
        group.push(path);
      } else {
        grouped.set(label, [path]);
      }
    }
    let resolvedCount = 0;
    for (const [label, group] of grouped) {
      if (group.length !== 1) {
        continue;
      }
      const path = group[0];
      if (!path) {
        continue;
      }
      labels.set(path, label);
      unresolved.delete(path);
      resolvedCount += 1;
    }
    if (resolvedCount === 0) {
      for (const path of unresolved) {
        labels.set(path, path);
      }
      break;
    }
  }
  return labels;
}
function splitPathSegments(path) {
  return path.trim().split(/[\\/]/).filter(Boolean);
}
function isSuccessfulFileChangeToolMessage(message) {
  if (normalizeToken(message.kind) !== "tool_call") {
    return false;
  }
  const normalizedStatus = normalizeToken(message.status ?? void 0);
  if (normalizedStatus && normalizedStatus !== "completed" && normalizedStatus !== "success") {
    return false;
  }
  const payload = objectValue(message.payload);
  const activityKind = stringValue(payload?.activityKind);
  if (activityKind === "write_file" || activityKind === "edit_file" || activityKind === "delete_file") {
    return true;
  }
  if (stringValue(payload?.fileChangeKind)) {
    return true;
  }
  const input = objectValue(payload?.input);
  const toolCall = objectValue(input?.toolCall) ?? objectValue(payload?.toolCall);
  const toolCallKind = normalizeToken(stringValue(toolCall?.kind) ?? void 0);
  if (toolCallKind === "write" || toolCallKind === "edit" || toolCallKind === "delete") {
    return true;
  }
  const toolName = normalizeToolName(
    stringValue(payload?.toolName) ?? stringValue(payload?.title) ?? stringValue(payload?.name) ?? ""
  );
  return isFileChangeNormalizedToolName(toolName);
}
function isFileChangeNormalizedToolName(normalizedToolName) {
  if (!normalizedToolName) {
    return false;
  }
  const exactMatches = /* @__PURE__ */ new Set([
    "write",
    "writefile",
    "create",
    "createfile",
    "delete",
    "deletefile",
    "edit",
    "editfile",
    "multiedit",
    "applypatch",
    "move",
    "notebookedit"
  ]);
  if (exactMatches.has(normalizedToolName)) {
    return true;
  }
  for (const prefix of exactMatches) {
    if (normalizedToolName.startsWith(`${prefix}/`)) {
      return true;
    }
  }
  return false;
}
function fileChangePaths(files, normalizePath = defaultChangedFilePathNormalizer) {
  if (!files) {
    return [];
  }
  return files.map((file) => normalizePath(objectValue(file)?.path)).filter((path) => path !== null);
}
function changeMapPaths(value, normalizePath = defaultChangedFilePathNormalizer) {
  const changes = objectValue(value);
  if (!changes) {
    return [];
  }
  return Object.keys(changes).map((path) => normalizePath(path)).filter((path) => path !== null);
}
function contentDiffPaths(value, normalizePath = defaultChangedFilePathNormalizer) {
  const content = arrayValue(value);
  if (!content) {
    return [];
  }
  return content.map((entry) => {
    const record = objectValue(entry);
    if (!record || stringValue(record.type) !== "diff") {
      return null;
    }
    return normalizePath(record.path);
  }).filter((path) => path !== null);
}
function pathsValue(value, normalizePath = defaultChangedFilePathNormalizer) {
  const paths = arrayValue(value);
  if (!paths) {
    return [];
  }
  return paths.map((path) => normalizePath(path)).filter((path) => path !== null);
}
function objectValue(value) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    return null;
  }
  return value;
}
function arrayValue(value) {
  return Array.isArray(value) ? value : null;
}
function stringValue(value) {
  return typeof value === "string" && value.trim() ? value.trim() : null;
}
function dedupeStrings(values) {
  return [
    ...new Set(
      values.filter(
        (value) => typeof value === "string" && value.length > 0
      )
    )
  ];
}
function normalizeToolName(value) {
  return value.trim().toLowerCase().replaceAll("_", "").replaceAll("-", "").replaceAll(" ", "");
}
function isStructuredPayloadPath(path) {
  if (/[\r\n]/.test(path)) {
    return true;
  }
  if (!path.startsWith("{") && !path.startsWith("[")) {
    return false;
  }
  try {
    JSON.parse(path);
    return true;
  } catch {
    return false;
  }
}
function readTimeUnixMs(session, status, fallbackUnixMs) {
  if (status === "completed" || status === "failed") {
    return session.endedAtUnixMs ?? session.updatedAtUnixMs ?? fallbackUnixMs;
  }
  return fallbackUnixMs;
}
function firstUserMessageText(messages) {
  const firstUserMessage = messages.map((message) => ({
    message,
    text: messageDisplayText(message),
    time: messageTime(message)
  })).filter(
    (item) => messageRole(item.message) === "user" && item.text.length > 0
  ).sort((left, right) => {
    const timeDiff = (left.time ?? 0) - (right.time ?? 0);
    if (timeDiff !== 0) {
      return timeDiff;
    }
    return (left.message.id ?? 0) - (right.message.id ?? 0) || left.message.messageId.localeCompare(right.message.messageId);
  })[0];
  return firstUserMessage?.text ?? "";
}
function latestDisplayableMessage(messages) {
  return messages.map((message) => ({
    message,
    text: messageDisplayText(message),
    time: messageTime(message)
  })).filter(
    (item) => item.text.length > 0 && normalizeToken(item.message.kind) !== "tool_call"
  ).sort((left, right) => {
    const timeDiff = (right.time ?? 0) - (left.time ?? 0);
    if (timeDiff !== 0) {
      return timeDiff;
    }
    return (right.message.id ?? 0) - (left.message.id ?? 0) || right.message.messageId.localeCompare(left.message.messageId);
  })[0] ?? null;
}
function messageDisplayText(message) {
  const payload = message.payload ?? {};
  const text = normalizeAgentTitleText(
    compactText2(
      stringValue(payload.content) || stringValue(payload.text) || stringValue(payload.message) || stringValue(payload.body) || stringValue(payload.title) || ""
    )
  );
  return isWorkspaceAgentSyntheticControlMessage(text) ? "" : text;
}
function messageRole(message) {
  return normalizeToken(message.role);
}
function messageTime(message) {
  return message.occurredAtUnixMs ?? message.completedAtUnixMs ?? message.startedAtUnixMs;
}
function normalizeToken(value) {
  return value?.trim().toLowerCase() ?? "";
}
function compareActivities(left, right) {
  const timeDiff = right.sortTimeUnixMs - left.sortTimeUnixMs;
  if (timeDiff !== 0) {
    return timeDiff;
  }
  return left.sessionId.localeCompare(right.sessionId);
}
function compactText2(value) {
  return value.replace(/\s+/g, " ").trim();
}
function workspaceAgentUntitledTaskLabel() {
  return normalizeAgentTitleText(
    translate("agentHost.workspaceAgentsUntitledTask")
  );
}
function workspaceAgentSessionMessageAliases(session) {
  const values = [
    session.syncState?.agentSessionId,
    session.agentSessionId,
    session.providerSessionId
  ];
  const seen = /* @__PURE__ */ new Set();
  const aliases = [];
  for (const value of values) {
    const normalized = value?.trim() ?? "";
    if (!normalized || seen.has(normalized)) {
      continue;
    }
    seen.add(normalized);
    aliases.push(normalized);
  }
  return aliases;
}
function stripTrailingParentheticalEmailFromLabel(label) {
  return label.trim().replace(/\s*\([^)]*@[^)]+\)\s*$/u, "").trim();
}

export {
  normalizeOptionalWorkspaceAgentStatus,
  isWorkspaceAgentSyntheticControlMessage,
  isWorkspaceAgentUntitledTask,
  WORKSPACE_AGENT_ACTIVITY_RUNTIME_SESSION_ORIGIN,
  isWorkspaceAgentActivityRuntimeSessionOrigin,
  selectWorkspaceAgentActivityOverlayMessages,
  mergeWorkspaceAgentActivityDurableAndOverlayMessages,
  collectWorkspaceAgentGeneratedFiles,
  buildWorkspaceAgentActivityListViewModel,
  reuseWorkspaceAgentActivityListViewModelIfUnchanged,
  resolveWorkspaceAgentActivityStatus,
  resolveWorkspaceAgentActivityTitle
};
//# sourceMappingURL=chunk-DHOAJJ3K.js.map