{"version":3,"file":"parseMessageParts.mjs","names":[],"sources":["../../../../../src/plugins/AIComponents/MessageParts/parseMessageParts.ts"],"sourcesContent":["import type {\n  AIMessagePartData,\n  AIReasoningPart,\n  AIToolApprovalData,\n  AIToolAuthorizationData,\n  AIToolCallPart,\n  AIToolCallStatus,\n} from './types';\nimport { isObject, withCustomFields } from '../utils';\n\n/** The attachment type prefix every AI step uses. */\nexport const AI_MESSAGE_PART_TYPE_PREFIX = 'ai_';\n/** The newest format version of the built-in kinds this SDK understands. */\nexport const AI_MESSAGE_PART_SUPPORTED_VERSION = 1;\n\ntype JSONObject = Record<string, unknown>;\n\n// Lenient reads: a field of the wrong type reads as missing, and an empty string as absent.\nconst string = (object: JSONObject, key: string) => {\n  const value = object[key];\n  return typeof value === 'string' && value !== '' ? value : undefined;\n};\n\nconst int = (object: JSONObject, key: string) => {\n  const value = object[key];\n  return typeof value === 'number' && Number.isFinite(value)\n    ? Math.trunc(value)\n    : undefined;\n};\n\nconst date = (object: JSONObject, key: string) => {\n  const value = string(object, key);\n  if (value === undefined) return undefined;\n  const time = Date.parse(value);\n  return Number.isNaN(time) ? undefined : time;\n};\n\nconst parseApproval = (object: JSONObject): AIToolApprovalData | undefined => {\n  // A question with no title asks nothing.\n  const title = string(object, 'title');\n  if (!title) return undefined;\n  return {\n    allowTitle: string(object, 'allow_title'),\n    decision: string(object, 'decision'),\n    declineTitle: string(object, 'decline_title'),\n    message: string(object, 'message'),\n    reason: string(object, 'reason'),\n    title,\n  };\n};\n\nconst isWebURL = (value: string) => {\n  try {\n    const url = new URL(value);\n    return (url.protocol === 'https:' || url.protocol === 'http:') && url.host !== '';\n  } catch {\n    return false;\n  }\n};\n\nconst parseAuthorization = (object: JSONObject): AIToolAuthorizationData | undefined => {\n  // A sign-in with no title, or no web page to open, asks nothing.\n  const title = string(object, 'title');\n  const url = string(object, 'url');\n  if (!title || !url || !isWebURL(url)) return undefined;\n  return {\n    expiresAt: date(object, 'expires_at'),\n    handoffToken: string(object, 'handoff_token'),\n    message: string(object, 'message'),\n    provider: string(object, 'provider') ?? '',\n    providerName: string(object, 'provider_name'),\n    status: string(object, 'status'),\n    title,\n    type: string(object, 'type') ?? 'oauth',\n    url,\n  };\n};\n\nconst parseReasoning = (id: string, object: JSONObject): AIReasoningPart => ({\n  durationMs: int(object, 'duration_ms'),\n  id,\n  preview: string(object, 'preview'),\n  status: string(object, 'status') ?? 'completed',\n  summary: string(object, 'summary'),\n});\n\nconst parseToolCall = (id: string, object: JSONObject): AIToolCallPart => {\n  const approval = object.approval;\n  const authorization = object.authorization;\n  const args = object.arguments;\n  return {\n    approval: isObject(approval) ? parseApproval(approval) : undefined,\n    arguments: args === null ? undefined : args,\n    authorization: isObject(authorization)\n      ? parseAuthorization(authorization)\n      : undefined,\n    displayTitle: string(object, 'display_title'),\n    durationMs: int(object, 'duration_ms'),\n    executor: string(object, 'executor') ?? 'server',\n    id,\n    name: string(object, 'name') ?? '',\n    status: string(object, 'status') ?? 'running',\n    summary: string(object, 'summary'),\n    targetClientId: string(object, 'target_client_id'),\n    targetUserId: string(object, 'target_user_id'),\n  };\n};\n\n/**\n * Decodes one attachment, or returns `undefined` when it is not an AI step.\n *\n * @param attachment The attachment, as it is on the message (with its `type`).\n * @param position The attachment's index, used as the identity of a step with no ID of its own.\n */\nexport const parseMessagePart = (\n  attachment: unknown,\n  position = 0,\n): AIMessagePartData | undefined => {\n  if (!isObject(attachment)) return undefined;\n  const type = attachment.type;\n  if (typeof type !== 'string' || !type.startsWith(AI_MESSAGE_PART_TYPE_PREFIX)) {\n    return undefined;\n  }\n  const fields = withCustomFields(attachment);\n  const id = string(fields, 'id') ?? `${type}-${position}`;\n  const version = int(fields, 'v') ?? 1;\n  const known = version <= AI_MESSAGE_PART_SUPPORTED_VERSION;\n  return {\n    id,\n    kind: type,\n    payload: fields,\n    reasoning: known && type === 'ai_reasoning' ? parseReasoning(id, fields) : undefined,\n    toolCall: known && type === 'ai_tool_call' ? parseToolCall(id, fields) : undefined,\n    version,\n  };\n};\n\n/**\n * Decodes the AI steps among a message's attachments, in order. Attachments that are not AI\n * steps (images, files and so on) are skipped. Decoding is lenient: missing fields get\n * defaults, and a step newer than this SDK understands keeps its payload but has no typed\n * view.\n *\n * ```ts\n * const parts = parseMessageParts(message.attachments);\n * ```\n */\nexport const parseMessageParts = (attachments: readonly unknown[] | null | undefined) =>\n  (attachments ?? []).reduce<AIMessagePartData[]>((parts, attachment, position) => {\n    const part = parseMessagePart(attachment, position);\n    if (part) parts.push(part);\n    return parts;\n  }, []);\n\n/** Whether this SDK has a typed view of the step. */\nexport const isSupportedPart = (part: AIMessagePartData) =>\n  part.reasoning !== undefined || part.toolCall !== undefined;\n\n/** Whether the call has finished, one way or another. */\nexport const isToolCallFinished = (status: AIToolCallStatus) =>\n  status === 'completed' || status === 'failed' || status === 'cancelled';\n\n/**\n * Whether the person declined the call, or the sign-in it waited for, so it never ran.\n */\nexport const isDeclined = (call: AIToolCallPart) =>\n  call.approval?.decision === 'declined' || call.authorization?.status === 'declined';\n\n/**\n * Whether this call is waiting for this device: a client tool, still awaiting its result,\n * targeted at this person and this install.\n */\nexport const isAwaitingClient = (\n  call: AIToolCallPart,\n  userId: string,\n  clientId: string,\n) =>\n  call.executor === 'client' &&\n  call.status === 'awaiting_client' &&\n  call.targetUserId === userId &&\n  call.targetClientId === clientId;\n\n/**\n * Whether this call is waiting for this person to allow it, on this device: still awaiting\n * approval, targeted at this person, and at this install when it names one (a client tool\n * does; a server tool's question may be answered from any of their devices).\n */\nexport const isAwaitingApproval = (\n  call: AIToolCallPart,\n  userId: string,\n  clientId: string,\n) =>\n  call.status === 'awaiting_approval' &&\n  call.approval !== undefined &&\n  call.targetUserId === userId &&\n  (call.targetClientId === undefined || call.targetClientId === clientId);\n\n/** Whether this call is waiting for this person to sign in, from any of their devices. */\nexport const isAwaitingAuthorization = (call: AIToolCallPart, userId: string) =>\n  call.status === 'awaiting_authorization' &&\n  call.authorization !== undefined &&\n  call.targetUserId === userId;\n\n/** Whether a sign-in that is still asked for has passed its `expiresAt`. */\nexport const isAuthorizationExpired = (\n  authorization: AIToolAuthorizationData,\n  now = Date.now(),\n) =>\n  authorization.status === 'expired' ||\n  (authorization.status === undefined &&\n    authorization.expiresAt !== undefined &&\n    authorization.expiresAt <= now);\n"],"mappings":";;;AAWA,IAAa,8BAA8B;;AAE3C,IAAa,oCAAoC;AAKjD,IAAM,UAAU,QAAoB,QAAgB;CAClD,MAAM,QAAQ,OAAO;CACrB,OAAO,OAAO,UAAU,YAAY,UAAU,KAAK,QAAQ,KAAA;AAC7D;AAEA,IAAM,OAAO,QAAoB,QAAgB;CAC/C,MAAM,QAAQ,OAAO;CACrB,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IACrD,KAAK,MAAM,KAAK,IAChB,KAAA;AACN;AAEA,IAAM,QAAQ,QAAoB,QAAgB;CAChD,MAAM,QAAQ,OAAO,QAAQ,GAAG;CAChC,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;CAChC,MAAM,OAAO,KAAK,MAAM,KAAK;CAC7B,OAAO,OAAO,MAAM,IAAI,IAAI,KAAA,IAAY;AAC1C;AAEA,IAAM,iBAAiB,WAAuD;CAE5E,MAAM,QAAQ,OAAO,QAAQ,OAAO;CACpC,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,OAAO;EACL,YAAY,OAAO,QAAQ,aAAa;EACxC,UAAU,OAAO,QAAQ,UAAU;EACnC,cAAc,OAAO,QAAQ,eAAe;EAC5C,SAAS,OAAO,QAAQ,SAAS;EACjC,QAAQ,OAAO,QAAQ,QAAQ;EAC/B;CACF;AACF;AAEA,IAAM,YAAY,UAAkB;CAClC,IAAI;EACF,MAAM,MAAM,IAAI,IAAI,KAAK;EACzB,QAAQ,IAAI,aAAa,YAAY,IAAI,aAAa,YAAY,IAAI,SAAS;CACjF,QAAQ;EACN,OAAO;CACT;AACF;AAEA,IAAM,sBAAsB,WAA4D;CAEtF,MAAM,QAAQ,OAAO,QAAQ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