@getfamiliar/shared 0.1.2
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/AgentRun.d.ts +187 -0
- package/build/AgentRun.js +1 -0
- package/build/AgentRunBus.d.ts +147 -0
- package/build/AgentRunBus.js +362 -0
- package/build/Calendar.d.ts +450 -0
- package/build/Calendar.js +37 -0
- package/build/ChatMessage.d.ts +53 -0
- package/build/ChatMessage.js +11 -0
- package/build/ChatMessageBus.d.ts +110 -0
- package/build/ChatMessageBus.js +257 -0
- package/build/Config.d.ts +83 -0
- package/build/Config.js +1 -0
- package/build/ContainerTool.d.ts +34 -0
- package/build/ContainerTool.js +1 -0
- package/build/CronExpression.d.ts +53 -0
- package/build/CronExpression.js +77 -0
- package/build/Event.d.ts +280 -0
- package/build/Event.js +14 -0
- package/build/EventBus.d.ts +198 -0
- package/build/EventBus.js +482 -0
- package/build/HandlerCatalog.d.ts +75 -0
- package/build/HandlerCatalog.js +165 -0
- package/build/InferenceEvent.d.ts +30 -0
- package/build/InferenceEvent.js +1 -0
- package/build/InferenceEventBus.d.ts +39 -0
- package/build/InferenceEventBus.js +80 -0
- package/build/Mail.d.ts +250 -0
- package/build/Mail.js +73 -0
- package/build/MailStyleTemplate.d.ts +71 -0
- package/build/MailStyleTemplate.js +47 -0
- package/build/ModelMetaData.d.ts +63 -0
- package/build/ModelMetaData.js +12 -0
- package/build/PathGlob.d.ts +20 -0
- package/build/PathGlob.js +33 -0
- package/build/Plugin.d.ts +709 -0
- package/build/Plugin.js +29 -0
- package/build/PostgresConnection.d.ts +75 -0
- package/build/PostgresConnection.js +162 -0
- package/build/ScheduledSubagent.d.ts +49 -0
- package/build/ScheduledSubagent.js +1 -0
- package/build/ScheduledSubagentBus.d.ts +94 -0
- package/build/ScheduledSubagentBus.js +187 -0
- package/build/Schema.d.ts +84 -0
- package/build/Schema.js +570 -0
- package/build/StepResult.d.ts +103 -0
- package/build/StepResult.js +1 -0
- package/build/StepResultBus.d.ts +64 -0
- package/build/StepResultBus.js +169 -0
- package/build/Timezone.d.ts +58 -0
- package/build/Timezone.js +84 -0
- package/build/ToolCall.d.ts +25 -0
- package/build/ToolCall.js +1 -0
- package/build/ToolCallBus.d.ts +65 -0
- package/build/ToolCallBus.js +110 -0
- package/build/ToolLevel.d.ts +20 -0
- package/build/ToolLevel.js +2 -0
- package/build/ToolRunner.d.ts +118 -0
- package/build/ToolRunner.js +192 -0
- package/build/ToolsExpressionUtils.d.ts +80 -0
- package/build/ToolsExpressionUtils.js +102 -0
- package/build/WorkspaceFile.d.ts +104 -0
- package/build/WorkspaceFile.js +7 -0
- package/build/estimateTokens.d.ts +16 -0
- package/build/estimateTokens.js +18 -0
- package/build/index.d.ts +37 -0
- package/build/index.js +26 -0
- package/build/logging/Logger.d.ts +66 -0
- package/build/logging/Logger.js +90 -0
- package/build/markdownHtml.d.ts +14 -0
- package/build/markdownHtml.js +21 -0
- package/build/markdownTerminal.d.ts +14 -0
- package/build/markdownTerminal.js +376 -0
- package/build/testing/MockAgentRunBus.d.ts +52 -0
- package/build/testing/MockAgentRunBus.js +175 -0
- package/build/testing/MockBusStore.d.ts +22 -0
- package/build/testing/MockBusStore.js +22 -0
- package/build/testing/MockEventBus.d.ts +20 -0
- package/build/testing/MockEventBus.js +57 -0
- package/build/testing/MockLogger.d.ts +52 -0
- package/build/testing/MockLogger.js +65 -0
- package/build/testing/index.d.ts +4 -0
- package/build/testing/index.js +4 -0
- package/package.json +63 -0
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SQL that defines the bus-state schema. Idempotent: every statement is
|
|
3
|
+
* `IF NOT EXISTS` / `CREATE OR REPLACE` / `DROP IF EXISTS`, so it's safe
|
|
4
|
+
* to run on every daemon start without a migrations framework.
|
|
5
|
+
*
|
|
6
|
+
* Two tables:
|
|
7
|
+
*
|
|
8
|
+
* - `events` is the immutable record of "the world said this happened".
|
|
9
|
+
* One row per external trigger, idempotency-keyed. Events do not
|
|
10
|
+
* participate in any worker state machine themselves; they are
|
|
11
|
+
* referenced by `agentruns` rows that do the actual work.
|
|
12
|
+
* - `agentruns` is the assistant's response tree. Each row is one agent
|
|
13
|
+
* invocation. The container's input-event watcher inserts the root
|
|
14
|
+
* agentrun for each new event; child agentruns are spawned by the
|
|
15
|
+
* `schedule_subagent` (fire-and-forget when called without `when`) and
|
|
16
|
+
* `start_subagent` (suspending) tools inside a running handler.
|
|
17
|
+
*
|
|
18
|
+
* Four tables, five NOTIFY channels:
|
|
19
|
+
*
|
|
20
|
+
* - `events_new` — fires on INSERT into `events`. Wakes the container's
|
|
21
|
+
* input-event watcher.
|
|
22
|
+
* - `events_state` — fires on state UPDATE on `events`. Lets host-side
|
|
23
|
+
* plugins wait for a specific event to settle.
|
|
24
|
+
* - `agentruns_changed` — fires on INSERT and on state UPDATE on
|
|
25
|
+
* `agentruns`. Wakes the agentrun watcher. Payload format is
|
|
26
|
+
* `<event_id>:<id>` so subscribers can route on event_id without a
|
|
27
|
+
* JOIN.
|
|
28
|
+
* - `stepresults_new` — fires on INSERT into `stepresults`. Lets host-side
|
|
29
|
+
* subscribers (e.g. `HostContext.events.emit`'s `onStep` callback) tail
|
|
30
|
+
* per-step audit rows as the agent loop produces them. Payload format
|
|
31
|
+
* is `<event_id>:<agent_run_id>:<id>` so subscribers can route on
|
|
32
|
+
* event_id without a JOIN.
|
|
33
|
+
* - `chatmessages_new` — fires on INSERT into `chatmessages`. Lets
|
|
34
|
+
* host-side channel plugins (cli-chat, telegram, …) stream assistant
|
|
35
|
+
* replies. Payload format is `<channel_id>:<role>:<id>`; channel is
|
|
36
|
+
* JOINed from `events.preferred_chat_channel_id` so subscribers can
|
|
37
|
+
* filter on the prefix without a query roundtrip.
|
|
38
|
+
*/
|
|
39
|
+
export declare const EVENTS_NEW_CHANNEL = "events_new";
|
|
40
|
+
export declare const EVENTS_STATE_CHANNEL = "events_state";
|
|
41
|
+
export declare const AGENTRUNS_CHANNEL = "agentruns_changed";
|
|
42
|
+
export declare const STEPRESULTS_NEW_CHANNEL = "stepresults_new";
|
|
43
|
+
export declare const CHATMESSAGES_NEW_CHANNEL = "chatmessages_new";
|
|
44
|
+
/**
|
|
45
|
+
* NOTIFY channel for `scheduled_subagents` mutations. Payload format is
|
|
46
|
+
* `<key>:<op>` where `op` is `u` (insert / update) or `d` (delete). The
|
|
47
|
+
* host-side `ScheduledSubagentScheduler` listens here to install or
|
|
48
|
+
* cancel Croner jobs as the agent schedules / unschedules one-off
|
|
49
|
+
* subagents.
|
|
50
|
+
*/
|
|
51
|
+
export declare const SCHEDULED_SUBAGENTS_CHANNEL = "scheduled_subagents_changed";
|
|
52
|
+
/**
|
|
53
|
+
* Topic regex used by the events check constraint and by the container
|
|
54
|
+
* runtime when resolving handler files. One word, optionally followed
|
|
55
|
+
* by any number of `:`-prefixed sub-topic words. Examples:
|
|
56
|
+
* `mail`, `chat:cli`, `chat:telegram:group:reaction`.
|
|
57
|
+
*
|
|
58
|
+
* The container resolves a handler for topic `a:b:c` by walking the
|
|
59
|
+
* chain `a/b/c/<basename>.md → a/b/<basename>.md → a/<basename>.md`
|
|
60
|
+
* deepest-first and merging every existing layer (see HandlerFile.load).
|
|
61
|
+
*/
|
|
62
|
+
export declare const TOPIC_PATTERN = "^\\w+(:\\w+)*$";
|
|
63
|
+
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-- Optional override for the root agentrun's handler. When NULL the\n-- input-event watcher falls back to 'index' \u2014 same behaviour as\n-- before this column existed. Set by the emitter on NewEvent.\nALTER TABLE events ADD COLUMN IF NOT EXISTS start_handler text;\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 handler 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-- 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 system prompt (SOUL.md + CONTEXT.md + handler body +\n-- tool list) 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 handler 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\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";
|
|
64
|
+
/**
|
|
65
|
+
* SQL fragment that flips the parent event's terminal state when the
|
|
66
|
+
* **root** agentrun settles. Run inside the same transaction as the
|
|
67
|
+
* agentrun's terminal UPDATE.
|
|
68
|
+
*
|
|
69
|
+
* The event's outcome mirrors the root agentrun's outcome. Non-root
|
|
70
|
+
* agentruns — `start_subagent` children that surface their result back
|
|
71
|
+
* to the parent, and `schedule_subagent` immediate-mode children that
|
|
72
|
+
* the parent fired and forgot — are out-of-band side effects. They
|
|
73
|
+
* never flip the event on their own; the root decides.
|
|
74
|
+
*
|
|
75
|
+
* Settling a non-root agentrun is therefore a no-op for this update
|
|
76
|
+
* (the EXISTS guard fails). Settling the root writes the event's
|
|
77
|
+
* terminal state to the root's terminal state directly.
|
|
78
|
+
*
|
|
79
|
+
* Parameters (in order):
|
|
80
|
+
* $1 = event_id (bigint, as string)
|
|
81
|
+
* $2 = id of the just-settled agentrun (bigint, as string)
|
|
82
|
+
* $3 = state of the just-settled agentrun ('done' | 'failed')
|
|
83
|
+
*/
|
|
84
|
+
export declare const EVENT_TERMINAL_UPDATE_SQL = "\nUPDATE events\nSET state = $3, updated_at = now()\nWHERE id = $1\n AND state = 'running'\n AND EXISTS (\n SELECT 1 FROM agentruns\n WHERE id = $2\n AND event_id = $1\n AND parent_agentrun_id IS NULL\n )\n";
|