### Quick Start: Send an iMessage Source: https://photon.codes/docs/opensource/imessage-kit A basic example demonstrating how to initialize the SDK and send a message. Ensure the SDK is properly installed and configured. ```typescript import { IMessageSDK } from "@photon-ai/imessage-kit"; const sdk = new IMessageSDK(); await sdk.send("+1234567890", "Hello from iMessage Kit!"); await sdk.close(); ``` -------------------------------- ### Install Standalone Binary for Apple Silicon Mac Source: https://photon.codes/docs/cli/installation Example of downloading and installing the standalone binary for an Apple Silicon Mac. ```sh curl -L -o /usr/local/bin/photon \ https://github.com/photon-hq/cli/releases/latest/download/photon-darwin-arm64 chmod +x /usr/local/bin/photon ``` -------------------------------- ### Install Hono and Run Server Source: https://photon.codes/docs/webhooks/quickstart Commands to add Hono as a dependency and start the server in watch mode for automatic restarts on file changes. ```bash bun add hono bun --hot server.ts ``` -------------------------------- ### Install WhatsApp Business SDK with bun Source: https://photon.codes/docs/advanced-kits/whatsapp/getting-started Use this command to install the SDK using bun. Requires Bun. ```bash bun add @photon-ai/whatsapp-business ``` -------------------------------- ### Install the Advanced iMessage SDK Source: https://photon.codes/docs/advanced-kits/imessage/getting-started Install the SDK using npm, pnpm, yarn, or bun. ```bash npm install @photon-ai/advanced-imessage ``` ```bash pnpm add @photon-ai/advanced-imessage ``` ```bash yarn add @photon-ai/advanced-imessage ``` ```bash bun add @photon-ai/advanced-imessage ``` -------------------------------- ### Install WhatsApp Business SDK with yarn Source: https://photon.codes/docs/advanced-kits/whatsapp/getting-started Use this command to install the SDK using yarn. Requires Node.js 18+. ```bash yarn add @photon-ai/whatsapp-business ``` -------------------------------- ### Install Standalone Binary Source: https://photon.codes/docs/cli/installation Download and install a prebuilt binary for environments that require no runtime dependencies, such as CI. Ensure you replace and with your specific platform details. ```sh # : darwin | linux # : arm64 | x64 curl -L -o /usr/local/bin/photon \ https://github.com/photon-hq/cli/releases/latest/download/photon-- chmod +x /usr/local/bin/photon photon --version ``` -------------------------------- ### Install iMessage Kit with Bun Source: https://photon.codes/docs/opensource/imessage-kit Install the iMessage Kit using Bun. This method has zero runtime dependencies. ```bash bun add @photon-ai/imessage-kit ``` -------------------------------- ### Install WhatsApp Business SDK with npm Source: https://photon.codes/docs/advanced-kits/whatsapp/getting-started Use this command to install the SDK using npm. Requires Node.js 18+. ```bash npm install @photon-ai/whatsapp-business ``` -------------------------------- ### Install WhatsApp Business SDK with pnpm Source: https://photon.codes/docs/advanced-kits/whatsapp/getting-started Use this command to install the SDK using pnpm. Requires Node.js 18+. ```bash pnpm add @photon-ai/whatsapp-business ``` -------------------------------- ### Install Spectrum TS with bun Source: https://photon.codes/docs/spectrum-ts/getting-started Install the Spectrum TS library using bun. Requires TypeScript 5 or later. ```bash bun add spectrum-ts ``` -------------------------------- ### Basic Hono Server Setup Source: https://photon.codes/docs/webhooks/quickstart Initial setup for a Hono server to listen for POST requests on the /spectrum-webhook endpoint. This version logs the raw body. ```typescript import { Hono } from 'hono'; const app = new Hono(); app.post('/spectrum-webhook', async (c) => { const body = await c.req.text(); console.log('received', body.slice(0, 200)); return c.text('ok', 200); }); export default { port: 3000, fetch: app.fetch }; ``` -------------------------------- ### Execute Globally Installed CLI Source: https://photon.codes/docs/cli/installation Once installed globally, you can run commands directly using the 'photon' executable. A 'pho' shortcut is automatically created. ```sh photon login ``` -------------------------------- ### Install iMessage Kit with npm Source: https://photon.codes/docs/opensource/imessage-kit Install the iMessage Kit using npm. Requires `better-sqlite3` as an optional peer dependency. ```bash npm install @photon-ai/imessage-kit better-sqlite3 ``` -------------------------------- ### Verify Photon CLI Installation Source: https://photon.codes/docs/cli/installation Check if the Photon CLI is installed correctly and accessible by running version and ping commands. ```sh photon --version photon ping ``` -------------------------------- ### Install heif2jpeg using bun Source: https://photon.codes/docs/utilities/heif2jpeg Install the heif2jpeg package using bun. bun is a fast all-in-one JavaScript runtime. ```bash bun add heif2jpeg ``` -------------------------------- ### Initiate Subscription Checkout Source: https://photon.codes/docs/cli/billing Starts a Stripe Checkout session to subscribe to a plan. An interactive picker is shown by default, but specific tiers or Stripe price IDs can be provided to skip it. Use `--no-browser` to get the URL instead of opening it. ```sh # Interactive picker — recommended for first-time use photon billing checkout # Skip the picker with a positional tier photon billing checkout pro photon billing checkout business --qty 5 # Use a specific Stripe price (escape hatch) photon billing checkout --plan price_xxx ``` -------------------------------- ### Install Spectrum TS with pnpm Source: https://photon.codes/docs/spectrum-ts/getting-started Install the Spectrum TS library using pnpm. Requires TypeScript 5 or later. ```bash pnpm add spectrum-ts ``` -------------------------------- ### List Projects Source: https://photon.codes/docs/cli/projects Lists all available projects. Use the --json flag to get the output in JSON format. ```sh photon projects ls photon projects ls --json ``` -------------------------------- ### Install Spectrum TS with yarn Source: https://photon.codes/docs/spectrum-ts/getting-started Install the Spectrum TS library using yarn. Requires TypeScript 5 or later. ```bash yarn add spectrum-ts ``` -------------------------------- ### Install Spectrum TS with npm Source: https://photon.codes/docs/spectrum-ts/getting-started Install the Spectrum TS library using npm. Requires TypeScript 5 or later. ```bash npm install spectrum-ts ``` -------------------------------- ### Global CLI Installation Source: https://photon.codes/docs/cli/installation Install the Photon CLI globally for everyday use, making the 'photon' command available on your system's PATH. Requires Node.js version 18 or higher. ```sh npm install -g @photon-ai/cli ``` ```sh pnpm add -g @photon-ai/cli ``` ```sh yarn global add @photon-ai/cli ``` ```sh bun add -g @photon-ai/cli ``` -------------------------------- ### Initialize Spectrum Client Source: https://photon.codes/docs/webhooks/overview Initialize the Spectrum client with your project credentials. This setup is necessary before processing messages, whether through polling or webhooks. ```typescript const app = await Spectrum({ projectId, projectSecret, providers: [imessage.config()] }); // Without webhooks, you'd run this loop yourself, forever. for await (const [space, message] of app.messages) { /* ... */ } ``` -------------------------------- ### Start Typing Indicator Source: https://photon.codes/docs/spectrum-ts/providers/terminal Use `space.startTyping()` to show a live typing indicator to the user. ```typescript space.startTyping() ``` -------------------------------- ### Basic Terminal Agent Example Source: https://photon.codes/docs/spectrum-ts/providers/terminal A basic example of an agent using the terminal provider. This code sends back an 'echo' of any text message received. It requires importing Spectrum and the terminal provider. ```typescript import { Spectrum } from "spectrum-ts"; import { terminal } from "spectrum-ts/providers/terminal"; const app = await Spectrum({ providers: [terminal.config()], }); for await (const [space, message] of app.messages) { if (message.content.type === "text") { await space.send(`echo: ${message.content.text}`); } } ``` -------------------------------- ### Example Incoming Message Format Source: https://photon.codes/docs/webhooks/quickstart This is an example of the raw text output you might see in your terminal when a message is received via webhook. It shows the sender's identifier and the message content. ```text message from +15550100 : { type: 'text', text: 'hi' } ``` -------------------------------- ### Webhook List Response Example Source: https://photon.codes/docs/webhooks/managing-webhooks This is an example of the JSON response structure when listing webhooks. It includes details like ID, URL, and timestamps. ```json { "succeed": true, "data": [ { "id": "6a4d2e8c-7b1f-4d3a-9a8e-2c5d6f7e8a9b", "webhookUrl": "https://your-app.com/spectrum-webhook", "createdAt": "2026-05-14T19:00:00Z", "updatedAt": "2026-05-14T19:00:00Z" }, { "id": "9f1e3d4b-2c8a-4f5d-b7e6-1a2b3c4d5e6f", "webhookUrl": "https://staging.your-app.com/spectrum-webhook", "createdAt": "2026-05-15T09:30:00Z", "updatedAt": "2026-05-15T09:30:00Z" } ] } ``` -------------------------------- ### typing Source: https://photon.codes/docs/spectrum-ts/content Send a typing indicator signal through the content pipeline. Defaults to "start". ```APIDOC ## typing ### Description Send a typing indicator signal through the content pipeline. Defaults to `"start"`. ### Method `space.send(typing(state))` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **state** (string) - Optional. The state of the typing indicator. Defaults to `"start"`. Can be `"start"` or `"stop"`. ### Request Example ```ts import { typing } from "spectrum-ts"; await space.send(typing()); // start typing await space.send(typing("stop")); // stop typing ``` ### Response `undefined` (fire-and-forget) ### Error Handling Platforms without a typing-indicator API silently no-op. ``` -------------------------------- ### Get a Single Message by GUID Source: https://photon.codes/docs/advanced-kits/imessage/messages Use `im.messages.get(guid)` to retrieve a specific message when you have its GUID. This method throws a `NotFoundError` if the message does not exist. ```typescript const message = await im.messages.get(sent.guid); console.log(message.content.text); ``` -------------------------------- ### Basic Photon CLI Commands Source: https://photon.codes/docs/cli/overview A quick demonstration of common Photon CLI commands after installation, including logging in, listing projects, setting the current project, managing Spectrum resources, and checking billing. ```sh # Log in (opens a browser to approve the device) photon login # List your projects photon projects ls # Set a project for the current shell session export PHOTON_PROJECT_ID= # Manage Spectrum resources photon spectrum users ls photon spectrum lines ls # Check billing photon billing show ``` -------------------------------- ### Get a Specific Chat Source: https://photon.codes/docs/advanced-kits/imessage/chats Fetches a chat by its GUID. Throws NotFoundError if the chat does not exist. Requires the chat GUID as an argument. ```typescript const chat = await im.chats.get("any;-;alice@example.com"); console.log(chat.displayName, chat.unreadCount, chat.isGroup); ``` -------------------------------- ### Build Promo Launch Template with Buttons Source: https://photon.codes/docs/advanced-kits/whatsapp/templates Constructs a promotional launch template with a text header, text body, and both quick-reply and URL buttons. This shows how to use `.button()` and `.urlButton()` with their respective index and parameter helpers. ```typescript const msg = template("promo_launch", "en_US") .header(text("Spring sale")) .body(text("Alice"), text("30%")) .button(0, payload("apply_code")) // quick-reply button .urlButton(1, text("spring-30")); // dynamic URL suffix ``` -------------------------------- ### Get Message Source: https://photon.codes/docs/advanced-kits/imessage/messages Retrieves a specific message by its GUID. ```APIDOC ## im.messages.get ### Description Retrieves a specific message by its GUID. ### Method GET (assumed) ### Endpoint /im.messages.get ### Parameters #### Query Parameters - **chat.guid** (string) - Required - The server's chat identifier. - **messageGuid** (string) - Required - The GUID of the message to retrieve. ``` -------------------------------- ### Map iMessage Events to Message GUIDs Source: https://photon.codes/docs/advanced-kits/imessage/events Use `.filter()` and `.map()` in sequence to transform events. This example first filters for received messages and then maps them to their GUIDs. ```typescript const messageGuids = im.messages .subscribeEvents() .filter((event) => event.type === "message.received") .map((event) => event.message.guid); ``` -------------------------------- ### Get Poll State Source: https://photon.codes/docs/advanced-kits/imessage/polls Retrieves the latest state of a poll using its message GUID. This is useful for getting updated option IDs or current vote counts. ```APIDOC ## get ### Description Retrieves the latest state of a poll using its message GUID. This is useful for getting updated option IDs or current vote counts. Missing polls will throw a `NotFoundError`. ### Method `im.polls.get(pollMessageGuid: string)` ### Parameters #### Path Parameters - `pollMessageGuid` (string) - Required - The GUID of the poll message to retrieve. ### Response #### Success Response (200) Returns the latest `Poll` object with updated `title`, `options`, and `votes`. ### Response Example ```json { "pollMessageGuid": "poll-message-guid", "chatGuid": "any;+;group-id", "title": "Lunch?", "options": [ { "optionIdentifier": "option-1", "text": "Pizza" } ], "votes": [ { "optionIdentifier": "option-1", "participant": { "address": "alice@example.com", "service": "iMessage" } } ] } ``` ``` -------------------------------- ### Get a Chat Source: https://photon.codes/docs/advanced-kits/imessage/chats Retrieves a specific chat by its GUID. Throws NotFoundError if the chat does not exist or cannot be resolved. ```APIDOC ## Get a Chat ### Description Retrieves a specific chat using its unique identifier (GUID). This method is useful for fetching detailed information about a single chat conversation. ### Method `get(guid: string)` ### Parameters #### Path Parameters - **guid** (string) - Required - The unique identifier of the chat to retrieve. ### Response #### Success Response (Chat Object) - **guid** (string) - The GUID of the chat. - **displayName** (string) - The display name of the chat. - **isGroup** (boolean) - Indicates if the chat is a group chat. - **participants** (array) - An array of chat participants. - **service** (string) - The service the chat belongs to (e.g., "iMessage"). - **isArchived** (boolean) - Indicates if the chat is archived. - **isFiltered** (boolean) - Indicates if the chat is filtered by the system. - **unreadCount** (number) - The number of unread messages (may be absent). - **lastMessage** (object) - The latest message in the chat, if available. ### Error Handling - **NotFoundError**: Thrown when the chat does not exist or cannot be resolved. ``` -------------------------------- ### Get One Message Source: https://photon.codes/docs/advanced-kits/imessage/messages Retrieves a single message using its unique GUID. If the message is not found, a NotFoundError will be thrown. ```APIDOC ## Get One Message ### Description Retrieves a single message using its unique GUID. If the message is not found, a NotFoundError will be thrown. ### Method `get(guid: string)` ### Parameters #### Path Parameters - **guid** (string) - Required - The unique identifier of the message. ### Request Example ```ts const message = await im.messages.get(sent.guid); console.log(message.content.text); ``` ### Response #### Success Response - **message** (object) - The retrieved message object. - **guid** (string) - The unique identifier of the message. - **content** (object) - The content of the message. - **text** (string) - The text content of the message. ### Error Handling - **NotFoundError**: Thrown if the message with the specified GUID does not exist. ``` -------------------------------- ### Create a New Project Source: https://photon.codes/docs/cli/projects Creates a new Photon project. An interactive prompt is used by default, or flags can be provided for direct configuration. ```sh photon projects create ``` ```sh photon projects create --name "My Project" --location us-east --spectrum ``` -------------------------------- ### Get Attachment Metadata Source: https://photon.codes/docs/advanced-kits/imessage/attachments Retrieves metadata for an uploaded attachment using its GUID. Use this to inspect attachment state and confirm readiness for download. ```typescript const attachment = await im.attachments.get(uploaded.attachment.guid); console.log(attachment.fileName, attachment.mimeType, attachment.totalBytes); ``` -------------------------------- ### Message Object Structure Source: https://photon.codes/docs/advanced-kits/imessage/messages This is an example of the common fields found in a `Message` object returned by sending functions. It includes details like GUID, chat associations, content, sender status, and creation date. ```typescript const message = { // Message GUID. Use it for edits, unsends, reactions, replies, and lookups. guid: "message-guid", // Chats that contain this message. chatGuids: ["any;-;alice@example.com"], content: { text: "Hello", attachments: [], formatting: [], mentions: [], }, isFromMe: true, dateCreated: new Date("2026-01-01T12:00:00Z"), }; ``` -------------------------------- ### Run First Spectrum App with iMessage Provider Source: https://photon.codes/docs/spectrum-ts/getting-started This snippet shows how to initialize a Spectrum app with project credentials and the iMessage provider, then logs incoming messages and sends a reply. ```typescript import { Spectrum } from "spectrum-ts"; import { imessage } from "spectrum-ts/providers/imessage"; const app = await Spectrum({ projectId: "your-project-id", projectSecret: "your-project-secret", providers: [ imessage.config(), ], }); for await (const [space, message] of app.messages) { if (message.content.type === "text") { console.log(`[${message.platform}] ${message.sender.id}: ${message.content.text}`); await space.send("hello world"); } } ``` -------------------------------- ### Install heif2jpeg using npm Source: https://photon.codes/docs/utilities/heif2jpeg Install the heif2jpeg package using npm. This is the standard package manager for Node.js. ```bash npm install heif2jpeg ``` -------------------------------- ### Initialize Spectrum with Providers Source: https://photon.codes/docs/spectrum-ts/introduction Initialize the Spectrum application with project credentials and configure multiple providers like iMessage and Terminal. This sets up the agent to receive messages from various platforms. ```typescript import { Spectrum } from "spectrum-ts"; import { imessage, terminal } from "spectrum-ts/providers"; const app = await Spectrum({ projectId: process.env.PROJECT_ID!, projectSecret: process.env.PROJECT_SECRET!, providers: [ imessage.config(), terminal.config(), ], }); for await (const [space] of app.messages) { await space.send("How can I help?"); } ``` -------------------------------- ### Run Spectrum App with Terminal Provider (Projectless) Source: https://photon.codes/docs/spectrum-ts/getting-started Demonstrates initializing a Spectrum app using the terminal provider without requiring project credentials. This is useful for local testing or command-line interactions. ```typescript import { Spectrum } from "spectrum-ts"; import { terminal } from "spectrum-ts/providers/terminal"; const app = await Spectrum({ providers: [terminal.config()], }); ``` -------------------------------- ### Initialize Spectrum with Telegram Provider Source: https://photon.codes/docs/spectrum-ts/providers/telegram Initialize the Spectrum app with the Telegram provider. This example shows how to set up the app and listen for incoming messages, echoing text messages back to the sender. ```typescript import { Spectrum } from "spectrum-ts"; import { telegram } from "spectrum-ts/providers/telegram"; const app = await Spectrum({ projectId: process.env.PROJECT_ID!, projectSecret: process.env.PROJECT_SECRET!, providers: [ telegram.config({ botToken: process.env.TELEGRAM_BOT_TOKEN!, }), ], }); for await (const [space, message] of app.messages) { if (message.content.type === "text") { await space.send(`Echo: ${message.content.text}`); } } ``` -------------------------------- ### Install heif2jpeg using pnpm Source: https://photon.codes/docs/utilities/heif2jpeg Install the heif2jpeg package using pnpm. pnpm is an alternative package manager for Node.js. ```bash pnpm add heif2jpeg ``` -------------------------------- ### Initialize Spectrum Agent with Providers Source: https://photon.codes/docs This snippet shows how to initialize the Spectrum agent with project credentials and configure multiple providers, such as iMessage and terminal. It then enters a message loop to send a greeting to each incoming message space. ```typescript import { Spectrum } from "spectrum-ts"; import { imessage, terminal } from "spectrum-ts/providers"; const app = await Spectrum({ projectId: process.env.PROJECT_ID!, projectSecret: process.env.PROJECT_SECRET!, providers: [ imessage.config(), terminal.config(), ], }); for await (const [space] of app.messages) { await space.send("How can I help?"); } ``` -------------------------------- ### Initialize Developer Profile Source: https://photon.codes/docs/cli/profile-and-utilities Walks you through an interactive prompt to create a developer or organization profile. Can be used non-interactively with flags. ```sh photon profile init ``` -------------------------------- ### Initialize Client, Send Message, and Subscribe to Events Source: https://photon.codes/docs/advanced-kits/whatsapp/getting-started This snippet demonstrates how to create a WhatsApp client, send a text message, and subscribe to incoming message events. Ensure your environment variables for access token, phone number ID, and app secret are set. ```typescript import { createClient } from "@photon-ai/whatsapp-business"; const client = createClient({ accessToken: process.env.WA_ACCESS_TOKEN!, phoneNumberId: process.env.WA_PHONE_NUMBER_ID!, appSecret: process.env.WA_APP_SECRET!, }); await client.messages.send({ to: "+15551234567", text: "Hello from the SDK!", }); for await (const event of client.events.subscribe()) { if (event.type === "message") { console.log(event.message); } } ``` -------------------------------- ### Update Globally Installed CLI Source: https://photon.codes/docs/cli/installation Update your globally installed Photon CLI to the latest version using your package manager. ```sh npm update -g @photon-ai/cli ``` ```sh pnpm update -g @photon-ai/cli ``` ```sh yarn global upgrade @photon-ai/cli ``` ```sh bun update -g @photon-ai/cli ``` -------------------------------- ### Photon CLI Command Tree Source: https://photon.codes/docs/cli/overview An overview of the Photon CLI's command structure, showing available commands and subcommands for managing various aspects of Photon services. ```text photon ├── ping hit /api/health ├── env current print resolved API host ├── login [--api-host] [--no-browser] device-auth login ├── logout [--api-host] clear stored credentials ├── whoami [--api-host] current user on this backend ├── auth status [--json] login state across all backends ├── config show [--json] dump active configuration ├── profile │ ├── show account & profile details │ ├── init create developer or org profile │ └── update [flags] update profile fields ├── projects │ ├── ls [--json] list projects │ ├── show [id] [--json] project detail │ ├── create [--name --location --spectrum] new project │ ├── update [id] [flags] rename / toggle flags │ ├── delete [id] [-y] permanent delete │ ├── regenerate-secret [id] [-y] rotate Spectrum API secret │ ├── open [id] [--no-browser] open dashboard in browser │ ├── upgrade [id] [tier] subscribe / open Stripe portal │ └── check-phone phone number availability ├── spectrum │ ├── profile show / update project Spectrum profile │ ├── users ls / add / remove manage Spectrum users │ ├── lines ls / add / remove manage phone lines │ ├── platforms ls / enable / disable toggle messaging platforms │ └── avatar upload upload Spectrum avatar └── billing ├── plans available plans ├── show [--json] current subscription ├── checkout [tier] [--plan ] [--qty ] Stripe Checkout └── manage Stripe Customer Portal ``` -------------------------------- ### Send Text Message with Chat GUID Source: https://photon.codes/docs/advanced-kits/imessage/getting-started This snippet shows the exact format for sending a text message using a chat GUID. ```typescript await im.messages.sendText(chat.guid, "Hello from the SDK"); ``` -------------------------------- ### Start and Stop Real-time Watching Source: https://photon.codes/docs/opensource/imessage-kit Shows how to initiate real-time message watching with various callbacks for different message types and errors, and how to stop the watcher later. Essential for receiving immediate updates. ```typescript await sdk.startWatching({ onMessage: (msg) => console.log(`New: ${msg.text}`), onDirectMessage: (msg) => console.log(`DM from ${msg.sender}`), onGroupMessage: (msg) => console.log(`Group: ${msg.chatId}`), onError: (err) => console.error(err), }); // Later sdk.stopWatching(); ``` -------------------------------- ### Install heif2jpeg using yarn Source: https://photon.codes/docs/utilities/heif2jpeg Install the heif2jpeg package using yarn. yarn is another popular package manager for Node.js. ```bash yarn add heif2jpeg ``` -------------------------------- ### Start Watching Source: https://photon.codes/docs/opensource/imessage-kit Starts a real-time watcher that polls for new messages and dispatches them to registered callbacks. Call `stopWatching` to end the process. ```APIDOC ## Real-time Watching ### Description Starts a real-time watcher that polls the Messages database for new messages and triggers registered callbacks. Use `sdk.stopWatching()` to disable the watcher. ### Method `sdk.startWatching(events: WatcherEvents)` ### Parameters #### Request Body - **events** (WatcherEvents) - An object containing callback functions for different message events: - `onMessage` (MessageCallback) - Optional - Called for every new message. - `onDirectMessage` (MessageCallback) - Optional - Called for new direct messages. - `onGroupMessage` (MessageCallback) - Optional - Called for new group messages. - `onError` ((error: Error) => void) - Optional - Called when an error occurs. ### Request Example ```ts await sdk.startWatching({ onMessage: (msg) => console.log(`New message received: ${msg.text}`), onDirectMessage: (msg) => console.log(`DM from ${msg.sender}`), onGroupMessage: (msg) => console.log(`Group message in chat ${msg.chatId}`), onError: (err) => console.error(`Watcher error: ${err}`), }); // To stop watching later: // sdk.stopWatching(); ``` ``` -------------------------------- ### Configure and Combine Multiple Providers (Individual Imports) Source: https://photon.codes/docs/spectrum-ts/providers This snippet demonstrates configuring and combining multiple providers (iMessage, WhatsApp Business, Terminal) by importing each provider individually. The configurations are then passed to the Spectrum constructor. ```typescript import { Spectrum } from "spectrum-ts"; import { imessage } from "spectrum-ts/providers/imessage"; import { terminal } from "spectrum-ts/providers/terminal"; import { whatsappBusiness } from "spectrum-ts/providers/whatsapp-business"; const app = await Spectrum({ projectId: "...", projectSecret: "...", providers: [ imessage.config(), whatsappBusiness.config({ accessToken: process.env.WA_TOKEN!, phoneNumberId: process.env.WA_NUMBER_ID!, appSecret: process.env.WA_SECRET!, }), terminal.config(), ], }); ``` -------------------------------- ### Open Project in Dashboard Source: https://photon.codes/docs/cli/projects Opens the project's Dashboard page in the default browser. Use `--no-browser` to print the URL instead. ```sh photon projects open photon projects open photon projects open --no-browser # prints the URL instead ``` -------------------------------- ### Spectrum API Introduction Source: https://photon.codes/docs/llms.txt This section provides an introduction to the Spectrum API, outlining its purpose for managing Spectrum projects, webhooks, and platform configurations over HTTPS. ```APIDOC ## Spectrum API Introduction ### Description Manage Spectrum projects, webhooks, and platform configuration over HTTPS. ### Base URL `https://spectrum.photon.codes/` (or similar, based on OpenAPI spec) ### Authentication Requires API key or other authentication methods as specified in the API reference. ``` -------------------------------- ### Create Project Source: https://photon.codes/docs/api-reference/projects/create-project Creates a new project owned by the authenticated user. If `spectrum` is true, a Spectrum project is provisioned and its `spectrumProjectId` and `projectSecret` are set on the response. ```APIDOC ## POST /api/projects/ ### Description Creates a new project owned by the authenticated user. When `spectrum` is true, a Spectrum project is provisioned and its `spectrumProjectId` + `projectSecret` are set on the response. ### Method POST ### Endpoint /api/projects/ ### Parameters #### Request Body - **name** (string) - Required - The name of the project. - **location** (string) - Optional - The location of the project. Example: United States. - **spectrum** (boolean) - Optional - Whether to provision a Spectrum project. Defaults to false. - **template** (boolean) - Optional - Whether to create the project from a template. Defaults to false. - **observability** (boolean) - Optional - Whether to enable observability for the project. Defaults to false. - **platforms** (array) - Optional - An array of strings specifying the platforms for the project. Allowed values: `imessage`, `whatsapp_business`, `voice`. ### Request Example { "name": "My New Project", "location": "Europe", "spectrum": true, "platforms": ["imessage", "voice"] } ### Response #### Success Response (200) - **id** (string) - The unique identifier for the project. - **name** (string) - The name of the project. - **location** (string) - The location of the project. - **status** (string) - The current status of the project. - **spectrum** (boolean) - Indicates if a Spectrum project was provisioned. - **spectrumProjectId** (string) - The Spectrum project ID, if applicable. - **projectSecret** (string) - The Spectrum project secret, if applicable. - **template** (boolean) - Indicates if the project was created from a template. - **observability** (boolean) - Indicates if observability is enabled. - **userId** (string) - The ID of the user who owns the project. - **createdAt** (string) - The timestamp when the project was created. - **updatedAt** (string) - The timestamp when the project was last updated. #### Response Example { "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "name": "My New Project", "location": "Europe", "status": "running", "spectrum": true, "spectrumProjectId": "sp_abc123", "projectSecret": "ps_xyz789", "template": false, "observability": true, "userId": "user-12345", "createdAt": "2023-10-27T10:00:00Z", "updatedAt": "2023-10-27T10:05:00Z" } ``` -------------------------------- ### Fetch iMessage Attachment by GUID Source: https://photon.codes/docs/spectrum-ts/providers/imessage Retrieves an iMessage attachment using its GUID. The attachment object is lazy, requiring .read() or .stream() to download. Requires cloud or dedicated mode. ```typescript import { imessage } from "spectrum-ts/providers/imessage"; const im = imessage(app); const att = await im.getAttachment("p:0/GUID"); if (att) { console.log(att.name, att.mimeType, att.size); const bytes = await att.read(); } ``` -------------------------------- ### Example Webhook Delivery Payload Source: https://photon.codes/docs/webhooks/events This is an example of an inbound iMessage delivery. The exact ID formats and platform values vary by provider. Do not pattern-match on these strings; use them as opaque identifiers. ```http POST /your-webhook-path HTTP/1.1 Host: your-app.com Content-Type: application/json User-Agent: spectrum-webhook/0.1.0 X-Spectrum-Event: messages X-Spectrum-Webhook-Id: 60d6d04f-f9fa-4a7b-9c97-37c9c90ce91c X-Spectrum-Timestamp: 1747242392 X-Spectrum-Signature: v0=fc9bf49ef3ba4122ba4be6e289f88ac692f5ce8e13f0415cb38d59428eae8a8c { "event": "messages", "space": { "id": "any;-;+15550100", "platform": "iMessage", "type": "dm", "phone": "+15551234567" }, "message": { "id": "spc-msg-00000000-0000-4000-8000-000000000001", "platform": "iMessage", "direction": "inbound", "timestamp": "2026-05-14T19:06:32.000Z", "sender": { "id": "+15550100", "platform": "iMessage" }, "space": { "id": "any;-;+15550100", "platform": "iMessage", "type": "dm", "phone": "+15551234567" }, "content": { "type": "text", "text": "hey, what time is dinner?" } } } ``` -------------------------------- ### Login to Photon CLI Source: https://photon.codes/docs/cli/overview Log in to your Photon account using the CLI. This command will open a browser for device approval. ```sh npx @photon-ai/cli login ``` -------------------------------- ### Using the 'pho' Alias Source: https://photon.codes/docs/cli/overview Demonstrates the usage of the 'pho' alias for the Photon CLI, which is automatically created for global installs. This alias provides a shorter way to invoke common commands. ```sh pho projects ls # same as: photon projects ls pho whoami ``` -------------------------------- ### Enable a Spectrum Platform Source: https://photon.codes/docs/cli/spectrum Enable a specific messaging platform for your project by providing its name. ```sh photon spectrum platforms enable ``` -------------------------------- ### OpenAPI Specification for Get User Source: https://photon.codes/docs/api-reference/users/get-user This OpenAPI 3.1.0 specification defines the GET /projects/{projectId}/users/{userId}/ endpoint for retrieving user details. It includes request parameters, authentication requirements, and response schemas. ```yaml openapi: 3.1.0 info: title: Spectrum Cloud External API description: Client-facing API for Spectrum Cloud. version: 1.0.0 servers: - url: https://spectrum.photon.codes security: [] tags: - name: billing description: Billing and subscription operations - name: imessage description: iMessage platform operations - name: lines description: Phone line enumeration across platforms - name: platforms description: Platform management operations - name: users description: User operations - name: voice description: Voice platform operations - name: webhooks description: Webhook registration for receiving Spectrum events - name: whatsapp-business description: WhatsApp Business platform operations - name: slack description: Slack platform operations paths: /projects/{projectId}/users/{userId}/: get: tags: - users summary: Get user description: >- Returns a single user by ID. Requires Authorization: Basic base64(projectId:projectSecret). operationId: getProjectsByProjectIdUsersByUserId parameters: - name: userId in: path required: true schema: type: string format: uuid pattern: >- ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ - name: projectId in: path required: true schema: type: string format: uuid pattern: >- ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ responses: '200': description: Response for status 200 content: application/json: schema: type: object properties: succeed: type: boolean const: true data: type: object properties: id: type: string projectId: type: string type: type: string enum: - shared - dedicated firstName: anyOf: - type: string - type: 'null' lastName: anyOf: - type: string - type: 'null' email: anyOf: - type: string - type: 'null' phoneNumber: type: string format: e164 pattern: ^\+[1-9]\d{6,14}$ assignedPhoneNumber: type: string format: e164 pattern: ^\+[1-9]\d{6,14}$ meta: anyOf: - type: object propertyNames: type: string additionalProperties: {} - type: 'null' createdAt: type: string required: - id - projectId - type - firstName - lastName - email - phoneNumber - assignedPhoneNumber - meta - createdAt additionalProperties: false required: - succeed - data additionalProperties: false ``` -------------------------------- ### Show Project Details Source: https://photon.codes/docs/cli/projects Displays details for a specific project. If no project ID is provided, it defaults to the PHOTON_PROJECT_ID environment variable. ```sh photon projects show photon projects show ``` -------------------------------- ### Get Project OpenAPI Specification Source: https://photon.codes/docs/api-reference/projects/get-project This OpenAPI specification defines the GET /projects/{projectId}/ endpoint. It details the request parameters, authentication requirements, and the structure of the successful response, including project name, slug, and optional profile information. ```yaml openapi: 3.1.0 info: title: Spectrum Cloud External API description: Client-facing API for Spectrum Cloud. version: 1.0.0 servers: - url: https://spectrum.photon.codes security: [] tags: - name: billing description: Billing and subscription operations - name: imessage description: iMessage platform operations - name: lines description: Phone line enumeration across platforms - name: platforms description: Platform management operations - name: users description: User operations - name: voice description: Voice platform operations - name: webhooks description: Webhook registration for receiving Spectrum events - name: whatsapp-business description: WhatsApp Business platform operations - name: slack description: Slack platform operations paths: /projects/{projectId}/: get: tags: - projects summary: Get project description: >- Returns the project's display name plus, when set, its profile (firstName, lastName, avatarUrl). When a profile is set, the response also includes `imessageSynced`: true iff every active iMessage line for the project has an avatar on Tailor and a firstName/lastName matching the project profile. Worst-case latency is one Tailor timeout (~10s) regardless of line count. Requires Authorization: Basic base64(projectId:projectSecret). operationId: getProjectsByProjectId parameters: - name: projectId in: path required: true schema: type: string format: uuid pattern: >- ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ responses: '200': description: Response for status 200 content: application/json: schema: type: object properties: succeed: type: boolean const: true data: type: object properties: name: type: string slug: type: string profile: anyOf: - type: object properties: firstName: type: string lastName: type: string avatarUrl: anyOf: - type: string - type: 'null' imessageSynced: type: boolean required: - firstName - lastName - avatarUrl - imessageSynced additionalProperties: false - type: 'null' required: - name - slug - profile additionalProperties: false required: - succeed - data additionalProperties: false ``` -------------------------------- ### Register and Use a Custom Platform Source: https://photon.codes/docs/spectrum-ts/custom-platforms Register a custom platform with its configuration and then use it to interact with your application. Ensure the API key is securely provided. ```typescript const app = await Spectrum({ providers: [ myPlatform.config({ apiKey: process.env.MY_KEY! }), ], }); const mine = myPlatform(app); const user = await mine.user("user-123"); const space = await mine.space.create(user); await space.send("Hello from my custom platform."); ``` -------------------------------- ### OpenAPI Specification for Get iMessage Info Source: https://photon.codes/docs/api-reference/imessage/get-imessage-info This OpenAPI specification defines the GET endpoint for retrieving iMessage service information. It outlines the request parameters, authentication requirements, and the structure of the JSON response, including the iMessage service type. ```yaml openapi: 3.1.0 info: title: Spectrum Cloud External API description: Client-facing API for Spectrum Cloud. version: 1.0.0 servers: - url: https://spectrum.photon.codes security: [] tags: - name: billing description: Billing and subscription operations - name: imessage description: iMessage platform operations - name: lines description: Phone line enumeration across platforms - name: platforms description: Platform management operations - name: users description: User operations - name: voice description: Voice platform operations - name: webhooks description: Webhook registration for receiving Spectrum events - name: whatsapp-business description: WhatsApp Business platform operations - name: slack description: Slack platform operations paths: /projects/{projectId}/imessage/: get: tags: - imessage summary: Get iMessage info description: >- Returns the iMessage service type (shared or dedicated) for the project. Requires Authorization: Basic base64(projectId:projectSecret). operationId: getProjectsByProjectIdImessage parameters: - name: projectId in: path required: true schema: type: string format: uuid pattern: >- ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ responses: '200': description: Response for status 200 content: application/json: schema: type: object properties: succeed: type: boolean const: true data: type: object properties: type: type: string enum: - shared - dedicated required: - type additionalProperties: false required: - succeed - data additionalProperties: false ```