diff --git a/AGENTS.md b/AGENTS.md index 808c6feb..da3024e1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -87,9 +87,10 @@ change in both repos. section whose members are all elsewhere stays off (`SimpleBotsSectioning.elsewhere`). + in Bots mode is New Bot, New Group Chat and New Section, each only where it can work (`SimpleBotsNewItem`); the bot and group chat menus come from `SimpleBotsMenuAction`. - - First run (`FirstRunOnboardingView`) is Welcome, Connect, the optional plugin, notifications (only once the - plugin is in), then Choose your mode (`FirstRunMode`: Bots, Sessions, Code). Optional steps have a small Skip; - Connect and the mode don't. `FirstRunOnboarding.afterConnectKey` keeps it on screen after host setup's own + - First run (`FirstRunOnboardingView`) is Welcome (with an optional Appearance step behind Appearance options), + the AI data agreement if not given yet, Connect, the optional plugin, notifications (only once the plugin is + in), then Choose your mode (`FirstRunMode`: Bots, Chat for `.sessions`, Code). Optional steps have a small + Skip; Connect and the mode don't. `FirstRunOnboarding.afterConnectKey` keeps it on screen after host setup's own finish. The mode cards show screenshots (`OnboardingMode*` assets); retake them when those homes change. - While every host's data shows (all-hosts view or Multi-gateway), the other hosts stay connected (`keepsFleetHostsConnected`), through the background grace too, so opening on one is instant. diff --git a/Bighelp/Wiki/INTEGRATION.md b/Bighelp/Wiki/INTEGRATION.md index 1282b141..d05c7037 100644 --- a/Bighelp/Wiki/INTEGRATION.md +++ b/Bighelp/Wiki/INTEGRATION.md @@ -1,5 +1,20 @@ # Native Wiki integration API +> **Historical.** This page describes a Wiki provider for the retired Link transport. Link is gone. Chat and +> plugin features use native Hermes now (see [docs/NATIVE_TRANSPORT.md](../../docs/NATIVE_TRANSPORT.md)). Wiki +> is no longer a feature. +> +> - The bighelp plugin removed the wiki routes and no longer lists `native-wiki-v1` (bighelp-plugin README › +> Legacy code). Files that the routes saved stay on hosts, but nothing reads them. +> - The app has no Wiki screen. `WikiBrowserView`, `WikiConnectionView`, `WikiDocumentView` and +> `WikiSaveControls` are not in it. +> - Hermes tools leaves Wiki out (`WorkspaceDestination.appMenuCases`). +> - If someone sends a Wiki or GitHub reference in chat, the app says that these references are no longer +> available (`ReferenceChatComposition`). +> - What is left is inactive code: the models, store, drafts and persistence in `Bighelp/Wiki/`, the request +> codec (`WikiLinkClient`), `DirectHermesWikiClient` (the `wiki/*` plugin routes, behind `native-wiki-v1`) and +> the reference adapter in `Bighelp/References/`. + This is an optional, source-only native provider candidate. The parent owns composition, tests, review, project membership and execution. It has no fixture provider and no direct HTTP/dashboard-token path. ## Construction and ownership diff --git a/README.md b/README.md index 41fb6dea..80ed734d 100644 --- a/README.md +++ b/README.md @@ -112,10 +112,10 @@ xcodebuild test -project Bighelp.xcodeproj -scheme Bighelp \ | `BighelpMacUpdater/` | The Mac app's updates (Sparkle) | | `BighelpTests/`, `BighelpUITests/`, `BighelpVisionUITests/`, `BighelpWatchUITests/` | Tests | | `BighelpMac/`, `BighelpMacTests/` | An early desktop prototype on sample data. It is not the Mac app. | -| `services/` | Cloudflare Workers: the notification service and relay, usage and diagnostics, the template and avatar catalogs, and the provider logos | +| `services/` | Cloudflare Workers: the notification service, usage and diagnostics, the template and avatar catalogs, and the provider logos (plus the recovered source of an old relay, never deployed). See [docs/CLOUDFLARE_INFRASTRUCTURE.md](docs/CLOUDFLARE_INFRASTRUCTURE.md) | | `Scripts/` | Tests against real Hermes hosts, the Mac release, and other tools | | `Design/AvatarKit/` | Avatar artwork and the tools that export it | -| `docs/` | Contracts and deep dives | +| `docs/` | Contracts and deep dives. Start with [ARCHITECTURE.md](docs/ARCHITECTURE.md), [NATIVE_TRANSPORT.md](docs/NATIVE_TRANSPORT.md) and [DEVELOPMENT.md](docs/DEVELOPMENT.md) | [DESIGN.md](DESIGN.md) describes the look and feel. [AGENTS.md](AGENTS.md) is the guide for people and AI agents that work on the code. diff --git a/contracts/wiki-v1.md b/contracts/wiki-v1.md index a2ff3d18..98a5df4e 100644 --- a/contracts/wiki-v1.md +++ b/contracts/wiki-v1.md @@ -1,5 +1,20 @@ # Wiki v1 Link contract +> **Historical.** This contract is for the retired Link transport (`targetHostId`, `senderEpoch`, the `wiki.v1` +> capability). Link is gone. Chat and plugin features use native Hermes now (see +> [docs/NATIVE_TRANSPORT.md](../docs/NATIVE_TRANSPORT.md)). Wiki is no longer a feature. +> +> - The bighelp plugin removed the wiki routes and no longer lists `native-wiki-v1` (bighelp-plugin README › +> Legacy code). Files that the routes saved stay on hosts, but nothing reads them. +> - The app has no Wiki screen. `WikiBrowserView`, `WikiConnectionView`, `WikiDocumentView` and +> `WikiSaveControls` are not in it. +> - Hermes tools leaves Wiki out (`WorkspaceDestination.appMenuCases`). +> - If someone sends a Wiki or GitHub reference in chat, the app says that these references are no longer +> available (`ReferenceChatComposition`). +> - What is left is inactive code: the models, store, drafts and persistence in `Bighelp/Wiki/`, the request +> codec (`WikiLinkClient`), `DirectHermesWikiClient` (the `wiki/*` plugin routes, behind `native-wiki-v1`) and +> the reference adapter in `Bighelp/References/`. + Implementation contract for issue #135. User-approved Wiki/reference spec governs privacy, optionality and source fidelity. All operations are optional and advertised using existing negotiated capability string arrays (`wiki.v1`); no new unsolicited top-level response fields. Old hosts are unavailable for Wiki, not broken for chat. ## Authentication diff --git a/docs/ACCOUNT_CATALOG_COMPATIBILITY.md b/docs/ACCOUNT_CATALOG_COMPATIBILITY.md index 0b813f0a..efe34327 100644 --- a/docs/ACCOUNT_CATALOG_COMPATIBILITY.md +++ b/docs/ACCOUNT_CATALOG_COMPATIBILITY.md @@ -1,5 +1,11 @@ # Account catalog compatibility +> **Historical.** This page records a 2026 incident in the retired bighelp account's device catalog (Link +> transport, passkey sign-in, paired hosts). The app no longer has the account or Link: chat and plugin features +> run over native Hermes ([NATIVE_TRANSPORT.md](NATIVE_TRANSPORT.md)), and at launch the app removes the old Link +> keychain items and settings once (`BighelpLinkAccountRetirement`). The catalog code (`/v1/devices`) still lives +> in the notification service Worker (`services/link`, `link.loopdy.app`), but no current app build reads it. + ## September 10, 2026 incident After the build 13 Link deployment, an account with a persisted `native_host` diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index fe73636f..c695ca58 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -3,25 +3,27 @@ Production transport contract: **native Hermes only for chat**. Cloud services are used only for optional notifications and Live Activities, which BuzzKit delivers. The current composition, voice boundary, enrollment isolation and verification requirements are defined -in [Native transport](NATIVE_TRANSPORT.md). Historical Link/paired-Direct protocol -names remain in shared value types and migration boundaries. Their names do not -imply a selectable chat transport; the disabled iOS transport graph is removed. +in [Native transport](NATIVE_TRANSPORT.md). The retired Link transport (a bighelp +account, pairing and an encrypted relay) is gone. Some of its names remain in +shared value types and cleanup code (`Bighelp/Link/`, `BighelpLink…`). These +names do not select a chat transport. This document describes the current iOS codebase and its end-to-end interaction with an authorized Hermes host and bighelp's notification services. This document follows the implementation rather than older design proposals. -The [iPhone device-tools contract](IPHONE_DEVICE_TOOLS.md) describes the native -HealthKit (read only), EventKit and location service, the connect cards for tools that are off, -host-scoped permissions, authenticated Hermes tool -context, and negotiated directed Link frames. +The [iPhone device-tools contract](IPHONE_DEVICE_TOOLS.md) describes the phone's +tools (Apple Health read only, Calendar, Reminders, Location and the rest), the +connect cards for tools that are off, the one permission list for every host and +agent, and the plugin's `device-tools/{connect,poll,result,close}` routes that +carry the calls over the native connection. ## 1. System boundaries Native workspaces connect directly to an independently authenticated Hermes -host through its public interfaces. A bighelp account, Link pairing and the -notification relay are not required for that connection. The optional -Link and notification paths have their own authorization and trust boundaries. +host through its public interfaces. No bighelp account and no notification +service are needed for that connection. Notifications are optional and have +their own authorization and trust boundaries. bighelp has five important trust boundaries: @@ -34,8 +36,9 @@ bighelp has five important trust boundaries: 3. **The authorized Hermes host** authenticates native workspace access and owns agent execution and session state. Native host authority is independent of optional cloud account credentials and account deletion. -4. **The notification relay** manages APNs delivery material and sends encrypted - alert envelopes or bounded Live Activity state. +4. **The notification service's delivery path** (the same `services/link` + Worker) keeps the APNs delivery material and sends sealed alert envelopes or + bounded Live Activity state, straight to APNs or through BuzzKit. 5. **External AI and tool providers** may receive plaintext needed to perform a request. The Hermes host selects and controls these providers. @@ -64,15 +67,14 @@ Start at the owner of a behavior, then follow its typed boundary: | Rail, goal, tasks and subagent sheets | `Bighelp/Chat/SessionStatusRailView.swift`, `SessionGoalSheet.swift`, `SessionTasksSheet.swift`, `SessionSubagentRosterSheet.swift` | Presentation does not invent execution or session authority. | | Local appearance | `Bighelp/DesignSystem/BighelpThemeReader.swift` | Resolve the consuming view's traits, including sheet and hosted-row overrides. | | Shared Swift wire values | Domain-named `*WireModels.swift` files in `Bighelp/Link/`; `SharedWireValidation.swift` | A historical Link name does not select a transport. Distinct field and byte policies remain distinct. | -| Plugin HTTP mechanics | `bighelp-plugin/loopdy_plugin/http_contracts.py` | Route families keep their own errors, caps, authentication and context rechecks. | -| Python wire contracts | `bighelp-plugin/loopdy_plugin/link_contracts.py` and its explicit domain imports | The facade preserves imports; domain modules validate values without owning transport state. | -| Plugin adapter lifecycle | `bighelp-plugin/loopdy_plugin/adapter.py` and `adapter_*.py` | One adapter owns state and lifecycle. Helpers operate on that instance, not parallel controllers. | +| Hermes socket and dashboard client | `Bighelp/DirectHermes/DirectHermesNetworking.swift`, `DirectHermesConversationClient.swift` | Every socket sends `client.capabilities {server_requests: true}`; sessions carry `source: "bighelp"`. | +| Plugin routes in the app | `Bighelp/DirectHermes/DirectHermesNativeContext.swift`, `Bighelp/Workspace/WorkspaceOperation.swift` | Each route is a `WorkspaceOperation` case plus a `Route` gated by a `/native/context` feature. | +| Plugin route families | `bighelp-plugin/loopdy_plugin/native_api.py`, `native_context.py` | Route families keep their own errors, caps, authentication and context rechecks. | +| Plugin registration and lifecycle | `bighelp-plugin/loopdy_plugin/registration.py`, `adapter.py`, `store.py` | One registration owns tools, hooks and the platform adapter. Feature modules don't add listeners or a second chat route. | -The plugin adapter's operation modules separate delivery, presentation, sessions, -pickers, requests, transport and voice. They do not add listeners or a fallback -chat route. Native default construction remains separate from explicitly injected -compatibility transports. The HTTP helper similarly shares byte and JSON -mechanics, not authorization decisions or a generic endpoint dispatcher. +The plugin runs inside Hermes' own processes (the dashboard and the messaging +gateway). Its routes share Hermes' authentication. It adds no listener and no +fallback chat route. ## 2. Apple-platform target structure @@ -104,9 +106,9 @@ and Live Activity extension compile the same validated state representation. Notification cryptography and trust code is likewise shared between the app and notification service extension. -The project uses Swift 6 strict concurrency, an iOS 17 deployment target, and a -macOS 15 deployment target. Passkey account flows use APIs available on iOS 18 -and fail as unavailable on older systems. +The project uses Swift 6 strict concurrency, an iOS 17 deployment target, a +visionOS 26 deployment target, and a macOS 15 deployment target for the +`BighelpMac` prototype. ### Paired Watch companion @@ -168,18 +170,18 @@ refreshes native history, and replaces only exact-generation transport leases. Changing authority retires those consumers without migrating a live session. There is no Link alternative or cloud recovery transport. -The compatibility map currently covers the tested stock `0.21.2` release -contract, not an attestation of a server commit or its current write permissions. -Feature reads, owner checks and mutation receipts remain necessary. Unknown -versions, optional plugin features, and missing room drivers are not inferred -from liveness. Native selected-checkpoint branching is unavailable because stock +There is no Hermes version map. Hermes versions never gate a connection or a +feature: the app reads `gateway.capabilities`, the plugin's `/native/context` +feature list and each route's answer. Feature reads, owner checks and mutation +receipts remain necessary. Unknown versions, optional plugin features, and +missing room drivers are not inferred from liveness. Native selected-checkpoint branching is unavailable because stock Hermes does not expose the matching visible-row/digest/CAS boundary. Optional surfaces without a native adapter fail explicitly rather than using Link or fixture implementations. `Bighelp/Workspace` defines transport-neutral, owner-bound operations and capability snapshots for the Direct workspace integration. Its authority -coordinates distinguish a native host principal from a paired Link device; +coordinates distinguish a native host principal from a legacy Link device record; connection generations invalidate callbacks without changing the stable cache scope. These types do not themselves authenticate, select, or enable a runtime. Feature clients remain responsible for typed payloads and authoritative readback. @@ -187,15 +189,15 @@ Feature clients remain responsible for typed payloads and authoritative readback Native plugin features use the same authenticated Hermes HTTP session, not a second listener. The client verifies the context principal against its native connection, retains only the bounded safe context projection, and attaches the -exact context ETag and a fresh request ID to fixed Wiki, template and room -observation operations. Success must echo both coordinates. A context conflict +exact context ETag (`If-Match`) and a fresh lowercase request ID +(`X-Loopdy-Request-ID`) to every plugin route. Success must echo both coordinates. A context conflict retires discovery without replaying a mutation; a lost mutation response remains unconfirmed. These request IDs are correlation, not a new exactly-once contract. Feature advertisement and the feature's own grant/revision checks remain independent requirements. -The existing host registry distinguishes independent native connections from -optional Link-owned connections. Independent hosts use a separate protected +The host registry distinguishes independent native connections from legacy +Link-era records (`BighelpHostConnectionMode.link`), which no longer connect. Independent hosts use a separate protected registry root and device-only Keychain service; their records have no bighelp account identity. Cloud credential changes do not retarget or erase that selection. Legacy account-keyed Direct records stay private in their original @@ -244,11 +246,7 @@ catalog, before the runtime's refresh finishes (the same point the home chat opens at launch); host-only screens ask which host first. Removing a host deletes its snapshot. -The optional account device list retains separate selected/primary preferences -for account management and fixtures. Those paired-device preferences cannot -choose, reset or gate the production native workspace. - -Signing out of or deleting the optional notification account clears its scoped +Resetting the optional notification installation clears its scoped delivery state and retires its enrollment. It does not replace the native shell, retarget a host, or erase independent native credentials and journals. Changing native authority retires the old workspace consumers before replacement. Fixture @@ -273,7 +271,7 @@ optical geometry remain authoritative. Remote artwork cannot add provider capabilities or bypass those rules. Artwork is published independently through the static-only service documented in -`services/provider-logos/README.md`. No Link/relay or Hermes deployment is required +`services/provider-logos/README.md`. No notification service or Hermes deployment is required for a logo update. Shipping the first app version containing this loader remains an ordinary, separately authorized app release. @@ -374,7 +372,7 @@ for main chats, subagents, and scheduled tasks. Session-level picker changes are separate from agent-level defaults. Personality controls use the selected native host's supported operations; -unsupported surfaces stay unavailable rather than falling back to Link. +unsupported surfaces stay unavailable; there is no fallback path. ### Chat @@ -476,7 +474,9 @@ versioned storage rather than writing the value into a legacy v1 cache. The app validates attachments locally and enforces size and integrity limits. Native ordinary-file uploads use the public session-bound `file.attach` call, -never a host-path upload or Link fallback. They retain the 8 MiB per-file and 24 MiB per-message limits, validate +never a host-path upload. They retain the 8 MiB per-file and 24 MiB per-message limits +(`ChatAttachment.maximumBytes`, `DirectHermesFileAttachments.maximumBatchBytes`). Bigger files, up to 256 MiB, go +to the plugin's `uploads/*` routes instead (`BigFileUploader`, plugin `native-uploads-v1`). Small files validate the whole batch first, and serialize staging. Only acknowledged `ref_text` values are appended to `prompt.submit`; the original local caption and selected attachment disclosure are preserved. Photos use Hermes' `image.attach_bytes` @@ -485,8 +485,8 @@ takes the staged pictures with the message. Unknown or cancelled upload attempts remain reviewable without automatic replay. A contact or event made from a picture is a reviewed draft, never a write ([Image drafts](IMAGE_DRAFTS.md)). -The app processes and stores avatar images locally; avatar -image bytes are not part of the cloud account directory. +The app processes avatar images on the device before it saves them to the +agent's profile on the host (`profiles.set_asset`), and caches them locally. The app renders a streaming assistant draft only when its session and agent coordinates match the active request. It validates the final response before @@ -494,8 +494,10 @@ adding it to the canonical timeline. ### Local customization -bighelp has no Marketplace, public catalog, publishing workflow, install gateway, -or Marketplace service. Card templates remain a local feature. Themes are gone: +Card templates remain a local feature. There is no card template catalog, +publishing workflow or install gateway. (Settings › Marketplace is Hermes' own +catalog of apps, skills and plugins, and agent templates come from the Template +Catalog; see AGENTS.md.) Themes are gone: the look is one bubble color and a light and dark page, kept on the device, and old saved themes and their logo files are removed at launch. @@ -504,12 +506,15 @@ old saved themes and their logo files are removed at launch. `loopdy.card` version 1 adds a display-only declarative document alongside the existing `loopdy.generative_ui` version 1 and 2 envelopes. The Hermes plugin validates and canonicalizes the agent's document, adds the content hash, card -ID, creation time, and origin. Native chat renders bounded `loopdy-card` fenced -payloads through `ChatCardMessageProjection`, then validates the envelope and -finite element tree before mapping it to native SwiftUI views. Retained card -DTOs also support cached timelines and optional notification payloads. - -Build 3 supports static Cards only. All displayed values are embedded in the +ID, creation time, and origin. The agent puts the result, a fenced `loopdy-card` +block, in its reply, so the card travels as reply text over the native chat +connection. Native chat renders bounded `loopdy-card` fenced payloads through +`ChatCardMessageProjection`, then validates the envelope and finite element tree +before mapping it to native SwiftUI views. Object cards (places, contacts, +events) go only to chats whose app listed them in `renders`, which the app sends +with `people/speaking`. Retained card DTOs also support cached timelines. + +Cards are static only. All displayed values are embedded in the document, `data_sources` must be empty, and the production data client fails closed. No Card network request or refresh occurs. @@ -528,14 +533,13 @@ sequenceDiagram ``` Live source bindings, refresh requests, and freshness states remain reserved for -a later release and are not production-reachable in build 3. +a later release and are not production-reachable. Installed templates are data bundles rather than executable extensions. The app verifies metadata, hashes, embedded card documents, versions, and parameter -slots before atomic account-scoped storage. Plugin template operations remain -part of the owner-bound native workspace contract; the app does not construct -the retired Link template-sync client. No production catalog URL is configured -until a separately governed and licensed catalog is approved. +slots before atomic storage. No production card catalog URL is configured +(`BighelpCardCatalogClient.productionIndexURL` is nil) until a separately +governed and licensed catalog is approved. See [bighelp Cards](BIGHELP_CARDS.md) for the complete wire contract, component catalog, static-data policy, privacy disclosures, template lifecycle, and legacy @@ -801,8 +805,7 @@ camera frames for presentation without recording or storing them. The Keychain stores: -- The device signing private key -- The account content-encryption key +- The notification installation's signing private key - Optional direct Hermes gateway credentials - The notification recipient private key - Host notification public keys pinned per grant @@ -841,15 +844,14 @@ and pinned agents, pinned sessions, user-facing identity, and gesture choices. Those explicit preferences survive sign-out and app updates until the user changes them. Project-section order and collapse state are device-local too, shared by the Sessions screen and Quick Workspace. Their versioned settings -payload is keyed by the signed-in device credential ID and selected host ID, -so fresh device enrollment starts a new layout scope. Layout is not synced to +payload is keyed by the sign-in scope and selected host ID, so a fresh sign-in +starts a new layout scope. Layout is not synced to other devices. Project names are display labels; stable project IDs own the saved layout, and reordering a filtered subset preserves absent project slots. -Deleting the bighelp account removes account-derived host and session preference -identifiers and retired Link outbox artifacts. Native host credentials, journals -and repositories remain outside that cloud-account erasure boundary. The app no -longer creates a Link chat outbox. UserDefaults does not store account private -keys or access tokens. +Phones that once used the retired bighelp account lose its keys and Link +settings once, at launch (`BighelpLinkAccountRetirement`). The app no longer +creates a Link chat outbox. UserDefaults does not store private keys or access +tokens. ## 7. Production and fixture modes @@ -890,9 +892,10 @@ from physical-device or release claims. ## Wiki folder connections -This section records the retained native service, source and migration contracts. -It does not advertise a current Wiki browser or References entry point in the -app's navigation; those provider screens are retired. +This section is history. Current plugins no longer serve the Wiki routes +(`native-wiki-v1`), and the app has no Wiki browser or References entry point. +The app still holds the Wiki client and its stores (`Bighelp/Wiki/`); see +[Wiki integration](../Bighelp/Wiki/INTEGRATION.md). Wiki uses a plugin-owned registration store distinct from Hermes Projects and Files grants. Add Wiki browses existing host folder suggestions, then explicitly saves through the negotiated `wiki.connect` workspace operation. Suggestions and `wiki.resolve` never register folders. The host creates a new read-only registration pinned to the verified initiating device, selected profile, pairing authority, directory identity and generation. Existing grants are never overwritten by this operation; overlapping registrations belonging to another authority, profile or device fail closed. Only host administration can change write policy. @@ -903,7 +906,8 @@ References opens with a bounded recursive file catalog for connected Wikis, even ### Account recovery and host-switch ownership -The signed `/v1/devices` catalog exposes only `phone`, `tablet`, `computer` and +The notification service (`services/link`) still serves the retired account's +signed `/v1/devices` catalog to older app builds. It exposes only `phone`, `tablet`, `computer` and `hermes_host`. Persisted Native or future-runtime records must not enter that projection: shipping clients decode the finite v1 kind set strictly, so one unknown kind can reject the entire list and block account readiness after login. diff --git a/docs/BACKGROUND_CHAT_CONTINUITY.md b/docs/BACKGROUND_CHAT_CONTINUITY.md index e5350349..c6482396 100644 --- a/docs/BACKGROUND_CHAT_CONTINUITY.md +++ b/docs/BACKGROUND_CHAT_CONTINUITY.md @@ -1,6 +1,25 @@ # Background chat continuity -bighelp uses iOS's existing `remote-notification` wake capability. Background execution is discretionary: silent pushes may be delayed, combined, or omitted; force-quit prevents background relaunch until the app is opened again. There is no audio/VoIP/location keepalive and no guarantee the phone stays current while suspended. +bighelp's `UIBackgroundModes` are `audio` (CarPlay voice with the iPhone locked), `fetch` (Background App Refresh +for widgets) and `remote-notification` (quiet pushes). Background execution is discretionary: silent pushes may be +delayed, combined, or omitted; force-quit prevents background relaunch until the app is opened again. There is no +keepalive for chat and no guarantee the phone stays current while suspended. + +## Going away and coming back + +- **Background grace.** Going to the background keeps the host connection for 25 seconds + (`BighelpBackgroundGrace.duration`, inside iOS's background allowance of about 30 seconds), with background time + from iOS. Coming back in time cancels the close, so the chat finds a live connection. If iOS asks for its time + back early, the connection closes then. While a Shortcut, CarPlay or another outside caller holds the connection + (`BighelpShortcutService.holdsHostConnection`), the grace's close leaves it open. On the Mac, which doesn't + suspend apps, no background task is taken. +- **Saving.** Going to the background writes every chat's pending changes at once + (`flushChatPersistence`) and publishes the widgets' data. +- **Coming back.** The app reconnects (`reconnect()`). The reconnect's recovery reattaches the open chats it held + (`NativeWorkspaceSessionRecovery`, the chat on screen first) and reads each one's newest history page again, + keeping the earlier pages it already has (`refreshHeldHistory`). After a turn ends, the host's saved history is + the truth. A chat on screen that had no connection of its own opens again (`openDetachedChat`). See + [idle startup reliability](IDLE_STARTUP_RELIABILITY.md) for launch. ## Preserve content, defer presentation @@ -11,27 +30,32 @@ Coalescing presentation or persistence must not discard canonical events or reintroduce delayed scrolling that overrides a drag. Keep the existing lifecycle flushes when changing tool-event checkpoint frequency. -```text -signed encrypted frame - -> normal authenticated decode and event handling - -> canonical items/activity + existing protected local persistence - -> one accumulated transcript projection when catch-up finishes -``` +The app does not discard activity, generated cards, drafts, or terminal messages in expectation of a later history fetch. Existing request continuations, approval handling, sender/session checks and receipt order remain intact. -The app does not discard activity, generated cards, drafts, or terminal messages in expectation of a later history fetch. Existing request continuations, approval handling, sender/session checks, receipt order, and account boundaries remain intact. Route-owned chat models defer their derived transcript presentation; Home, sidebar and Sessions likewise hold a stable catalog presentation until catch-up ends. Routing and actions continue to resolve canonical session state. Canonical item and activity mutations are still applied, and persistence remains coalesced while presentation is deferred. Never force a full catalog write per catch-up event. A newly prepared chat inherits the current presentation boundary. Closing the boundary rebuilds its transcript once and flushes the shared catalog after the model snapshots, preserving source ordering and consolidated tool groups. Suspension and background-wake completion likewise flush all dirty conversations together. Queued final answers also defer automatic Home reloads to one refresh at catch-up completion; see [idle startup reliability](IDLE_STARTUP_RELIABILITY.md). +`ShellFeatureStore.setChatPresentationDeferred` can hold presentation while a batch of events arrives: route-owned chat models defer their derived transcript (`setTranscriptPresentationDeferred`), and the session catalog keeps a stable copy of its rows (`SessionCatalogStore.setPresentationDeferred`). Canonical items and activity are still applied, and persistence stays coalesced. Closing it rebuilds each transcript once, flushes the catalog in one write and runs one deferred Home refresh. Setting it twice to the same value does nothing. Today only the idle replay fixture (`CanvasStreamingFixtureClient`) opens it; the live background and foreground paths above do not. -The presentation boundary is idempotent rather than an accumulating nesting counter. Backgrounding opens it synchronously before reconnect can deliver queued frames. Foreground recovery uses the existing authenticated account/socket refresh and a bounded drain before revealing accumulated transcript state. It does not issue another history fetch that could overwrite newer live output. Existing catalog/hydration logic still owns cold-open history recovery. +## Quiet pushes -## Runtime budget +A quiet push reaches `BighelpLinkWakeCenter` (a legacy name from the retired Link transport). The app handles two +kinds: -A silent wake has a default 20-second transport budget beginning before connection establishment, rather than two separate connection and drain budgets. The normal quiet window is 500 milliseconds after at least two seconds. Foreground recovery uses a shorter maximum three-second drain with a 150-millisecond quiet window. Expiry, cancellation, and failure close wake-owned presentation boundaries. Account reset also releases the old boundary. +- **Sign-in renewal** (`bighelp_wake`, type `renew-sign-in`). The plugin asks the notification service to send it + about every 8 hours (`_SIGN_IN_WAKE_SECONDS` in the plugin's `managed_notifications.py`). The app renews each + computer's rotating sign-in that isn't connected (`renewSignInWhileAway`). +- **Notification wake** (`loopdy_link`, version 2, type `wake`). The app reconciles notification delivery: pending + revocations, Live Activity recovery for each computer, then a flush of pending card operations + (`BighelpManagedNotificationIntegration.recoverWake`). It does not open chats or read their history. -These are application limits, not an entitlement to iOS runtime. Local flush work and system scheduling are not hard real-time operations. When network recovery fails, the existing connection error remains visible and the app retains its cached data; it does not claim to show current server state. If a backlog cannot be drained in the bounded foreground window, later arrivals continue through the normal live path. +bighelp's own handler reports "new data" only when a sign-in was renewed, and never "failed" for a wake it +handled, so iOS does not throttle later wakes. BuzzKit's answer for the same push is merged in. The app sets no time budget of its own for a wake; iOS's limit applies. -## Host reduction +## Host side -The bighelp plugin limits assistant draft presentation frames to one per 250 milliseconds per active turn. Intermediate text snapshots may be coalesced. Final responses are complete and unthrottled, and tool, approval, attachment, and canonical history records are not coalesced away. This uses the existing encrypted Link transport, with no new plaintext cloud cache or Hermes core change. +The plugin does not throttle or coalesce chat streaming for the phone. Hermes sends each answer a few words at a +time over the chat's socket, and the app paces its own redraws (see AGENTS.md › Streaming under a drag). ## Verification boundary -Focused checks exercise a 75-message deferred presentation batch with local persistence, wake timeout including connection establishment, encrypted notification delivery/receipt, idempotent presentation boundaries, and retained native chat scrolling. Physical APNs scheduling and microphone acoustics are not simulator guarantees. They are not release gates for this work. +Unit tests (`ChatModelTests`, `ShellFeatureStoreTests`, `SessionCatalogStoreTests`) cover a 75-event deferred +presentation batch with local persistence, idempotent presentation boundaries, and retained native chat scrolling. Physical push scheduling is not a simulator guarantee and is not a +release gate for this work. diff --git a/docs/BIGHELP_CARDS.md b/docs/BIGHELP_CARDS.md index 5d0fc70d..75f58ef3 100644 --- a/docs/BIGHELP_CARDS.md +++ b/docs/BIGHELP_CARDS.md @@ -1,22 +1,27 @@ # bighelp Cards bighelp Cards are declarative, display-only interfaces generated by an agent and -rendered as native SwiftUI. Build 3 ships static Cards only: every displayed -value is embedded in the payload and `data_sources` must be empty. The card is +rendered as native SwiftUI. Cards are static only: every displayed value is +embedded in the payload and `data_sources` must be empty. The card is data: it cannot contain Swift, JavaScript, HTML, a WebView, downloaded code, arbitrary actions, or a request body. Live Card data refresh is reserved for a later release. -The Hermes plugin validates and canonicalizes the original document, adds its -identity fields, and sends it once through the encrypted conversation path. The -iOS app validates it again before rendering. Neither side fetches Card data in -build 3. +An agent makes a card with one of the plugin's `bighelp_render_*` tools. The +plugin validates and canonicalizes the document, adds its identity fields, and +returns it in a `loopdy.card_delivery` result. That result's `display_markdown` +is the card as a fenced `loopdy-card` code block, and the agent puts it in its +reply exactly once. The card then travels as ordinary reply text over the native +chat connection, and Hermes saves it with the message. The app finds each +`loopdy-card` block in an assistant message (`ChatCardMessageProjection`) and +validates it again before rendering. Neither side fetches Card data. ## Complete wire example The following is a complete `loopdy.card` version 1 document after the renderer has added `content_hash`, `card_id`, `created_at`, and `origin`. This object is -carried in the existing generated-interface event or event detail. +the `card` field of the renderer's `loopdy.card_delivery` result, and the JSON +inside the `loopdy-card` block of the agent's reply. ```json { @@ -206,10 +211,20 @@ these by hand); the full contract is [Image drafts](IMAGE_DRAFTS.md). beside every field and Save or Discard. The card never writes and never asks for a permission. - The app adds the two names to `renders` only when `/native/context` lists - `native-image-drafts-v1`. In any other chat the plugin refuses the draft tools. + `native-image-drafts-v1` (and `native-card-objects-v1`, which sends `renders` + at all). In any other chat the plugin refuses the draft tools. - `-use-demo-fixtures -test-image-drafts` opens a chat with a made-up business card and event poster and a draft for each. +## App cards + +Plugin feature `native-html-apps-v1` adds `html_app`: a card for an HTML app the +agent made with `bighelp_show_app` (title, description and Open App). The card +itself holds no HTML. Open App shows the page full screen, outside the chat; the +full contract is [HTML apps](HTML_APPS.md). The app adds `html_app` to `renders` +only when `/native/context` lists `native-html-apps-v1` (and +`native-card-objects-v1`). + ## Weather backgrounds A `card` element may carry an animated weather background beside its `props`: @@ -257,44 +272,55 @@ background, and parses it leniently: ## Bindings, expressions, and formatting -A component value in build 3 uses the literal binding form: +A component value uses the literal binding form: ```json { "literal": "Open" } ``` Source bindings, JSON Pointer resolution, and expressions are reserved for a -later live-data release. They are not valid in build-3 delivered Cards. +later live-data release. They are not valid in delivered Cards. The only format styles are `text`, `integer`, `number`, `currency`, `percent`, `date`, `time`, and `relative_date`. The app owns locale-aware formatting. -## Build-3 delivery sequence +## Delivery sequence ```mermaid sequenceDiagram - participant U as User - participant I as Bighelp iOS app - participant L as Bighelp Link - participant H as Authorized Hermes host - - - H->>H: Generate and validate canonical card - H->>L: Encrypt original card document - L->>I: Route encrypted generated-interface event - I->>I: Decrypt, validate, store canonical card - U->>I: Open static card - I->>I: Render embedded values as native components - I-->>U: Display native static Card + participant U as Person + participant I as bighelp app + participant H as Hermes host and bighelp plugin + participant M as Agent's model + + M->>H: Call a bighelp_render_* tool with the card + H->>H: Check renders for object cards, validate, canonicalize, add card_id and content_hash + H-->>M: loopdy.card_delivery with display_markdown + M->>H: Reply text with the loopdy-card block, once + H->>I: Reply streams over the native chat connection + I->>I: Find each loopdy-card block, validate the card again + I-->>U: Native static card in the chat ``` There is no Card network request, polling loop, background refresh, or catch-up -loop in build 3. The canonical transcript document, its hash, and its card ID -remain unchanged. +loop. The canonical transcript document, its hash, and its card ID remain +unchanged. + +The card is part of the message text, so it comes back with the chat's saved +history and copies with the message. Only an assistant message's blocks are +cards, and a `loopdy-card` block inside an ordinary code block is not one. Each +block is at most 64 KiB (`ChatCardMessageProjection.maximumCardBytes`). While a +reply streams, an open block shows as a loader shaped like the card it names. In +a finished message, a block that never closed, doesn't validate or repeats a card +already shown shows "This card couldn't be shown." instead. + +A reply alert never shows the raw block: the plugin turns each card into plain +words (the render call's `notification_text`, else words made from the card's +own fields, else "Sent a card."). ## Live-data policy -Live data is unavailable in build 3. The plugin schema permits zero data +Live data is unavailable. The plugin schema permits zero data sources, the plugin validator rejects nonempty `data_sources`, the iOS envelope validator rejects them again, and the production data client fails closed. Network-policy and source-binding code retained for development is not a shipped @@ -313,17 +339,18 @@ The main contract limits are: | Boundary | Receives or controls | Does not receive or control | |---|---|---| -| Hermes agent and plugin | User intent, embedded Card values, canonicalization, validation, content hash | Device credentials or executable Card code | -| bighelp Link | Encrypted original Card event and routing metadata | Decrypted Card content under the documented Link assumptions | -| bighelp iOS app | Decrypted Card, embedded values, native rendering | Executable code supplied by a Card or live Card source traffic | -| Third-party Card source host | Nothing in build 3 | Device IP, Card values, account keys, credentials, or transcript | -| bighelp notification infrastructure | No Card refresh request or response | Decrypted Card content or live source traffic | -| Template catalog and stores | Reviewed template data, metadata, integrity values, parameters, and install state | Native executable extensions or automatic permission expansion | - -Build 3 makes no third-party Card request, so opening a Card does not disclose a +| Hermes agent and plugin | User intent, embedded Card values, canonicalization, validation, content hash, and which components each chat's app draws (`renders`) | Device credentials or executable Card code | +| The agent's AI provider | The card document, in the render call and in the reply the model writes | Anything the conversation does not already hold | +| Native chat connection | The reply text that holds the card, like any other message | Separate Card requests or live Card source traffic | +| bighelp iOS app | The card from the reply text, embedded values, native rendering | Executable code supplied by a Card or live Card source traffic | +| Third-party Card source host | Nothing | Device IP, Card values, account keys, credentials, or transcript | +| bighelp notification infrastructure | A sealed reply alert, whose preview names each card in plain words; no Card refresh request or response | Card content in readable form, or live source traffic | +| Template stores | Reviewed template data, metadata, integrity values, parameters, and install state | Native executable extensions or automatic permission expansion | + +bighelp makes no third-party Card request, so opening a Card does not disclose a device IP address, request URL, timing, or query to a Card source host. Embedded -values still travel through the ordinary encrypted conversation path and remain -subject to the documented endpoint and provider trust boundaries. +values still travel in the conversation itself, to the host and its AI provider, +and remain subject to the documented endpoint and provider trust boundaries. ## Visible states and failures @@ -363,8 +390,12 @@ A template bundle is declarative data with `id`, `version`, `name`, `summary`, does not rewrite cards already stored in transcripts. Templates never install native code or add new component capabilities. No -production catalog URL is configured in this repository. Public catalog -publication requires a separately reviewed catalog repository, governance, +production catalog URL is configured in this repository +(`BighelpCardCatalogClient.productionIndexURL` is nil), so the card catalog +screen (`BighelpCardCatalogView`) opens only on a local fixture catalog +(`-show-card-catalog -use-card-catalog-fixture`). The Template Catalog at +`catalog.bighelp.app` holds agent templates, not card templates. Public card +catalog publication requires a separately reviewed catalog repository, governance, signing-key custody, and an explicit open-source license. ## Compatibility and non-goals diff --git a/docs/CACHE_FIRST_SESSIONS.md b/docs/CACHE_FIRST_SESSIONS.md index 2808cc20..c8fdd809 100644 --- a/docs/CACHE_FIRST_SESSIONS.md +++ b/docs/CACHE_FIRST_SESSIONS.md @@ -5,8 +5,10 @@ Existing chat navigation mounts the retained ChatModel or the host/account-scoped local transcript before awaiting network work. Mounting an existing model does not reconcile an older catalog over live text. The canonical recent-history -refresh still owns remote identities and live-state recovery. The composer can -be edited immediately, while Send waits for a ready native client. +refresh still owns remote identities and live-state recovery. The composer and +Send work at once: a message sent before the native client is ready waits at the +bottom of the chat with "Sending…" (`stagedSends`) and goes out once the chat can +take it. Commands (`/…`) and PDF pages still wait in the box for the connection. ```text open saved chat @@ -45,7 +47,8 @@ host approvals and clarification requests, not old steered text. ## Reopen identity and group readiness Hosted groups use their own verified group client. Their unused direct-chat -placeholder does not gate Send; direct chats still wait for their own transport. +placeholder does not gate Send. Direct chats stage a message until their own +transport is ready. Programmatic direct sends preserve the draft while that transport is unavailable. Authoritative history may refine a stored result's tool-call linkage at a page diff --git a/docs/CHAT_INTERACTION_CONTRACT.md b/docs/CHAT_INTERACTION_CONTRACT.md index eab731e5..1658f96d 100644 --- a/docs/CHAT_INTERACTION_CONTRACT.md +++ b/docs/CHAT_INTERACTION_CONTRACT.md @@ -23,6 +23,7 @@ plans do not authorize reverting to their earlier scroll implementations. | A long answer gains text or formatting | Keep exact text, Markdown-derived formatting, Unicode boundaries, and valid selection. Earlier formatting corrections and shorter replacements must still apply. | | The user types while messages and tools arrive | Preserve the native editor, first responder, caret, selection, undo state, and draft. Streaming must not reopen a dismissed keyboard or dismiss an active editor. Explicit user dismissal remains available. | | The user taps the visible input surface | The entire visible input, including its padding, focuses the native editor. Padding hit surfaces sit behind the editor so native caret placement and text selection keep their gestures. | +| The user sends while the agent is working | A tap on Send uses the default from Settings › Chat › While an agent is working (Steer, Queued, or Interrupt and Send; Steer out of the box). Touch and hold Send for 1 second (`ChatComposerInteractionPolicy.sendOptionsLongPressDuration`) to pick another choice; an outline fills around Send while you hold, and moving more than 50 points cancels. On a keyboard, Command-Return shows the same choices. | | The composer is empty or contains one line | The microphone and Send controls share the input's vertical center. Preserve bottom alignment when the native editor grows to multiple lines. | | A tool or clarification card scrolls offscreen and returns | Preserve explicit disclosure choices and request-scoped unsent clarification text/choices. Reusing a cell for another row must not transfer local state to it. | | A session or model owner is replaced | Retire old callbacks and state ownership even when row IDs match. Actions and live presentation must reflect the current owner. | diff --git a/docs/CHAT_PERFORMANCE_VALIDATION.md b/docs/CHAT_PERFORMANCE_VALIDATION.md index 589572b3..175784c9 100644 --- a/docs/CHAT_PERFORMANCE_VALIDATION.md +++ b/docs/CHAT_PERFORMANCE_VALIDATION.md @@ -33,7 +33,7 @@ follow-up. Reader preparation has a separate cancellation regression. | 100 consecutive expanded tools + second active chat | 9 s | 63 ms | 35 ms | 66 ms | 117 ms | This removes the reproduced fixture hang; 66 ms display p95 does not establish -60 FPS. Real-device performance, relay backlog behavior, direct Tailscale routing, +60 FPS. Real-device performance, host backlog behavior, direct Tailscale routing, and long Shortcut execution remain separate acceptance checks. ## Diagnosis diff --git a/docs/CLOUDFLARE_INFRASTRUCTURE.md b/docs/CLOUDFLARE_INFRASTRUCTURE.md index b1cd40c6..3aab7800 100644 --- a/docs/CLOUDFLARE_INFRASTRUCTURE.md +++ b/docs/CLOUDFLARE_INFRASTRUCTURE.md @@ -1,242 +1,182 @@ # Cloudflare infrastructure -This document describes the deployed bighelp services based on read-only -verification performed on August 29, 2026. It omits non-public production -identifiers, private routes, database and namespace identifiers, schema -definitions, anti-abuse thresholds, exact retention intervals, and secrets. -The public client service origin and public app identifiers necessarily remain -visible in the application bundle. - -Cloudflare account, Link and notification services are optional to an -independently authenticated native Hermes connection. They retain their own -authorization and erasure boundaries; a cloud outage or sign-out does not select -another transport for an active Direct session. This does not establish -cloud-independent closed-app APNs delivery. - -An independent native workspace does not use the Link workspace account-refresh -loop to connect or recover. Native Agents, Sessions, Projects, -Scheduled Tasks and supported hosted rooms use that host's authenticated public -interfaces and isolated device caches. This composition change adds no Worker, -relay registration, cloud schema or deployment. - -The Cloudflare deployment has two bighelp Workers, two D1 databases, one Durable -Object namespace, an asynchronous delivery queue with dead-letter handling, and -an internal service binding. The bighelp Workers do not currently bind KV or R2. - -The native Workspace management layer introduces no Cloudflare service, schema, -retention or deployment change. Its bounded read models use the selected -owner's operation transport and remain in device memory; this feature does not -upload credentials, file previews or diagnostic logs to a new cloud endpoint. -See [Workspace management](WORKSPACE_MANAGEMENT.md) for its scope boundaries. - -## 1. Logical topology +This page describes bighelp's Cloudflare services as their source and Wrangler configs in `services/` define them. +It omits non-public production identifiers, private routes, database and namespace identifiers, anti-abuse +thresholds, exact retention intervals and secrets. The public service hostnames and app identifiers are already +visible in the app and in this repo. -```mermaid -flowchart TB - IOS["iOS device"] - Host["Authorized Hermes host"] - Identity["Account and link Worker"] - DO["Per-account Durable Object"] - Accounts["Account metadata D1"] - Relay["Notification relay Worker"] - RelayDB["Delivery metadata D1"] - Queue["Asynchronous delivery queue"] - APNS["APNs"] - - IOS -->|"passkey and signed device operations"| Identity - Identity --> Accounts - IOS <-->|"authenticated encrypted frames"| DO - Host <-->|"authenticated encrypted frames"| DO - Identity --> DO - Identity -->|"internal service call"| Relay - Relay --> RelayDB - Relay --> Queue - Queue --> APNS - APNS --> IOS -``` - -## 2. Account and link Worker +Chat never goes through Cloudflare. The app talks straight to the person's Hermes host over native Hermes (REST +sign-in, the WebSocket JSON-RPC gateway and the plugin's routes under `/api/plugins/loopdy/native/…`; see +[Native transport](NATIVE_TRANSPORT.md)). The Cloudflare services are optional extras: notifications and Live +Activities, the template catalog, avatars, provider logos and usage numbers. If they are down, chat still works. +Agents, sessions, projects, scheduled tasks and workspace management use the host's own interfaces and add no +cloud service. -The account/link Worker is responsible for: +The retired bighelp account and its Link transport (pairing, and encrypted frames relayed between the phone and +a paired host) are gone from the app. See [Retired services](#retired-services). -- Passkey registration and assertion challenges -- Verification of WebAuthn responses -- Short-lived access authorization -- Device public-key registration and revocation -- Encrypted device-label storage -- Pairing challenge coordination -- Signed device-management operations -- WebSocket admission -- Routing a connection to the correct per-account Durable Object -- Passing push and Live Activity enrollment to the relay through an internal - service binding +## 1. The Workers -It is not responsible for running agents or storing readable chat sessions. +`services/` holds five Workers with a production config, plus the recovered source of an older relay: -### Durable account metadata +| Folder | Worker | Hostname | What it binds | +|---|---|---|---| +| `services/link` | `loopdy-link` | `link.loopdy.app` | D1 `ACCOUNTS` and `MARKETPLACE_RETIREMENT`, Durable Object `USER_LINKS`, queue `APNS_RETRY`, service `TELEMETRY` | +| `services/telemetry` | `bighelp-telemetry` | `telemetry.bighelp.app` | two Rate Limiting bindings, no storage | +| `services/catalog` | `bighelp-catalog` | `catalog.bighelp.app` | D1 `DB`, static assets `REVIEWER_ASSETS`, a daily cron | +| `services/avatars` | `bighelp-avatars` | `avatars.bighelp.app` | static assets `ASSETS` (the Worker runs first) | +| `services/provider-logos` | `loopdy-provider-logos` | `logos.loopdy.app` | static assets only, no script | +| `services/relay` | (recovery only) | none | none: `wrangler.recovery.jsonc` is a local check that must never be deployed | -The account database holds the minimum durable material needed for identity and -authorization: +None of them binds KV or R2. Every Worker has `workers_dev` and preview URLs turned off. `services/link`, +`services/catalog` and `services/telemetry` also have a `wrangler.test.jsonc` for local tests, which must never be +deployed. -- Opaque account coordinates -- Passkey public credential material -- Expiring authentication challenges -- Hashed access-session tokens -- Device public keys and authorization state -- Pairing challenges and replay-prevention metadata -- An encrypted account-key envelope +## 2. Logical topology -The passkey biometric or device-unlock secret never leaves the Apple -authentication system. The client creates the account content key; the service -stores only its encrypted envelope. +```mermaid +flowchart TB + IOS["iPhone, iPad, Mac or Vision Pro app"] + Host["Hermes host with the bighelp plugin"] + Link["Notification service Worker (loopdy-link)"] + DO["Per-owner Durable Object (UserLink)"] + Accounts["Notification D1 (ACCOUNTS)"] + Retry["APNs retry queue + dead-letter queue"] + BuzzKit["BuzzKit"] + APNS["APNs"] + Telemetry["Telemetry Worker"] + Static["Catalog, avatars and logo Workers"] + + IOS -->|"signed installation requests, push targets"| Link + Host -->|"grant-signed alerts and Live Activity updates"| Link + Link --> Accounts + Link --> DO + Link -->|"direct send"| APNS + Link --> Retry + Retry --> APNS + Link -->|"fallback and older builds"| BuzzKit + BuzzKit --> APNS + APNS --> IOS + Link -->|"service binding (RPC)"| Telemetry + IOS --> Telemetry + IOS --> Static +``` -## 3. Per-account Durable Object +## 3. Notification service Worker (`services/link`) -The account/link Worker maps each account to one Durable Object instance that -coordinates authorized endpoints. The object stores only: +The Worker kept its first name, `loopdy-link`, and its hostname, `link.loopdy.app`: installed phones and plugins +already use them. Today it is the notification service. It is responsible for: -- Authorized-host routing grants -- Frame identifiers and sequencing metadata -- A count-bounded queue of encrypted frames awaiting delivery +- Notification installations: each phone registers its own signing key (`/v1/notifications/bootstrap`, + `/v1/notifications/installations/current`), and can revoke it. +- Host grants: a Hermes host enrolls for one agent and sends alerts and Live Activity updates under that grant + (`/v1/notifications/host-grants/…`). +- Push targets: the phone's APNs token for alerts and its Live Activity tokens (`/v1/notifications/push-target`, + `/v1/notifications/live-activity-target`). The Worker encrypts the tokens at rest with + `PUSH_TOKEN_KEY`. +- Agent avatars for alerts (`/v1/notifications/buzzkit/assets`). +- Delivery to APNs, directly or through BuzzKit (below). -The queued frame body is ciphertext created by an endpoint holding the account -key. The deployed Worker has no frame-decryption path. Frames are removed after -an authenticated recipient acknowledgement or when the affected endpoint is -revoked. We found no independent time-based expiration for offline Link frames. -Do not describe this storage as automatically short-lived. +It does not run agents or store readable chats. -This Durable Object is a coordination mechanism, not a conversation database. +### Bindings -## 4. Notification relay Worker +- **D1 `ACCOUNTS`** (`loopdy-link-accounts`, `migrations/`): notification installations, grants, revocation + records and push targets. Migrations `0001` to `0004` are the retired account and pairing tables. +- **D1 `MARKETPLACE_RETIREMENT`** (`loopdy-marketplace`, `marketplace-migrations/`): the old marketplace's + tables are dropped. Only a receipt is left, which the Worker checks before it deletes an old account. +- **Durable Object `USER_LINKS`** (class `UserLink`, SQLite storage): one instance per owner. It holds that + owner's notification state, such as Live Activity rows and alert avatars, and the retired Link frame queue. +- **Queue `APNS_RETRY`** (`loopdy-link-apns-retry`, dead-letter queue `loopdy-link-apns-retry-dlq`): the Worker + produces to it and consumes it. Pushes APNs could not take at once wait there. +- **Service `TELEMETRY`**: the telemetry Worker's `TelemetryIngest` entrypoint. Without it the Worker still works + and sends no events. -The notification relay is isolated from the account/link Worker. It receives -authorized internal requests and manages: +Workers Logs are on and sampled. Invocation logs are off, because a request URL can carry a grant ID. The code logs +fixed codes only. -- Device push registrations -- Recipient public-key coordinates -- APNs token ciphertext -- Encrypted alert payloads -- Delivery attempts and status -- Live Activity registrations and revocations -- Bounded Live Activity delivery state -- Nonces, idempotency receipts, tombstones, and aggregate usage counters -- Asynchronous APNs delivery through a queue +### Direct APNs and BuzzKit -The relay encrypts push tokens and alert payloads at rest. The authorized source -encrypts human-readable notification content for the destination device before -APNs delivery. +The Worker can send a push straight to APNs for installations whose app registered a push target with it. +Transient APNs failures go to the retry queue. A push that cannot be sent directly falls back to BuzzKit, which is +also the route for older app builds. `DIRECT_APNS` (`off`, `shadow` or `on`) controls direct sends, and +`APNS_ENVIRONMENTS` says which APNs environments get them. The APNs secrets are `APNS_KEY_P8`, `APNS_KEY_ID`, +`APNS_TEAM_ID` and `PUSH_TOKEN_KEY`. BuzzKit has its own secrets. See [Direct APNs relay](DIRECT_APNS_RELAY.md) for +the routes, payloads and rollout. -Live Activity updates are different from alert notifications: they contain a -deliberately reduced, generic progress projection suitable for a Lock Screen -surface. They must not contain prompts, tool inputs, unrestricted model output, -credentials, or private attachments. +### Alert content and Live Activities -### Direct APNs delivery from the Link Worker +Current plugins seal each alert's title, text and avatar for the one enrolled phone (alert version 3). The Worker +and BuzzKit see only a neutral placeholder, and the phone opens the sealed content. For older plugins, the Worker +still accepts the earlier alert format, which carries readable title and text. -The Link Worker (`loopdy-link`) can also send a push straight to APNs for installations whose app registered a push -token with it. The token is stored encrypted in the `loopdy-link-accounts` database. Transient APNs failures wait in a -retry queue with a dead-letter queue, and a message that cannot be sent directly falls back to BuzzKit. The Worker has -Workers Logs on (sampled), an optional service binding to the telemetry Worker, and these secrets: `APNS_KEY_P8`, -`APNS_KEY_ID`, `APNS_TEAM_ID` and `PUSH_TOKEN_KEY`. `DIRECT_APNS` (`off`, `shadow` or `on`) turns it on and `off` is the -way back. See [Direct APNs relay](DIRECT_APNS_RELAY.md) for the routes, payloads and rollout. +Live Activity updates carry a reduced, generic progress state for the Lock Screen: a phase, a time, a count of +helpers and the latest tool. They must not contain prompts, tool inputs, unrestricted model output, credentials or +private attachments. Chat titles and agent names stay on the phone. See +[Live Activity groups](LIVE_ACTIVITY_GROUPS.md). -## 5. What Cloudflare can and cannot see +## 4. What Cloudflare can and cannot see ### Cloudflare can process -- Source network metadata inherent to an HTTPS/WebSocket service -- Connection timing and duration -- Ciphertext sizes -- Opaque account, device, frame, and delivery coordinates +- Network metadata that comes with any HTTPS service, and connection timing +- Opaque installation, grant, delivery and activity identifiers - Public keys and authorization epochs -- Encrypted device labels -- Encrypted APNs tokens and encrypted alert payloads +- Encrypted push tokens and sealed alert payloads, and their sizes +- Readable alert title and text from older plugins that do not seal alerts - Generic Live Activity progress state -- Delivery status, coarse presence, and aggregate usage counters - -### Not available to the deployed frame-routing path +- Delivery status and aggregate counters -- Chat prompts or replies carried inside bighelp Link frames -- Attachment bytes carried inside bighelp Link frames -- Voice transcripts or synthesized audio carried inside bighelp Link frames -- Agent instructions and workspace operations carried inside bighelp Link frames -- Private account content keys -- Device signing private keys -- Notification recipient private keys -- Passkey biometric or device-unlock secrets +### Cannot see -This does not make the system anonymous. Infrastructure providers can still -observe network and routing metadata, and the authorized Hermes host receives -plaintext because it must perform the requested work. Pairing keys are bound to -a host-generated commitment carried in the QR code or compared as a separate -16-character manual verification code. +- Chats, prompts, replies, attachments or voice: these go straight between the app and the host +- The content of sealed alerts +- Device signing private keys and notification recipient private keys -## 6. Session storage statement +This does not make the system anonymous. Infrastructure providers can still see network and routing metadata, and +the Hermes host receives plaintext because it does the work. -bighelp's Cloudflare deployment does **not** contain a database of readable -sessions, messages, or transcripts. +## 5. Storage statement -Encrypted frames may be held while an authorized endpoint is offline. That -ciphertext is deleted after recipient acknowledgement or endpoint revocation. -The iOS app may cache readable session state. The authorized Hermes host may -maintain it according to its configuration. +bighelp's Cloudflare deployment does **not** contain a database of readable sessions, messages or transcripts. +The app may cache readable session state on the device. The Hermes host keeps sessions according to its own +configuration. -The current service exposes device revocation and passkey-authorized account -deletion. Account deletion revokes push and Live Activity routes, deletes the -account/device directory rows, closes sockets, and purges the per-account -Durable Object twice around the directory deletion to close authenticated-request -races. Infrastructure backups and provider recovery systems can still outlive -logical deletion according to their configured policies. +A phone can revoke its notification installation. The Worker then revokes that installation's grants and deletes +its push targets and its BuzzKit subscriber. Infrastructure backups and provider recovery systems can still outlive logical deletion according to +their configured policies. -## 7. Operational safety +## 6. Operational safety Production operations should preserve these invariants: -- Never log plaintext frame bodies, credentials, push tokens, or decrypted alert - content. +- Never log plaintext alert content, credentials, push tokens or grant IDs. - Keep all public traffic on TLS. -- Restrict internal service bindings to the minimum required services. -- Keep secrets in Cloudflare secret bindings, not source or plain-text - variables. -- Preserve replay protection, bounded parsing, and authorization-epoch checks. -- Add and verify time-based cleanup for offline frame ciphertext in addition to - acknowledgement and revocation cleanup. -- Treat D1 migrations and Durable Object migrations as security-sensitive - changes. -- Treat host-key enrollment and rotation for sealed alerts as part of the - notification service trust boundary; pairing-key commitment does not provide - notification sender-key transparency. -- Test revocation from both active and offline endpoint states. -- Review privacy disclosures whenever a new durable field or storage product is - introduced. - -## 8. Reproducibility status - -The iOS repository does not currently include the Worker source, D1 migrations, -queue configuration, or infrastructure-as-code used by the deployed services. -This document describes and verifies the deployment but cannot reproduce it. - -For fully reproducible open-source infrastructure, publish a separate server -repository containing: - -- Worker source -- Durable Object classes and migrations -- D1 migrations -- Queue consumers -- Development-only configuration templates -- Local test harnesses -- Deployment instructions that use placeholder identifiers -- A threat model and protocol compatibility tests - -Do not publish production account identifiers, resource identifiers, API -tokens, APNs credentials, signing keys, production hostnames not already meant -to be public, or live operational thresholds. +- Restrict service bindings to the minimum required services. +- Keep secrets in Cloudflare secret bindings, not in source or plain-text variables. +- Preserve replay protection, bounded parsing and authorization-epoch checks. +- Treat D1 migrations and Durable Object migrations as security-sensitive changes. `wrangler deploy` does not + apply D1 migrations: apply and verify them first (see `services/link/SOURCE.md`). +- Treat host-key enrollment and rotation for sealed alerts as part of the notification service trust boundary. +- Test revocation from both active and offline states. +- Review privacy disclosures whenever a new durable field or storage product is introduced. + +## 7. Reproducibility + +This repo includes each Worker's source, its D1 migrations, its queue and Durable Object configuration, and its +tests (run from the Worker's folder). The +production `wrangler.jsonc` files are checked in. Secrets are set with `wrangler secret put` and stay out of +source. Some deploys also need a private config kept outside the repo, for example the catalog's reviewer +hostname (see `services/catalog/README.md`). Only the maintainer deploys these services. + +Do not publish API tokens, APNs credentials, signing keys, production hostnames not already meant to be public, +or live operational thresholds. ## Telemetry Worker The `bighelp-telemetry` Worker (`services/telemetry`) is a separate Worker at `telemetry.bighelp.app`. It accepts -batches from the app, the notification extension and the Hermes plugin. The Link relay reaches it over a service -binding that calls the `TelemetryIngest` entrypoint. +batches from the app, the notification extension and the Hermes plugin. The notification service reaches it over a +service binding that calls the `TelemetryIngest` entrypoint. - **It holds no storage.** There is no D1, KV, R2, queue or Durable Object. It checks each batch against an allowlist (`contracts/telemetry-v1.json`), applies two Workers Rate Limiting bindings (per ID, and per network by a @@ -249,6 +189,15 @@ binding that calls the `TelemetryIngest` entrypoint. See [Telemetry](TELEMETRY.md) for what is collected and how to turn it off. -## Wiki folder setup transport - -The optional Wiki family includes explicitly negotiated `wiki.connect` on the existing encrypted workspace transport. It carries an existing folder coordinate and selected profile; the authenticated envelope supplies device/host ownership. New registrations are host-persisted, read-only, and owner-scoped. Root responses may include a source folder path, which remains encrypted like Wiki content. This adds no relay-readable source storage, endpoint, routing authority, or recipient-only encryption. +## Retired services + +- **Link transport and the bighelp account.** The notification service's source still has the old passkey account, + pairing, device and `/v1/socket` routes and the Link frame queue in its Durable Object, but no current app build + uses them. The app removes old Link keys and settings at launch (`BighelpLinkAccountRetirement`). See + [Legacy Link recipient overflow policy](LINK_RETENTION.md) for the old frame limits. +- **Notification relay.** `services/relay` is a byte-exact recovery of an older notification relay Worker, kept + for reference and checks (`services/relay/README.md`). It has no production config or live bindings in this repo. + The notification service has no binding to it, and the plugin no longer sends to a relay. +- **Wiki.** The Wiki family (`wiki.connect` and the other `wiki.*` operations) ran over the Link transport and + later the plugin's routes. The plugin no longer serves them. See [contracts/wiki-v1.md](../contracts/wiki-v1.md). +- **Marketplace.** Its D1 tables are dropped (see the `MARKETPLACE_RETIREMENT` binding above). diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index d22cac16..1333723b 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -1,10 +1,13 @@ # Development guide -Production transport contract: **native Hermes only for chat**. Cloud services -are used only for optional notifications and Live Activities, which bighelp's own notification service sends. The current composition, +Production transport contract: **native Hermes only for chat**. Chat never goes +through bighelp's cloud services. They send optional notifications and Live +Activities (bighelp's own notification service), take usage and diagnostics +([Telemetry](TELEMETRY.md)) and serve public artwork and catalogs. The current composition, voice boundary, enrollment isolation and verification requirements are defined -in [Native transport](NATIVE_TRANSPORT.md). Retained Link/paired-Direct protocol -sections below describe legacy compatibility code, not a selectable chat path. +in [Native transport](NATIVE_TRANSPORT.md). The bighelp account and its Link +transport are retired. The app only removes their leftover keys and settings at +launch (`BighelpLinkAccountRetirement`). ## Requirements @@ -40,9 +43,9 @@ locking or corrupting shared incremental state. ## iPhone tools and input regressions -Run the native permission, Apple service, mutation journal/coordinator and directed -socket suites listed in [the device-tools contract](IPHONE_DEVICE_TOOLS.md). -`DeviceToolPermissionsUITests` must show three independent controls off without +Run the native permission, Apple service, mutation journal/coordinator and +device-tool channel suites listed in [the device-tools contract](IPHONE_DEVICE_TOOLS.md). +`DeviceToolPermissionsUITests` must show every phone tool's switch off without requesting real OS access. `ComposerInteractionUITests` must focus from visible padding and align microphone/Send on iPhone and iPad. Native grants must stay separate from system permission status, and delayed callbacks cannot restore @@ -58,7 +61,7 @@ plugin updates; apply the feature diff rather than replacing those modules. The Hermes `ToolExecutionContext` extension is a required host dependency. A plugin doctor/import check cannot establish running gateway activation. Verify -the loaded plugin revision and a fresh connected Link state after one restart. +the loaded plugin revision and a fresh native connection after one restart. Record physical Health/EventKit acceptance separately from injected-boundary and simulator checks. @@ -307,7 +310,6 @@ values. Never commit: - APNs keys or certificates - Signing certificates or provisioning profiles - Private host credentials -- Account content keys - Device private keys - Production database or namespace identifiers @@ -345,7 +347,8 @@ Local JSON repositories are schema-versioned. When changing a persisted model: ## Protocol changes -Multiple independently deployed components implement bighelp Link. +The app, the bighelp Hermes plugin and the notification service are deployed +independently and share the plugin routes and the notification protocol. Protocol changes require compatibility tests for: - Strict payload validation and bounds @@ -363,7 +366,7 @@ Do not document or log live protocol coordinates in public issues. Before merging a feature: - Does it add durable local or cloud data? -- Can the routing plane decrypt any new payload? +- Can the notification service read any new payload? - Does it add a required-reason API or collected-data category? - Does it place sensitive text on the Lock Screen? - Does it add a permission usage description? @@ -371,7 +374,7 @@ Before merging a feature: - Are all external strings, identifiers, counts, and byte sizes bounded? - Are callbacks and continuations identity-checked and settled exactly once? - Is cancellation safe? -- Does sign-out, unpair, or revocation remove access? +- Does removing a host, or revoking a notification grant, remove access? - Are logs redacted? - Are production and fixture paths both tested? @@ -383,9 +386,9 @@ Feature folders own their views, domain models, observable state, and adapters. Cross-target code belongs only in the explicit shared folders. Avoid moving secrets or production configuration into fixtures. -The `Hermes` folder contains a direct HTTPS client retained for compatibility -and testing. Production selects `NativeWorkspaceRuntime` and `DirectHermesWorkspaceClient`. -The older `HermesClient` is not the selected transport. +The `Hermes` folder holds the session catalog client +(`DirectHermesSessionCatalogClient`) and its helpers. Production selects +`NativeWorkspaceRuntime` and `DirectHermesWorkspaceClient`. ## Documentation safety @@ -458,13 +461,10 @@ explicit manual confirmation. It installs the supplied identity in a temporary k and deletes temporary signing files when finished. It uses the committed Fastlane bundle and needs no preconfigured `asc` login on the runner. -Wiki folder registration also requires deploying the updated bighelp Hermes -plugin that advertises `wiki.connect`. The iOS workflow does not update or restart -an unrelated host. Deploy the committed plugin on the authorized host with the -existing plugin release procedure, then verify `hermes plugins doctor loopdy ---ci`, gateway health, and Wiki folder Save from the paired device. Existing -Wiki connections remain available on compatible older hosts; a missing new -operation produces an explicit host-update message. +Wiki folder registration works only on an older host whose plugin still +advertises `wiki.connect`: current plugin releases no longer have the Wiki routes. +The iOS workflow does not update or restart an unrelated host. A host without +the operation produces an explicit host-update message. Implementation references: [Fastlane TestFlight action](https://docs.fastlane.tools/actions/upload_to_testflight/), [Fastlane Xcode signing](https://docs.fastlane.tools/codesigning/xcode-project/). @@ -472,14 +472,13 @@ Implementation references: [Fastlane TestFlight action](https://docs.fastlane.to ## Hermes Bot Mode and instance regression checks Use [Hermes Bot Mode](HERMES_BOT_MODE.md) as the current runtime contract. Keep -its Link client, room-store and ChatModel integration suites green. Include +its native client, room-store and ChatModel integration suites green. Include pending-send recovery, canonical event IDs, cursor/authority checks, explicit Stop, failed-task retry and task-specific approvals. A direct-chat fixture is not proof of native Hermes room execution or of the bighelp Native harness. The UI gate includes default/AX XXXL suggested prompts, root content clearance -in portrait/landscape/accessibility sizes, Wiki navigation, Hosts/Connected -Devices and long-press instance switching. Keep primary-host preference separate +in portrait/landscape/accessibility sizes, Hosts and long-press instance switching. Keep primary-host preference separate from immediate selection. Preserve the chat performance gate alongside this work. @@ -498,14 +497,13 @@ Host selection must disable the old composer before any `await`. Account tests must distinguish protected-data recovery and partial-store failure from missing credentials or a lost/replaced verified connection. -Link catalog changes and Worker rollbacks must also run the signed HTTP catalog -regressions in `services/link/test/http.test.ts`, the full Link suite, type check -and deployment dry run. The regression fixture must include a forward-migrated +The retired account catalog still lives in the notification service Worker +(`services/link`). Changes to it and Worker rollbacks must also run the signed +HTTP catalog regressions in `services/link/test/http.test.ts`, the full +`services/link` suite, type check and deployment dry run. The regression fixture must include a forward-migrated Native row alongside an existing phone and Hermes host. Verify that v1 returns its supported kinds and that all persisted rows, grants and schema are unchanged. Do not fix this by revoking devices, changing keys or coercing Native to Hermes. -After deployment, verify the live signed account profile and device list; source -tests alone do not establish successful iPhone sign-in. For drawer changes, run `BighelpMenuUITests` and look at the drawer on screen, light and dark, checking hit targets as well as layout. Keep navigation before the bounded pinned-agent preview and sessions; diff --git a/docs/DIRECT_HERMES_SESSIONS.md b/docs/DIRECT_HERMES_SESSIONS.md index c02f38aa..fda18034 100644 --- a/docs/DIRECT_HERMES_SESSIONS.md +++ b/docs/DIRECT_HERMES_SESSIONS.md @@ -1,11 +1,17 @@ # Direct Hermes sessions -> Current transport contract: [NATIVE_TRANSPORT.md](NATIVE_TRANSPORT.md). Session creation, fork support and recovery have evolved since this narrative. Where transport details differ, use the versioned native contract and its source links. +> Transport: [NATIVE_TRANSPORT.md](NATIVE_TRANSPORT.md). The app reaches Hermes in two ways: WebSocket JSON-RPC on +> the dashboard's `/api/ws` (singular method names such as `session.create`, `session.delete`) and the dashboard's REST +> routes (`/api/sessions…`). Where this page and that contract differ, the contract and the code win. `DirectHermesSessionCatalogClient` is a feature adapter over the shared, owner-bound `WorkspaceOperationPerforming`. It owns no connection, credential, -agent loop, session database, ChatModel or canvas. The physical Direct adapter -maps its finite operations to native REST and TUI RPC. +agent loop, session database, ChatModel or canvas. `DirectHermesWorkspaceClient` +maps each `WorkspaceOperation` to either a dashboard REST request or a +WebSocket JSON-RPC call. Some operation names don't match the Hermes method: +for example `WorkspaceOperation.sessionDelete` (raw value `sessions.delete`) is +the dashboard's `DELETE /api/sessions/{id}`, while +`WorkspaceOperation.nativeSessionDelete` is the socket's `session.delete`. ## Identity and opening @@ -38,14 +44,20 @@ durable identifiers. A selected folder comes only from the explicitly injected host-folder provider; an active Project alone never supplies CWD. A returned CWD that disagrees with that request is unconfirmed, not a successful selection. -First canonical birth is a separate, explicitly authorized action. It checks the -exact `Bot Chat` registry, creates only when no prior positive identity exists, -persists the title through `session.title`, requires `pending:false`, and reads -the registry back. A title-conflict winner is adopted from that registry. +First canonical birth (`createFirstCanonicalChat`) is a separate, explicitly +authorized action. It checks the exact `Bot Chat` registry and creates only when +no prior positive identity exists. On a plugin with `native-bot-chat-v1` the +plugin makes the chat (see "Bot Chats are Hermes' own" below). Otherwise the app +uses `session.create`, persists the title through `session.title`, requires +`pending:false`, and reads the registry back. A title-conflict winner is adopted from that registry. No introductory prompt or other model call is submitted. -Native creation is neither atomic nor idempotent. An unknown create/title -outcome remains guarded; the client does not blindly retry it. A vanished +Native creation is not atomic. Every `session.create` sends the creation +record's `intentID` as `idempotency_key` (#440). Hermes keeps that key for about +5 minutes and answers a retry with the same session; a Hermes without the key +ignores it. So an unfinished first Bot Chat creates again under the same key, or +resumes the session Hermes made and asks for its title again. It never blocks +New Chat. An unknown title outcome stays guarded and is not blindly retried. A vanished unpersisted draft may remain unresolvable without a separate human decision. Creation receipts and the eventual canonical winner are retained as different facts, rather than relabeling a losing draft. @@ -79,7 +91,8 @@ turned into guessed attachment IDs or paths. Tool calls/results join only on exact unambiguous native call IDs. Their original content remains in activity detail, never assistant final text. Unknown outcomes use the app-only `recorded` lifecycle, which is neither running nor success and cannot drive -Live Activities. Legacy Link wire rejects that lifecycle. +Live Activities. The older activity wire model kept from the retired Link +transport (`Bighelp/Link/ActivityEventWireModels.swift`) refuses that lifecycle. In-memory history windows are bounded and disposable. Evicted or stale paging coordinates require a fresh read. This is not a competing transcript authority. @@ -145,9 +158,21 @@ route, which sends a fresh lowercase-UUID `request_id` and `expected_revision` ( when the row's detail has an integer `runtime_revision`, tries once more on `revision_conflict` or `stale_generation`, and sends the plain body when the detail has no revision. -Generic conversation deletion is disabled. The explicit internal -`deleteNativeRow` operation refreshes the catalog target and returns a row-only -receipt that warns other history may remain. Hermes deletes that row and +How a delete is sent: `DirectHermesSessionEditor.delete` first calls the socket's +`session.delete` (JSON-RPC). Hermes refuses it while the chat is open, and that +message reaches the person. A `4007` answer means the row is already gone and +counts as deleted. Only when the socket doesn't know the method does it fall +back to the dashboard's `DELETE /api/sessions/{id}`, fenced as above. + +Generic conversation deletion is disabled: the Direct catalog reports +`canDeleteConversation == false`, so the chat list offers no Delete, and +`delete(_:)` throws `nativeRowDeletionOnly`. The explicit internal +`deleteNativeRow` operation refreshes the catalog target, deletes through the +editor and returns a row-only receipt that warns other history may remain. The +app itself uses the editor's delete only to remove the empty chat a failed Bot +Chat title claim left behind. Bulk clean-up in Session Maintenance (Nerd Mode) +uses separate dashboard routes (`/api/sessions/bulk-delete`, `/api/sessions/empty`, +`/api/sessions/prune`) through `DirectHermesSessionMaintenanceClient`. Hermes deletes that row and delegate children but orphans branch/compression descendants; neither root nor tip deletion proves conversation-wide erasure. Root must obtain explicit row-semantic confirmation before exposing that narrower action. diff --git a/docs/DIRECT_STREAMING_AND_LIVE_VOICE.md b/docs/DIRECT_STREAMING_AND_LIVE_VOICE.md index 5a7f0a30..90e061dd 100644 --- a/docs/DIRECT_STREAMING_AND_LIVE_VOICE.md +++ b/docs/DIRECT_STREAMING_AND_LIVE_VOICE.md @@ -1,16 +1,18 @@ # Direct streaming and live voice -> Current transport contract: [NATIVE_TRANSPORT.md](NATIVE_TRANSPORT.md). Its Link fallback and account-backed admission discussion describes an older transport. Where transport details differ, use the versioned native contract and its source links. +> Transport: [NATIVE_TRANSPORT.md](NATIVE_TRANSPORT.md). This page covers streaming presentation and live voice only. bighelp keeps Hermes as the execution and canonical-history owner. The native app uses bounded session pages and a separate disposable live overlay. Full tool content is retrieved only when you open its complete-content reader. -## Routes +## Transport -A paired host can expose the plugin-owned listener through a private Tailscale HTTPS origin. Configure the plugin with `hermes loopdy direct configure --origin https://HOST:PORT --port LOOPBACK_PORT --enabled`, then restart Hermes when ready. In the app, select that host and use its optional Direct Connection section to verify and enroll the route. The account-paired identity is required; Tailscale membership alone is not authorization. +The app talks straight to the person's Hermes host: REST sign-in, WebSocket JSON-RPC on the dashboard's `/api/ws`, +dashboard REST, and the plugin's HTTP routes under `/api/plugins/loopdy/native/…` (`loopdy` is the plugin's legacy +ID). There is no bighelp account, no relay and no second route to fall back to. A command whose delivery is unknown +is never sent again by itself. The full contract is in [NATIVE_TRANSPORT.md](NATIVE_TRANSPORT.md). -Direct requests reuse existing chat, workspace, attachments, approvals, voice and device-tool interfaces. A connection failure before a request can use Link. An ambiguously delivered command is not automatically repeated through another route. Direct admission uses a fresh device lifecycle lease from the account service, so this is not indefinite cloud-independent authorization. - -State-backed relay clients explicitly negotiate `state-backed-presentation-v1`. Recoverable drafts and activity do not accumulate as an offline animation backlog for those recipients. Reliable commands, results, attachments and legacy clients retain their existing delivery contract. A slow subscriber receives a reset and reconnects without blocking another phone. Transient sequence tracking never advances the reliable replay watermark. +The old bighelp Link transport (account pairing, a plugin-owned listener set up with a `hermes loopdy direct` +command, `state-backed-presentation-v1` relay negotiation) is retired, and chat no longer uses it. ## Voice @@ -30,7 +32,7 @@ in the first person and never says "your agent" or "Hermes". ### GPT-Live -GPT-Live defaults to **Codex subscription** (`gpt-live-1-codex`). The plugin uses Hermes-managed subscription credentials; the phone receives no bearer token. Native WebRTC carries audio directly to the provider while authenticated bighelp messages carry setup, captions and job controls. The provider sideband is connected before the answer SDP is returned. +GPT-Live defaults to **Codex subscription** (`gpt-live-1-codex`). The plugin uses Hermes-managed subscription credentials; the phone receives no bearer token. The phone's WebRTC peer (`BighelpRealtimeAudioPeer`) carries audio directly to the provider. Setup, captions and job controls go through the plugin's `voice/status`, `voice/offer`, `voice/poll`, `voice/result` and `voice/close` routes (feature `native-voice-v1`) on the signed-in host connection. The provider sideband is connected before the answer SDP is returned. Requests the voice model hands over never wait for each other, so you can keep talking while work runs (`NativeLiveVoiceSession`). A request runs as a turn in the open chat when the chat is free. One made while the chat is working runs at once as a Hermes background task for that chat (`prompt.background`), beside the running turn; its answer goes back to the call when it arrives (`background.complete`) and shows in the chat. A background task uses the agent's Hermes tools, but not the phone's (Device access reaches only the chat itself). The same request said twice shares one run. Muting, barge-in and ending the call do not cancel accepted work. Unknown admission outcomes are reported, never resubmitted. @@ -39,7 +41,7 @@ An explicitly selected API-key mode uses the distinct public `gpt-live-1` protoc ### Gemini Live On plugins that list `native-voice-gemini-v1`, the plugin answers a Gemini offer with a single-use token made -from the agent's own `GEMINI_API_KEY` (the key stays on the host). The token locks the model, voice, brief and +from the agent's own `GEMINI_API_KEY` or `GOOGLE_API_KEY` (the key stays on the host). The token locks the model, voice, brief and tools. `GeminiLiveAudioPeer` opens the phone's own WebSocket to Gemini with it and sends only the model name, then 16 kHz microphone audio from one voice-processing `AVAudioEngine`, which cancels the agent's voice from the microphone without muting it, so the person can talk over the agent. @@ -95,10 +97,10 @@ voice only: no realtime model. The button shows only when the host can speak for ## Security and compatibility -The plugin does not modify Hermes core or start a second model-execution service. All jobs use supported platform-adapter ingress and lifecycle/approval/clarification callbacks. iPhone device tools remain opt-in and require the existing verified host-context capability; unsupported hosts do not gain authority from a voice transcript or device identifier. +The plugin does not modify Hermes core or start a second model-execution service. Voice work runs on the chat's own socket, as an ordinary turn (`prompt.submit`) or a Hermes background task (`prompt.background`), with Hermes' own approval and clarification requests. iPhone device tools remain opt-in and require the existing verified host-context capability; unsupported hosts do not gain authority from a voice transcript or device identifier. Per-session protected content files replace repeated whole-catalog transcript writes. Migration retains the old snapshot until the new manifest commits. Failed writes preserve the prior committed content. Account erasure removes all scoped revisions. ## Validation boundaries -Automated verification covers state paging, content reconstruction, cache saturation, owner changes, independent jobs, subscription wire formatting, relay recipient isolation, native audio offer/answer handling and simulator UI. The subscription endpoint was exercised using actual Hermes-managed authentication with native SDP. Physical-device testing is not required for this release. Network conditions, Bluetooth/audio hardware and subjective conversational quality still warrant normal beta testing. +Automated verification covers state paging, content reconstruction, cache saturation, owner changes, independent jobs, subscription wire formatting, native audio offer/answer handling and simulator UI. The subscription endpoint was exercised using actual Hermes-managed authentication with native SDP. Physical-device testing is not required for this release. Network conditions, Bluetooth/audio hardware and subjective conversational quality still warrant normal beta testing. diff --git a/docs/HERMES_BOT_MODE.md b/docs/HERMES_BOT_MODE.md index 49e3be71..15f62d23 100644 --- a/docs/HERMES_BOT_MODE.md +++ b/docs/HERMES_BOT_MODE.md @@ -1,30 +1,36 @@ # Hermes Bot Mode -> Current transport contract: [NATIVE_TRANSPORT.md](NATIVE_TRANSPORT.md). Its legacy Link transport discussion is historical; the current native groups path uses core JSON-RPC. Where transport details differ, use the versioned native contract and its source links. +> Transport: [NATIVE_TRANSPORT.md](NATIVE_TRANSPORT.md). Group chats use Hermes' own `groups.*` JSON-RPC methods over +> the app's native WebSocket connection to the dashboard. The retired bighelp Link relay plays no part. Some type +> names still say `Link` (for example `BighelpLinkHermesBotModeClient`, aliased as `HermesHostedRoomClient`); they +> are legacy names only. ## Product boundary -bighelp supports Hermes and is building its own bighelp Native harness. Neither -path replaces the other. The Goose-based iOS/Companion runtime remains under -development; the local Bot Mode fixture runner is not that production engine. - -For Hermes hosts, Hermes owns room membership, routing, task execution, -idempotency, fencing and the durable event log. The iOS app presents that state through one typed `groups.*` client. It can use -native authenticated Direct workspace operations or explicitly selected, -authenticated encrypted Link. Direct does not require a bighelp account. -The plugin forwards these fixed operations through Hermes' existing -`tui_gateway.server.handle_request` dispatcher. No second daemon, private -database adapter or synthesized member-turn prompt is needed. +Group chats run on Hermes. The local Bot Mode fixture runner +(`BotModeFixtureClient`) only drives fixtures and tests; it is not a production +engine. + +Hermes owns room membership, routing, task execution, idempotency, fencing and +the durable event log. The iOS app presents that state through one typed +`groups.*` client (`HermesHostedRoomClient`, made in `NativeWorkspaceRuntime`). +It sends each operation as a `WorkspaceOperation` that +`DirectHermesWorkspaceClient` maps to a core Hermes JSON-RPC call on the +signed-in socket, with a fixed list of allowed fields per method. No bighelp +account, second daemon, private database adapter or synthesized member-turn +prompt is needed. The plugin is needed only for the optional room activity and +typing feed (see below), which reads Hermes' own room state through its +`tui_gateway.server.handle_request` dispatcher. ## Readiness and ownership -The client is bound to the selected transport's verified authority, selected host -and authentication/connection generations. Only that host's rooms are listed; +The client is bound to the current `WorkspaceOwner`: the selected host, its +sign-in and its connection generation. Only that host's rooms are listed; switching hosts retires old catalog results, observers and actions before the replacement context is exposed. Check ownership and cancellation around every await. A stale completion must -never update a newly selected instance. Negotiate `groups.capabilities` after -Link verification. Execution requires protocol 2, a running driver, an authority +never update a newly selected instance. Negotiate `groups.capabilities` once the +connection is signed in. Execution requires protocol 2, a running driver, an authority identifier, the necessary methods and the `room_identity` and `monotonic_log` features. Advertising methods alone does not prove that the driver runs. Peer room-link enablement is not required for local hosted rooms. @@ -75,11 +81,9 @@ verified same-owner data; no automatic cross-owner or cross-transport pending intent import is authorized. Hermes history is normally recovered through its room catalog and log. -Link advertises `groups-results-v1` for a separately bounded groups-result -envelope. Only an opted-in request receives the corresponding result marker. -Legacy envelopes and limits remain unchanged. Native log authority is validated -at its exact schema path; this never permits gateway or secret-bearing keys in -arbitrary workspace payloads. Event bytes are never truncated to fit transport. +Native log authority is validated at its exact schema path; this never permits +gateway or secret-bearing keys in arbitrary workspace payloads. Event bytes are +never truncated to fit transport. ## Agents on other computers @@ -285,20 +289,18 @@ an unconfirmed close relies on the host's bounded inactivity lease. ## Verification and release Run `HermesBotModeContractTests`, `HermesGroupsHostPathTests` (both paths' recorded replies), `HermesGroupRoomSettingsTests`, `BighelpLinkHermesBotModeClientTests`, -`BighelpLinkHermesBotModeApprovalTests`, `BotModeRoomStoreTests` and +`BighelpLinkHermesBotModeApprovalTests`, `NativeHermesGroupFlowTests`, `BotModeRoomStoreTests` and `ChatBotModeIntegrationTests` along with the chat interaction regression gate. -The Link client tests cover request shapes, cancelled/stale results, idempotency, +The `BighelpLinkHermesBotModeClient` tests (a legacy name) cover request shapes, cancelled/stale results, idempotency, cursor validation and driver status. Store checks cover persistence, replay, capability gating and room execution. Preserve the separate local fixture tests. -Run the plugin contract and workspace-control suites with the official Hermes -source on `PYTHONPATH`. Publish the matching plugin separately from the iOS +Run the plugin's room activity tests (`tests/test_room_activity.py`) with the +official Hermes source on `PYTHONPATH`. Publish the matching plugin separately from the iOS archive, then activate it using Hermes' supported installer/updater. An app upload does not activate a plugin on a user's host. Record source, simulator, live host and TestFlight evidence separately; none substitutes for the others. -Include `test_hosted_room_contract` and the portable -`bighelp-plugin/tests/fixtures/groups-result-v1.json` vector for negotiated -envelope and encryption coverage. +`Scripts/RoomLinkProbe.py` checks a room across two isolated real hosts. Room discovery on the Hermes host must exclude invalid profile directories and deleted-profile tombstones. In the September 10 host version, enumerating every diff --git a/docs/IDLE_STARTUP_RELIABILITY.md b/docs/IDLE_STARTUP_RELIABILITY.md index 2fea0b6f..712b9e7f 100644 --- a/docs/IDLE_STARTUP_RELIABILITY.md +++ b/docs/IDLE_STARTUP_RELIABILITY.md @@ -35,8 +35,9 @@ Treat these as app investigation evidence, not an iOS-version explanation. They must not start a dashboard request per historical answer. An account boundary discards a pending refresh from the previous owner. - Keep live turn completion and strict reference-send durability boundaries. - Preserve encrypted sequence validation, event identities, ordered receipt - commit and acknowledgements. No transport data is dropped to improve timing. + Preserve event identities. No transport data is dropped to improve timing. + (At build 14 this also covered the Link transport's encrypted sequence + validation, ordered receipts and acknowledgements; Link is now retired.) ## Reproduction and evidence limits diff --git a/docs/IOS27_DESIGN_CONTRACT.md b/docs/IOS27_DESIGN_CONTRACT.md index ce69a69e..a639f0a5 100644 --- a/docs/IOS27_DESIGN_CONTRACT.md +++ b/docs/IOS27_DESIGN_CONTRACT.md @@ -14,20 +14,26 @@ The retained Figma design-context responses establish native toolbar, sheet tool A new user should understand how to connect and chat in roughly 30 seconds, with the low effort of Muse AI or similar chat apps. This is a comprehension target, not an unmeasured authentication-time guarantee. Keep one obvious primary action, group related settings in clear menus, and keep those settings editable. A setting does not need a separate screen. The source inventory preserves capabilities; it is not a page quota. Use progressive disclosure for advanced choices and recovery mechanics without hiding safety consequences. -The primary first-run path is Welcome → Connect → Choose your mode. Appearance customization is optional, not a required stop before setup, and remains accessible through Settings. After Connect, the bighelp plugin step is optional; notifications are offered only once the plugin is in. Every optional step has a small Skip at the top right; Connect and Choose your mode don't. The mode cards (Bots, Sessions, Code) each open a preview of their mode, and the screen says the choice can be changed later. +The first-run path (`FirstRunOnboardingView`) is Welcome → Connect → Choose your mode, with optional steps between them. The progress bar counts four steps: Welcome, Connect, Plugin or Notifications, and Your mode. + +1. **Welcome.** Get Started goes on to Connect. A small Appearance options button under it opens the optional Appearance step (System, Light or Dark, and the bubble color). That step has Back and Skip, is not counted in the progress bar, and goes on to Connect. Appearance stays editable in Settings. +2. **AI data agreement.** Before Connect, anyone who hasn't agreed yet is asked once (`AIDataConsent`). +3. **Connect.** Host setup. It has no Skip. +4. **Plugin.** Optional, with Skip. It installs the bighelp plugin on the computer. +5. **Notifications.** Optional, with Skip. It shows only after the plugin is installed and running. Skip on the plugin step, or a plugin that still needs Hermes restarted, goes straight to the mode. +6. **Choose your mode.** No Skip. The cards are Bots, Chat and Code (`FirstRunMode` `.bots`, `.sessions`, `.code`). Tapping a card shows its preview large, with its Use button. The screen says the choice can be changed later. ## Visual system ```text -Saved theme document, unchanged -├── Explicit document preview and portable export +Saved appearance choices (light/dark, accent) └── Live presentation ├── Shared adaptive neutral surfaces, labels and status colors ├── Shared native typography, icon treatment and geometry └── Theme accent → outgoing messages and appropriate actions/links ``` -The same neutral system applies to every bubble color. Light/dark presentation adapts through semantic platform colors. Resolve outgoing text contrast against the actual displayed accent, including dynamic system colors, not only retained hex fields. Non-system accents minimally adjust brightness when needed for readable action/link ink on native canvas, card and incoming-bubble surfaces, including elevated surfaces; the default keeps native system blue. Partner and custom themes were removed; don't bring back a second theme system that can overwrite the bubble color. +The same neutral system applies to every bubble color. Light/dark presentation adapts through semantic platform colors. Resolve outgoing text contrast against the actual displayed accent, including dynamic system colors, not only retained hex fields. Non-system accents minimally adjust brightness when needed for readable action/link ink on native canvas, card and incoming-bubble surfaces, including elevated surfaces. The default accent is Ink (`BighelpBubbleColor.graphite`). Partner and custom themes, and theme import and export, were removed. Don't bring back a second theme system that can overwrite the bubble color. Use native navigation, toolbars, search, lists, forms, sections, menus, alerts, pickers, text inputs and system sheets. Custom content remains appropriate for message bubbles, agent artwork, inline artifacts and expressive media. Do not recreate native glass with decorative overlays around every control. @@ -42,7 +48,7 @@ Use native navigation, toolbars, search, lists, forms, sections, menus, alerts, ## Preservation boundaries -Retain every current-main capability and its production construction path: first-run progress, root/modal input ownership, optional notification setup, clone/template creation, readiness/retry protection, structured multi-question Clarify, native selection/reactions, exact-owner editing, live activity labels, native goal controls, configured-workspace artifacts, theme import and staged provider/model selection. +Retain every current-main capability and its production construction path: first-run progress, root/modal input ownership, optional notification setup, clone/template creation, readiness/retry protection, structured multi-question Clarify, native selection/reactions, exact-owner editing, live activity labels, native goal controls, configured-workspace artifacts and staged provider/model selection. Models, transport contracts, canonical timeline identity, data retention, security/permission boundaries and uncertain-operation handling are not redesign targets. Platform-owned dialogs are qualified through their real invocation and dismissal, not rewritten. diff --git a/docs/IPHONE_DEVICE_TOOLS.md b/docs/IPHONE_DEVICE_TOOLS.md index c22e0002..cfdcd16f 100644 --- a/docs/IPHONE_DEVICE_TOOLS.md +++ b/docs/IPHONE_DEVICE_TOOLS.md @@ -1,15 +1,13 @@ # iPhone tools for Hermes -> Current transport contract: [NATIVE_TRANSPORT.md](NATIVE_TRANSPORT.md). Its Link delivery discussion is historical; current native tools use the authenticated native device-tools bridge. Where transport details differ, use the versioned native contract and its source links. +> How the app talks to Hermes in general: [NATIVE_TRANSPORT.md](NATIVE_TRANSPORT.md). This page is the +> contract for the phone tools and their channel, the plugin's `device-tools/*` routes. -Requires bighelp plugin 2.11.0 or later on the Hermes host. - -Host plugin 2.11.2 is required for the corrected phone-tool delivery path. -Version 2.11.1 accepts Hermes' canonical composite turn IDs; 2.11.2 schedules the -whole tool operation on the gateway's Link event loop. Hermes async tools run on -separate worker loops and cannot directly acquire the gateway connection's send -lock or own its response futures. Update the host plugin and restart the gateway -to activate these fixes. Build 13 and existing iOS permissions remain compatible. +The phone tools need the bighelp plugin on the Hermes host, with `native-device-tools-v1` in +`/native/context`. That feature covers Apple Health, Calendar and Reminders. Every other tool has a feature +of its own (see [Supported operations](#supported-operations)). The plugin lists none of them when Hermes +has no tool execution middleware for it ([Components](#components-and-required-versions)). After a plugin +update, restart the Hermes dashboard so the new copy runs. ## User contract @@ -22,14 +20,16 @@ keep the post-fetch authorization check. See Apple's [asynchronous reminder retrieval](https://developer.apple.com/documentation/eventkit/retrieving-events-and-reminders). Device access has independent switches for Apple Health, Calendar, Reminders, Contacts, -Photos, Location, Arriving and leaving, Alarms and timers, Music, Focus and Shortcuts. +Photos, Location, Arriving and leaving, Alarms and timers, Music, Focus, Shortcuts, +Appearance and Show you around (Navigation). Apple Health came back in #750 (see [Apple Health](#apple-health)); 2.3.0 (105) had removed it after App Review (guideline 2.5.1) found no health feature in the app. Every data control starts off. An agent can still ask for one that's off: its call shows a connect card in the chat ([Connect cards](#connect-cards)), whose Turn on flips the same switch. Enabling one requests its native iOS permission from -that explicit foreground action. Appearance ("Let agents change how bighelp looks") is -the exception: it shares no data and Appearance undoes any change, so it's on until the -person turns it off, and it needs no iOS permission. Calendar and Reminders authorize direct reads, +that explicit foreground action. Appearance ("Let agents change how bighelp looks") and +Navigation ("Let agents show you around bighelp") are the exceptions: they share no data +and change nothing the person can't change back, so they're on until the person turns them +off, and they need no iOS permission. Calendar and Reminders authorize direct reads, creation, updates and deletion after enablement, with no per-operation approval. Location is read-only. OS permission by itself never enables agent access. @@ -42,7 +42,7 @@ switch off: the tool is paused (`isUsable` is false, it isn't offered to the hos the row says to allow access in iOS Settings; it comes back when iOS allows it again. Turning a control off invalidates active work immediately. Switching host, signing out, the background grace ending or losing protected-data access invalidates in-flight -operations. Account erasure deletes persisted grants and mutation outcomes. +operations. Re-enabling a grant cannot revive a read started under an older grant revision. The phone must be unlocked and connected, and bighelp open: active, or inactive (a @@ -62,34 +62,31 @@ reminder text or request arguments. The journal is protected, atomically written excluded from backups and bounded to 512 records / 2 MB. No raw Apple data should be added to diagnostics. -Hermes and the future bighelp Native harness remain complementary. The unfinished -Native harness is not required and is not treated as operational. - ## Components and required versions | Component | Responsibility | | --- | --- | -| Hermes `ToolExecutionContext` extension | Carries immutable authenticated ingress ownership to official plugin handlers and hooks, with official session/turn/tool-call IDs. | -| bighelp plugin 2.11.2 | Registers `iphone_health`, `iphone_calendar`, `iphone_reminders`; uses the gateway connection loop to target the verified phone and correlate canonical Hermes turn IDs. | -| Link relay with `directed-frames-v1` | Negotiates exact-recipient delivery and queues only for that active paired device. Legacy sockets never receive a broadcast fallback. | -| iOS `DeviceToolPermissions` | Persists opt-in grants and fences asynchronous work by scope/revision. | -| iOS `DeviceToolCoordinator` | Validates envelopes, deadlines, ownership and grants; bounds concurrency and journals mutation outcomes. | -| iOS `AppleDeviceToolService` | Executes the finite HealthKit, EventKit and location operations with authorization checks around native boundaries. | -| iOS `DeviceAccessCardStore` | Shows a connect card in the chat when an agent calls a tool that's off, and lets the call go on once the person turns it on (`DeviceAccessAsk`). | -| iOS live socket | Receipts authenticated requests before native execution and sends directed correlated results without blocking chat streaming. | - -The generic Hermes source extension is documented in -`docs/TOOL_EXECUTION_CONTEXT.md` in the Hermes checkout. It is required: plugin -registration omits phone tools on older Hermes versions. The context is -runtime-only, excluded from prompts, tool schemas, transcripts and session -persistence. Queued events retain exact ownership; different owners are not -merged or steered into each other's turns. CLI, cron, restart-recovered events -and delegated children lack phone context and fail closed. Never infer a phone -from the last active chat or model-provided arguments. - -The plugin constructs context from the verified Link frame's phone ID and -phone epoch, with the authenticated host ID as an attribute and profile as -scope. Phone and host authorization epochs are independent. +| Hermes tool execution middleware | Hermes runs each `iphone_*` call through the middleware the plugin registers (`register_middleware`, `hermes_cli.middleware`), with Hermes' own profile, session, turn and tool call IDs. A Hermes without that middleware surface gets no phone tools: the plugin leaves `native-device-tools-v1` out of `/native/context`. | +| Plugin phone-tool hub (`native_device_tools.py`) | Holds each chat's channel and its lease, checks every call's arguments (`device_tool_contract.py`), queues calls for the phone, waits for answers and remembers finished calls so a retry never runs twice. Every profile's copy of the plugin in one Hermes process shares one hub. | +| Plugin routes `device-tools/connect`, `poll`, `result`, `close` | The phone's side of the channel, under `/api/plugins/loopdy/native/`, behind the dashboard's own sign-in. | +| iOS `NativeDeviceToolSession` | Opens the open chat's channel, polls it, checks each request, sends each result and closes the channel. Opens it again when the host ended it (`runReopeningWhileHeld`). | +| iOS `DeviceToolPermissions` | Keeps the switches (`grantsKey`) and a revision that fences work started under an older grant. | +| iOS `DeviceAccessCardStore`, `DeviceAccessAsk` | Shows a connect card in the chat when an agent calls a tool that's off, and lets the call go on once the person turns it on ([Connect cards](#connect-cards)). | +| iOS `DeviceToolCoordinator` | Checks each request's envelope, deadline, owner and grant before and after it runs. Runs at most four calls and one change at a time, and journals changes (`DeviceToolFileJournal`). | +| iOS `DeviceToolCatalog` | Lists every operation the phone answers and which ones are journaled. | +| iOS `DeviceToolRouter` | Sends each operation to the `DeviceCapabilityTool` that owns it (Contacts, Photos, Arriving and leaving, Alarms, Music, Focus, Shortcuts) after it checks that iOS still allows it. Apple Health, Calendar, Reminders and Location go to `AppleDeviceToolService`. The coordinator calls `DeviceAppearanceTool` and `DeviceNavigationTool` itself. | + +Hermes passes the call's coordinates to the middleware. The plugin drops any channel, device, host, +session, agent, turn or request ID that the model adds to the arguments. A call matches a channel only by its +agent and chat (`(profile, session)`). A chat with no channel (the command line, a scheduled job, a helper +agent's own session) has no phone: its call fails with `phone_unavailable` at once, unless that chat had a +channel in the last two minutes ([Transport](#transport-and-ownership)). Never infer a phone from the last +active chat or from model-provided arguments. + +The phone opens the channel with its own device ID (`loopdy.native-device-tools.device-id`, a UUID kept +on the device), the host ID and authorization epoch of its scope (`DeviceToolScope`), the agent and the +chat's session ID. The plugin copies them into every request, and checks that each result names the same +ones. Every agent on the host has the phone tools when the plugin lists `native-device-tools-agents-v1` (plugin 3.30.0): Hermes loads a separate copy of the @@ -114,55 +111,92 @@ connects again in a moment; if another device keeps the chat, it says so. A channel that the host ended opens again by itself while the chat stays open and its tools stay on. The host ends a channel that the phone still uses when its -30-second lease runs out while a slow tool runs (the phone does not poll while a -tool runs), when the same phone opens another channel for the chat, when Hermes +30-second lease runs out while a slow tool runs past its call's deadline (the phone +does not poll while a tool runs, and the plugin holds the channel only until that +deadline), when the same phone opens another channel for the chat, when Hermes unloads the agent's plugin, or when the plugin starts again. The next poll or answer then gets `phone_unavailable` or `channel_not_found`. A lost connection, a -time-out, a changed context (`context_changed`) and a plugin that is not ready -(`device_tools_unavailable`) also end a channel. The phone opens a new channel +time-out, a changed context (`context_changed`), a missed request (`feed_gap`), a +channel opened under another sign-in or an earlier run of the plugin +(`channel_owner_changed`) and a plugin that is not ready (`device_tools_unavailable`) also end a channel. The phone opens a new channel after 1, 2, 4, 8, 16 and 32 seconds (`NativeDeviceToolSession.reopenWaits`). Then it stops, and Device access says that it is not connected. The first try comes -quickly: for two minutes, the plugin keeps a call that finds no channel waiting -for the phone that had one, and the new channel takes the call. A channel that -stayed open for a minute starts the waits again. A refusal that a new channel -can't fix (`profile_not_served`, `profile_not_found`, `session_not_found`, -`channel_capacity`) stops at once. A change to the chat or connection, or the end -of the background grace, cancels the wait. +quickly: for two minutes (`LAPSE_MEMORY_SECONDS`), the plugin keeps a call that +finds no channel waiting for the phone that had one, and the new channel takes the +call. A channel that stayed open for a minute starts the waits again. A refusal +that a new channel can't fix (`profile_not_served`, `profile_not_found`, +`session_not_found`, `channel_capacity`) stops at once. A change to the chat or +connection, or the end of the background grace, cancels the wait. A tool that runs past its call's window loses only that answer. Location's -precise-location question, its fix and the address can take 40 seconds, and the -host waits 30. At the deadline the host tells the agent, and then it refuses the -late answer (`result_replay`, `result_unknown` or `result_expired`). The channel -continues with the next call. +precise-location question, its fix and the address can take a while, so the +plugin gives `location.current` 60 seconds instead of the usual 30. At the +deadline the host tells the agent, and then it refuses the late answer +(`result_replay`, `result_unknown` or `result_expired`). The channel continues +with the next call. ## Transport and ownership -The existing encrypted Link connection carries version-1 -`device.tool.status`, `device.tool.request` and `device.tool.result` payloads. -The outer frame's `targetDeviceId` must identify an active opposite-role device -in the same account. Unknown, revoked, wrong-role, self or unsupported targets -are rejected without fan-out. This controls routing; existing account content -encryption is shared across paired account participants, not a new -recipient-specific encryption scheme. +The phone reaches the plugin over HTTP, on the same signed-in dashboard connection +as the rest of the app's plugin routes. Each route is a `POST` to +`/api/plugins/loopdy/native/device-tools/` with the native request guard: +`If-Match` with the context ETag and a lowercase-UUID `X-Loopdy-Request-ID`. The +phone refuses an answer that doesn't echo its request ID or that has another ETag. +Answers are at most 256 KiB. + +- `connect`: `channelId` (a new lowercase UUID for each channel), `deviceId`, + `hostId`, `authorizationEpoch`, `agentId`, `sessionId` and `enabled` (the tools + that are on and that iOS allows now). With `native-device-permission-request-v1` + it also sends `askable` ([Connect cards](#connect-cards)). The phone leaves out a + tool whose own feature the plugin doesn't list, because an older plugin refuses + the whole channel over a name it doesn't know. The answer is + `{channelId, connected: true}`. Refusals that open nothing: `channel_ambiguous`, + `profile_not_served`, `profile_not_found`, `session_not_found`, + `channel_capacity` (64 channels on a host) and `channel_id_consumed`. +- `poll`: `channelId` and `after`, the last sequence the phone handled. The + answer has `next` and at most 8 `requests`, each `{sequence, request}`, in + order. The phone checks the whole batch before it runs any of it. Each poll + renews the channel's 30-second lease. The phone polls every 0.75 seconds. A + channel with only Appearance and Navigation polls every 8 seconds while the + chat's turn isn't running. +- `result`: `channelId` and one `device.tool.result`. The answer is + `{accepted: true}`. An answer the host no longer waits for is refused with + `result_replay`, `result_unknown` or `result_expired`. +- `close`: `channelId`. When the channel ends only because bighelp went to the + background, and the plugin lists `native-device-tools-wait-v1`, the phone adds + `reason: "paused"`: calls the phone never received keep waiting for it. Any + other close fails the chat's waiting calls. Requests and results bind `requestId`, `deviceId`, `hostId`, `authorizationEpoch`, `sessionId`, `agentId`, `turnId`, `operation` and -`sentAt`; requests also carry `expiresAt` and bounded arguments. Official -tool-call coordinates generate a stable request ID. Reusing that ID with -different arguments produces a conflict. The native request limit is 20 KB; -the plugin additionally limits arguments to 16 KB. Native results are bounded -to 128 KB. Host timeout is normally 30 seconds (bounded to 20–60 seconds); -the native envelope permits no more than 120 seconds, or 300 seconds for a call to a -tool the channel offered as `askable` ([Connect cards](#connect-cards)). - -Status is advisory. Every operation still checks the live native grant, -open (active, inactive or background grace)/protected-data state, selected host, -account and expiry. Results -recheck those conditions after native execution and while waiting for the -outbox. Reconnect or backpressure cannot replay private results after permission -revocation, ownership change or downgrade to a legacy relay. A pending private -result without its original in-memory authorization guard is retired through -authenticated outbox reconciliation. +`sentAt`; requests also carry `expiresAt` and bounded arguments. Hermes' +tool-call coordinates make a stable request ID. Reusing that ID with +different arguments is `request_conflict`. The request limit is 20 KiB, and +arguments at most 16 KiB, on both sides. Results are bounded to 128 KB. + +The host gives most calls 30 seconds. `shortcuts.run`, `photos.save` and +`location.current` get 60, and the first two 10 more for a late answer. A call +to a tool the channel offered as `askable` gets 300. The phone refuses a request +whose window is longer than 120 seconds, or 300 for an askable tool. + +Before an operation runs, and again after each native step (`authorize`), the +coordinator checks: + +- the live switch and its grant revision +- that bighelp is open (active, inactive, the background grace or a Shortcuts handoff) +- protected data +- the selected host and chat +- the expiry + +The phone never sends a result made under a grant or owner that changed. It +answers `owner_changed`, `permission_disabled`, `device_unavailable`, +`request_cancelled` or `request_expired` instead. + +When the phone never answers, the host tells the agent which kind of silence it +was. A call the phone never received, or one that only reads, is +`phone_unavailable`: the agent may try again. A call that the phone received and +that can change something is `outcome_unknown`, and so is every `shortcuts.run` +and `photos.save`: the agent must check before it tries again. Native work permits at most four active operations and one mutation. The plugin keeps bounded pending requests and metadata-only mutation outcomes; read payloads @@ -541,8 +575,9 @@ the person types the names their agents may run in Device access › Shortcuts bighelp with its output. Returns `{id, status (completed, cancelled or failed), output, truncated}` (output ≤ 8000 characters; a failed run's output is Shortcuts' `errorMessage`). The journal keeps only `id`, so a retry - never runs it twice. The host waits up to 60 seconds and holds the channel's - lease meanwhile; a run that doesn't come back in time is `outcome_unknown`. + never runs it twice. The host gives the call 60 seconds, takes a late answer + for 10 more, and holds the channel meanwhile; a run that doesn't come back in + time is `outcome_unknown`. A second run while one is out is `device_busy`. - While the run is out in Shortcuts (at most 60 seconds), bighelp counts as open for the phone tools (`DeviceToolHandoff`): leaving for Shortcuts doesn't @@ -558,15 +593,18 @@ A contact or event read from a picture goes through a reviewed draft ([Image drafts](IMAGE_DRAFTS.md)), never straight to Contacts or Calendar. So in a chat that holds a picture the person sent, or one where `photos.get` gave the agent a photo, the phone answers `contacts.create` and `calendar.create` with -`failed` and code `review_required` before it journals or touches anything, and -`payload.note` tells the agent to use `bighelp_draft_contact` or -`bighelp_draft_event`. Lists, updates, deletes, every other tool, and every chat +`failed` and code `review_required` before it journals or touches anything +(`ImageDraftWriteFence`), and `payload.note` tells the agent to use +`bighelp_draft_contact` or `bighelp_draft_event`. The plugin gives the same answer +before the call leaves the host when it knows the chat holds such a picture. Lists, updates, deletes, every other tool, and every chat without a picture behave as before, standing grants included. ## Mutation reconciliation -Persist the request fingerprint as started before calling EventKit. Completed -mutations retain only ID/revision/deleted metadata. A duplicate completed request +Every operation `DeviceToolCatalog` marks as journaled is a mutation. The +coordinator saves the request fingerprint as started (`DeviceToolFileJournal`, +`device-tool-outcomes-v1.json`) before the native call. Completed mutations +retain only ID/revision/deleted metadata, and a shortcut run's `status`. A duplicate completed request returns the known result. A started request without a confirmed outcome returns `outcome_unknown` and is never automatically executed again. A callback failure after a possible commit is also uncertain; inspect current native state before @@ -599,25 +637,21 @@ The app reads HealthKit and never writes it. Keep it that way: Native suites: `DeviceToolPermissionsTests`, `AppleDeviceToolServiceTests`, -`DeviceToolCoordinatorTests`, `DeviceToolFileJournalTests`, `DeviceLocationToolTests`, -`DeviceAppearanceToolTests`, `AgentAppearanceUITests`, `DeviceAccessCardsTests`, -`DeviceAccessCardUITests`, -`BighelpLinkDirectedDeviceToolTests`, existing socket/backpressure and account -erasure suites, and `DeviceToolPermissionsUITests`. - -Plugin tests exercise registration with/without supported Hermes context, -authenticated ownership, independent phone/host epochs, same-second grant -transitions, directed frames, correlation, timeouts, concurrent identities, -mutation deduplication, uncertain writes and non-caching of private reads. -Hermes tests cover runtime-only context propagation, queued owner separation, -delegation isolation and official tool-call identifiers. Relay tests verify -single-device queues and negative routing without legacy fallback. - -The registered Calendar handler must also be tested from a separate worker loop -with the real encrypted Link client and a contended gateway send lock. Verify -one directed request, gateway-owned result futures, permission disable and -disconnect during a pending call, and a stopped gateway loop. Same-loop fake -clients do not establish the Hermes-to-phone delivery boundary. +`DeviceToolCoordinatorTests`, `DeviceToolFileJournalTests`, `NativeDeviceToolSessionTests`, +`DeviceToolHandoffTests`, `DeviceAccessCardsTests`, `DeviceLocationToolTests`, +`DeviceAppearanceToolTests`, `AgentDriveTests`, the other `Device*ToolTests` (Contacts, +Photos, Arriving and leaving, Alarms, Music, Focus, Shortcuts), `ImageDraftWriteFenceTests`, +and the UI tests `DeviceToolPermissionsUITests`, `DeviceAccessCardUITests`, +`AgentAppearanceUITests` and `AgentDriveUITests`. `DeviceAccessHostUITests` runs against a +real host. + +Plugin tests (`test_native_device_tools.py`, `test_native_device_tools_agents.py`, +`test_native_device_permission_request.py`, `test_device_tool_contract.py`, +`test_iphone_device_capabilities.py`) cover the middleware registration with and without +Hermes' middleware surface, channel ownership and leases, the same phone replacing its +own channel, calls that wait for a paused or lapsed phone, request IDs from Hermes' +call coordinates, timeouts, concurrent chats and agents, mutation deduplication, +uncertain writes, askable calls and non-caching of private reads. Run iPhone and iPad composer interaction checks alongside this integration. Preserve the full visible input focus target and microphone/Send alignment in diff --git a/docs/LINK_RETENTION.md b/docs/LINK_RETENTION.md index ca0183c1..6da0966e 100644 --- a/docs/LINK_RETENTION.md +++ b/docs/LINK_RETENTION.md @@ -1,5 +1,14 @@ # Legacy Link recipient overflow policy +> **Historical.** This page covers the retired Link transport (bighelp account, pairing, and encrypted frames +> sent through the Link Worker's per-account Durable Object). The app no longer uses it. Chat and plugin features +> now run over native Hermes: see [NATIVE_TRANSPORT.md](NATIVE_TRANSPORT.md), and +> [SECURITY_AND_PRIVACY.md](SECURITY_AND_PRIVACY.md) for what is stored where. The app keeps no Link frames. At +> launch it removes the old Link keychain items and settings one time (`BighelpLinkAccountRetirement`; a locked +> phone tries again at the next launch). The Worker in `services/link` (`link.loopdy.app`) is now the notification +> service. Its source still holds the Link frame queue and the limits on this page +> (`services/link/src/pending-delivery.ts`), but no current app build sends frames to it. + Related incident: #75. This repair changes legacy encrypted-v1 admission only; it does not require Direct, recipient lanes, native-session migration, a host plugin update, or a new native application build. diff --git a/docs/LONG_SESSION_PERFORMANCE.md b/docs/LONG_SESSION_PERFORMANCE.md index fa932467..607b9b6e 100644 --- a/docs/LONG_SESSION_PERFORMANCE.md +++ b/docs/LONG_SESSION_PERFORMANCE.md @@ -54,7 +54,7 @@ This is removal of a specific history-scaled UI cost, not an end-to-end app spee - The actual ChatView in a UIHostingController follows growing same-row content and idle incoming messages. - Earlier focused runs also passed live-tail projection, activity insertion/group append and background catch-up preservation checks. -Use the repository's explicit `xcodebuild test` command and select `BighelpAppReadinessTests`, the named recovery tests in `BighelpLinkLiveSocketTests`, and the scroll/visible-canvas tests in `ChatModelTests`. Performance reproduction: `-only-testing:'BighelpTests/ChatModelTests/timelineScrollObservationCostDoesNotGrowWithSettledHistory()'`. Use one explicit project, simulator and reusable DerivedData root. A shared runner switched to an unrelated checkout during one attempted retry reproduction; that zero-selection result was excluded and the correct checkout was exercised directly. +Use the repository's explicit `xcodebuild test` command and select `BighelpAppReadinessTests`, the named recovery tests in `BighelpLinkLiveSocketTests`, and the scroll/visible-canvas tests in `ChatModelTests`. Performance reproduction: `-only-testing:'BighelpTests/ChatModelTests/timelineScrollObservationCostDoesNotGrowWithSettledHistory()'`. Use one explicit project, simulator and reusable DerivedData root. A shared runner switched to an unrelated checkout during one attempted retry reproduction; that zero-selection result was excluded and the correct checkout was exercised directly. Neither `BighelpAppReadinessTests` nor `BighelpLinkLiveSocketTests` is in the repository today. The Link transport is retired. ## Remaining opportunities, not claimed fixes diff --git a/docs/SECURITY_AND_PRIVACY.md b/docs/SECURITY_AND_PRIVACY.md index 9ed36d20..ebfeffc6 100644 --- a/docs/SECURITY_AND_PRIVACY.md +++ b/docs/SECURITY_AND_PRIVACY.md @@ -3,8 +3,10 @@ Production transport contract: **native Hermes only for chat**. Cloudflare is limited to optional notifications and Live Activities. The current composition, voice boundary, enrollment isolation and verification requirements are defined -in [Native transport](NATIVE_TRANSPORT.md). Retained Link/paired-Direct protocol -sections below describe legacy compatibility code, not a selectable chat path. +in [Native transport](NATIVE_TRANSPORT.md). The optional bighelp account and its +Link transport are retired: the app no longer has them, and on a phone that once +used them it deletes their leftover keys and settings at launch +(`BighelpLinkAccountRetirement`). This document describes the technical behavior of the current implementation. It is not legal advice and does not replace a jurisdiction-specific privacy @@ -13,17 +15,17 @@ policy, App Store disclosure review, or independent security audit. ## Optional iPhone tools -The next release candidate adds independent, default-off Health, Calendar, -Reminders and Location controls in Settings › Connections › Device access. Health data is read only for the user's health +Settings › Connections › Device access has independent, default-off controls for +Health, Calendar, Reminders, Location and the other phone tools. Health data is read only for the user's health and fitness questions. Before Health's first grant, a one-time note says that shared Health data goes to the person's Hermes computer and its AI provider, is not used for advertising, and can be turned off at any time. When an agent asks for a tool that's off, a card in the chat can turn on the same switch; it never turns one on by itself, and Not now refuses the call. Location shares where the phone is only when an agent asks, with While Using the App access; it's approximate unless the person allows precise location for that call. Calendar and Reminders permit direct reads and changes -after explicit enablement and iOS authorization. Grants belong to the phone, its -authorization epoch and the selected host. Turning a grant off blocks new and -in-flight access; it does not revoke the underlying iOS permission. +after explicit enablement and iOS authorization. One list of grants covers the +phone, every host and every agent. Turning a grant off blocks new and in-flight +access; it does not revoke the underlying iOS permission. ## What a live voice call tells the voice model @@ -43,12 +45,13 @@ phone data and needs no iOS permission, so it's on until the person turns off "Let agents change how bighelp looks" in Device access (one switch for every host). It works only while that chat is open and bighelp is in front. -Requested results travel through encrypted directed Link frames to the selected -Hermes host and may be sent to its AI provider and retained in normal tool/chat +Requested results travel over the chat's native Hermes connection to the host of +that chat and may be sent to its AI provider and retained in normal tool/chat history. The native mutation journal and plugin retry cache retain only bounded identity and reconciliation metadata, never private read payloads. Health data -is not used for advertising or analytics. Availability is foreground-only. -Account erasure removes saved grants and the local mutation journal. See the +is not used for advertising or analytics. Tools answer while bighelp is in front +or in its short background grace. Only Arriving and leaving and a Shortcuts run +reach past the open chat. See the [iPhone device-tools contract](IPHONE_DEVICE_TOOLS.md) for exact boundaries, Health empty-result semantics and the physical-device acceptance requirements. @@ -138,7 +141,8 @@ or address is kept. See [TELEMETRY.md](TELEMETRY.md#host-location). bighelp aims to: -- Keep message content unreadable to the Cloudflare routing layer. +- Keep chat off bighelp's cloud services, and keep alert text unreadable to the + notification service. - Authenticate every authorized endpoint independently. - Make endpoint revocation enforceable without rotating every other device. - Prevent replay, cross-session substitution, malformed payloads, and stale @@ -147,38 +151,31 @@ bighelp aims to: preferences. - Deliver notification text only after cryptographic authentication and decryption on the recipient device. -- Minimize durable cloud data and separate account routing from APNs delivery. +- Minimize durable cloud data. ## 2. Cryptographic design -### Link account content key +### Retired bighelp account and Link -For a bighelp Link account, the app creates a random account content key on the -device. Link message and workspace payloads are authenticated and encrypted with -AES-GCM before they enter the bighelp Link routing plane. An independently -authenticated native Hermes workspace does not acquire a Link account key or -require Link pairing. - -During account registration, the app uses a passkey PRF result to wrap the -account content key. The cloud stores the resulting encrypted envelope, not the -plaintext account key. On sign-in, the passkey PRF result unwraps the key on the -device. +Older versions had an optional bighelp account (passkey sign-in, an account +content key) and a Link transport that carried encrypted frames between the +phone and a paired host. Both are gone from the app. Chat and plugin features +run only over native Hermes ([Native transport](NATIVE_TRANSPORT.md)). At launch, +the app deletes the account's leftover Keychain items and settings once +(`BighelpLinkAccountRetirement`). ### Device authentication -Each independently authenticated Link device creates its own P-256 signing key. The private key remains in the -device Keychain; the public key is registered with the account service. -Authenticated requests include freshness and replay-protection material and are -verified against the device's current authorization epoch. - -Device-friendly names are encrypted with the account content key before cloud -storage. +Each phone's notification installation creates its own P-256 signing key. The +private key remains in the device Keychain. The app registers the public key +with the notification service. Signed requests include a timestamp, a nonce and the +installation's current authorization epoch. ### Paired Watch companion -The companion Watch is not an independent Link endpoint. It uses the -OS-managed paired WatchConnectivity channel and receives no account content -key, signing key, passkey grant or reusable host credential. The paired Watch +The companion Watch never talks to a host. It uses the OS-managed paired +WatchConnectivity channel to the iPhone and receives no signing key or reusable +host credential. The paired Watch is trusted with the bounded session, approval and attention content displayed on its screen. The phone revalidates authority, offer identity, expiry and exact approval scope before submitting an action to the authorized host. @@ -187,7 +184,7 @@ Phone action receipts and Watch recovery records are bounded, atomic, backup-excluded Application Support files protected until first user authentication. They can retain a bounded final voice reply for recovery for up to 24 hours. Watch recovery does not persist prompts or whole snapshots. -Account/host changes invalidate offers and clear state when the Watch receives +Host changes invalidate offers and clear state when the Watch receives the new context; already displayed data cannot be erased remotely while it is offline. Stale data cannot authorize new actions. @@ -196,30 +193,6 @@ settings; it is not covered by the phone's on-device recognition guarantee. The app sends the reviewed text draft through the phone, not a raw microphone recording. Reply speech is explicitly requested and stops on backgrounding. -### Host pairing - -Pairing uses a short-lived human-readable challenge. Approval transfers the -account content key to the new Hermes host through an ephemeral Curve25519 key -agreement, HKDF-derived wrapping key, and authenticated encryption. The pairing -code is not a reusable credential and does not contain a private key. - -The host locally commits to the pairing flow, device coordinate, signing public -key, and agreement public key. QR pairing carries the complete SHA-256 -commitment. Manual pairing requires a separately displayed 16-character -fingerprint derived from that commitment. The app derives the commitment again -from the server-inspected keys and refuses to release the account key if it does -not match. The plugin ignores any pairing URL supplied by the service and -constructs the verified URL from its own keys. - -### Link frames - -WebSocket frames contain routing and sequencing metadata plus AES-GCM -ciphertext. The account/link Worker and Durable Object route this envelope -without decrypting the content. - -The endpoints enforce monotonic sequence handling, acknowledgements, duplicate -recognition, request/session matching, and bounded decoding. - ### Encrypted alerts Each mobile device owns a notification recipient key. Alert encryption uses an @@ -250,8 +223,7 @@ notification service remains in the notification trust boundary. ### Not trusted with plaintext message content -- bighelp's Cloudflare routing Worker -- The per-account Durable Object +- bighelp's notification service Worker (`link.loopdy.app`) - The notification relay database - The asynchronous APNs delivery queue - Apple Push Notification service for encrypted alert bodies @@ -266,15 +238,17 @@ this build. ### Local customization -bighelp does not expose a Marketplace, public catalog, publishing workflow, or -remote installation service. Theme and card-template customization stays local. +bighelp has no marketplace or publishing service for themes or card templates. +Theme and card-template customization stays local. (Settings › Marketplace lists +Hermes' own apps, skills and plugins, and installs them on the person's Hermes +computer, not into bighelp.) Portable theme import and export move only files the user explicitly selects and do not upload, publish, or install executable content. ### Public provider artwork Provider logos use a dedicated public Cloudflare static-asset endpoint, separate -from authenticated Link traffic. Requests contain no account credentials, +from the notification service. Requests contain no credentials, conversation content, model selections, provider configuration or tracking IDs. The app retrieves the complete approved artwork catalog regardless of the selected provider. Cloudflare still receives ordinary connection metadata such as IP @@ -288,7 +262,7 @@ compromised publishing account. Publishers control artwork only, never app code, provider identities or model routing. A bounded, replaceable cache of public images and catalog metadata lives in the -app's Caches directory, independent of account data and excluded from backups by +app's Caches directory, apart from other app data and excluded from backups by the operating system. Failed refreshes keep the last-good catalog; no cache uses bundled artwork. Successful catalog withdrawal removes the remote override on the next refresh, but cannot remotely erase copies on offline devices. Daily @@ -317,39 +291,35 @@ never leave the device for speech, and which agents use it stays on the device. ### Important limitation -End-to-end encryption protects content while it passes through bighelp's cloud -services. It cannot protect content on a compromised authorized device or -Hermes host. A configured provider may receive plaintext needed for the request. +Chat does not pass through bighelp's cloud services: it goes from the phone to +the Hermes host. End-to-end encryption protects alert text while it passes +through the notification service. Neither can protect content on a compromised +authorized device or Hermes host. A configured provider may receive plaintext needed for the request. Screen capture and visible Lock Screen content can also expose information. It also does not hide traffic metadata such as IP address, timing, connection duration, ciphertext size, or device-routing relationships from infrastructure providers. -The routing service can still delay, suppress, or replay-invalid pairing -traffic, but it cannot substitute a different host key without failing the QR -commitment or separately displayed manual verification code. +The notification service can still delay or drop alerts and Live Activity +updates. ## 4. Data inventory | Data | On iOS device | bighelp Cloudflare | Hermes / providers | |---|---|---|---| -| Messages and replies | Local session cache | Transient ciphertext only | Plaintext as needed to run the agent | -| Attachments | Local session cache; memory during upload | Transient ciphertext only | Plaintext as needed to process the request | +| Messages and replies | Local session cache | Not sent (chat goes straight to the host) | Plaintext as needed to run the agent | +| Attachments | Local session cache; memory during upload | Not sent | Plaintext as needed to process the request | | Voice audio | Memory during on-device recognition | Not sent by bighelp | TTS voice: not sent as raw microphone audio. Full Duplex: streamed from the phone straight to the live voice provider the person picked (GPT-Live or Gemini Live) | -| Voice transcript | Local session cache | Transient ciphertext only | Plaintext as the user request | -| Synthesized speech audio | Memory during playback | Transient ciphertext only | Generated by the configured voice service | -| Agent instructions/settings | Local presentation cache | Transient ciphertext for workspace operations | Stored according to Hermes configuration | +| Voice transcript | Local session cache | Not sent | Plaintext as the user request | +| Synthesized speech audio | Memory during playback | Not sent | Generated by the configured voice service | +| Agent instructions/settings | Local presentation cache | Not sent | Stored according to Hermes configuration | | Device private/signing keys | Keychain | Never | Only keys generated by that endpoint | -| Account content key | Keychain | Encrypted envelope only | Present on authorized endpoints | -| Passkey biometric data | Apple authentication system | Never | Never | -| Passkey public credential | System-managed locally | Durable public metadata | Not required | -| Device name | Local | Authenticated ciphertext | Readable by authorized account endpoints | | Device/public-key metadata | Local | Durable operational metadata | Used to authorize endpoints | | APNs token | System/app memory and Keychain-related state | Encrypted at rest in relay storage | Not required | | Alert title/body | Device after decryption | Encrypted payload | Created by the authorized source | | Live Activity state | ActivityKit | Bounded state, encrypted at rest but readable during relay delivery and by Apple | Created from agent activity | -| Static Card document and embedded values | Local transcript cache | Transient ciphertext only | Generated and validated on the authorized Hermes host | +| Static Card document and embedded values | Local transcript cache | Not sent | Generated and validated on the authorized Hermes host | | Live Card source URL, response, and request metadata | Not accepted in build 3 | Not accepted in build 3 | Not accepted in build 3 | | Preferences | UserDefaults | Not uploaded as preferences | Not required | | Avatars | App sandbox | Filename metadata only through workspace flows | Image upload is not part of the current directory path | @@ -363,24 +333,22 @@ available after the first device unlock so background networking and notification processing can operate. Native Hermes credentials use their stricter existing -when-unlocked/device-only protection. Independent native hosts do not acquire a -bighelp account identity: their metadata, credential items and drafts are scoped -separately from optional cloud credentials. Cloud sign-out and account deletion -do not erase independent host authentication or legacy account-keyed Direct -sources awaiting verified migration. Those sources are not automatically exposed -to another account or adopted by matching an address. Explicit host removal -controls local Direct credential deletion; it is not remote token revocation. -Opaque provider/principal comparisons are byte-exact, not display-name equality. +when-unlocked/device-only protection. Each host's metadata, credential items and +drafts are scoped to that host and are not adopted by another host that matches +its address. Removing a host in the app deletes its saved credentials, its local +notification enrollment and its drafts, and clears the phone's caches of agents' +files, photo drafts and agents' apps. It never deletes the host's chats. Neither +removal nor uninstalling the app is remote token revocation. Opaque provider/principal comparisons are +byte-exact, not display-name equality. The native workspace also owns separate protected content manifests, transcript -revisions, creation-intent journals and host-scoped preferences. Cloud erasure -does not erase these independent sources or reset their navigation. Native +revisions, creation-intent journals and host-scoped preferences. Native session creation persists its bounded intent before every non-idempotent mutation; a lost response remains uncertain across reconnect and cannot trigger an automatic replacement session. Recorded historical tool evidence uses a separate versioned cache and cannot imply a live or successful tool outcome. Native connection leases reject stale results without closing the shared host -socket or switching to Link. +socket. Ordinary native files stay local until Send. The complete batch is checked before upload, then files are staged serially through the exact live session. @@ -404,21 +372,13 @@ agent's own `contacts.create` and `calendar.create` (`review_required`), so standing Device access can't turn a picture into a new contact or event without the person's review. Other phone tools keep their own switches and rules. -Signing out attempts a signed request to revoke this device and its push/Live -Activity authorization, then deletes bighelp Link runtime credentials, -notification recipient keys, pinned host keys, account-scoped defaults, local -content files, and all account-scoped in-memory state. Local erasure still runs -if the remote revocation is unavailable, and the app surfaces that revocation -could not be confirmed. Uninstall behavior alone should not be treated as -remote revocation. - -The app stores the account and signing keys as software keys in device-only -Keychain items rather than as Secure Enclave private-key objects. A sufficiently +The app stores its notification signing and recipient keys as software keys in +device-only Keychain items rather than as Secure Enclave private-key objects. A sufficiently privileged compromise after the first unlock may expose them. ### App sandbox -Scratchpad text is an in-memory draft owned by the active account/host. Closing +Scratchpad text is an in-memory draft owned by the active host. Closing the editor retains it for that running app session; switching owner or signing out clears it. It is not a cross-launch saved document unless the user exports it through the native Files picker. Sending to an agent only stages a Markdown @@ -434,55 +394,35 @@ agent metadata, settings, avatars, and the last Plugins and Skills Hub lists of computer (Caches, at most a month old) in its private container. The JSON repositories are versioned and crash-safe but do not add a separate application-level encryption layer. JSON and attachment directories explicitly -use complete-until-first-user-authentication protection so background Link and +use complete-until-first-user-authentication protection so background notification reconciliation can continue after the first unlock. Avatar files and directories use complete protection and remain unavailable while locked. -Protected files and directories, including Link's pending encrypted transport -state and corruption recovery backups, are explicitly excluded from device -backups. - -The pending encrypted Link frame and its sequence/acknowledgement state are -stored in protected Application Support JSON rather than backup-eligible -UserDefaults. Existing per-device UserDefaults snapshots migrate to this file -before their legacy keys are removed. +Protected files and directories, including corruption recovery backups, are +explicitly excluded from device backups. Anyone who can unlock or compromise the device may be able to read this local content. ## 6. Cloud retention -The current Cloudflare deployment stores durable identity and delivery metadata -but no readable chat-session database. - -- Passkey public records, account coordinates, and active device public keys - remain while the account/device remains authorized. -- The service stores only hashes of access tokens. -- Authentication challenges and access sessions become invalid after expiry or - consumption; immediate physical deletion of every expired row is not claimed. -- Encrypted frames waiting for an offline endpoint are removed after recipient - acknowledgement or endpoint revocation. No independent time-based frame - expiration was verified. - The recipient overflow repair preserves these accepted obligations while - permitting future copies to saturated recipients to be skipped before - acceptance. It reserves recipient-local capacity rather than allowing one - offline device to exhaust every device's budget. Fresh session recovery can - restore only content actually stored by the host, not every skipped transient - event. See [Legacy Link retention](LINK_RETENTION.md) for the policy, migration, - ordering, and separately authorized rollout requirements. -- Push registrations persist while authorized or leased. +The current Cloudflare deployment stores notification delivery metadata but no +chat-session database. Chat never passes through it. + +- Notification installations and their device public keys remain while + authorized. +- Push registrations persist while authorized or leased. Push tokens are + encrypted at rest. - Alert payloads are encrypted at rest and delivery records are pruned by the relay lifecycle. - Revocation tombstones and idempotency metadata are retained only for consistency and replay protection. - Aggregate counters do not contain prompts or replies. -Account deletion is available in the app and requires a fresh passkey assertion. -The Link service revokes every device push registration and Live Activity, -deletes the passkey account and device directory rows, closes active sockets, -and purges the per-account Durable Object. The service performs a second object -purge after deleting the account directory to close races with an already -authenticated request. The app removes its local account-scoped state only -after the service confirms deletion. +The app no longer creates a bighelp account and no longer offers account +deletion. The current app does not use records that older versions made for the +retired account (passkey public records, account coordinates, device public +keys and encrypted Link frames). See [Legacy Link retention](LINK_RETENTION.md) +for how the service treated them. Logical deletion is not a guarantee that every infrastructure backup or provider recovery copy is immediately physically unrecoverable. Cloudflare, @@ -496,15 +436,14 @@ should remain short, reviewed, and enforced automatically. | Permission/service | Why it is used | Privacy behavior | |---|---|---| -| Camera | Pairing QR codes and optional Reflective Vision | Frames are not recorded or stored by the feature | +| Camera | Photos and document scans you attach to chats, and optional Reflective Vision | Reflective Vision frames are not recorded or stored; photos and scans go only to the chat you send them in | | Microphone | Voice conversation input | TTS voice: raw audio remains on device. Full Duplex: raw audio goes from the phone straight to the chosen live voice provider while the call is open, never through bighelp's services | | Speech recognition | Convert speech to text | On-device recognition is required | | Photos | Select profile and agent avatars | Images are processed and stored locally | | Location (while using the app) | The agent's `iphone_location` tool, after you turn on Location for a host | Asked for when you turn the switch on; approximate unless you allow precise location for a call; sent to that host and its AI provider, never kept by bighelp | -| Face ID / device authentication | Passkey user verification | Biometric data is handled by the OS | | Notifications | Agent alerts | Alert text is encrypted for the recipient device | | Live Activities | Agent progress on Lock Screen/Dynamic Island | Shows bounded status plus session and agent labels | -| Local network | Connecting to an explicitly configured native Hermes host | Native-first workspace access still requires host authentication; HTTPS uses Apple trust, and policy-supported local HTTP requires explicit consent. Link is a separate optional connection | +| Local network | Connecting to an explicitly configured native Hermes host | Native-first workspace access still requires host authentication; HTTPS uses Apple trust, and policy-supported local HTTP requires explicit consent | Apple and network providers necessarily process delivery metadata such as IP addresses, device tokens, app topics, timing, and service diagnostics according @@ -536,19 +475,24 @@ The app declares: - Tracking: **false** - Tracking domains: none -- Collected data: a linked device identifier used for app functionality -- Required-reason API use: preferences and elapsed-time measurement - -bighelp does not declare user content as collected by its cloud because the -current deployed frame-routing path receives authenticated ciphertext, has no -frame-decryption operation, and does not retain a readable session store. This -classification depends on the documented key-establishment design. Review it +- Collected data, each linked to the install ID, for app functionality and + analytics, never for tracking: device ID, product interaction, crash data, + performance data and other diagnostic data (see Usage and diagnostics) +- Required-reason API use: preferences, file timestamps and system boot time + (elapsed-time measurement) + +bighelp does not declare user content as collected by its cloud. Chat goes from +the phone straight to the person's Hermes host. With current plugins, alert +text reaches the notification service only as ciphertext for the phone (older +plugins that don't seal alerts still send readable title and text). No cloud service keeps a +readable session store. This classification depends on the documented +alert-encryption design. Review it with qualified privacy counsel before release. This conclusion must be revisited if any of the following changes: - Cloud code gains a content-decryption key -- Pairing or sender-key provisioning changes the documented trust assumptions +- Notification sender-key provisioning changes the documented trust assumptions - Message, transcript, attachment, or prompt content is logged - Readable content is added to D1, Durable Object, KV, R2, Analytics, or queues - Retention expands beyond real-time delivery needs @@ -580,13 +524,11 @@ clients of the serving profile, not per-device ACLs. No generic filesystem, conf control or raw-microphone-upload surface is added. See [Workspace management](WORKSPACE_MANAGEMENT.md) for the exact feature scope. -Native Wiki recovery records distinguish authenticated Hermes endpoint/provider/ -principal/profile ownership from legacy Link device ownership. The bounded -native principal coordinates are held in protected local Wiki state; no token, -password, device enrollment, or account content key is introduced. Its storage -namespace cannot overlap a legacy Link account namespace. Legacy Link encoding -and local recovery filenames remain unchanged. Current transport authorization -is checked separately from the stable persisted principal identity. +Native Wiki recovery records are owned by the authenticated Hermes +endpoint/provider/principal/profile. The bounded native principal coordinates +stay in protected local Wiki state. This adds no token, password or device +enrollment. Current transport authorization is checked separately from the +stable persisted principal identity. Read-only native Project Changes uses the canonical plugin's registered Project/session checks and existing safe Git engine. It does not infer @@ -596,13 +538,12 @@ sent to new analytics or cloud endpoints. The content token is an optimistic before/after check, not an immutable filesystem lease; this adapter cannot stage, commit, fetch, pull, push or execute commands. -The iOS app includes no analytics, advertising, crash-reporting, or behavioral -tracking SDK. Production code must not log: +The iOS app includes no third-party analytics, advertising, crash-reporting, or +behavioral tracking SDK (its own usage and diagnostics are described above). Production code must not log: - Credentials or private keys -- Passkey assertions - APNs tokens -- Account or device authorization material +- Host or device authorization material - Plaintext prompts, responses, attachments, or decrypted notifications - Full server error bodies @@ -615,20 +556,17 @@ redacted and minimize retention. - This project makes no claim of an independent third-party security audit. - The custom protocol depends on correct implementation at both iOS and Hermes endpoints. -- A compromised authorized endpoint can read account content. +- A compromised authorized endpoint can read the content it is authorized for. - A compromised device after unlock can read local caches. -- Manual pairing relies on the user comparing the host's separate 16-character - verification code; QR pairing carries the full key commitment. -- The account service provisions notification sender trust. No separate +- The notification service provisions notification sender trust. No separate transparency or continuity system verifies it. - E2E content encryption does not provide anonymity or hide traffic patterns. - Availability depends on Cloudflare, APNs, the Hermes host, configured providers, and Apple services used by enabled features. - Live Activity state is privacy-reduced, not equivalent to the encrypted alert channel. -- Independently authenticated native Hermes is selected by production composition - for its own workspace. Its native API, authentication and Apple-networking - acceptance are separate from Link validation; neither proves the other. +- Chat runs only over native Hermes, so its protection depends on the Hermes + host's own authentication and on Apple networking. ## 12. Export and legal review @@ -644,15 +582,16 @@ Report suspected vulnerabilities privately using the process in ## Explicit Wiki folder setup -Saving Add Wiki authorizes a safe existing host folder for the current authenticated device/profile through the separately negotiated `wiki.connect` operation. New grants are read-only; a typed suggestion alone grants nothing. Filesystem traversal, symlink ancestors, sensitive and system roots, the configured Hermes control home, and Wiki state are excluded. The operation cannot adopt, overwrite or bypass overlapping grants held by another device/profile/pairing authority. Existing grants retain their generation and policy; new grants receive a fresh generation. Host-local grant/revoke administration remains separate. +Current bighelp plugin releases no longer have the Wiki routes. This section applies only to an older host that still lists `native-wiki-v1`. + +Saving Add Wiki authorizes a safe existing host folder for the current authenticated device/profile through the separately negotiated `wiki.connect` operation. New grants are read-only; a typed suggestion alone grants nothing. Filesystem traversal, symlink ancestors, sensitive and system roots, the configured Hermes control home, and Wiki state are excluded. The operation cannot adopt, overwrite or bypass overlapping grants held by another device or profile. Existing grants retain their generation and policy; new grants receive a fresh generation. Host-local grant/revoke administration remains separate. -Authorized Wiki metadata can disclose the chosen absolute source folder over the existing account-wide encrypted Link. When a page or section is explicitly referenced, its full source path accompanies the selected snapshot as bounded JSON metadata and follows normal chat/model-provider disclosure. Visible tags use the title. Other holders of the account key may decrypt this traffic. Path metadata is absent on older hosts and is not inferred from a display name. +Authorized Wiki metadata can disclose the chosen absolute source folder to the app over the authenticated native Hermes connection. When a page or section is explicitly referenced, its full source path accompanies the selected snapshot as bounded JSON metadata and follows normal chat/model-provider disclosure. Visible tags use the title. Path metadata is absent on older hosts and is not inferred from a display name. ## Group presentation preferences The Agents screen keeps pinned and archived group preferences locally on this device, scoped to the authenticated workspace. Archiving here hides the group from the active Agents list; Archived groups can restore it. This does not stop -Hermes work or delete its transcript. Account-data erasure clears these -preferences. Delete is a separate confirmed action through Hermes' native +Hermes work or delete its transcript. Delete is a separate confirmed action through Hermes' native `groups.disband` operation, which stops the room and permanently retires its ID. diff --git a/docs/STANDALONE_DIRECT.md b/docs/STANDALONE_DIRECT.md index cfc4dc21..6c726a53 100644 --- a/docs/STANDALONE_DIRECT.md +++ b/docs/STANDALONE_DIRECT.md @@ -1,15 +1,25 @@ # Standalone Direct Hermes -> Current transport contract: [NATIVE_TRANSPORT.md](NATIVE_TRANSPORT.md). Its account setup, Link comparison and missing-feature list describe an older implementation. Where transport details differ, use the versioned native contract and its source links. +> **Historical name.** "Standalone Direct" was the native Hermes connection while the bighelp Link transport +> (bighelp account, pairing, relay) still existed beside it. Link is retired. The native connection is now the only +> way bighelp talks to Hermes, and it needs no bighelp account. The current contract is +> [NATIVE_TRANSPORT.md](NATIVE_TRANSPORT.md). This page keeps the parts that are still true: setup, credentials and +> recovery limits. -Connect your bighelp account to a reachable `hermes serve` backend without bighelp Link chat pairing. Account sign-in, host authentication and optional notification enrollment have separate authority. Existing Link chats remain separate. +bighelp connects straight to a reachable Hermes dashboard (`hermes dashboard` or `hermes serve`): REST sign-in, +WebSocket JSON-RPC on `/api/ws`, dashboard REST, and the optional plugin's routes under +`/api/plugins/loopdy/native/…` (`loopdy` is the plugin's legacy ID). Host authentication and optional notification +enrollment have separate authority. ## Connect -1. Sign in to or create your bighelp account. With no configured hosts, the shared Connect Host wizard opens. Later, use **Accounts and Devices → Add Host**. +1. On first run, the Connect step opens host setup. Later, use **Settings › System › Computers › Add a computer**. 2. Enter your host URL or IP and port. -3. Choose a supported provider-issued access token, host username/password login, or browser sign-in. Browser sign-in uses the system authentication session, IPv4 loopback callback and PKCE. -4. Connect, then enable optional notifications or continue without them. Select a profile and start or reopen an eligible native session. +3. Sign in the way the host allows: a provider-issued access token, host username and password, or browser sign-in. + Browser sign-in uses the system authentication session, an IPv4 loopback callback and PKCE. A host with no + sign-in set up connects with the dashboard's own session token. A host behind Cloudflare Access also takes an + Access service token (client ID and secret). +4. Connect, then add the plugin and notifications if you want them. Pick an agent and start or reopen a chat. Your host must already be running a current Hermes backend and be reachable from the phone. For Tailscale, both devices must be connected to the appropriate tailnet. bighelp does not install Tailscale, start the host, expose a listener, or modify tailnet access rules. @@ -19,23 +29,26 @@ See the [official Hermes remote-backend guide](https://hermes-agent.nousresearch ## Credentials -A remote access token is a bearer issued by the host's authentication provider. A model-provider API key or legacy dashboard bootstrap token is not interchangeable with it. Legacy bootstrap tokens are supported only for an explicitly allowed literal loopback endpoint whose backend advertises that mode. +A remote access token is a bearer issued by the host's authentication provider. A model-provider API key is not interchangeable with it. The dashboard's session token is used only when the host reports that no sign-in is required. Username/password login uses the host's native authorization exchange. bighelp stores the resulting session in device-only Keychain storage, not the password. Login redirects are validated rather than followed blindly. Connections are bound to the exact endpoint and verified host account. Forgetting a connection removes the local login, not server history. -## Included +## What works -- Profile and saved native-session discovery. -- Streaming assistant text, reasoning, tool results and subagent activity. -- Stop, steer and queued text, supported slash commands, session model selection, approvals and single-question clarification. -- Retained drafts and native history/replay recovery. A confirmed turn can settle after a same-process reconnect without manual receipt cleanup. An unconfirmed submission is never automatically resent. -- Independent Direct and Link ownership. Direct does not take over an active messaging-gateway chat. +Chat, files and pictures (`file.attach`, `image.attach_bytes`, `pdf.attach`, and big files through the plugin), +streaming text, reasoning, tool results and subagent activity, Stop, steer and queue, slash commands, model choice, +approvals and clarifying questions (several at once too) all run over this connection. With the plugin installed, +the plugin features also work: live voice, cards and forms, device tools, project changes, notifications and the +rest listed in [hermes/EXTENSIONS.md](hermes/EXTENSIONS.md). Each one shows only when the host's `/native/context` +lists its feature; otherwise the app says to update the plugin. + +Drafts are kept, and history and replay recovery are native. A confirmed turn can settle after a same-process reconnect without manual receipt cleanup. An unconfirmed submission is never automatically resent. The app does not take over a chat that is active on a messaging gateway. ## Current limits -This is a standalone native connection, **not full feature parity with bighelp Link**. Attachments, voice, Wiki, bighelp Cards/form RPC, phone integration, project-change browsing, the full provider/model picker, multi-question clarification and subagent detail/control windows are not connected through this mode yet. Unavailable composer actions are hidden; the connection menu explains support boundaries. None silently falls back to Link. +Wiki: the app still has a Wiki client (plugin feature `native-wiki-v1`), but the current plugin no longer lists that feature, so Wiki is unavailable on current hosts. -The direct chat socket does not itself provide closed-app APNs. Optional managed notifications use separate signed-device enrollment and a compatible installed plugin; iOS can suspend the connection. Reopening reattaches the native session where possible. If the original runtime has disappeared, explicitly open its saved session; the app does not silently invoke the host's cold-resume/auto-continuation policy. +The chat socket does not itself provide closed-app pushes. Optional notifications use a separate signed-device enrollment and the plugin; iOS can suspend the connection. Coming back reattaches the chat. If Hermes ended the chat's runtime meanwhile, the app resumes the saved session by itself (`onRetainedStreamsNeedResume`) and a chat route without its model reopens (`reopenChatRoute`). The host's replay ring is finite. When complete live replay is unavailable, retained rows stay in place and additional native snapshot information may appear as recovery detail. Saved tool history can contain less detail than the live stream. Uncertain queue/steer consumption remains reviewable. @@ -43,4 +56,4 @@ The host's replay ring is finite. When complete live replay is unavailable, reta The source was exercised against an isolated, unmodified Hermes backend using generated credentials and an explicitly synthetic local model. Hermes ran an actual temporary-directory terminal command. Apple URLSession and iOS Keychain checks covered password and bearer authentication, refusal, streaming, history and reconnect. Native UI checks covered both login modes, typing/sending, close/reopen and a second send. An active-reconnect check preserved row identities and an unsent draft. -These are native simulator and loopback integration results. They do not claim a physical iPhone/Tailscale trial, real-provider latency measurement, production host activation, or APNs delivery. No host, plugin, relay or cloud rollout is included in this source change. +These are native simulator and loopback integration results. They do not claim a physical iPhone/Tailscale trial, real-provider latency measurement, production host activation, or push delivery. diff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.md index 0040ff46..2202d05c 100644 --- a/docs/TELEMETRY.md +++ b/docs/TELEMETRY.md @@ -20,8 +20,9 @@ the file is dropped at the edge. the plugin and Hermes versions. Tool names are sent only for built-in Hermes tools and `bighelp_*` tools. Other tools report `mcp` or `custom`. The Worker adds the host's country and, in the United States, its state (see [Host location](#host-location)). -- **The Link relay** reports `push.sent`, `push.token_invalid`, `push.retry`, `push.dlq`, `push.fallback_buzzkit` and - `push.shadow`: the event type, a result code, timings and counts. +- **The notification service** (`services/link`, the `loopdy-link` Worker behind `link.loopdy.app`) reports + `push.sent`, `push.token_invalid`, `push.retry`, `push.dlq`, `push.fallback_buzzkit` and `push.shadow`: the event type, a result + code, timings and counts. Each batch also names a random ID: an install ID the app keeps in the Keychain, or a telemetry ID the host keeps in its own plugin data. Neither is derived from an account, an Apple ID or the host's notification key. @@ -53,7 +54,8 @@ Cloudflare's edge assigns to the connection (for example `DE`), and `usState`, t United States (for example `TX`, or `DC`). The Worker reads them from the request's Cloudflare properties after the batch passes validation, so a host can't set or change them. Nothing finer is kept: no city, postal code or coordinates, and not the address. Unknown and Tor connections get neither value, and a US region that is not one of -the 50 states or DC keeps only the country. App, notification-extension and relay reports carry no location. +the 50 states or DC keeps only the country. App, notification-extension and notification-service reports carry no +location. This is where the connection comes from, not where a person lives. A host on a cloud server reports its data center's country, and a host behind a VPN reports the VPN's. @@ -64,7 +66,7 @@ center's country, and a host behind a VPN reports the VPN's. flowchart LR App["bighelp app"] --> Worker["telemetry.bighelp.app (Cloudflare Worker)"] Host["Hermes host plugin"] --> Worker - Relay["Link relay Worker"] -->|"service binding"| Worker + Relay["Notification service Worker (services/link)"] -->|"service binding"| Worker Worker -->|"track API"| AI["Application Insights"] --> LA["Log Analytics"] ``` @@ -105,8 +107,9 @@ The maintainer runs these steps. The Azure side is in 2. Deploy the Worker: `cd services/telemetry && npx wrangler deploy`. 3. Set the secrets `APPINSIGHTS_CONNECTION_STRING` and `IP_HASH_KEY` with `wrangler secret put`. 4. Send the test batch from the Azure README and look for it in Application Insights. -5. Bind the Worker to the Link relay (`TELEMETRY` service binding to `bighelp-telemetry`, entrypoint - `TelemetryIngest`). +5. Deploy the notification service (`services/link`). Its `wrangler.jsonc` binds it to this Worker (`TELEMETRY` + service binding to `bighelp-telemetry`, entrypoint `TelemetryIngest`). Without the binding it still delivers + pushes and sends no events. **If ingestion stops** - `curl` the test batch. A 202 means the Worker is fine and the problem is after it. @@ -115,7 +118,7 @@ The maintainer runs these steps. The Azure side is in - Many `429` answers: the rate limits are 60 batches a minute for one ID and 600 for one network. Change them in `services/telemetry/wrangler.jsonc`. - The budget alert fired: if the monthly credit runs out, Azure disables the resources until the next cycle. The - relay is not affected. + notification service is not affected. **Stop telemetry quickly** - Turn off ingestion for everyone: `npx wrangler secret delete APPINSIGHTS_CONNECTION_STRING`. The Worker still diff --git a/docs/WORKSPACE_MANAGEMENT.md b/docs/WORKSPACE_MANAGEMENT.md index 844a7295..9e4d29a9 100644 --- a/docs/WORKSPACE_MANAGEMENT.md +++ b/docs/WORKSPACE_MANAGEMENT.md @@ -8,9 +8,12 @@ second scheduler. Artifacts means files in their originating sessions, not an invented universal host catalog. Scratchpad, GitHub and Wiki remain retired from app navigation. The Workspace -menu and its search use `appMenuCases`, not the complete backend destination -catalog. Native Wiki contracts, clients and plugin tests remain supported -without adding a visible Wiki menu entry. +menu (Hermes Tools) and its search use `appMenuCases`, not the complete backend +destination catalog: it also leaves out Tasks, Usage (☰ › Usage) and the +destinations for this app's own settings, which live in Settings. Native Wiki +contracts and clients remain for older hosts that still list `native-wiki-v1` +(current plugin releases no longer have the Wiki routes), without adding a +visible Wiki menu entry. `NativeWorkspaceManagementClient` consumes the shared `WorkspaceOperationPerforming` boundary. It does not open a second socket, proxy arbitrary URLs, invoke shell @@ -159,12 +162,13 @@ composition or a live user's Project authorization. ### Native Wiki identity -Wiki ownership distinguishes legacy Link device authority from authenticated -native Hermes principal authority. Native identity contains the endpoint, +Wiki ownership keeps the retired Link transport's device authority +(`WikiOwner.Authority.link`) apart from authenticated native Hermes principal +authority, which is the only kind the app makes today. Native identity contains the endpoint, provider, principal and profile, with no invented Link device, account or authorization epoch. Its local storage namespace is domain-separated; opaque -principal equality is byte-exact. Existing Link JSON encoding remains unchanged -so protected filenames and recovery journals remain readable. +principal equality is byte-exact. The legacy Link JSON encoding remains unchanged +so protected filenames and recovery journals from older versions remain readable. The shared Wiki codecs retain byte/revision/upload validation and accept a finite native request seam without manufacturing Link frames. Native transport @@ -174,7 +178,7 @@ The selected Codex UI retires Wiki navigation and the legacy chat reference-provider interface. Native Wiki contracts and clients remain available for backend integration without restoring those app surfaces. -Native login does not require separate Wiki pairing or device enrollment. +Native login does not require Wiki pairing or device enrollment. The compatible canonical plugin still owns grants, revision checks, shared principal/profile uploads, and protected source policy. Generated, mirrored and exported sources remain read-only even if the host supports file creation. diff --git a/docs/hermes/EXTENSIONS.md b/docs/hermes/EXTENSIONS.md index 804be2b7..ffc5aba5 100644 --- a/docs/hermes/EXTENSIONS.md +++ b/docs/hermes/EXTENSIONS.md @@ -146,6 +146,17 @@ Each board request has `agentId`. The board is per agent; Feed, Ideas and Goals | `agents/plugins/share` | M / `native-agent-plugin-links-v1` | `{agentId}` | `{linked,kept:[{name,reason}]}` / 32,768; 30 s | | `host/restart` | M / `native-host-restart-v1` | `{confirm:true}` | `{restarting:true,runtimeId,...}`; connection drops | | `telemetry` (PUT) | M / `native-host-telemetry-v1` | `{enabled:boolean}` | host telemetry state / 16,384; 10 s | +| `bot-chat/create` | M / `native-bot-chat-v1` | `{profile,idempotencyKey}` | the agent's new Bot Chat / 16,384; 60 s | +| `marketplace/plugins` | R / `native-marketplace-v1` | `{}` | marketplace plugins with stars, featured picks and install checks / 1 MiB; 30 s | +| `voice-catalog` | R / `native-voice-catalog-v1` | `{profile,provider}` | the provider's voices / 131,072; 20 s | +| `vault/link` | M / `native-vault-link-v1` | `{profile,item_ids,origins}` | `{copies,...}` / 65,536 | +| `skills/import` | M / `native-skills-import-v1` | `{agentId,fileName,kind:"zip",data,category?}` (base64 zip, up to about 3 MB) | import receipt / 65,536; 60 s | +| `html-apps/get` | R / `native-html-apps-v1` | `{agentId,appId,knownSha256?}`, then `{agentId,appId,offset,htmlSha256}` | `{app,html?,offset,nextOffset}`, pieces of up to 2 MiB; 60 s | +| `html-apps/data` | R / same | `{agentId,appId}` | `{appId,data,updatedAt,problem?}` / 2 MiB + 128 KiB; 10 s | +| `uploads/start`, `uploads/status`, `uploads/discard` | M (status R) / `native-uploads-v1` | `{agentId,fileName,mimeType,byteCount,sha256}` for start, `{uploadId}` otherwise | upload receipt / 16,384; 30 s | +| `uploads/finish` | M / same | `{uploadId}` | the finished file's place / 16,384; 60 s | + +Big files (over 8 MiB) send their bytes to `uploads/chunk` as raw 4 MiB pieces outside this JSON route table (`DirectHermesBigFileChunk`); the full contract is the plugin's docs/BIG_FILES.md. [HTML apps](../HTML_APPS.md) describes `html-apps/*`. A board item has `id,kind,title,body,icon,section,status,note,links:[{url,title}],images:[{url? ,index?}],files,source,liked,rating?,reason?,read?,dismissed,category?,createdAt,updatedAt`. A file entry has `index,fileName,mimeType,byteCount,addedAt?`; never derive its fetch path from its display name. Identity documents are `{text,updatedAt,truncated}`. Activity rows carry `id,sessionId,title,request,summary,category,outcome,createdAt`; approval history carries `id,sessionTitle,description,command,choice,createdAt` (Unix seconds). diff --git a/services/catalog/README.md b/services/catalog/README.md index d218f6ce..21d7128b 100644 --- a/services/catalog/README.md +++ b/services/catalog/README.md @@ -203,21 +203,24 @@ webapp deletions. `scripts/catalog-sync.py sync --apply` remains an explicit rep `POST /review/templates` takes an optional `id` (lowercase letters, digits and dashes) so the repo and the catalog keep the same ids; a taken id answers 409. -## App integration (not built yet) - -What the app needs, in the same style as `ProviderLogoStore`: - -1. A store that fetches `/v1/board-blueprints.json` and `/v1/agent-templates.json` on foreground at - most every few hours, with `If-None-Match`, a size cap (say 1 MB), https and host checks, and no - cookies. It keeps the last good copy in Caches and uses the bundled JSON when there is none. -2. `BoardBlueprintCatalog.shared` becomes "remote snapshot if present, else bundled". The parser - already ignores unknown keys (`credit`, `schemaVersion`, `revision`). -3. The agent picker's Templates rail reads remote agents. `AgentSoulTemplate.soul` reads from the - bundle today; remote templates carry `instructions` inline. Fall back to - `person.crop.square` when `symbol` is missing, and show `credit` on community cards. -4. Demo fixtures keep the bundled data; `-use-demo-fixtures` must not hit the network. -5. Optional: a "Share a template" link in the Blueprints sheet and agent picker to - `https://bighelp.app/templates#submit`. +## App integration + +The app reads the catalog through `TemplateCatalogStore` (`Bighelp/Board/TemplateCatalogStore.swift`): + +- It fetches `https://catalog.bighelp.app/v1/catalog.json` when the app comes to the front, at most once every + 6 hours. A failed request doesn't count toward the 6 hours. +- The request uses https to `catalog.bighelp.app` only, an ephemeral session with no cookies and no URL cache, + a 20-second timeout and a 1 MB (1,048,576 bytes) cap. It sends the saved `ETag` as `If-None-Match`, without + Cloudflare's `W/` prefix, and a 304 keeps the saved copy. +- The last good copy and its ETag stay in Caches (`TemplateCatalog/catalog.json`). Until there is one, the app + uses its bundled blueprints and agent templates. The app takes each half of a download (blueprints or agents) + only if it has at least one good item. So a failed or empty download never replaces a good copy. +- `BoardBlueprintCatalog.shared` and `AgentSoulTemplate.all` read from the store. Agent rows are parsed + leniently: a bad row is dropped, never the file. A missing or unknown `symbol` falls back to + `person.crop.square`, and community templates show their `credit`. +- Demo fixtures (`-use-demo-fixtures`) and tests keep the bundled data and never use the network. +- The Blueprints sheet, the template browser and the agent start picker link to + `https://bighelp.app/templates#submit`. There is no in-app submit form. Community text is untrusted: render it as plain text, never Markdown links or HTML. diff --git a/services/provider-logos/README.md b/services/provider-logos/README.md index 070ae45a..6f97a21a 100644 --- a/services/provider-logos/README.md +++ b/services/provider-logos/README.md @@ -2,7 +2,7 @@ A separate Cloudflare Workers Static Assets service serves public provider artwork. It has no JavaScript entrypoint, account bindings, credentials, R2 dependency or -request-time image transforms. Link, notifications and the marketing site are not +request-time image transforms. The notification service and the marketing site are not modified by a logo deployment. Cloudflare currently documents static-file requests as free and unlimited, with no additional asset-storage charge: diff --git a/services/relay/README.md b/services/relay/README.md index 9010977b..5d75f675 100644 --- a/services/relay/README.md +++ b/services/relay/README.md @@ -1,5 +1,10 @@ # Recovered Loopdy relay +> **Historical.** This is a byte-exact recovery of an older deployed relay Worker. The app does not talk to it: its +> notifications go through the notification service in [`services/link`](../link) (`link.loopdy.app`), and chat +> goes straight to the Hermes host. The recovered fragments still name "Link enrollment" because they are exact +> byte copies of the old module. The Link transport is retired in the app. + Source-only recovery of the deployed **primary** relay into this repository. This is not a new service, notification feature, dependency upgrade, or deployment.