@getfamiliar/shared 0.1.15 → 0.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/Schema.d.ts CHANGED
@@ -62,7 +62,7 @@ export declare const SCHEDULED_SUBAGENTS_CHANNEL = "scheduled_subagents_changed"
62
62
  * match exactly (see `HandlerResolution.ts`).
63
63
  */
64
64
  export declare const TOPIC_PATTERN = "^[\\w-]+(:[\\w-]+)*$";
65
- export declare const SCHEMA_SQL = "\n-- Drop legacy single-table artifacts from before the events/agentruns\n-- split. Safe no-ops on fresh databases. The current schema reuses the\n-- name events_notify_new() for its own NOTIFY function, so we do NOT\n-- drop it here (CREATE OR REPLACE FUNCTION below handles the update);\n-- dropping would fail anyway once the current events_new_trg exists.\nDROP TRIGGER IF EXISTS events_notify_changed_trg ON events;\nDROP TRIGGER IF EXISTS events_notify_new_trg ON events;\nDROP FUNCTION IF EXISTS events_notify_changed();\nDROP INDEX IF EXISTS events_pending_priority_idx;\nDROP INDEX IF EXISTS events_state_priority_idx;\n\nCREATE TABLE IF NOT EXISTS events (\n id bigserial PRIMARY KEY,\n topic text NOT NULL,\n priority smallint NOT NULL DEFAULT 50,\n state text NOT NULL DEFAULT 'pending',\n payload jsonb NOT NULL DEFAULT '{}'::jsonb,\n idempotency_key text UNIQUE,\n privileged boolean NOT NULL DEFAULT false,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now(),\n CONSTRAINT events_topic_format CHECK (topic ~ '^[\\w-]+(:[\\w-]+)*$')\n);\n\n-- Drop legacy columns from earlier schema generations. Single-instance\n-- project; column drops are fine.\nALTER TABLE events DROP COLUMN IF EXISTS supervisor_prompt;\nALTER TABLE events DROP COLUMN IF EXISTS causation_chain;\n\n-- Chat-aware event metadata. `is_chat` opts into automatic user-message\n-- persistence in EventBus.add; `preferred_chat_channel_id` names the\n-- channel an assistant reply should reach the user on. The container is\n-- channel-blind \u2014 both fields are read host-side (for routing) or via\n-- JOIN inside the chatmessages NOTIFY trigger.\nALTER TABLE events ADD COLUMN IF NOT EXISTS is_chat boolean NOT NULL DEFAULT false;\nALTER TABLE events ADD COLUMN IF NOT EXISTS preferred_chat_channel_id text;\n-- Required for non-chat events (validated at `EventBus.add` time and at\n-- the type level via `NewEvent`'s discriminated union); always null for\n-- chat events because the user's text in `chatmessages` already serves\n-- as the agent-visible \"what happened\" message. The EventWatcher copies\n-- this verbatim into the root `agentruns.prompt` so the agent sees the\n-- emitter's framing without the EventWatcher having to reach into the\n-- payload schema.\nALTER TABLE events ADD COLUMN IF NOT EXISTS prompt text;\n-- The topic is the handler's whole address now; the separate start\n-- handler basename is gone.\nALTER TABLE events DROP COLUMN IF EXISTS start_handler;\n-- When true the topic must name an existing handler file exactly; when\n-- false (world events) handler resolution falls back up the topic chain.\n-- Copied onto the root agentrun by the input-event watcher.\nALTER TABLE events ADD COLUMN IF NOT EXISTS is_exact_topic boolean NOT NULL DEFAULT false;\n-- Privileged events originate from a trusted user-input source (operator\n-- at the local terminal via cli-chat, operator on Telegram). The flag\n-- propagates verbatim to the root agentrun and to every child agentrun\n-- spawned via schedule_subagent / start_subagent, so future system tools can\n-- gate risky reads / writes (editing SOUL.md etc.) on whether the run\n-- descends from a trusted input. Default false: any plugin that doesn't\n-- explicitly opt in produces non-privileged events.\nALTER TABLE events ADD COLUMN IF NOT EXISTS privileged boolean NOT NULL DEFAULT false;\n-- When true and the event ends in 'failed', `HostContextImpl.emitAndAwait`\n-- writes a role='assistant' chatmessage with the failure text before\n-- rejecting handle.settled. Default false: only chat plugins (cli-chat,\n-- telegram) opt in. See [[outputChatOnFailure]] on NewEvent for the\n-- rationale.\nALTER TABLE events ADD COLUMN IF NOT EXISTS output_chat_on_failure boolean NOT NULL DEFAULT false;\n\nCREATE INDEX IF NOT EXISTS events_state_priority_idx\n ON events (state, priority DESC, id ASC);\nCREATE INDEX IF NOT EXISTS events_topic_idx ON events (topic);\n\nCREATE TABLE IF NOT EXISTS agentruns (\n id bigserial PRIMARY KEY,\n event_id bigint NOT NULL REFERENCES events(id) ON DELETE CASCADE,\n parent_agentrun_id bigint REFERENCES agentruns(id) ON DELETE CASCADE,\n topic text NOT NULL,\n priority smallint NOT NULL DEFAULT 50,\n state text NOT NULL DEFAULT 'pending',\n prompt text,\n payload jsonb NOT NULL DEFAULT '{}'::jsonb,\n result jsonb,\n result_text text,\n error text,\n privileged boolean NOT NULL DEFAULT false,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now(),\n CONSTRAINT agentruns_topic_format CHECK (topic ~ '^[\\w-]+(:[\\w-]+)*$')\n);\n\n-- Forward-compat ALTER for databases created before result_text landed.\n-- Safe no-op on fresh databases where the column already exists.\nALTER TABLE agentruns ADD COLUMN IF NOT EXISTS result_text text;\n-- The topic is the handler's whole address; the basename column is gone.\nALTER TABLE agentruns DROP COLUMN IF EXISTS handler;\n-- Whether handler resolution must match the topic exactly. Root\n-- agentruns copy the event's flag; spawned children are always exact.\nALTER TABLE agentruns ADD COLUMN IF NOT EXISTS is_exact_topic boolean NOT NULL DEFAULT true;\n-- Inherited from the originating event (root agentrun) or parent\n-- agentrun (children spawned via schedule_subagent / start_subagent). See\n-- the matching ALTER on the events table for the trust-model rationale.\nALTER TABLE agentruns ADD COLUMN IF NOT EXISTS privileged boolean NOT NULL DEFAULT false;\n-- Number of retry attempts already made on this agentrun. Bumped each\n-- time AgentRunner postpones the row due to a retryable inference\n-- error (APICallError.isRetryable). Capped per-handler via maxRetries\n-- (frontmatter override) or globally via inference.maxRetries.\nALTER TABLE agentruns ADD COLUMN IF NOT EXISTS retry_count int NOT NULL DEFAULT 0;\n-- Earliest moment the agentrun watcher is allowed to re-claim this\n-- row. NULL = claim immediately (default for fresh rows). A future\n-- timestamp = leave the row alone until then; the watcher's claim\n-- query gates on this so a parked row doesn't waste the slot while\n-- other agentruns (potentially using different models) can still run.\nALTER TABLE agentruns ADD COLUMN IF NOT EXISTS not_before timestamptz;\n-- Resolved model id for this agentrun, of the form\n-- `<provider>/<modelId>` (e.g. `featherless/zai-org/GLM-5.1`).\n-- Populated by AgentRunner once it builds the model client; stays\n-- NULL for any agentrun that never reached generate() (failed at\n-- handler-load time, etc.).\nALTER TABLE agentruns ADD COLUMN IF NOT EXISTS model text;\n-- Resolved prompt (rendered prompt template: system prompt, then\n-- user-message head) used for this agentrun. Populated by AgentRunner\n-- only when core.logSystemPrompt is true; otherwise NULL. Surfaced\n-- by the report layer's Agentrun Start section when the consumer\n-- opts into withDetails.\nALTER TABLE agentruns ADD COLUMN IF NOT EXISTS system_prompt text;\n-- Verbatim model-message array assembled for the first agent.generate()\n-- call (prior history + the run's leading user turn). Populated by\n-- AgentRunner only when inference.captureInitialMessageHistory is true;\n-- otherwise NULL. Surfaced by the report layer's -vv view so an operator\n-- can see exactly what was sent into the model loop.\nALTER TABLE agentruns ADD COLUMN IF NOT EXISTS initial_messages jsonb;\n\n-- Distinguishes how a child agentrun was spawned.\n-- NULL \u2014 root agentrun (created by the input-event watcher, no parent).\n-- 'scheduled' \u2014 fire-and-forget child spawned by `schedule_subagent` without\n-- a future `when` (immediate dispatch under the same event).\n-- 'started' \u2014 synchronous child spawned via the `start_subagent` tool; the\n-- parent is parked in state='waiting' until this row settles.\n-- The Scheduler reads this column to decide whether settling a row should\n-- wake a waiting parent.\nALTER TABLE agentruns ADD COLUMN IF NOT EXISTS calltype text;\nALTER TABLE agentruns DROP CONSTRAINT IF EXISTS agentruns_calltype_format;\nALTER TABLE agentruns ADD CONSTRAINT agentruns_calltype_format\n CHECK (calltype IS NULL OR calltype IN ('scheduled','started'));\n\n-- Partial index for the \"are all started children of $parent settled?\"\n-- check the Scheduler runs after every 'started' child settles. Indexes\n-- only the rows that actually participate in the question.\nCREATE INDEX IF NOT EXISTS agentruns_parent_calltype_state_idx\n ON agentruns (parent_agentrun_id, state)\n WHERE calltype = 'started';\n\n-- Forward-compat: relax the topic CHECK constraint to allow arbitrarily\n-- deep `a:b:c:\u2026` topics. CREATE TABLE IF NOT EXISTS above doesn't\n-- update existing constraints, so we drop+re-add unconditionally. The\n-- DROP IF EXISTS / ADD pair is idempotent.\nALTER TABLE events DROP CONSTRAINT IF EXISTS events_topic_format;\nALTER TABLE events ADD CONSTRAINT events_topic_format CHECK (topic ~ '^[\\w-]+(:[\\w-]+)*$');\nALTER TABLE agentruns DROP CONSTRAINT IF EXISTS agentruns_topic_format;\nALTER TABLE agentruns ADD CONSTRAINT agentruns_topic_format CHECK (topic ~ '^[\\w-]+(:[\\w-]+)*$');\n\nCREATE INDEX IF NOT EXISTS agentruns_state_priority_idx\n ON agentruns (state, priority DESC, id ASC);\nCREATE INDEX IF NOT EXISTS agentruns_event_id_idx ON agentruns (event_id);\nCREATE INDEX IF NOT EXISTS agentruns_parent_idx ON agentruns (parent_agentrun_id);\n\nCREATE TABLE IF NOT EXISTS stepresults (\n id bigserial PRIMARY KEY,\n agent_run_id bigint NOT NULL REFERENCES agentruns(id) ON DELETE CASCADE,\n event_id bigint NOT NULL REFERENCES events(id) ON DELETE CASCADE,\n step_number int NOT NULL,\n finish_reason text NOT NULL,\n result_text text,\n reasoning_text text,\n input_tokens int,\n output_tokens int,\n total_tokens int,\n tool_call_count int NOT NULL DEFAULT 0,\n tool_calls jsonb NOT NULL DEFAULT '[]'::jsonb,\n tool_results jsonb NOT NULL DEFAULT '[]'::jsonb,\n created_at timestamptz NOT NULL DEFAULT now(),\n CONSTRAINT stepresults_step_number_unique UNIQUE (agent_run_id, step_number)\n);\n\nCREATE INDEX IF NOT EXISTS stepresults_agent_run_id_idx ON stepresults (agent_run_id);\nCREATE INDEX IF NOT EXISTS stepresults_event_id_idx ON stepresults (event_id);\n\n-- AI SDK per-step usage breakdown\n-- (LanguageModelUsage.inputTokenDetails / outputTokenDetails). Each\n-- column is NULL when the provider doesn't report that detail.\nALTER TABLE stepresults ADD COLUMN IF NOT EXISTS input_tokens_no_cache int;\nALTER TABLE stepresults ADD COLUMN IF NOT EXISTS input_tokens_cache_read int;\nALTER TABLE stepresults ADD COLUMN IF NOT EXISTS input_tokens_cache_write int;\nALTER TABLE stepresults ADD COLUMN IF NOT EXISTS output_tokens_text int;\nALTER TABLE stepresults ADD COLUMN IF NOT EXISTS output_tokens_reasoning int;\n-- Full step object snapshot, populated only when the operator opts\n-- in via inference.captureRawStepResultToDatabase: true. Used to\n-- inspect provider-specific fields (Anthropic cache control,\n-- OpenAI logprobs, ...) that don't fit dedicated columns.\nALTER TABLE stepresults ADD COLUMN IF NOT EXISTS raw_result jsonb;\n\n-- \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 chatmessages \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n--\n-- Persistent chat history across all channels. Each row links to the\n-- event whose lifecycle the message belongs to:\n-- * For role='user': the event the host plugin emitted with isChat=true.\n-- * For role='assistant': the event whose agentrun called send_chat.\n-- The channel is reachable via JOIN to events.preferred_chat_channel_id;\n-- there is intentionally no channel_id column here \u2014 channel routing is\n-- a host-side concern, the container never names a channel.\n--\n-- delivered_at is set when ANY listener returns true from its async\n-- handler. New subscribers replay all undelivered matching rows on\n-- registration so a message produced when nobody was listening is still\n-- delivered later.\nCREATE TABLE IF NOT EXISTS chatmessages (\n id bigserial PRIMARY KEY,\n event_id bigint NOT NULL REFERENCES events(id) ON DELETE CASCADE,\n role text NOT NULL CHECK (role IN ('user','assistant')),\n text_content text NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now(),\n delivered_at timestamptz\n);\n\nCREATE INDEX IF NOT EXISTS chatmessages_event_idx\n ON chatmessages (event_id);\nCREATE INDEX IF NOT EXISTS chatmessages_undelivered_idx\n ON chatmessages (created_at) WHERE delivered_at IS NULL;\n\n-- \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 NOTIFY triggers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nCREATE OR REPLACE FUNCTION events_notify_new() RETURNS trigger AS $$\nBEGIN\n PERFORM pg_notify('events_new', NEW.id::text);\n RETURN NEW;\nEND;\n$$ LANGUAGE plpgsql;\n\nDROP TRIGGER IF EXISTS events_new_trg ON events;\nCREATE TRIGGER events_new_trg\n AFTER INSERT ON events\n FOR EACH ROW EXECUTE FUNCTION events_notify_new();\n\nCREATE OR REPLACE FUNCTION events_notify_state() RETURNS trigger AS $$\nBEGIN\n PERFORM pg_notify('events_state', NEW.id::text || ':' || NEW.state);\n RETURN NEW;\nEND;\n$$ LANGUAGE plpgsql;\n\nDROP TRIGGER IF EXISTS events_state_trg ON events;\nCREATE TRIGGER events_state_trg\n AFTER UPDATE OF state ON events\n FOR EACH ROW EXECUTE FUNCTION events_notify_state();\n\nCREATE OR REPLACE FUNCTION agentruns_notify_changed() RETURNS trigger AS $$\nBEGIN\n PERFORM pg_notify(\n 'agentruns_changed',\n NEW.event_id::text || ':' || NEW.id::text\n );\n RETURN NEW;\nEND;\n$$ LANGUAGE plpgsql;\n\nDROP TRIGGER IF EXISTS agentruns_notify_changed_trg ON agentruns;\nCREATE TRIGGER agentruns_notify_changed_trg\n AFTER INSERT OR UPDATE OF state ON agentruns\n FOR EACH ROW EXECUTE FUNCTION agentruns_notify_changed();\n\nCREATE OR REPLACE FUNCTION stepresults_notify_new() RETURNS trigger AS $$\nBEGIN\n PERFORM pg_notify(\n 'stepresults_new',\n NEW.event_id::text || ':' || NEW.agent_run_id::text || ':' || NEW.id::text\n );\n RETURN NEW;\nEND;\n$$ LANGUAGE plpgsql;\n\nDROP TRIGGER IF EXISTS stepresults_new_trg ON stepresults;\nCREATE TRIGGER stepresults_new_trg\n AFTER INSERT ON stepresults\n FOR EACH ROW EXECUTE FUNCTION stepresults_notify_new();\n\n-- chatmessages NOTIFY: payload is \"<channel_id>:<role>:<id>\". Channel\n-- comes from the parent event's preferred_chat_channel_id, JOINed at\n-- trigger time. Empty channel becomes empty prefix \u2014 listeners will\n-- filter it out unless they explicitly subscribe to channelId=\"\".\nCREATE OR REPLACE FUNCTION chatmessages_notify_new() RETURNS trigger AS $$\nDECLARE\n channel text;\nBEGIN\n SELECT preferred_chat_channel_id INTO channel FROM events WHERE id = NEW.event_id;\n PERFORM pg_notify(\n 'chatmessages_new',\n COALESCE(channel, '') || ':' || NEW.role || ':' || NEW.id::text\n );\n RETURN NEW;\nEND;\n$$ LANGUAGE plpgsql;\n\nDROP TRIGGER IF EXISTS chatmessages_new_trg ON chatmessages;\nCREATE TRIGGER chatmessages_new_trg\n AFTER INSERT ON chatmessages\n FOR EACH ROW EXECUTE FUNCTION chatmessages_notify_new();\n\n-- \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 calendars + calendar_events \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n--\n-- Plugin-agnostic calendar data layer. `calendars` lists every\n-- subscription (own or shared) any provider plugin (ms365, future\n-- google/caldav) has surfaced; `calendar_events` stores every\n-- instance. Providers persist every occurrence of a recurring\n-- series independently (no master-expansion in core).\n--\n-- Identity:\n-- * `calendars.unique_key` is the provider's stable id. Uniqueness\n-- within `(plugin_id, unique_key)` lets multiple providers\n-- coexist.\n-- * `calendar_events.id` is provider-prefixed (e.g. `ms365:<graph-id>`)\n-- so collisions across providers are impossible by construction.\n--\n-- Refresh reconciliation uses a scan-generation tag: a refresh walk\n-- bumps `calendars.scan_generation`, upserts every event in window\n-- with the new value, then DELETEs events whose generation is older\n-- than the calendar's current value.\n\nCREATE TABLE IF NOT EXISTS calendars (\n id bigserial PRIMARY KEY,\n plugin_id text NOT NULL,\n unique_key text NOT NULL,\n name text NOT NULL,\n type text NOT NULL CHECK (type IN ('own','shared')),\n owner_name text,\n scan_generation int NOT NULL DEFAULT 0,\n created_at timestamptz NOT NULL DEFAULT now(),\n UNIQUE (plugin_id, unique_key)\n);\n\n-- The provider's own \"default calendar\" flag (Graph's\n-- `isDefaultCalendar`). Used by `CalendarService.resolveDefaultCalendar`\n-- as the fallback when `core.defaultCalendar` is unset \u2014 we pick the\n-- first registered calendar (lowest id) flagged here. Added via\n-- ALTER so existing databases don't need a schema reset.\nALTER TABLE calendars ADD COLUMN IF NOT EXISTS is_default smallint NOT NULL DEFAULT 0;\n\nCREATE INDEX IF NOT EXISTS calendars_plugin_id_idx ON calendars (plugin_id);\n\nCREATE TABLE IF NOT EXISTS calendar_events (\n id text PRIMARY KEY,\n calendar_id bigint NOT NULL REFERENCES calendars(id) ON DELETE CASCADE,\n series_master_id text,\n type text NOT NULL CHECK (type IN ('singleInstance','occurrence','exception','seriesMaster')),\n subject text,\n start_dt text NOT NULL,\n end_dt text NOT NULL,\n event_tz text,\n is_all_day smallint NOT NULL DEFAULT 0,\n is_cancelled smallint NOT NULL DEFAULT 0,\n show_as text,\n sensitivity text,\n importance text,\n location text,\n is_online_meeting smallint NOT NULL DEFAULT 0,\n online_meeting_url text,\n organizer_name text,\n organizer_email text,\n response_status text,\n attendees_json jsonb,\n body text,\n attachments jsonb,\n scan_generation int NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now()\n);\n\nCREATE INDEX IF NOT EXISTS calendar_events_window_idx\n ON calendar_events (calendar_id, start_dt);\nCREATE INDEX IF NOT EXISTS calendar_events_series_idx\n ON calendar_events (series_master_id);\nCREATE INDEX IF NOT EXISTS calendar_events_generation_idx\n ON calendar_events (calendar_id, scan_generation);\n\n-- \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 scheduled_subagents \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n--\n-- One-off agent-scheduled wake-ups. Each row is upserted by the\n-- container's `schedule_subagent` tool and read by the host-side\n-- `ScheduledSubagentScheduler`, which installs a Croner job per row\n-- and atomically deletes the row when it fires. `key` is the\n-- agent-supplied unique id used for replace-on-conflict semantics\n-- (\"rescheduling a key overwrites the previous timing\"). `fire_at`\n-- is the UTC firing time; the agent passes wall-clock-in-`core.timezone`\n-- and the container projects to UTC before insert. On daemon startup,\n-- past-due rows are deleted with a warn log; future rows are\n-- reinstalled. See [[feedback_agent_facing_format]] \u2014 UTC storage,\n-- local-tz projection at every agent-facing edge.\nCREATE TABLE IF NOT EXISTS scheduled_subagents (\n key text PRIMARY KEY,\n fire_at timestamptz NOT NULL,\n topic text NOT NULL,\n prompt text,\n payload jsonb NOT NULL DEFAULT '{}'::jsonb,\n priority smallint NOT NULL DEFAULT 50,\n privileged boolean NOT NULL DEFAULT false,\n created_at timestamptz NOT NULL DEFAULT now(),\n CONSTRAINT scheduled_subagents_topic_format CHECK (topic ~ '^[\\w-]+(:[\\w-]+)*$')\n);\n\n-- The topic is the handler's whole address; the basename column is gone.\nALTER TABLE scheduled_subagents DROP COLUMN IF EXISTS handler;\n-- Re-add the topic CHECK so a widened TOPIC_PATTERN reaches existing tables.\nALTER TABLE scheduled_subagents DROP CONSTRAINT IF EXISTS scheduled_subagents_topic_format;\nALTER TABLE scheduled_subagents ADD CONSTRAINT scheduled_subagents_topic_format CHECK (topic ~ '^[\\w-]+(:[\\w-]+)*$');\n\nCREATE INDEX IF NOT EXISTS scheduled_subagents_fire_at_idx\n ON scheduled_subagents (fire_at);\n\nCREATE OR REPLACE FUNCTION scheduled_subagents_notify_changed() RETURNS trigger AS $$\nDECLARE\n payload_key text;\n op text;\nBEGIN\n IF TG_OP = 'DELETE' THEN\n payload_key := OLD.key;\n op := 'd';\n ELSE\n payload_key := NEW.key;\n op := 'u';\n END IF;\n PERFORM pg_notify('scheduled_subagents_changed', payload_key || ':' || op);\n RETURN COALESCE(NEW, OLD);\nEND;\n$$ LANGUAGE plpgsql;\n\nDROP TRIGGER IF EXISTS scheduled_subagents_notify_changed_trg ON scheduled_subagents;\nCREATE TRIGGER scheduled_subagents_notify_changed_trg\n AFTER INSERT OR UPDATE OR DELETE ON scheduled_subagents\n FOR EACH ROW EXECUTE FUNCTION scheduled_subagents_notify_changed();\n\n-- \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 inference_events \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n--\n-- Append-only audit trail of every upstream model HTTP call attempt.\n-- Written by AgentRunner on each generate() outcome (success / retryable /\n-- fatal). Read by the host-side `inference_status` reflection tool to\n-- answer \"is this model misbehaving right now?\". One row per attempt;\n-- retries write multiple rows. NULL agent_run_id is kept for runs whose\n-- row was later deleted (parent event cascade) so the historical signal\n-- survives.\nCREATE TABLE IF NOT EXISTS inference_events (\n id bigserial PRIMARY KEY,\n provider text NOT NULL,\n model text NOT NULL,\n agent_run_id bigint REFERENCES agentruns(id) ON DELETE SET NULL,\n outcome text NOT NULL CHECK (outcome IN ('success','retryable','fatal')),\n status_code int,\n error_excerpt text,\n occurred_at timestamptz NOT NULL DEFAULT now()\n);\n\nCREATE INDEX IF NOT EXISTS inference_events_model_time_idx\n ON inference_events (model, occurred_at DESC);\nCREATE INDEX IF NOT EXISTS inference_events_occurred_at_idx\n ON inference_events (occurred_at DESC);\n\n-- \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 tool_calls \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n--\n-- Append-only record of every tool invocation an agentrun attempted,\n-- tagged with the resolved handler markdown path and whether the call\n-- threw. Written by the tool wrapper in the container's ToolsFactory on\n-- each execute() outcome. Read by the heuristic tool-preloader\n-- (ToolCallBus.topToolsForHandler): the tools a handler successfully\n-- used across its recent non-error runs get loaded up front on the next\n-- run, so warm handlers rarely need a tool_list / tool_call round-trip.\n-- NULL agent_run_id survives a parent-event cascade so the historical\n-- usage signal outlives the run row.\nCREATE TABLE IF NOT EXISTS tool_calls (\n id bigserial PRIMARY KEY,\n agent_run_id bigint REFERENCES agentruns(id) ON DELETE SET NULL,\n handler_path text NOT NULL,\n tool_name text NOT NULL,\n successful boolean NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now()\n);\n\nCREATE INDEX IF NOT EXISTS tool_calls_handler_run_idx\n ON tool_calls (handler_path, agent_run_id DESC);\nCREATE INDEX IF NOT EXISTS tool_calls_created_at_idx\n ON tool_calls (created_at DESC);\n";
65
+ export declare const SCHEMA_SQL = "\n-- Drop legacy single-table artifacts from before the events/agentruns\n-- split. Safe no-ops on fresh databases. The current schema reuses the\n-- name events_notify_new() for its own NOTIFY function, so we do NOT\n-- drop it here (CREATE OR REPLACE FUNCTION below handles the update);\n-- dropping would fail anyway once the current events_new_trg exists.\nDROP TRIGGER IF EXISTS events_notify_changed_trg ON events;\nDROP TRIGGER IF EXISTS events_notify_new_trg ON events;\nDROP FUNCTION IF EXISTS events_notify_changed();\nDROP INDEX IF EXISTS events_pending_priority_idx;\nDROP INDEX IF EXISTS events_state_priority_idx;\n\nCREATE TABLE IF NOT EXISTS events (\n id bigserial PRIMARY KEY,\n topic text NOT NULL,\n priority smallint NOT NULL DEFAULT 50,\n state text NOT NULL DEFAULT 'pending',\n payload jsonb NOT NULL DEFAULT '{}'::jsonb,\n idempotency_key text UNIQUE,\n privileged boolean NOT NULL DEFAULT false,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now(),\n CONSTRAINT events_topic_format CHECK (topic ~ '^[\\w-]+(:[\\w-]+)*$')\n);\n\n-- Drop legacy columns from earlier schema generations. Single-instance\n-- project; column drops are fine.\nALTER TABLE events DROP COLUMN IF EXISTS supervisor_prompt;\nALTER TABLE events DROP COLUMN IF EXISTS causation_chain;\n\n-- Chat-aware event metadata. `is_chat` opts into automatic user-message\n-- persistence in EventBus.add; `preferred_chat_channel_id` names the\n-- channel an assistant reply should reach the user on. The container is\n-- channel-blind \u2014 both fields are read host-side (for routing) or via\n-- JOIN inside the chatmessages NOTIFY trigger.\nALTER TABLE events ADD COLUMN IF NOT EXISTS is_chat boolean NOT NULL DEFAULT false;\nALTER TABLE events ADD COLUMN IF NOT EXISTS preferred_chat_channel_id text;\n-- Required for non-chat events (validated at `EventBus.add` time and at\n-- the type level via `NewEvent`'s discriminated union); always null for\n-- chat events because the user's text in `chatmessages` already serves\n-- as the agent-visible \"what happened\" message. The EventWatcher copies\n-- this verbatim into the root `agentruns.prompt` so the agent sees the\n-- emitter's framing without the EventWatcher having to reach into the\n-- payload schema.\nALTER TABLE events ADD COLUMN IF NOT EXISTS prompt text;\n-- The topic is the handler's whole address now; the separate start\n-- handler basename is gone.\nALTER TABLE events DROP COLUMN IF EXISTS start_handler;\n-- When true the topic must name an existing handler file exactly; when\n-- false (world events) handler resolution falls back up the topic chain.\n-- Copied onto the root agentrun by the input-event watcher.\nALTER TABLE events ADD COLUMN IF NOT EXISTS is_exact_topic boolean NOT NULL DEFAULT false;\n-- Privileged events originate from a trusted user-input source (operator\n-- at the local terminal via cli-chat, operator on Telegram). The flag\n-- propagates verbatim to the root agentrun and to every child agentrun\n-- spawned via schedule_subagent / start_subagent, so future system tools can\n-- gate risky reads / writes (editing SOUL.md etc.) on whether the run\n-- descends from a trusted input. Default false: any plugin that doesn't\n-- explicitly opt in produces non-privileged events.\nALTER TABLE events ADD COLUMN IF NOT EXISTS privileged boolean NOT NULL DEFAULT false;\n-- When true and the event ends in 'failed', `HostContextImpl.emitAndAwait`\n-- writes a role='assistant' chatmessage with the failure text before\n-- rejecting handle.settled. Default false: only chat plugins (cli-chat,\n-- telegram) opt in. See [[outputChatOnFailure]] on NewEvent for the\n-- rationale.\nALTER TABLE events ADD COLUMN IF NOT EXISTS output_chat_on_failure boolean NOT NULL DEFAULT false;\n\nCREATE INDEX IF NOT EXISTS events_state_priority_idx\n ON events (state, priority DESC, id ASC);\nCREATE INDEX IF NOT EXISTS events_topic_idx ON events (topic);\n\nCREATE TABLE IF NOT EXISTS agentruns (\n id bigserial PRIMARY KEY,\n event_id bigint NOT NULL REFERENCES events(id) ON DELETE CASCADE,\n parent_agentrun_id bigint REFERENCES agentruns(id) ON DELETE CASCADE,\n topic text NOT NULL,\n priority smallint NOT NULL DEFAULT 50,\n state text NOT NULL DEFAULT 'pending',\n prompt text,\n payload jsonb NOT NULL DEFAULT '{}'::jsonb,\n result jsonb,\n result_text text,\n error text,\n privileged boolean NOT NULL DEFAULT false,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now(),\n CONSTRAINT agentruns_topic_format CHECK (topic ~ '^[\\w-]+(:[\\w-]+)*$')\n);\n\n-- Forward-compat ALTER for databases created before result_text landed.\n-- Safe no-op on fresh databases where the column already exists.\nALTER TABLE agentruns ADD COLUMN IF NOT EXISTS result_text text;\n-- The topic is the handler's whole address; the basename column is gone.\nALTER TABLE agentruns DROP COLUMN IF EXISTS handler;\n-- Whether handler resolution must match the topic exactly. Root\n-- agentruns copy the event's flag; spawned children are always exact.\nALTER TABLE agentruns ADD COLUMN IF NOT EXISTS is_exact_topic boolean NOT NULL DEFAULT true;\n-- Inherited from the originating event (root agentrun) or parent\n-- agentrun (children spawned via schedule_subagent / start_subagent). See\n-- the matching ALTER on the events table for the trust-model rationale.\nALTER TABLE agentruns ADD COLUMN IF NOT EXISTS privileged boolean NOT NULL DEFAULT false;\n-- Number of retry attempts already made on this agentrun. Bumped each\n-- time AgentRunner postpones the row due to a retryable inference\n-- error (APICallError.isRetryable). Capped per-handler via maxRetries\n-- (frontmatter override) or globally via inference.maxRetries.\nALTER TABLE agentruns ADD COLUMN IF NOT EXISTS retry_count int NOT NULL DEFAULT 0;\n-- Earliest moment the agentrun watcher is allowed to re-claim this\n-- row. NULL = claim immediately (default for fresh rows). A future\n-- timestamp = leave the row alone until then; the watcher's claim\n-- query gates on this so a parked row doesn't waste the slot while\n-- other agentruns (potentially using different models) can still run.\nALTER TABLE agentruns ADD COLUMN IF NOT EXISTS not_before timestamptz;\n-- Resolved model id for this agentrun, of the form\n-- `<provider>/<modelId>` (e.g. `featherless/zai-org/GLM-5.1`).\n-- Populated by AgentRunner once it builds the model client; stays\n-- NULL for any agentrun that never reached generate() (failed at\n-- handler-load time, etc.).\nALTER TABLE agentruns ADD COLUMN IF NOT EXISTS model text;\n-- Resolved prompt (rendered prompt template: system prompt, then\n-- user-message head) used for this agentrun. Populated by AgentRunner\n-- only when core.logSystemPrompt is true; otherwise NULL. Surfaced\n-- by the report layer's Agentrun Start section when the consumer\n-- opts into withDetails.\nALTER TABLE agentruns ADD COLUMN IF NOT EXISTS system_prompt text;\n-- Verbatim model-message array assembled for the first agent.generate()\n-- call (prior history + the run's leading user turn). Populated by\n-- AgentRunner only when inference.captureInitialMessageHistory is true;\n-- otherwise NULL. Surfaced by the report layer's -vv view so an operator\n-- can see exactly what was sent into the model loop.\nALTER TABLE agentruns ADD COLUMN IF NOT EXISTS initial_messages jsonb;\n\n-- Distinguishes how a child agentrun was spawned.\n-- NULL \u2014 root agentrun (created by the input-event watcher, no parent).\n-- 'scheduled' \u2014 fire-and-forget child spawned by `schedule_subagent` without\n-- a future `when` (immediate dispatch under the same event).\n-- 'started' \u2014 synchronous child spawned via the `start_subagent` tool; the\n-- parent is parked in state='waiting' until this row settles.\n-- The Scheduler reads this column to decide whether settling a row should\n-- wake a waiting parent.\nALTER TABLE agentruns ADD COLUMN IF NOT EXISTS calltype text;\nALTER TABLE agentruns DROP CONSTRAINT IF EXISTS agentruns_calltype_format;\nALTER TABLE agentruns ADD CONSTRAINT agentruns_calltype_format\n CHECK (calltype IS NULL OR calltype IN ('scheduled','started'));\n\n-- Partial index for the \"are all started children of $parent settled?\"\n-- check the Scheduler runs after every 'started' child settles. Indexes\n-- only the rows that actually participate in the question.\nCREATE INDEX IF NOT EXISTS agentruns_parent_calltype_state_idx\n ON agentruns (parent_agentrun_id, state)\n WHERE calltype = 'started';\n\n-- Forward-compat: relax the topic CHECK constraint to allow arbitrarily\n-- deep `a:b:c:\u2026` topics. CREATE TABLE IF NOT EXISTS above doesn't\n-- update existing constraints, so we drop+re-add unconditionally. The\n-- DROP IF EXISTS / ADD pair is idempotent.\nALTER TABLE events DROP CONSTRAINT IF EXISTS events_topic_format;\nALTER TABLE events ADD CONSTRAINT events_topic_format CHECK (topic ~ '^[\\w-]+(:[\\w-]+)*$');\nALTER TABLE agentruns DROP CONSTRAINT IF EXISTS agentruns_topic_format;\nALTER TABLE agentruns ADD CONSTRAINT agentruns_topic_format CHECK (topic ~ '^[\\w-]+(:[\\w-]+)*$');\n\nCREATE INDEX IF NOT EXISTS agentruns_state_priority_idx\n ON agentruns (state, priority DESC, id ASC);\nCREATE INDEX IF NOT EXISTS agentruns_event_id_idx ON agentruns (event_id);\nCREATE INDEX IF NOT EXISTS agentruns_parent_idx ON agentruns (parent_agentrun_id);\n\nCREATE TABLE IF NOT EXISTS stepresults (\n id bigserial PRIMARY KEY,\n agent_run_id bigint NOT NULL REFERENCES agentruns(id) ON DELETE CASCADE,\n event_id bigint NOT NULL REFERENCES events(id) ON DELETE CASCADE,\n step_number int NOT NULL,\n finish_reason text NOT NULL,\n result_text text,\n reasoning_text text,\n input_tokens int,\n output_tokens int,\n total_tokens int,\n tool_call_count int NOT NULL DEFAULT 0,\n tool_calls jsonb NOT NULL DEFAULT '[]'::jsonb,\n tool_results jsonb NOT NULL DEFAULT '[]'::jsonb,\n created_at timestamptz NOT NULL DEFAULT now(),\n CONSTRAINT stepresults_step_number_unique UNIQUE (agent_run_id, step_number)\n);\n\nCREATE INDEX IF NOT EXISTS stepresults_agent_run_id_idx ON stepresults (agent_run_id);\nCREATE INDEX IF NOT EXISTS stepresults_event_id_idx ON stepresults (event_id);\n\n-- AI SDK per-step usage breakdown\n-- (LanguageModelUsage.inputTokenDetails / outputTokenDetails). Each\n-- column is NULL when the provider doesn't report that detail.\nALTER TABLE stepresults ADD COLUMN IF NOT EXISTS input_tokens_no_cache int;\nALTER TABLE stepresults ADD COLUMN IF NOT EXISTS input_tokens_cache_read int;\nALTER TABLE stepresults ADD COLUMN IF NOT EXISTS input_tokens_cache_write int;\nALTER TABLE stepresults ADD COLUMN IF NOT EXISTS output_tokens_text int;\nALTER TABLE stepresults ADD COLUMN IF NOT EXISTS output_tokens_reasoning int;\n-- Full step object snapshot, populated only when the operator opts\n-- in via inference.captureRawStepResultToDatabase: true. Used to\n-- inspect provider-specific fields (Anthropic cache control,\n-- OpenAI logprobs, ...) that don't fit dedicated columns.\nALTER TABLE stepresults ADD COLUMN IF NOT EXISTS raw_result jsonb;\n\n-- \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 chatmessages \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n--\n-- Persistent chat history across all channels. Each row links to the\n-- event whose lifecycle the message belongs to:\n-- * For role='user': the event the host plugin emitted with isChat=true.\n-- * For role='assistant': the event whose agentrun called send_chat.\n-- The channel is reachable via JOIN to events.preferred_chat_channel_id;\n-- there is intentionally no channel_id column here \u2014 channel routing is\n-- a host-side concern, the container never names a channel.\n--\n-- delivered_at is set when ANY listener returns true from its async\n-- handler. New subscribers replay all undelivered matching rows on\n-- registration so a message produced when nobody was listening is still\n-- delivered later.\nCREATE TABLE IF NOT EXISTS chatmessages (\n id bigserial PRIMARY KEY,\n event_id bigint NOT NULL REFERENCES events(id) ON DELETE CASCADE,\n role text NOT NULL CHECK (role IN ('user','assistant')),\n text_content text NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now(),\n delivered_at timestamptz\n);\n\nCREATE INDEX IF NOT EXISTS chatmessages_event_idx\n ON chatmessages (event_id);\nCREATE INDEX IF NOT EXISTS chatmessages_undelivered_idx\n ON chatmessages (created_at) WHERE delivered_at IS NULL;\n\n-- \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 NOTIFY triggers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nCREATE OR REPLACE FUNCTION events_notify_new() RETURNS trigger AS $$\nBEGIN\n PERFORM pg_notify('events_new', NEW.id::text);\n RETURN NEW;\nEND;\n$$ LANGUAGE plpgsql;\n\nDROP TRIGGER IF EXISTS events_new_trg ON events;\nCREATE TRIGGER events_new_trg\n AFTER INSERT ON events\n FOR EACH ROW EXECUTE FUNCTION events_notify_new();\n\nCREATE OR REPLACE FUNCTION events_notify_state() RETURNS trigger AS $$\nBEGIN\n PERFORM pg_notify('events_state', NEW.id::text || ':' || NEW.state);\n RETURN NEW;\nEND;\n$$ LANGUAGE plpgsql;\n\nDROP TRIGGER IF EXISTS events_state_trg ON events;\nCREATE TRIGGER events_state_trg\n AFTER UPDATE OF state ON events\n FOR EACH ROW EXECUTE FUNCTION events_notify_state();\n\nCREATE OR REPLACE FUNCTION agentruns_notify_changed() RETURNS trigger AS $$\nBEGIN\n PERFORM pg_notify(\n 'agentruns_changed',\n NEW.event_id::text || ':' || NEW.id::text\n );\n RETURN NEW;\nEND;\n$$ LANGUAGE plpgsql;\n\nDROP TRIGGER IF EXISTS agentruns_notify_changed_trg ON agentruns;\nCREATE TRIGGER agentruns_notify_changed_trg\n AFTER INSERT OR UPDATE OF state ON agentruns\n FOR EACH ROW EXECUTE FUNCTION agentruns_notify_changed();\n\nCREATE OR REPLACE FUNCTION stepresults_notify_new() RETURNS trigger AS $$\nBEGIN\n PERFORM pg_notify(\n 'stepresults_new',\n NEW.event_id::text || ':' || NEW.agent_run_id::text || ':' || NEW.id::text\n );\n RETURN NEW;\nEND;\n$$ LANGUAGE plpgsql;\n\nDROP TRIGGER IF EXISTS stepresults_new_trg ON stepresults;\nCREATE TRIGGER stepresults_new_trg\n AFTER INSERT ON stepresults\n FOR EACH ROW EXECUTE FUNCTION stepresults_notify_new();\n\n-- chatmessages NOTIFY: payload is \"<channel_id>:<role>:<id>\". Channel\n-- comes from the parent event's preferred_chat_channel_id, JOINed at\n-- trigger time. Empty channel becomes empty prefix \u2014 listeners will\n-- filter it out unless they explicitly subscribe to channelId=\"\".\nCREATE OR REPLACE FUNCTION chatmessages_notify_new() RETURNS trigger AS $$\nDECLARE\n channel text;\nBEGIN\n SELECT preferred_chat_channel_id INTO channel FROM events WHERE id = NEW.event_id;\n PERFORM pg_notify(\n 'chatmessages_new',\n COALESCE(channel, '') || ':' || NEW.role || ':' || NEW.id::text\n );\n RETURN NEW;\nEND;\n$$ LANGUAGE plpgsql;\n\nDROP TRIGGER IF EXISTS chatmessages_new_trg ON chatmessages;\nCREATE TRIGGER chatmessages_new_trg\n AFTER INSERT ON chatmessages\n FOR EACH ROW EXECUTE FUNCTION chatmessages_notify_new();\n\n-- \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 calendars + calendar_events \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n--\n-- Plugin-agnostic calendar data layer. `calendars` lists every\n-- subscription (own or shared) any provider plugin (ms365, future\n-- google/caldav) has surfaced; `calendar_events` stores every\n-- instance. Providers persist every occurrence of a recurring\n-- series independently (no master-expansion in core).\n--\n-- Identity:\n-- * `calendars.unique_key` is the provider's stable id. Uniqueness\n-- within `(plugin_id, unique_key)` lets multiple providers\n-- coexist.\n-- * `calendar_events.id` is provider-prefixed (e.g. `ms365:<graph-id>`)\n-- so collisions across providers are impossible by construction.\n--\n-- Refresh reconciliation uses a scan-generation tag: a refresh walk\n-- bumps `calendars.scan_generation`, upserts every event in window\n-- with the new value, then DELETEs events whose generation is older\n-- than the calendar's current value.\n\nCREATE TABLE IF NOT EXISTS calendars (\n id bigserial PRIMARY KEY,\n plugin_id text NOT NULL,\n unique_key text NOT NULL,\n name text NOT NULL,\n type text NOT NULL CHECK (type IN ('own','shared')),\n owner_name text,\n scan_generation int NOT NULL DEFAULT 0,\n created_at timestamptz NOT NULL DEFAULT now(),\n UNIQUE (plugin_id, unique_key)\n);\n\n-- The provider's own \"default calendar\" flag (Graph's\n-- `isDefaultCalendar`). Used by `CalendarService.resolveDefaultCalendar`\n-- as the fallback when `core.defaultCalendar` is unset \u2014 we pick the\n-- first registered calendar (lowest id) flagged here. Added via\n-- ALTER so existing databases don't need a schema reset.\nALTER TABLE calendars ADD COLUMN IF NOT EXISTS is_default smallint NOT NULL DEFAULT 0;\n\nCREATE INDEX IF NOT EXISTS calendars_plugin_id_idx ON calendars (plugin_id);\n\nCREATE TABLE IF NOT EXISTS calendar_events (\n id text PRIMARY KEY,\n calendar_id bigint NOT NULL REFERENCES calendars(id) ON DELETE CASCADE,\n series_master_id text,\n type text NOT NULL CHECK (type IN ('singleInstance','occurrence','exception','seriesMaster')),\n subject text,\n start_dt text NOT NULL,\n end_dt text NOT NULL,\n event_tz text,\n is_all_day smallint NOT NULL DEFAULT 0,\n is_cancelled smallint NOT NULL DEFAULT 0,\n show_as text,\n sensitivity text,\n importance text,\n location text,\n is_online_meeting smallint NOT NULL DEFAULT 0,\n online_meeting_url text,\n organizer_name text,\n organizer_email text,\n response_status text,\n attendees_json jsonb,\n body text,\n attachments jsonb,\n scan_generation int NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now()\n);\n\nCREATE INDEX IF NOT EXISTS calendar_events_window_idx\n ON calendar_events (calendar_id, start_dt);\nCREATE INDEX IF NOT EXISTS calendar_events_series_idx\n ON calendar_events (series_master_id);\nCREATE INDEX IF NOT EXISTS calendar_events_generation_idx\n ON calendar_events (calendar_id, scan_generation);\n\n-- \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 scheduled_subagents \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n--\n-- One-off agent-scheduled wake-ups. Each row is upserted by the\n-- container's `schedule_subagent` tool and read by the host-side\n-- `ScheduledSubagentScheduler`, which installs a Croner job per row\n-- and atomically deletes the row when it fires. `key` is the\n-- agent-supplied unique id used for replace-on-conflict semantics\n-- (\"rescheduling a key overwrites the previous timing\"). `fire_at`\n-- is the UTC firing time; the agent passes wall-clock-in-`core.timezone`\n-- and the container projects to UTC before insert. On daemon startup,\n-- past-due rows are deleted with a warn log; future rows are\n-- reinstalled. See [[feedback_agent_facing_format]] \u2014 UTC storage,\n-- local-tz projection at every agent-facing edge.\nCREATE TABLE IF NOT EXISTS scheduled_subagents (\n key text PRIMARY KEY,\n fire_at timestamptz NOT NULL,\n topic text NOT NULL,\n prompt text,\n payload jsonb NOT NULL DEFAULT '{}'::jsonb,\n priority smallint NOT NULL DEFAULT 50,\n privileged boolean NOT NULL DEFAULT false,\n created_at timestamptz NOT NULL DEFAULT now(),\n CONSTRAINT scheduled_subagents_topic_format CHECK (topic ~ '^[\\w-]+(:[\\w-]+)*$')\n);\n\n-- The topic is the handler's whole address; the basename column is gone.\nALTER TABLE scheduled_subagents DROP COLUMN IF EXISTS handler;\n-- Re-add the topic CHECK so a widened TOPIC_PATTERN reaches existing tables.\nALTER TABLE scheduled_subagents DROP CONSTRAINT IF EXISTS scheduled_subagents_topic_format;\nALTER TABLE scheduled_subagents ADD CONSTRAINT scheduled_subagents_topic_format CHECK (topic ~ '^[\\w-]+(:[\\w-]+)*$');\n\nCREATE INDEX IF NOT EXISTS scheduled_subagents_fire_at_idx\n ON scheduled_subagents (fire_at);\n\nCREATE OR REPLACE FUNCTION scheduled_subagents_notify_changed() RETURNS trigger AS $$\nDECLARE\n payload_key text;\n op text;\nBEGIN\n IF TG_OP = 'DELETE' THEN\n payload_key := OLD.key;\n op := 'd';\n ELSE\n payload_key := NEW.key;\n op := 'u';\n END IF;\n PERFORM pg_notify('scheduled_subagents_changed', payload_key || ':' || op);\n RETURN COALESCE(NEW, OLD);\nEND;\n$$ LANGUAGE plpgsql;\n\nDROP TRIGGER IF EXISTS scheduled_subagents_notify_changed_trg ON scheduled_subagents;\nCREATE TRIGGER scheduled_subagents_notify_changed_trg\n AFTER INSERT OR UPDATE OR DELETE ON scheduled_subagents\n FOR EACH ROW EXECUTE FUNCTION scheduled_subagents_notify_changed();\n\n-- \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 inference_events \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n--\n-- Append-only audit trail of every upstream model HTTP call attempt.\n-- Written by AgentRunner on each generate() outcome (success / retryable /\n-- fatal). Read by the host-side `inference_status` reflection tool to\n-- answer \"is this model misbehaving right now?\". One row per attempt;\n-- retries write multiple rows. NULL agent_run_id is kept for runs whose\n-- row was later deleted (parent event cascade) so the historical signal\n-- survives.\nCREATE TABLE IF NOT EXISTS inference_events (\n id bigserial PRIMARY KEY,\n provider text NOT NULL,\n model text NOT NULL,\n agent_run_id bigint REFERENCES agentruns(id) ON DELETE SET NULL,\n outcome text NOT NULL CHECK (outcome IN ('success','retryable','fatal')),\n status_code int,\n error_excerpt text,\n occurred_at timestamptz NOT NULL DEFAULT now()\n);\n\nCREATE INDEX IF NOT EXISTS inference_events_model_time_idx\n ON inference_events (model, occurred_at DESC);\nCREATE INDEX IF NOT EXISTS inference_events_occurred_at_idx\n ON inference_events (occurred_at DESC);\n\n-- \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 tool_calls \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n--\n-- Append-only record of every tool invocation an agentrun attempted,\n-- tagged with the resolved handler markdown path and whether the call\n-- threw. Written by the tool wrapper in the container's ToolsFactory on\n-- each execute() outcome. Read by the heuristic tool-preloader\n-- (ToolCallBus.topToolsForHandler): the tools a handler successfully\n-- used across its recent non-error runs get loaded up front on the next\n-- run, so warm handlers rarely need a tool_list / tool_call round-trip.\n-- NULL agent_run_id survives a parent-event cascade so the historical\n-- usage signal outlives the run row.\nCREATE TABLE IF NOT EXISTS tool_calls (\n id bigserial PRIMARY KEY,\n agent_run_id bigint REFERENCES agentruns(id) ON DELETE SET NULL,\n handler_path text NOT NULL,\n tool_name text NOT NULL,\n successful boolean NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now()\n);\n\nCREATE INDEX IF NOT EXISTS tool_calls_handler_run_idx\n ON tool_calls (handler_path, agent_run_id DESC);\nCREATE INDEX IF NOT EXISTS tool_calls_created_at_idx\n ON tool_calls (created_at DESC);\n\n-- \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 web_login_tokens / web_sessions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n--\n-- Authentication state of the host webserver (host-only; the container\n-- never reads these). A login token is a one-time link minted by\n-- `familiar web login`; redeeming it deletes the row and creates a\n-- session. Only sha256 hashes of tokens are stored, never the tokens.\nCREATE TABLE IF NOT EXISTS web_login_tokens (\n token_hash text PRIMARY KEY,\n login text NOT NULL,\n expires_at timestamptz NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now()\n);\n\nCREATE TABLE IF NOT EXISTS web_sessions (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n token_hash text NOT NULL UNIQUE,\n login text NOT NULL,\n user_agent text,\n created_at timestamptz NOT NULL DEFAULT now(),\n last_seen_at timestamptz NOT NULL DEFAULT now(),\n expires_at timestamptz NOT NULL\n);\n";
66
66
  /**
67
67
  * SQL fragment that flips the parent event's terminal state when the
68
68
  * **root** agentrun settles. Run inside the same transaction as the
package/build/Schema.js CHANGED
@@ -549,6 +549,29 @@ CREATE INDEX IF NOT EXISTS tool_calls_handler_run_idx
549
549
  ON tool_calls (handler_path, agent_run_id DESC);
550
550
  CREATE INDEX IF NOT EXISTS tool_calls_created_at_idx
551
551
  ON tool_calls (created_at DESC);
552
+
553
+ -- ───────── web_login_tokens / web_sessions ─────────
554
+ --
555
+ -- Authentication state of the host webserver (host-only; the container
556
+ -- never reads these). A login token is a one-time link minted by
557
+ -- \`familiar web login\`; redeeming it deletes the row and creates a
558
+ -- session. Only sha256 hashes of tokens are stored, never the tokens.
559
+ CREATE TABLE IF NOT EXISTS web_login_tokens (
560
+ token_hash text PRIMARY KEY,
561
+ login text NOT NULL,
562
+ expires_at timestamptz NOT NULL,
563
+ created_at timestamptz NOT NULL DEFAULT now()
564
+ );
565
+
566
+ CREATE TABLE IF NOT EXISTS web_sessions (
567
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
568
+ token_hash text NOT NULL UNIQUE,
569
+ login text NOT NULL,
570
+ user_agent text,
571
+ created_at timestamptz NOT NULL DEFAULT now(),
572
+ last_seen_at timestamptz NOT NULL DEFAULT now(),
573
+ expires_at timestamptz NOT NULL
574
+ );
552
575
  `;
553
576
  /**
554
577
  * SQL fragment that flips the parent event's terminal state when the
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Per-event scratch folders (`/scratch/<event-id>/` in the containers,
3
+ * `<scratchDir>/<event-id>/` on the host).
4
+ *
5
+ * Convention: files whose name starts with `.` are internal (spilled tool
6
+ * results, plugin bookkeeping). They are left out wherever scratch files
7
+ * are listed for the model ("staged files" in the prompt) or the user
8
+ * (downloads in the web chat).
9
+ */
10
+ /** A file in an event's scratch folder, as `ctx.scratch.listFiles` reports it. */
11
+ export interface ScratchFile {
12
+ /** Basename inside `/scratch/<event-id>/`. */
13
+ readonly name: string;
14
+ /** Size in bytes. */
15
+ readonly size: number;
16
+ /** Last modification. */
17
+ readonly modifiedAt: Date;
18
+ }
19
+ /**
20
+ * Whether a scratch file is internal (dotfile) and must not be offered
21
+ * to the model or the user as a staged or produced file.
22
+ *
23
+ * @param name Basename.
24
+ * @returns True for hidden files.
25
+ */
26
+ export declare function isHiddenScratchFile(name: string): boolean;
27
+ /**
28
+ * File name for spilling an oversized tool result to scratch: hidden
29
+ * (leading `.`, see {@link isHiddenScratchFile}) and with a 4-byte random
30
+ * hex token before the extension, so concurrent spills with the same
31
+ * suggestion never collide — `result.json` → `.result-a1b2c3d4.json`.
32
+ *
33
+ * @param suggestedName Name proposed by the tool runner.
34
+ * @returns The basename to write.
35
+ */
36
+ export declare function scratchSpillFileName(suggestedName: string): string;
@@ -0,0 +1,29 @@
1
+ import { randomBytes } from "node:crypto";
2
+ /**
3
+ * Whether a scratch file is internal (dotfile) and must not be offered
4
+ * to the model or the user as a staged or produced file.
5
+ *
6
+ * @param name Basename.
7
+ * @returns True for hidden files.
8
+ */
9
+ export function isHiddenScratchFile(name) {
10
+ return name.startsWith(".");
11
+ }
12
+ /**
13
+ * File name for spilling an oversized tool result to scratch: hidden
14
+ * (leading `.`, see {@link isHiddenScratchFile}) and with a 4-byte random
15
+ * hex token before the extension, so concurrent spills with the same
16
+ * suggestion never collide — `result.json` → `.result-a1b2c3d4.json`.
17
+ *
18
+ * @param suggestedName Name proposed by the tool runner.
19
+ * @returns The basename to write.
20
+ */
21
+ export function scratchSpillFileName(suggestedName) {
22
+ const suffix = randomBytes(4).toString("hex");
23
+ const base = suggestedName.replace(/^\.+/, "");
24
+ const dotIdx = base.lastIndexOf(".");
25
+ const named = dotIdx <= 0
26
+ ? `${base}-${suffix}`
27
+ : `${base.slice(0, dotIdx)}-${suffix}${base.slice(dotIdx)}`;
28
+ return `.${named}`;
29
+ }
@@ -0,0 +1,166 @@
1
+ /**
2
+ * Trusted-proxy contract of the core webserver.
3
+ *
4
+ * A reverse proxy in front of the webserver (a user-run Authelia /
5
+ * oauth2-proxy, or a plugin's own proxy such as the tailscale sidecar)
6
+ * proves that a request went through it by sending
7
+ * {@link PROXY_SECRET_HEADER} with a shared secret. Only then does the
8
+ * webserver read the proxy's user header; without a matching secret,
9
+ * identity headers are ignored. Shared because plugins register such
10
+ * proxies through `ctx.web.registerTrustedProxy`.
11
+ *
12
+ * Also the contract of a web UI plugin's root controller
13
+ * ({@link WebUiEnv}, see `PluginHostManifest.webUi`).
14
+ */
15
+ import type { IncomingMessage, ServerResponse } from "node:http";
16
+ import type { Hono } from "hono";
17
+ import type { WebMenuEntry } from "./WebMenu.js";
18
+ import type { WebPageEntry } from "./WebPlugin.js";
19
+ /** Request header carrying a trusted proxy's shared secret (lowercase, as Hono / node normalize it). */
20
+ export declare const PROXY_SECRET_HEADER = "x-familiar-proxy-secret";
21
+ /** Minimum length of a trusted-proxy secret; shorter ones are rejected. */
22
+ export declare const MIN_PROXY_SECRET_LENGTH = 32;
23
+ /** A reverse proxy whose user header the webserver trusts once its secret matches. */
24
+ export interface TrustedProxyRegistration {
25
+ /** Shared secret the proxy sends in {@link PROXY_SECRET_HEADER}; at least {@link MIN_PROXY_SECRET_LENGTH} characters. */
26
+ readonly secret: string;
27
+ /** Header holding the authenticated login (e.g. `Tailscale-User-Login`, `Remote-User`). Empty or absent means "no identity". */
28
+ readonly userHeader: string;
29
+ /** Optional header holding a display name (e.g. `Tailscale-User-Name`). */
30
+ readonly nameHeader?: string;
31
+ /**
32
+ * Optional: where browsers reach the webserver through this proxy right
33
+ * now (e.g. `https://familiar.<tailnet>.ts.net`), or null while it is
34
+ * not serving. Used to build login links that work from the user's
35
+ * other devices. Called on demand; must be cheap and must not throw.
36
+ */
37
+ readonly publicBaseUrl?: () => string | null;
38
+ /**
39
+ * Whether the proxy signs users in by itself: an allowed user who opens
40
+ * {@link publicBaseUrl} is already authenticated (Tailscale identity,
41
+ * an Authelia login page, …), so a login link is pointless there and is
42
+ * not offered under that URL; the URL is listed as "signs in
43
+ * automatically" instead. Default `false`: login links are built for
44
+ * the proxy's URL.
45
+ */
46
+ readonly hasBuiltInAuth?: boolean;
47
+ }
48
+ /** Webserver hooks exposed to plugins as `ctx.web`. */
49
+ export interface WebApi {
50
+ /**
51
+ * Register this plugin as a trusted proxy of the webserver; its id is
52
+ * the plugin id. Call it from **`prepare()`**. The host drops the
53
+ * registration when the plugin restarts.
54
+ *
55
+ * @throws {Error} When the secret is shorter than
56
+ * {@link MIN_PROXY_SECRET_LENGTH}, the user header is empty, or the
57
+ * plugin already registered a proxy.
58
+ */
59
+ registerTrustedProxy(registration: TrustedProxyRegistration): void;
60
+ /**
61
+ * The web UI menu: every running plugin's `webMenu(ctx)` items, sorted
62
+ * by plugin weight (then plugin id), each plugin's items in its own
63
+ * order. Read it per request; it changes when plugins restart. For
64
+ * the web UI plugin; others contribute through their `webMenu` hook.
65
+ *
66
+ * @returns The flat, sorted item list (empty when nobody contributes).
67
+ */
68
+ listMenuItems(): readonly WebMenuEntry[];
69
+ /**
70
+ * The plugin pages (`webPlugin(ctx)` hooks with a `page`), one per
71
+ * plugin, sorted by plugin id. Read it per request. For the web UI
72
+ * plugin, which loads the page owning the current route.
73
+ *
74
+ * @returns The pages.
75
+ */
76
+ listPages(): readonly WebPageEntry[];
77
+ }
78
+ /** Who a request belongs to, as resolved by the core auth middleware. */
79
+ export interface WebPrincipal {
80
+ /** Login as listed in `webserver.auth.users`. */
81
+ readonly login: string;
82
+ /** Display name from the proxy's name header, else the login. */
83
+ readonly displayName: string;
84
+ /** `session`, or the id of the trusted proxy that vouched for the login (`plugin:tailscale`, `config:authelia`). */
85
+ readonly via: string;
86
+ }
87
+ /**
88
+ * Node bindings the webserver passes on every request (`c.env`), the same
89
+ * shape as `HttpBindings` of `@hono/node-server`. A UI controller may
90
+ * hand them to node-style middleware (e.g. Vite's dev server) and answer
91
+ * with `RESPONSE_ALREADY_SENT`.
92
+ */
93
+ export interface WebUiBindings {
94
+ readonly incoming: IncomingMessage;
95
+ readonly outgoing: ServerResponse;
96
+ }
97
+ /**
98
+ * Hono environment of a web UI plugin's root controller. Every request
99
+ * reaching the controller passed the core auth middleware, so
100
+ * `c.get("principal")` is always set.
101
+ */
102
+ export interface WebUiEnv {
103
+ Bindings: WebUiBindings;
104
+ Variables: {
105
+ /** The signed-in, allowlisted user. */
106
+ principal: WebPrincipal;
107
+ /** Whether the browser talks HTTPS (directly, or to a trusted proxy that says so). */
108
+ isHttps: boolean;
109
+ };
110
+ }
111
+ /**
112
+ * One of the core login-flow pages, described as data. The core decides
113
+ * which page is shown, with which status code, and handles every form
114
+ * submission itself; a web UI only turns the view into markup
115
+ * ({@link WebUi.renderAuthPage}).
116
+ */
117
+ export type WebAuthPageView =
118
+ /** `GET /login` with an allowed identity: who is signed in, link to the app. */
119
+ {
120
+ readonly kind: "signedIn";
121
+ readonly principal: WebPrincipal;
122
+ /** Where "continue" leads (`/`). */
123
+ readonly continueUrl: string;
124
+ /** Form action of the sign-out button (`POST`, `/logout`). */
125
+ readonly logoutAction: string;
126
+ }
127
+ /** `GET /login` without identity: how to get a login link. */
128
+ | {
129
+ readonly kind: "signedOut";
130
+ /** CLI command that prints a login link (`familiar web login`). */
131
+ readonly loginCommand: string;
132
+ }
133
+ /** `GET /login/:token`: confirm before the one-time token is redeemed. */
134
+ | {
135
+ readonly kind: "confirmLoginLink";
136
+ /** Form action redeeming the token (`POST`, `/login/<token>`). */
137
+ readonly formAction: string;
138
+ }
139
+ /** `POST /login/:token` with an invalid, used or expired token. */
140
+ | {
141
+ readonly kind: "invalidLoginLink";
142
+ /** CLI command that prints a new login link. */
143
+ readonly loginCommand: string;
144
+ };
145
+ /**
146
+ * What a web UI plugin hands the core webserver from its `webUi(ctx)` hook.
147
+ */
148
+ export interface WebUi {
149
+ /**
150
+ * Root controller mounted at `/`, behind the core auth middleware and
151
+ * after the core login routes.
152
+ */
153
+ readonly controller: Hono<WebUiEnv>;
154
+ /**
155
+ * Optional: render a login-flow page as a complete HTML document.
156
+ * The page is served under a strict Content-Security-Policy (no
157
+ * scripts, no external resources; inline styles and `data:` fonts /
158
+ * images only; forms may post to the same origin only), so it must
159
+ * be self-contained. Text content must be escaped by the renderer.
160
+ * When it is absent or throws, the core serves its plain page.
161
+ *
162
+ * @param view The page the core decided to show.
163
+ * @returns The HTML document.
164
+ */
165
+ readonly renderAuthPage?: (view: WebAuthPageView) => Promise<string>;
166
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Trusted-proxy contract of the core webserver.
3
+ *
4
+ * A reverse proxy in front of the webserver (a user-run Authelia /
5
+ * oauth2-proxy, or a plugin's own proxy such as the tailscale sidecar)
6
+ * proves that a request went through it by sending
7
+ * {@link PROXY_SECRET_HEADER} with a shared secret. Only then does the
8
+ * webserver read the proxy's user header; without a matching secret,
9
+ * identity headers are ignored. Shared because plugins register such
10
+ * proxies through `ctx.web.registerTrustedProxy`.
11
+ *
12
+ * Also the contract of a web UI plugin's root controller
13
+ * ({@link WebUiEnv}, see `PluginHostManifest.webUi`).
14
+ */
15
+ /** Request header carrying a trusted proxy's shared secret (lowercase, as Hono / node normalize it). */
16
+ export const PROXY_SECRET_HEADER = "x-familiar-proxy-secret";
17
+ /** Minimum length of a trusted-proxy secret; shorter ones are rejected. */
18
+ export const MIN_PROXY_SECRET_LENGTH = 32;
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Navigation entries plugins contribute to the web UI's sidebar.
3
+ *
4
+ * A plugin returns one {@link WebMenuContribution} from its `webMenu(ctx)`
5
+ * hook; the core collects them, sorts them by weight and hands the flat
6
+ * list to the web UI plugin (`ctx.web.listMenuItems()`), which renders it.
7
+ */
8
+ /** Lucide icon id, kebab-case (`mail`, `calendar-days`), see https://lucide.dev/icons. */
9
+ export declare const WEB_MENU_ICON_PATTERN: RegExp;
10
+ /** A sub-entry of a collapsible menu item. */
11
+ export interface WebMenuSubItem {
12
+ /** Text shown in the menu. */
13
+ readonly label: string;
14
+ /** Path inside the web UI, starting with `/` (e.g. `/plugins/mail/inbox`). */
15
+ readonly route: string;
16
+ }
17
+ /**
18
+ * One top-level menu item: a direct link (`route` without `children`) or a
19
+ * collapsible group (`children`, optionally with its own `route`).
20
+ */
21
+ export interface WebMenuItem {
22
+ /** Lucide icon id (see {@link WEB_MENU_ICON_PATTERN}). */
23
+ readonly icon: string;
24
+ /** Text shown in the menu. */
25
+ readonly label: string;
26
+ /** Path inside the web UI, starting with `/`. Required when there are no children. */
27
+ readonly route?: string;
28
+ /** Sub-entries; makes the item collapsible. */
29
+ readonly children?: readonly WebMenuSubItem[];
30
+ }
31
+ /** What one plugin contributes to the menu. */
32
+ export interface WebMenuContribution {
33
+ /**
34
+ * Position of the plugin's items among all plugins: lower weights come
35
+ * first (default 0; ties are ordered by plugin id). The plugin's items
36
+ * keep their own order.
37
+ */
38
+ readonly weight?: number;
39
+ /** The plugin's items, in display order. */
40
+ readonly items: readonly WebMenuItem[];
41
+ }
42
+ /** A menu item as the core hands it to the web UI. */
43
+ export interface WebMenuEntry extends WebMenuItem {
44
+ /** Plugin that contributed the item. */
45
+ readonly pluginId: string;
46
+ }
47
+ /**
48
+ * The first route of a menu: the first item's own route, else its first
49
+ * child's route. The web UI opens it instead of an empty start page.
50
+ *
51
+ * @param items Sorted menu items.
52
+ * @returns The route, or null for an empty menu.
53
+ */
54
+ export declare function firstMenuRoute(items: readonly WebMenuItem[]): string | null;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Navigation entries plugins contribute to the web UI's sidebar.
3
+ *
4
+ * A plugin returns one {@link WebMenuContribution} from its `webMenu(ctx)`
5
+ * hook; the core collects them, sorts them by weight and hands the flat
6
+ * list to the web UI plugin (`ctx.web.listMenuItems()`), which renders it.
7
+ */
8
+ /** Lucide icon id, kebab-case (`mail`, `calendar-days`), see https://lucide.dev/icons. */
9
+ export const WEB_MENU_ICON_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/;
10
+ /**
11
+ * The first route of a menu: the first item's own route, else its first
12
+ * child's route. The web UI opens it instead of an empty start page.
13
+ *
14
+ * @param items Sorted menu items.
15
+ * @returns The route, or null for an empty menu.
16
+ */
17
+ export function firstMenuRoute(items) {
18
+ const first = items[0];
19
+ if (first === undefined) {
20
+ return null;
21
+ }
22
+ return first.route ?? first.children?.[0]?.route ?? null;
23
+ }
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Plugin pages and controllers of the web UI.
3
+ *
4
+ * A plugin's `webPlugin(ctx)` hook returns a {@link WebPluginUi}: a Hono
5
+ * controller the core webserver mounts at `/plugins/<plugin-id>/`
6
+ * (behind its authentication) and, optionally, a page module the web UI
7
+ * plugin loads into its content area for every browser route under
8
+ * `/plugins/<plugin-id>`.
9
+ */
10
+ import type { Hono } from "hono";
11
+ import type { WebPrincipal, WebUiEnv } from "./WebAuth.js";
12
+ /** Where a plugin page's ES module comes from. */
13
+ export interface WebPageModule {
14
+ /**
15
+ * Path of the built module relative to the plugin's controller mount,
16
+ * e.g. `page/page.js` → served as `/plugins/<id>/page/page.js` by the
17
+ * plugin's own controller.
18
+ */
19
+ readonly module: string;
20
+ /**
21
+ * Dev mode only: absolute path of the page's source entry (`.tsx`).
22
+ * A web UI with a dev server may load it from source instead (hot
23
+ * reload, one React); omit it in production.
24
+ */
25
+ readonly sourceFile?: string;
26
+ }
27
+ /** What a plugin hands the core from its `webPlugin(ctx)` hook. */
28
+ export interface WebPluginUi {
29
+ /**
30
+ * Controller mounted at `/plugins/<plugin-id>/`, behind the core auth
31
+ * middleware (`c.get("principal")` is set). Register concrete routes
32
+ * only (e.g. `/api/*`, `/page/*`) and **no catch-all**: every path the
33
+ * controller does not match falls through to the web UI, which is how
34
+ * the browser routes of the plugin's page (`/plugins/<id>`, …) reach it.
35
+ */
36
+ readonly controller: Hono<WebUiEnv>;
37
+ /** Optional page shown by the web UI for routes under `/plugins/<plugin-id>`. */
38
+ readonly page?: WebPageModule;
39
+ /**
40
+ * Optional WebSocket endpoints, served at `/plugins/<plugin-id><path>`.
41
+ * The core authenticates every handshake like an ordinary request
42
+ * (proxy login or session, allowlist) and additionally requires a
43
+ * same-origin `Origin` header; only then is `onConnection` called.
44
+ * All sockets of a plugin are closed when it restarts.
45
+ */
46
+ readonly sockets?: readonly WebPluginSocket[];
47
+ }
48
+ /** A WebSocket endpoint of a plugin (see {@link WebPluginUi.sockets}). */
49
+ export interface WebPluginSocket {
50
+ /**
51
+ * Path below the plugin's mount, starting with `/` (e.g. `/socket`
52
+ * → `/plugins/<plugin-id>/socket`). Matched exactly, query ignored.
53
+ */
54
+ readonly path: string;
55
+ /**
56
+ * Called once per authenticated connection. Must not throw; errors
57
+ * of the connection's own work belong on the peer (`close`).
58
+ *
59
+ * @param peer The open socket.
60
+ * @param info Who connected and how.
61
+ */
62
+ onConnection(peer: WebSocketPeer, info: WebSocketConnectionInfo): void;
63
+ }
64
+ /** Who opened a plugin WebSocket. */
65
+ export interface WebSocketConnectionInfo {
66
+ /** The signed-in, allowlisted user. */
67
+ readonly principal: WebPrincipal;
68
+ /** Whether the browser reached the server over HTTPS (directly or via a trusted proxy). */
69
+ readonly isHttps: boolean;
70
+ }
71
+ /**
72
+ * Minimal, library-independent view of an open WebSocket, so plugins do
73
+ * not depend on the server's WebSocket implementation.
74
+ */
75
+ export interface WebSocketPeer {
76
+ /**
77
+ * Send a text (string) or binary (bytes) frame. Silently dropped once
78
+ * the socket is closing.
79
+ *
80
+ * @param data Frame payload.
81
+ */
82
+ send(data: string | Uint8Array): void;
83
+ /**
84
+ * Close the socket.
85
+ *
86
+ * @param code WebSocket close code (default 1000; 4000–4999 are free for the application).
87
+ * @param reason Short human-readable reason (≤ 123 bytes).
88
+ */
89
+ close(code?: number, reason?: string): void;
90
+ /**
91
+ * Register the frame handler (one per peer; a second call replaces it).
92
+ *
93
+ * @param handler Receives text frames as string, binary frames as bytes.
94
+ */
95
+ onMessage(handler: (data: string | Uint8Array) => void): void;
96
+ /**
97
+ * Register the close handler (one per peer; a second call replaces
98
+ * it). Called exactly once, also when the server closed the socket.
99
+ *
100
+ * @param handler Receives the close code and reason.
101
+ */
102
+ onClose(handler: (code: number, reason: string) => void): void;
103
+ /** Bytes queued but not yet sent (for backpressure). */
104
+ readonly bufferedAmount: number;
105
+ /** Whether the socket is open (not connecting, closing or closed). */
106
+ readonly isOpen: boolean;
107
+ }
108
+ /** A plugin page as the core lists it for the web UI (`ctx.web.listPages()`). */
109
+ export interface WebPageEntry {
110
+ /** Plugin providing the page. */
111
+ readonly pluginId: string;
112
+ /** Browser route prefix the page owns: `/plugins/<plugin-id>`. */
113
+ readonly basePath: string;
114
+ /** URL of the built module (`/plugins/<plugin-id>/<module>`). */
115
+ readonly moduleUrl: string;
116
+ /** Dev mode: absolute source entry (see {@link WebPageModule.sourceFile}). */
117
+ readonly sourceFile?: string;
118
+ }
119
+ /** What the web UI passes to a page module's `mount`. */
120
+ export interface WebPageContext {
121
+ /** Route prefix of the page (`/plugins/<plugin-id>`). */
122
+ readonly basePath: string;
123
+ /** Current browser path (at or below `basePath`). */
124
+ readonly pathname: string;
125
+ /** The signed-in user. */
126
+ readonly user: WebPrincipal;
127
+ /** Navigate the web UI to another route. */
128
+ navigate(to: string): void;
129
+ }
130
+ /**
131
+ * Default export of a page module: render the page into `container`
132
+ * (the web UI's content area) and return a function that unmounts it.
133
+ * Framework-agnostic; a React page creates its own root.
134
+ */
135
+ export type MountWebPage = (container: HTMLElement, context: WebPageContext) => () => void;
136
+ /** Route prefix of a plugin's controller and page. */
137
+ export declare function webPluginBasePath(pluginId: string): string;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Plugin pages and controllers of the web UI.
3
+ *
4
+ * A plugin's `webPlugin(ctx)` hook returns a {@link WebPluginUi}: a Hono
5
+ * controller the core webserver mounts at `/plugins/<plugin-id>/`
6
+ * (behind its authentication) and, optionally, a page module the web UI
7
+ * plugin loads into its content area for every browser route under
8
+ * `/plugins/<plugin-id>`.
9
+ */
10
+ /** Route prefix of a plugin's controller and page. */
11
+ export function webPluginBasePath(pluginId) {
12
+ return `/plugins/${pluginId}`;
13
+ }