iMessage bridge

The iMessage bridge lets the owner talk to Firstmate from a phone. It is a small Bun service, fm-imessage@<slot>.service (behind the front unit fm-imessage.service, see Rolling deploys), that uses one or both of two transports for the iMessage line: a Photon Spectrum project (the default), and self-hosted BlueBubbles relays on Macs that you control. It is off by default.

What it does

For each message from the owner, the service does these steps:

  1. It turns the message into text. A threaded reply, a message effect, or a group of messages is unwrapped, so nothing that he writes is lost. A threaded reply also names who sent the earlier message: the owner, or in desk session mode us with the sender. When the bridge has no record, the note says so. It quotes that message's text, cut to 200 characters with "…". When that message is not in local history, the note shows no text. A message kind that the service does not know becomes a note that names the kind. Tapbacks, typing, read receipts, unsends, and chat changes are only signals, and the service ignores them.

  2. For a supported desk, it starts reading fm-inbox.sh status before saving the message. It saves the full input and a stable request id in the private routing.jsonl journal before transport acknowledgement. It also appends the owner text to desk memory. It keeps authored text separate from quoted thread metadata for action and social checks.

  3. It marks the text as read once the text is stored for routing, whether the desk answers it or Firstmate or a mate takes it. Each text is marked read once. A failed read mark is tried again, and a text that arrived while the service was down is marked read after it starts, if it arrives within the transport catch-up window. Records of sent receipts are deleted after 7 days.

  4. It combines text until 350 milliseconds of silence or 2 seconds from the first text, whichever comes first. This cap limits the batching wait, not status retrieval, model work, or delivery. Each new text cancels a running draft, resets the quiet timer, and starts a fresh status read. Text received during a draft starts a new batching wait; the next draft includes every pending message. The desk uses the latest status result after the wait without reading it again. Slow message persistence can make the status snapshot older than the batching wait. Attachments, unsupported content, group chats, and edits go to Firstmate without a model answer. A desk other than omp with claude-haiku-5-5 or inception with mercury-3 also sends every request to Firstmate.

  5. The desk model classifies the whole pending burst. The default is Claude Haiku 5.5 with thinking off, through the existing one-shot omp -p runner. Both providers use the existing omp -p tool runtime for classification. desk_provider: inception selects inception/<desk_model> without changing the provider or configured reasoning level. Inception needs an explicit desk_reasoning of instant, low, medium, or high; instant is valid only with Inception. A native provider hook preserves Inception's instant wire value; other reasoning levels pass through unchanged. A failed Inception call never falls back to another provider; requests follow the second-mate handoff rules. The Inception voice pass still uses its tool-free chat-completions request and instant reasoning. The runtime has native read, grep, glob, bash, and write tools, plus the existing zoom extension. desk-tools.yml enables secret masking; a native extension checks every write against the current owner's authorized target. Before evidence validation and the voice call, the extension uses native filters to remove credentials from replies and tool results. The bridge rejects server-tool output without this filtered result. Each classification call with server tools uses a private temporary directory with a native secret file for parent-known credentials. This includes configured relay passwords and connection passwords without adding them to the tool environment. The service removes the directory when the call exits. Automatic writes require one explicit write, set, or replace request with one absolute file path and an existing parent directory. The target is resolved before the call and checked again before writing, including symbolic links. The native-normalized destination must resolve to that same authorized target; normalization cannot select a different file. Empty writes and unapproved targets are blocked; retrieved content cannot add a target. A shebang write requires approval if the native writer would add execute permissions, including when it creates a file. Version-controlled projects, registered mate homes, and known credential stores are not automatic write targets. Direct reads stay on the local filesystem and local process or artifact interfaces. The guard decodes native file URLs before checking each target from quote removal and delimiter expansion. Network reads require approval. Shell commands still require native approval, except the listed system reads. The automatic service check is exactly systemctl --user is-active -- fm-imessage.service; other service commands require approval. The child receives only its provider credentials and required runtime variables, not transport credentials. Native tools retain XDG_RUNTIME_DIR and DBUS_SESSION_BUS_ADDRESS so local user-service inspection can connect to the existing bus. Its input combines desk memory, durable fm-inbox.sh status output, and pending messages. Reading status does not request a supervisor answer. The desk refreshes typing every four seconds during the model call, delivery lookups, queue waits, and retries. It stops when the transport accepts the first response bubble or the reaction, or when the response is cancelled or discarded; a handoff does not stop it, and the real answer does. The service stops refreshes before saving delivery progress, even if that save fails. A desk turn that runs past 150 seconds is aborted. If it is still current and no item has routed yet, it is handed off to Firstmate and the owner gets one short delay reply. A front model timeout has its own one-line ack; see V2 front desk. Shutdown stops typing and allows two seconds for pending cleanup. Supervisor typing starts after desk cleanup. Command typing has an eight-second expiry timer; another typing command renews it. The response-deadline callback stops typing only for its associated desk turn. A burst across different chats shows no typing because the model has not yet selected its response target. Informational noun phrases, including approval counts, reach this classifier after receipt or recovery.

  6. When not muted, a clear basic question can receive one direct answer without a Firstmate note or wake. The internal draft must equal complete evidence lines from status or successful current tool results. Stored chat, including supervisor records, is never evidence; when status has no answer, the desk uses a tool result or hands off. Model-identity evidence names the desk or supervisor and must match that subject's full configured model name. An unknown supervisor identity requires a handoff. The service checks every quote against its source and rejects conflicting draft text, missing evidence, and work claims. After those checks, the existing voice pass uses the original question and validated draft to write a short plain-text answer. It explains configuration values in context and preserves exact values, links, identifiers, and commands. The draft and question remain untrusted data; neither grants action authority. The native result envelope masks credentials in the original question before it reaches the voice pass. Before checking evidence, it also maps native credential placeholders and source credentials to the same [REDACTED] marker. The prompt requires every fact, name, number, link, subject, negation, and claim to stay unchanged. The service rejects changed protected tokens or polarity, empty replies, failed calls, work claims, and unrequested Markdown fences. Without an explicit exact-output request, the reply check rejects headings, bullets, pipe-style tables, configuration rows, bare source values, and replies that parse as JSON. A retained configuration row still causes rejection when other lines contain prose. Unrequested inline code also causes rejection; the service does not strip its formatting. The same rejection applies to blockquotes, single-underscore emphasis, and Markdown links; bare URLs and identifiers remain valid. An explanation containing “exactly” does not authorize raw output. Explicit output noun phrases and quote or copy requests can authorize it; ambiguous requests cannot. The voice prompt uses the reply check's exact-output decision to select quotation or prose instructions before the model call. Prose instructions retain descriptions after source labels; quotation instructions retain the full source line, including bullets and emphasis. Exact quotations must match the source character for character, including indentation and whitespace. The service sends accepted exact output without trimming it. Exact output over 1,000 characters splits at a line, then a sentence, then a word, and the service drops whitespace-only pieces. Normal prose still uses paragraph bubbles. The same rules apply when a request spans lines or combines several messages. Only supported formatting continuations, such as “One per line.”, retain exact-output permission. Any other unconsumed or conflicting instruction selects the normal prose checks. Validated model-identity replies can retain the configured model name alone. All source-backed answers can use up to 2,000 characters so bare values can become useful sentences. Protected tokens include identifiers, paths, #numbers, versions, numbers with units, comparison operators, and links; their text and case must match. Source comparison normalizes configuration separators and paired inline Markdown delimiters; it never changes delivered characters. Rewrites retain standalone scalar values, configuration field values, and the contents of inline code exactly. Prose configuration replies must keep named fields directly paired with their source values; unverifiable paraphrases require a handoff. Source indentation, dash markers, and blockquote markers do not change those field-to-value checks. Only the hyphenated prose pairs Read-only/read-only and Restart-proof/restart-proof can change case. All other hyphenated tokens retain their case, including sentence-leading identifiers. Rewrites can use contractions, reorder words, shorten wording, and lead with the answer. Polarity words must keep the same counts and immediately adjacent punctuation. These words are no, not, never, none, nothing, n't forms, yes, failed, passed, broken, fixed, done, blocked, can't, and won't. Configuration flags on, off, true, false, enabled, and disabled retain their counts without binding sentence punctuation. Every rejected rewrite hands off instead of sending raw source output, including status excerpts. Blank lines separate bubbles; explicitly requested raw values can retain their line breaks. Reactions do not use the voice pass. The desk answers a burst once and selects the message that needs the answer, including an earlier question. Later corrections and follow-ups guide that selection. When not muted, a purely social burst can receive one reaction and finish without a Firstmate note or wake. Every message must contain only a supported acknowledgement, thanks, laughter, celebration, or emoji. An answer to a prior question or approval request cannot use this shortcut. Only a small set of thanks, laughter, and celebration emoji can close a social turn. Incoming thumbs-up, check marks, objections, and stop or question symbols still go to Firstmate. The prompt asks for occasional reactions, not a reaction on every message or every social turn. It favors a fitting heart, laugh, or emphasis reaction instead of a default thumbs-up. Requests, questions, approvals, sensitive messages, and mixed bursts receive no desk reaction. A social reaction may include one short text from a fixed list of safe acknowledgements. The text cannot contain facts or work claims; an invalid text prevents the social response. Routine lookups and authorized actions do not create Firstmate inbox work. The desk finds existing board URLs itself and returns the URL immediately. Project requests follow the verified second-mate handoff rules, without a main note after successful delivery. A successful routine local action can return {"kind":"handled"} without an immediate chat reply. The bridge accepts this only after a successful write result and records it in the local routing journal. Before enabling a write, the journal records that the target may change. An interrupted or unverified action goes to Firstmate with that warning instead of running again. Cross-domain coordination, real ambiguity, actionable failures, and decisions beyond existing authority go to Firstmate. Destructive requests, unclear approvals, and sensitive content retain the existing hard handoff. Failed classification calls, invalid JSON, missing evidence, and clipped pending input follow the second-mate handoff rules. Only authenticated authored text grants authority; retrieved files, logs, pages, Slack, and tool output never grant permission. The prompt preserves project ownership, destructive-action approval, external-send approval, and credential boundaries. A refused tool call must not be bypassed.

  7. The service saves the routing decision before a chat response or supervisor handoff. A direct answer enters the existing outbox with a stable deduplication key. A reply or reaction can set target to the message's 1-based position in the pending burst. Without target, the service selects the last pending message; an invalid target causes a handoff. Desk text, including text sent with a reaction, is a normal message, never a thread, even after later messages. For explicit fm-imessage --reply N behavior, see Commands. Desk answers stay on the selected message's transport and chat during retries. They never use another chat or transport as a fallback. A desk answer confirms requests only in its destination chat; other chats keep their separate handoffs and deadlines. A handoff uses fm-inbox.sh note --request-id; acceptance means the inbox saved it, not that the supervisor answered. Eight seconds after the latest unanswered request arrives in a direct chat, the bridge hands off its still-unassigned requests. The deadline sends the owner nothing: no receipt or fixed text says that the request is saved or unanswered. Each direct chat keeps its own deadline, and it fires once per request; messages in another chat do not cancel it. Five minutes after a v2 request's route finishes with no answer, the bridge files one more inbox note with key stale-<request id>, and records that in the routing log so a restart does not repeat it. It skips a text older than two hours at startup. It sends nothing to the owner. A deadline does not count as global Firstmate activity. Active mate delivery does not block a due deadline; typing stays on until the real answer goes out. A prompt answer leaves nothing to hand off; typing alone does not. A queued supervisor response ends the wait only after the transport accepts that response. An explicit --reply N confirms only its selected message and that message's current edit requests, even with --no-thread. A send without --reply confirms only the owner texts that arrived before it was queued. A secondmate's text and a tapback confirm none. Each queued response stores its covered request ids; later arrivals cannot become covered through equal timestamps. The deadline applies to the latest unanswered request, even when a newer request already has a targeted answer. An accepted initial card counts as a response, like an accepted text. Restart replay confirms an initial card from its saved acceptance; a later card edit does not confirm newer requests. A checked desk answer already in the outbox keeps its place at the deadline. Purely social bursts and muted chats have no deadline handoff. Inbox failures retry from the durable journal; each inbox command has a five-second deadline. Named keep: synchronous inbox filing remains serial; two stalled commands can block the event loop for about ten seconds. This can delay the deadline and typing cleanup beyond eight seconds; their timers resume when filing returns. The five-second limit applies to each command, not the entire batch. The local regression test checks the eventual handoff after two command timeouts, typing staying on through it, and typing ending with the real answer. Firstmate activity cancels a draft and hands pending requests to Firstmate. A new owner text or Firstmate activity also stops the remaining bubbles of a queued desk answer. The service records already sent bubbles in memory and completes the cancelled answer without sending the remaining bubbles. Startup drops restored model answers that have unsent text bubbles and hands their requests to Firstmate, without waiting for inbound catch-up. Firstmate and service sends keep their durable recovery. Each transport checks cancellation after preparation and immediately before sending. Cancellation does not remove uncertain delivery records. For a live desk answer with an uncertain send, the service checks available transport history before cancellation. It keeps unresolved evidence in the completion receipt. Unavailable history cannot block later supervisor sends after cancellation. A history check that disproves delivery clears the uncertainty before the service decides whether to hand off.

Neither transport reports typing events from the owner, so only a new text starts the wait again.

When the owner edits a text on the Photon line, the service files [edited] <new text> (was: <old text>). The note wakes Firstmate. Edits of known messages keep the original chat reference, even when the raw event uses a different chat identifier. The service keeps his last 100 texts in memory for the old text. If it does not know the old text, the note says so. This can happen when the text came before the last restart. spectrum-ts does not pass edits on, so the service reads them from its own event stream on the line's client. An edit that the owner makes while that stream is down is lost. The BlueBubbles line does not report edits: an edit there files no note.

The classification runner has a 45-second process timeout, but the unanswered-response deadline can cancel it sooner. The voice pass uses the same desk model, no tools, and a separate five-second timeout. It disables omp reasoning and uses Inception's instant reasoning level. New messages and Firstmate activity cancel this pass through the same path as classification. The voice call receives the original question and checked draft, not chat history or unvalidated fleet status. The durable status reader has a separate 5-second timeout; a timeout causes a handoff. A completed desk turn records its outcome in the private desk.log, including handled and successful tool-call ids. The log also records read completion, typing start and stop, model start and result, inbox acceptance, and transport acceptance. These events contain timestamps and message ids, not model output or credentials. Typing events retain the originating message id when a newer message arrives before the transport operation completes. transport-accepted records successful transport completion before delivery-progress or response-confirmation writes. response-confirmed records routing confirmation and can repeat during recovery without another send. history-reconciled records a delivery found in transport history, not a new send. card-update-accepted records an accepted card edit separately from initial card delivery. Transport acceptance is not proof of user-visible delivery; verify the receiving device for live delivery checks.

For a standalone text, both desks accept classification answers only from one complete JSON object whose kind or decision is reply. The answer must be a non-empty string with no directive. iMessage checks the existing source evidence before passing that answer to the voice call. An action can occupy the whole trimmed output, any JSON kind or decision field, or the final line after prose. Recognized actions are REACT:<emoji>, TAPBACK:<emoji>, SKIP, HANDOFF, and the verified iMessage HANDLED result. A JSON tapback uses {"kind":"tapback","emoji":"👍"}. An action never sends the surrounding prose. A JSON iMessage tapback may include text, for example {"kind":"tapback","emoji":"❤️","text":"nice!"}. The allowed text is thanks, thank you, you're welcome, anytime, haha, nice, congrats, or love it. Capitalization may vary, and one final period or exclamation mark is allowed. Only a verified social burst can use this text, which shares the reaction's target and durable outbox item. The Instagram desk ignores this optional text. The parser validates the complete emoji; quotes, braces, and extra characters cannot become part of it. Repeated matching decision fields produce one action, while conflicts produce no direct model response. All other classification output, including plain prose, mixed prose and JSON, and malformed JSON, produces no direct model response. Each rejected draft records one short outcome without raw model text. Suppressed drafts and rejected non-social reactions retain the existing single request filing, without an extra operator request. Social reactions retain all original messages and the completion decision in the routing journal, without filing a request. Photon, BlueBubbles, and the Instagram desk share this parser.

The service replays unfinished routing after a restart. Completed routing records suppress repeated transport delivery. Keyed outbox receipts in outbox-done/ prevent a decided answer from entering the outbox twice after a crash. The journal stores response confirmations separately from routing completion. The outbox saves accepted bubble and reaction progress before recording response confirmation. If a routing-journal write or sync fails, retries confirm that saved progress without sending it again. Transport acceptance stops the desk's typing indicator before those writes. Restart recovery schedules the deadline for unresolved requests with saved receipt timestamps, regardless of their age. If no response bubble was delivered and the desk response is definitely undeliverable, the saved burst ids cause one stable-id Firstmate handoff. Dead-letter receipts recover that handoff if the bridge stops before its failure callback completes. A prior uncertain send or reaction blocks this failure handoff, except when startup drops restored desk text as described above. The outbox saves possible reaction delivery after all lookups, health checks, and capability checks, immediately before the mutation. It retains that state across retries and restarts. Read-only preparation does not add delivery uncertainty. It does not clear uncertainty from an earlier reaction attempt. For a combined social response, the service saves text delivery before attempting the reaction. Reaction retries and restarts do not repeat the text or hand it to Firstmate after delivery. Text deliveries use a stable outbox identity in memory, so restart recovery records each delivered reply once. This also recovers a reply when the bridge stops after saving delivery progress but before recording memory. Keep the journal, receipts, memory, downloads, and pending outbox together during backups or migration.

The basic-answer system prompt is deskPrompt in apps/imessage/desk.ts. The owner's name and the two model names come from the config.

The service ignores texts from all other senders. It saves attachments in ~/.local/state/fm-imessage/attachments/ for Firstmate to open. That directory is private to the account (mode 0700). The service also keeps the owner's latest text on each transport, with the time of the message (its own timestamp, or the time received when it has none), in ~/.local/state/fm-imessage/latest (and latest-<transport>). After a restart, typing and command tapbacks target the newest saved text. A file from before the time was kept counts as the oldest. The service replaces latest-message files atomically, including the direct-chat destinations described in Choose the transports.

Second-mate handoffs

The desk reads $FM_HOME/data/secondmates.md at runtime. Second-mate routing stays off when this file is missing, unreadable, empty, or contains an invalid entry. Single-home installs keep their existing behavior. Each entry uses the existing registry format:

- web-mate - Website owner (home: /srv/website-home; scope: Website pages and browser layout; projects: website; added 2026-10-23)

Each mate needs a unique id, an absolute home path, and a non-empty scope. The desk can make a separate model call to select a handoff target from these ids or firstmate. A failed or rejected basic-answer draft can still reach this call. Failed status reads or clipped handoff input go directly to Firstmate. The desk sends work to a mate only when the model reports high confidence and exactly one matching domain. It checks the whole pending burst, including recent context, rather than splitting related texts across mates. Invalid output, low confidence, ambiguous requests, and work across several domains go to Firstmate. Decisions, approvals, merges, destructive actions, external sends, credentials, and sensitive messages also stay with Firstmate. Before the desk sends a text to a mate, it looks in the newest 200 records of state/<mate>.inbox (open and handled/). A record with the line [desk request <request id>] counts as delivered, so the desk sends nothing and writes no note. Identical texts from different requests do not match. After a failed send, the desk writes one "may be incomplete" note for each message id, not one for each retry. Attachments, group chats, edits, and unsupported desk models keep their existing Firstmate handoff.

The sender is fm-send.sh, beside the resolved fm-inbox.sh executable, including an FM_INBOX_CMD override. The service sets FM_HOME to the main home that owns the second mates as tasks and holds the routing table. It passes the mate id and [from captain via desk] <verbatim text> followed by a final line [desk request <request id>] as separate arguments, without a shell. The sender uses the mate's existing inbox and normal acknowledgement recovery. The desk checks the registered id, home, and complete scope before each send. A missing or changed entry sends the remaining texts to Firstmate.

A successful delivery records routed to <mate-id> in the local journal and completes without a main inbox note. A failed sender, missing command, or five-second delivery timeout hands the request to Firstmate. The journal saves delivery uncertainty before calling the sender. The existing sender retains acknowledgement tracking; recovery never blindly repeats an uncertain send. A failed or interrupted send retains a warning so Firstmate checks the mate's inbox before sending again. The sender runs asynchronously, so inbound messages and Firstmate commands remain responsive during delivery. New owner text, Firstmate activity, and shutdown cancel the active sender and stop the remaining sends in that burst. Inbox retries and service restarts never repeat a recorded mate delivery.

Firstmate activity still cancels an unfinished routing decision and sends pending work to Firstmate. Direct short answers and social reactions stay unchanged, including evidence-backed questions about approval counts when a registry exists. Delayed handoffs follow the deadline rules.

Relay notices

When the desk relays text to a second mate, the bridge sends the owner one short iMessage that names the mate and gives a one-line summary of what was sent. The code is relayNotice in apps/imessage/relay.ts.

V2 front desk

Set crewship.imessage.desk_v2: true in .local/host.yml to select the V2 front desk. The setting defaults to false; omit it or set it to false to keep the legacy loop for rollback. The service renders this setting as FM_IMESSAGE_DESK_V2=true or false. With the default desk_session: true, the desk runs as one long omp session instead of the loop below. See Desk session. The code is apps/imessage/front.ts, dispatch-policy.ts, and subagent.ts. Deployment and a one-week trial require separate authorization. The front picks one of four results: social, status, dispatch, or relay. A purely social text gets one tapback and no text. Status answers a question about what the mates are doing. The desk reads the inbox status and each mate's last line from state/<mate>.status, and answers in one tool-free call, without the routing reply. It hands the text to Firstmate when the request is a decision, approval, money, deploy, public post or write, when the status text does not answer it, or when the call fails. Dispatch runs a subagent, and its reply goes out as written, threaded to the message it answers. Relay hands the work to the owning mate or to Firstmate. An invalid front answer fails closed to a Firstmate relay. Before relay or dispatch work starts, the desk sends no fixed receipt. The one exception is a front model timeout: the desk then sends one short honest line at once, once for each burst of texts in a chat, and the next desk reply in that chat starts a new burst. The 150-second turn limit and the desk-tasks/ sweep stay as backup. The typing indicator stays on until the real answer goes out. The typing indicator stops when a newer text replaces the running job.

Token log

Every desk and compaction call appends one line to tokens.jsonl in the state directory: {ts, kind, model, input_tokens, output_tokens}, with the counts the provider returned. kind is front, status, desk, desk-session, voice, or compaction. tokens-daily.log holds one line per day with the call count and the token totals. A call whose provider returns no counts adds no line. A failed write is logged and never fails the call.

Desk session

With desk_v2: true, the desk is one long omp session by default. Set crewship.imessage.desk_session: false to roll back to the one-shot V2 loop above. The setting has no effect without desk_v2. The service renders this setting as FM_IMESSAGE_DESK_SESSION=true or false. The code is apps/imessage/desk-session.ts, desk-session-turn.ts, desk-actions.ts, desk-delegate.ts, and desk-helper.ts.

If the missed chat since the last session turn is longer than 8,000 characters, the session gets the newest lines and drops the oldest.

Background tasks

The desk can answer the owner at once while the work goes on in the background. The session calls delegate_task with the target helper:install, helper:lookup, helper:read-link, firstmate or the id of one mate in data/secondmates.md, and with no text: the model writes none. The bridge records the owner's texts as answered at once, sends the owner "Your text is queued for Firstmate" or "Your text is queued for <mate>: <summary>" (the relay notice form), and then starts one background job. The ack never says that a send happened, and a new owner text during the send cannot start the same task again.

Helper

The desk handles a simple, self-contained ask itself: install a skill or tool, look something up, read a link. The desk model classifies each work ask as install, lookup, read-link or other. Only those three kinds go to a helper; the session calls delegate_task with the target helper:install, helper:lookup or helper:read-link and no text. Any other ask, including one that sends, posts, emails, replies, pays or deploys, goes to Firstmate. The bridge texts the owner at once that the text is queued.

The smoke command stays the same: run it with FM_DESK_SMOKE_STRICT=1.

Pane prompts and scripts

The desk can unblock a supervisor session that waits on a selection prompt, it can run an operator script, and it can write or send one file. The code is apps/imessage/desk-pane.ts, desk-scripts.ts, desk-deny.ts, desk-files.ts, desk-claim.ts and the opsTools function in desk-actions.ts.

Herdr status alerts

The bridge can text the owner when a worker agent changes status, so the agents do not need to report it themselves. It is off by default. Set crewship.imessage.herdr_alerts: true in .local/host.yml to turn it on. The service renders this setting as FM_IMESSAGE_HERDR_ALERTS=true or false. The code is apps/imessage/herdr-watch.ts. It runs only herdr agent list, which only reads status.

Every poll compares each worker pane with its last confirmed status. A new status counts only when it holds for the debounce time, so a status that flips back is ignored. One poll sends one text, with one sentence for each confirmed change. The sentence names the project and the task and has no pane id. The first poll only records the starting statuses. Supervisor panes are skipped: a pane with a who token, or one whose project folder is in the skip list. When a pane closes while a new status is held but not yet confirmed, the bridge sends the alert for that held status once, if the status is in the alert list.

Variable Default Meaning
FM_IMESSAGE_HERDR_ALERTS false true turns the alerts on; crewship.imessage.herdr_alerts sets it.
FM_IMESSAGE_HERDR_STATUSES done,blocked,idle The new statuses that send an alert. blocked means the agent needs input.
FM_IMESSAGE_HERDR_POLL_MS 15000 Time between polls.
FM_IMESSAGE_HERDR_DEBOUNCE_MS 20000 A new status must hold this long.
FM_IMESSAGE_HERDR_SKIP firstmate Project folders that are not workers.
FM_IMESSAGE_HERDR_BIN herdr The herdr executable.

Stuck supervisors

The bridge watches the sessions it feeds: the main session and each second mate. The code is apps/imessage/stuck-watch.ts. It is on by default and runs inside the bridge, beside the self-healing watchdog. Set FM_IMESSAGE_STUCK_MS=0 to turn it off. It runs herdr agent list and herdr pane read, which only read, and it needs the same herdr as the status alerts above.

A session counts as stuck when either of these holds for FM_IMESSAGE_STUCK_MS (default 15 minutes):

Each incident goes through these steps, once:

  1. Bump (unread notes only). The bridge files one inbox note marked [desk stuck-check]. For the main session it uses fm-inbox.sh note. For a mate it uses fm-send.sh --fire-and-forget, which rings the doorbell and arms no reply wait. The bump is not counted as an unread note. A bump that fails is tried again on each poll until one goes through or the grace period ends.

  2. Text. If the session is still stuck FM_IMESSAGE_STUCK_GRACE_MS (default 5 minutes) after the bump, the owner gets one text. It names the session, the time it has been stuck since (UTC), the number of unread notes, whether the bump went through, and the last lines of the prompt when the pane shows one. Long token-like strings in the prompt text are hidden.

  3. Recovery. When the session has moved for two polls in a row, the owner gets one more text. A text that cannot be queued (no chat yet, or muted) is tried again on the next poll.

Rate limit. The bridge reads the newest 429 retry-after row from ~/.omp/stats.db (read-only). A session counts as limited when the last 5 lines of its screen show rate_limit_error or exceeds retry.maxDelayMs, and name no other model than the limit. While the limit is on, a limited session gets no bump and no text of its own. After 2 minutes the owner gets one text that names the model, the stopped sessions and the reset time in Pacific time. When the limit clears, each stopped session gets one ring and the owner gets one text. There is no second ring within 10 minutes or for the same 429. A session that is still stopped 15 minutes after the ring gets the usual stuck text. A missing or unreadable stats.db does not stop the watch.

The bridge never bumps a session that sits on a prompt, and it never types an answer to any prompt. The doorbell line goes into the pane, and a prompt can take it as its answer, so a keyword list for credentials, payments or public posts would not be safe enough. For a prompt the owner gets the text at once, after the limit, with the last lines of the prompt, and no bump goes out.

The check turns itself off with one log line when the herdr executable is not found.

The bridge keeps the incident state in stuck-watch.json in its state directory, so a restart does not repeat a text.

Variable Default Meaning
FM_IMESSAGE_STUCK_MS 900000 Time a session must be stuck before it is bumped. 0 turns the check off.
FM_IMESSAGE_STUCK_GRACE_MS 300000 Time after the bump before the owner is texted.
FM_IMESSAGE_STUCK_POLL_MS 60000 Time between polls.
FM_IMESSAGE_HERDR_BIN herdr The herdr executable, shared with the status alerts.

Guarded front modules

The repository also contains a separate front, worker, dispatch policy, and relay validator. The service uses front.ts from bridge.ts for the V2 loop; it does not call the other modules. These modules do not enable a deployment or replace transport, memory, outbox recovery, or the acknowledgement rules.

The caller still owns durable request identity, routing decisions, delivery, and memory. The caller must check current() again before committing a worker result. The front, dispatch, worker, and relay regressions cover these module boundaries.

Self-healing

The line repairs itself without polling or periodic texts, up to the slot's retry limit. The code is apps/imessage/selfheal.ts.

To test a fault on a copy, set STATE_DIRECTORY, HOME, FM_IMESSAGE_SEND=false and FM_IMESSAGE_ALERT_STATUS, then run bun selfheal.ts start.

Rolling deploys

An install never restarts the bridge in place: a new process needs about 100 s before it listens. A build with broken natives can start while systemd says active. bun ~/.local/bin/imessage-deploy.ts rolls out the build in <imessage dir>/stage/ beside the running one. The Ansible role runs it as its only upgrade step. The code is apps/imessage/deploy.ts, ownership.ts and standby.ts.

Run imessage-deploy.ts with FM_IMESSAGE_DIR set; exit 0 means the new slot serves the line, 1 means the new build was rolled back or failed. After exit 1 the old slot serves only if it was serving before the deploy.

Upstream outages

The Photon service can be unavailable for minutes. It then answers UNAVAILABLE (gRPC) or HTTP 502 or 503. The queue code is apps/imessage/outbox.ts. Desk cancellation and restart exceptions follow the routing recovery contract.

Permanent errors also move an item out of the queue. These errors include missing or expired messages and attachments (HTTP 404 or 410, gRPC NOT_FOUND). They include invalid items (HTTP 400 or 422, gRPC INVALID_ARGUMENT) and files that do not parse. The service moves the file to ~/.local/state/fm-imessage/outbox-dead/ (for a download: downloads-dead/). It writes one log line and continues with the next item. Nothing is dropped without a trace. Retry only unkeyed items by moving their files back to the queue directory under new sequence numbers. Never requeue a direct desk answer by hand; follow the routing recovery contract. Delete an unkeyed item's file to drop it by hand. Keep keyed receipts with the journal as routing recovery requires. An error that can be systemic (for example HTTP 429 or 500, or PERMISSION_DENIED) holds its lane in order while it retries. The log shows each try. FM_IMESSAGE_RETRY_MS sets the first wait in milliseconds (default 1000); the longest wait is 60 times that value.

Desk memory

The desk remembers the whole conversation, after the design in UniiChat: one chat that never ends. The code is apps/imessage/memory.ts.

The memory, routing journal, desk session, background tasks, and sender record hold owner texts on the host in private state. Deleting only memory/ does not erase this history; routing recovery restores missing inbound records. For complete erasure, first finish every pending routing request, download, and outbox delivery. Then stop the bridge through the normal service procedure. Remove memory/, routing.jsonl, thread-senders.sqlite, senders.json, desk-session/, desk-session.seen, and desk-tasks/ together. Also remove completed outbox receipts in outbox-done/ and outbox-dead/. This also clears local routing deduplication, so retain transport seen records and do not replay old message history. Never erase these files while requests or uncertain sends still need recovery.

A memory error does not stop an outgoing send, a tapback, or a supervisor handoff. The service logs the error. An inbound memory-write failure hands the durable routing record to Firstmate instead of attempting a basic answer. At start, the service skips a memory log line that does not parse.

Instagram front desk

The Instagram desk uses the same decision parser, not the iMessage routing rules. instagram-desk.service runs apps/imessage/instagram-desk.ts and reuses the memory, runner, input budget, and timing helpers. Its channel-specific prompt does not use iMessage direct routing. It has no Instagram client. It follows two logs of the instagram-dm listener:

When the quiet period ends without a Firstmate action, the desk handles the whole burst in one turn. The service sends only the selected action or answer with fm-insta-reply --thread ID and INSTAGRAM_DM_ACTOR=desk. A desk reply does not stop the next desk turn. A new DM or Firstmate action cancels a draft before delivery. If the call fails or exceeds 45 seconds, the desk sends nothing; Firstmate already has the note. A burst with two or more different reel links gets no model call. After the long quiet, the service sends got N reels and one eyes tapback in one fm-insta-reply call. The log records batch got N reels for that batch.

The Instagram thread keeps its memory in ~/.local/state/instagram-desk/memory/; see Desk memory. The private ~/.local/state/instagram-desk/desk.log stores the time, message ID, and a short outcome without raw model text. Each model turn records reply, skip, handoff, react <emoji>, or skip (desk failed). The service saves its position in each log. After a restart, only rows from the last 60 seconds can trigger a desk turn. Older rows fill the memory but do not trigger replies. With no saved position, the service starts at the end of both logs. The desk does not show a typing indicator.

Set crewship_instagram_dm_operator, and the playbook installs the unit with the listener. The settings are the crewship_instagram_desk_* variables in blueprint/ansible/group_vars/all/instagram_dm.yml: model (default claude-haiku-5-5), owner_name, supervisor_model, quiet_ms, and reel_quiet_ms.

Set up the Photon project

Skip this section when transports is [bluebubbles].

  1. Sign in to the Photon dashboard and create a project with the iMessage provider. The free plan gives a shared line.

  2. In the project settings, copy the project ID and the project secret.

  3. Add them to the host's secret store, ~/super.env, as these two lines:

    PHOTON_PROJECT_ID=...
    PHOTON_PROJECT_SECRET=...
    

    Edit super.env on the primary VPS, push it, and fetch it on the host, as Shared credentials describes. On a host without the shared store, add the lines to ~/super.env directly and keep the file at mode 600. A later fetch replaces that file.

See Enable it for credential loading and shell requirements.

Use self-hosted BlueBubbles relays

A relay is a Mac that runs BlueBubbles server and is signed in to Messages. It costs nothing per month and does not depend on an outside messaging service. You can run the same Apple Account on several Macs: the bridge uses them as one line, in the order of the config.

Set up a relay

  1. Make an Apple Account for the line. An account with only an email address and no phone number works: the owner texts that email address, and imessage.owner stays his own phone number.

  2. On each Mac, sign in to Messages with that account. Download BlueBubbles server and copy the app into Applications, but do not open it or enable automatic start. Copy this repository onto the Mac.

  3. Disconnect the Mac from all networks, then run this command from the repository:

    bash apps/imessage/bluebubbles-relay prepare
    

    The command creates bluebubbles.yml in the account's home directory with a random password and proxy_service: "lan-url" (all tunnels off). It refuses to overwrite an existing file or continue while BlueBubbles or a tunnel runs. A fresh server otherwise starts its default public Cloudflare tunnel before you can set the password. BlueBubbles reads this file before startup. persist-config: false applies the settings synchronously, before services start. Do not create config.db yourself: an existing database disables initial schema creation. Keep the file for every launch; its settings override the UI settings. Protect the file and the server logs: BlueBubbles logs configuration values, including the password.

  4. Open BlueBubbles while the Mac remains disconnected. Give it Full Disk Access and Accessibility permission. Keep Proxy Setup on LAN URL during its setup. Read the password from bluebubbles.yml, then run this one-command check and enter the password at its hidden prompt:

    bash apps/imessage/bluebubbles-relay check
    

    The check requires no cloudflared, ngrok, or zrok process. It requires HTTP 401 without a password and with a wrong password, then HTTP 200 with the password. A failed check exits with a clear error; quit BlueBubbles and keep the Mac disconnected until you fix the cause. Do not continue until the check passes.

  5. Limit port 1234 to the agent host with the Mac's firewall or your private network before reconnecting the Mac. Do not configure port forwarding or select Cloudflare, ngrok, or zrok. Run the same check after reconnecting and after every server update.

  6. Enable the BlueBubbles Private API if you want typing bubbles, tapbacks, threaded replies, and read receipts. Plain texts and attachments work without it. The Private API needs System Integrity Protection partly off; read the BlueBubbles docs first.

  7. On each relay, register a webhook to http://<webhook_listen>/bluebubbles with the "New Messages" event. Use the server's API and Webhooks settings or POST /api/v1/webhook. Without a webhook on that relay, inbound messages wait for the bridge's per-minute catch-up.

  8. Make sure that the Mac does not sleep. Enable automatic start only after the safety check passes.

Add each password to ~/super.env as Shared credentials describes, for example BLUEBUBBLES_PASSWORD=.... The host config names the variable, never the password.

Choose the transports

First enable the bridge. Then add transports and the bluebubbles block to the imessage block in .local/host.yml, and run ./ship.sh launch:

    transports: [photon, bluebubbles]   # in order; [bluebubbles] uses the relays alone
    bluebubbles:
      relays:                      # in failover order
        - url: http://<relay-1>:1234
        - url: http://<relay-2>:1234
          password_env: RELAY_2_PASSWORD   # optional; the default is BLUEBUBBLES_PASSWORD
      webhook_listen: <agent host address>:8766   # where the relays post their webhooks

Use an address that only the configured relays can reach for webhook_listen, such as the agent host's private network address. The bridge trusts the webhook's tempGuid for sender attribution because the authenticated message lookup does not verify that association. Do not use the standby port (FM_IMESSAGE_NEXT_PORT, 8766 by default) on a wildcard or loopback address. The standby slot cannot bind that port while the live slot holds the webhook, so deployment fails. To use Photon alone again, remove transports and the bluebubbles block.

The bridge uses these routing rules with one or both transports:

How the relay set behaves

Enable it

The iMessage bridge and optional card tunnel use /bin/sh to source ~/super.env and export its assignments before starting. Use POSIX shell assignments, including export KEY=value, and quote values that contain spaces. Neither service passes this file to systemd's EnvironmentFile parser. Only source trusted content: shell commands in this file run as the service user. The credentials never go into the repository, the unit, or .local/host.yml.

Add this block to .local/host.yml, then run ./ship.sh launch. The firstmate profile must be on.

crewship:
  imessage:
    owner: "+<country code><number>"  # the owner's phone number, E.164 form
    owner_name: the owner           # optional; this is the default; how the desk prompt names him
    desk_provider: omp              # optional; this is the default; or inception
    desk_model: claude-haiku-5-5    # optional; this is the default; mercury-3 with inception
    desk_reasoning: "off"           # optional; this is the default; the omp thinking level or Inception reasoning effort
    desk_v2: false                  # optional; select the V2 loop with true
    desk_session: true              # optional; this is the default; with desk_v2, false keeps the one-shot V2 loop
    herdr_alerts: false             # optional; true alerts you from herdr agent status
    supervisor_model: ""            # optional; the model that runs Firstmate

See What it does for model-identity evidence and handoff rules.

Apply installs these items:

The service listens on 127.0.0.1:8765. To use a different port, set FM_IMESSAGE_PORT in a drop-in of the slot unit (systemctl --user edit fm-imessage@.service) and in the environment of the commands, including imessage-deploy.ts, which reads the port only from its own environment. FM_INBOX_CMD overrides the inbox command, which is <workspace>/firstmate/bin/fm-inbox.sh by default.

The service is for the host's own commands (fm-imessage, fm-location) only. Except during shutdown, it checks the header X-Firstmate: 1 and requires Host to be exactly 127.0.0.1:<port> before looking at the path. It answers 403 if either check fails. A web page open in a browser on the host cannot set a custom header without a CORS preflight, which the service never answers. The Host check stops DNS rebinding. So a page cannot send messages as Firstmate or read the location. If you call the service with your own curl, add -H "X-Firstmate: 1".

On SIGTERM or SIGINT, the bridge refuses new work and sends SIGTERM to its running desk, compaction, and inbox-status children. During shutdown, the command endpoint and BlueBubbles webhook answer 503 before other request checks. The bridge waits up to two seconds, then sends SIGKILL to children that remain. It waits up to another 500 ms for those children to exit, then exits with status 0. The unit sets KillMode=mixed and TimeoutStopSec=10 so systemd kills remaining service processes if shutdown stalls. See Desk memory for compaction recovery after a restart.

Install and upgrade only through Rolling deploys: imessage-deploy.ts is the one install path, so a bare systemctl --user restart fm-imessage is not an upgrade. After an update, check the installed slot with GET /health and one fm-imessage text to a test chat; use isolated transport fixtures and synthetic owner messages, never a real recipient.

To turn it off, remove the block, then run systemctl --user disable --now fm-imessage (the front unit stops the slots) and delete the units.

Commands

Command What it does
fm-imessage 'text' Queues a plain message using the proactive routing rules, even when his latest text is a thread reply. Without an argument, it reads the text from stdin. Paragraphs that a blank line separates become separate chat bubbles. The lines of one paragraph, for example a list or a schedule, stay in one bubble while it has 1,000 characters or fewer; a longer paragraph splits at a line, then a sentence, then a word, so that iMessage never cuts a bubble short. Before each bubble after the first, the typing bubble shows for 400 ms plus 25 ms for each character, 2.5 seconds at most.
fm-imessage --reply N 'text' Targets the owner's Nth most recent text (1 is the latest). The first bubble always threads to the target, even when it is the last bubble in its chat. A transport that cannot thread sends plain. The command picks the target when it runs, and the queued message keeps that target's id through retries and restarts. The service keeps at most 10 texts received since it started that were the newest text at that time. A text that arrives late (see Inbound) is not kept. If the Nth text is not kept, nothing is queued and the command exits non-zero. Any other value of N queues nothing and exits with code 2.
fm-imessage --reply-id ID 'text' Threads to the kept text with that exact message id, or the inbox request id <line>-<id> (for example photon-<id>), as --reply N does for position N. A newer text cannot move the target. --reply and --reply-id together are refused with code 2. An id that is not among the kept texts queues nothing and the command exits non-zero with the error. The routing log records the chosen id as a replyTarget row.
fm-imessage --no-thread 'text' Forces a plain send, even with --reply N, regardless of option order.
fm-imessage --key TOPIC 'text' Logs the text under a topic key. The same key with the same content on the same local day is skipped: nothing is queued and the command exits 0 with a skipped message. A second mate pushes a text to the owner with FM_HOME=<mate home> fm-imessage --key TOPIC 'text'; the sender log (sent.jsonl in the state directory) holds key, sender, content hash and time for every text sent by a mate, the desk or Firstmate. Unkeyed texts are logged and never skipped. A (repost) marker and spacing do not make a text new. With --image, the caption is logged and deduped; the photo is not.
fm-imessage --image PATH ['caption'] Queues a photo (png, jpg or webp), then the caption as text bubbles. See Send a photo. --reply N, --reply-id ID and --no-thread act on the photo as they act on the first bubble of a text.
fm-imessage --typing Shows the typing bubble on a best-effort basis. See the typing lifecycle for expiry and cleanup.
fm-imessage --react '👍' Queues a tapback in the outbox, in order with the sends. The tapback goes on the text that was his latest when the command ran.
fm-imessage --card '<json>' Queues a card: a link to a page with options to tap, a chart, a timeline, or a table. The argument is the card JSON, - for stdin, or a file. See Cards.
fm-imessage --help Shows the usage. It queues nothing.
fm-desk Lists the newest 20 turns of the desk session (local time, kind, first words), then asks which to open. fm-desk N opens turn N (1 is the newest); -n COUNT sets the list length. omp has no read-only viewer, so the command opens a temporary copy of the session file, cut after the chosen turn, with tools off; the session file is only read.
fm-desk --follow Waits for the next desk turn, then prints its session entries live as they are appended (time, role, text; tool calls and results as one-liners) and exits when the turn's final assistant message arrives (stopReason other than toolUse) and nothing follows within FM_DESK_GRACE seconds (default 10, so a retry reminder keeps the follow going), or, if none appears, once the file has been quiet for FM_DESK_SETTLE seconds (default 60). fm-desk --loop then waits for the next turn again. omp is not started and the session file is only read.
fm-location Prints the location that the owner shares with the line in Find My, as JSON.
fm-location --check Prints one line, ok, age <N> s, accuracy <M> m, and no coordinates. Use it to prove a read works. On failure both forms print one line to stderr (fm-location: HTTP <code>: ...) and exit 1.
fm-call --class prod|money|deadline|asked [--incident ID] 'reason' Rings the owner through Twilio when a text is not enough; fm-call --help shows the rules. When the ring ends unanswered (no-answer, busy, canceled, failed, or answered by voicemail or fax), it sends one Bark page per incident with level=critical, which breaks through silent mode on iPhone. An answered call sends no page. Set BARK_DEVICE_KEY (the device key in the Bark app) in the environment or in ~/super.env. Without it the command warns on stderr and sends no page.

Use -- before text that starts with a dash: fm-imessage -- '- first item'. Place send options before --: fm-imessage --reply 1 --no-thread -- '- first item'. All arguments after -- are text, not options.

If a spectrum-ts upgrade changes access to the Photon client, the service logs a warning. Until the bridge is updated, fm-location returns HTTP 503 and the service does not see edits. Plain Photon sends still use the public SDK. Explicit threaded replies can use a configured fallback because the bridge cannot check the latest bubble.

fm-imessage exits 0 only when the message is on disk in the outbox, and prints that it is queued. It exits non-zero when it queues nothing. An unknown option queues nothing and exits with code 2.

Mute

To block new outgoing items, create ~/.local/state/fm-imessage/muted. STATE_DIRECTORY overrides the default state directory. While that file exists, the bridge queues no outgoing item. Items already in the outbox can still send. Firstmate sends, desk answers, cards, photos, voice memos, and tapbacks all stay out of the queue. Inbound texts still arrive, and their notes still reach Firstmate. The bridge refuses send, reaction, card, photo, and typing commands with HTTP 503 and nothing queued: muted. fm-imessage exits non-zero for these refused commands. The bridge also refuses a command if mute starts while it reads the request. When mute blocks a desk answer or tapback, the bridge stops typing and hands every request to Firstmate. The bridge keeps each request until the inbox accepts its note, including across a restart. The desk can still show typing while it classifies inbound text. Refused photo and card commands leave no new files behind. Remove the file to resume sending.

touch ~/.local/state/fm-imessage/muted
rm ~/.local/state/fm-imessage/muted

Send a photo

fm-imessage --image PATH ['caption'] sends one photo. The command gives the file to the service, which sends it with the spectrum-ts attachment path (attachment() in space.send). The caption is optional. Blank lines in it make separate bubbles, as in a text. The photo goes first, and the caption bubbles follow it.

Voice memos and audio

A voice memo or an audio attachment (.caf, .m4a, .amr, .mp3, .aac, .wav, .ogg, .opus, .flac, .aiff, or any audio/* type) is saved in ~/.local/state/fm-imessage/attachments/, then transcribed on the host. apps/imessage/transcribe.ts runs ffmpeg to make a 16 kHz mono wav, then whisperx on the CPU with int8. No API is called.

The note reads [voice memo, 4s] <words>, then (audio saved for Firstmate at <path>). The desk memory records the same text, so the desk sees the transcript. If the audio holds no speech, the words are (no speech heard). If ffmpeg or whisperx fails or times out, the service logs the error, and the note still has the path and says transcription failed. If the file cannot be saved, the download retries as for any attachment, and the retry transcribes it.

The inbound loop waits for the transcription, so the next inbound message waits too (about 15 s on a warm host, up to 45 s on a cold start). Sends are not held up.

Variable Default Meaning
FM_IMESSAGE_WHISPERX ~/.cache/watch/whisperx-venv/bin/whisperx The whisperx executable. The watch skill's venv has it.
FM_IMESSAGE_WHISPER_MODEL small The Whisper model name.
FM_IMESSAGE_TRANSCRIBE_MS 120000 The time limit for each of the two commands.

Cards

fm-imessage --card sends a card: by default, a Spectrum app bubble. A tap opens the card's page as a full-width sheet inside Messages, in Photon's free "Spectrum" iMessage app; the bridge serves the page. He installs that app once, from the App Store prompt in Messages. The code is apps/imessage/cards.ts.

fm-imessage --card '{"kind":"choice","key":"layout","title":"Board layout?",
  "options":["Short list, one screen","Cards with a mock each","Table with all details"]}'

Every card has kind, key (1 to 40 letters, digits, ., _ or -), and title (up to 120 characters). Optional fields: subtitle (up to 200 characters), hours until the card expires (1 to 168, default 24), app (default true; false sends a link in place of the app bubble; see below), and live (default false: a tap opens the full sheet; true asks for the app's live view, which draws the page inside the bubble at a narrow width that Messages sets and the page cannot change). The kinds:

Kind Fields The page shows
choice options: 2 to 6 texts One button per option, A to F. One tap picks.
bars bars: 1 to 30 {"label", "value"}, optional unit A bar chart. With "unit": "%" a bar fills its track at 100; with any other unit, at the largest value.
timeline items: 1 to 50 {"when", "text"} A vertical timeline.
table columns: 1 to 8 texts; rows: 1 to 100 rows of that length A table.
text lines: 1 to 60 texts of up to 200 characters The lines of fm-text-card: # x starts a section, - x is a bullet, k: v is a row, and other lines are plain rows.

A bad card queues nothing, and the command names the first bad field.

Publish the card pages

The bubble opens on his phone, so the page listener needs a public HTTPS address. Use a named Cloudflare tunnel, because a quick tunnel gets a new address at each restart, and the old cards stop working.

  1. In the Cloudflare account that holds the domain, make a remotely managed tunnel (for example, crewship-cards). Give it one public hostname, for example cards.example.com, to http://127.0.0.1:8767. The catch-all rule stays http_status:404.

  2. Make sure that the DNS record of that hostname is a proxied CNAME to <tunnel id>.cfargotunnel.com.

  3. Add the tunnel token to ~/super.env as CARDS_TUNNEL_TOKEN=..., as Shared credentials describes.

  4. Add the cards block to the imessage block in .local/host.yml, then run ./ship.sh launch:

        cards:
          url: https://cards.example.com   # the public hostname of the tunnel
          port: 8767                       # optional; this is the default
          tunnel_token_env: CARDS_TUNNEL_TOKEN   # optional; this is the default
    

Apply then installs cloudflared and the unit fm-cards-tunnel.service, which runs the tunnel with the token from ~/super.env, and sets the card variables in the bridge unit. The tunnel reaches only the page listener. To turn cards off, remove the block, run ./ship.sh launch, then run systemctl --user disable --now fm-cards-tunnel and delete its unit.

Web chat

The bridge can serve one page that shows this thread and sends typed text to Firstmate. Use it on a device that has a browser but no Messages app, for example XR glasses. The code is apps/imessage/webchat.ts.

Publish the web chat

The page can send text as the owner and has no sign-in of its own. Never expose its port directly. Publish it only with tailscale serve, or through an access gateway that enforces sign-in on public requests and forwards to this port. With tailscale serve, each device and user that the tailnet access rules let reach this host can read the thread and send text. The listener allows one outside name: host (FM_IMESSAGE_WEB_HOST). With an access gateway, set host to the public hostname of the gateway, or make the gateway forward Host and Origin as that name; any other name gets 403. One host name serves one route, so the tailnet name and a gateway name do not work together. The page uses relative links, so a gateway can serve it under a path prefix such as /chat/ (the prefix needs a trailing slash).

  1. Add the web block to the imessage block in .local/host.yml, then run ./ship.sh launch:

        web:
          host: agent.example.ts.net   # the hostname that tailscale serve or the access gateway publishes the page under
          port: 8768                   # optional; this is the default
    
  2. Publish the port with tailscale serve (skip this step when an access gateway publishes the page):

    tailscale serve --bg http://127.0.0.1:8768
    
  3. Open https://agent.example.ts.net/ on a device in the tailnet, or the gateway's public hostname.

If you publish on an HTTPS port other than 443 (tailscale serve --bg --https=8443 ...), add that port to host, for example agent.example.ts.net:8443. To turn the web chat off, run tailscale serve reset, remove the block, and run ./ship.sh launch.

Outbound text filter

fm-imessage cleans each text and photo caption before it sends (apps/imessage/clean.ts, run with bun). The bridge refuses a text that is only a PR link, and any paragraph that starts with a task or mate id, has key= or corr= tokens, or has two or more commit hashes after a colon (hex inside a URL does not count as a hash). It answers HTTP 422 and queues nothing. Sub-agent answers pass the same filter in subagent.ts. The filter removes [Dxxxx] decision tags, [key=...], key= and corr= tags, pr=, mode=, yolo=, head= and task= tokens, mate ids (<x>-mate-<y> always; cf-<word> and sm-<word> only in backticks or as a leading label:), absolute paths with two or more segments (/a/b) and ~/... paths, state/ and data/ paths that end in a file extension, a status prefix (working:, done:, needs-decision:, paused:) at the start of a line, and a child <id> working: style prefix (also done, failed, blocked, paused, needs-decision, with an optional supervisor: before it). A line that starts with "decision stuck after N attempts" is dropped whole; inline, only the phrase is removed. A bare colon at the start of a line is dropped, also when the text had one before; emoticons such as ":)" stay. "the owner" and "the captain" (also the owner's) become "you" ("your"). A bare "owner" or "captain", "the owner of", "the captain Smith", and owner.json stay. URLs stay as they are. Text with none of these stays byte-exact, except that a bare colon at the start of a line is still dropped. If nothing is left, the original is sent without a leading colon. The CLI looks for bun with command -v bun, then beside the fm-imessage script, then in ~/.local/bin and ~/.bun/bin, so the filter also runs under cron with a minimal PATH. Without bun, or if the filter fails, the CLI warns and sends the text unchanged.

STE check on desk replies

Before the bridge sends a desk reply, it checks the text with Vale and the style in apps/imessage/ste-vale/. The style flags dashes between clauses, contractions, semicolons, sentences over 25 words, and a short list of idioms. If the check fails, the bridge asks the front model (mercury-3) for one rewrite. It sends the rewrite when the rewrite has fewer violations. Otherwise it sends the original text. The check runs once for each reply, before the first bubble. Vale gets 3 s, the rewrite gets 12 s. A missing vale binary (FM_STE_VALE or PATH), a timeout, or an error sends the original text, so the check never blocks a send. Text with a code fence is not checked.

Plain messages and the shared line

See Commands for plain sends and explicit replies. On Photon's free shared line, plain sends into the owner's conversation work. A conversation that the service opens itself is refused ("Target not allowed for this project"). See Upstream outages for retries and permanent refusals. Before the owner sends the first text, the commands fail with HTTP 503.

Location is personal data

Every home on this host calls fm-location from ~/.local/bin; no key or setup is needed.

fm-location works only while the owner shares his location with the line in Find My. The location is personal data. Use it only when the work needs it. Keep it on the host: do not put it in a commit, an issue, a PR, a log, or a chat.