@lobu/runtime-server 24.11.0 → 24.11.1
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/dist/catalogs/skills.json +1 -1
- package/dist/component.json +1 -1
- package/dist/db/migrations/20261115120000_events_unbound_tool_audit_without_bridge.sql +40 -0
- package/dist/db/migrations/20261115120001_events_unbound_tool_audit_validate.sql +19 -0
- package/dist/db/migrations/20261115120002_drop_events_linked_org_ids.sql +119 -0
- package/dist/server-main.bundle.mjs +50 -10
- package/npm-shrinkwrap.json +5 -5
- package/package.json +1 -1
- package/vendor/connector-sdk/package.json +1 -1
- package/vendor/core/package.json +1 -1
- package/vendor/views/package.json +1 -1
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
"version": "1.0.0",
|
|
9
9
|
"description": "Set up new Lobu agents end to end and operate existing Lobu projects and memory: interview, scaffold, validate, authenticate, connect feeds, execute operations, and test Automations.",
|
|
10
10
|
"detail": {
|
|
11
|
-
"instructions": "# Lobu\n\nUse this skill when setting up a brand-new Lobu agent from scratch (follow \"Onboarding a New Project\" below) or when running, validating, evaluating, or connecting an existing Lobu project, or operating Lobu memory from a coding agent.\n\nThe `AGENTS.md` generated into a new project is the source of truth for the config API (the `define*` helpers, connectors, auth, Automations, memory) — this skill does not duplicate it. For an existing project, jump to \"Core Model\" + the relevant reference section below.\n\n## Onboarding a New Project\n\nUse this playbook when a new user asks you to build them a Lobu agent from scratch. Set it up end to end: ground yourself in what the user already has, interview, discover, scaffold, prove the complete local path, then offer the deployment choice. Do not call the setup complete until every path the user selected has actually passed end to end. If an external provider, authorization, deployment, or rate limit blocks the proof, name the exact blocker and leave the setup as blocked rather than claiming success.\n\n### 1. Ground yourself in what the user already has\n\nBefore interviewing, look at what already exists so your questions and suggestions are personal rather than a blank slate. This is discovery, not a design decision — do not let it skip the interview.\n\n- Local: run `lobu context list` to see existing contexts (`--json` adds `loggedIn`, which reports stored credentials, not session validity); check the current directory and home for existing Lobu projects (`lobu.config.ts`), configured MCP servers, and CLI auth state. Note what the user already set up.\n- Cloud: if the user has an active session (do not create one just to look), call `client.organizations.list()`, `client.agents.list()` for each org, `client.catalog.listInstalled({ kinds: [\"connectors\"] })`, and `search_memory` for prior knowledge. This reveals existing agents, connectors, and memory you can build on.\n- Tell the user what you are looking at so they can correct you, and let what you find shape the options you offer. Never treat this discovery as an identity signal: orgs, emails, or domains never prove a company or product, and never mention a competitor or third party unless it actually appears in what you found.\n\nDo NOT ask for a login email during the interview. Email is only needed when a managed connector actually requires a session (step 3) or when the user chooses cloud deployment (step 6); ask for it at that point. Treat identity only as identity; never infer a company from an email address or domain.\n\n### 2. Interview with concrete, personalized options\n\nInterview the user one question at a time; wait for each answer, do not guess, and do not batch the questions. Anchor each question in what you found in step 1. Instead of asking \"what agent do you want?\" as a blank slate, summarize what you see and offer two or three concrete alternatives to choose from:\n\n- \"You already have org X with connectors A and B installed and N existing agents. Do you want to (a) add a new agent on top of those, (b) extend one of the existing agents, or (c) start something standalone?\"\n- \"For what it should do, the common shapes are (a) a triage agent that reads incoming chat and files a ticket, (b) a scheduled report that summarizes new activity each morning, (c) a research agent that answers questions from your connected tools. Which fits, or what would you change?\"\n\nOffer a default so the user can answer \"the first one\" — decisive users and undecided users both move faster with a concrete menu.\n\n- What company or product is this for?\n- What does it do, and who does it serve?\n- What is its public domain? (optional for a personal project)\n- Do I have permission to research the public website and other public sources?\n- What is the agent for?\n- What should we call it?\n- Who uses it: just me, my team, or each of my customers?\n- How should it behave, and what may it do unattended versus only with approval?\n- What should it remember? Model this as one to three entity types.\n- Where does its data come from? Pick one connector or custom source to start.\n- Where should people talk to it? Offer Web UI, API or SDK, MCP, Slack, Teams, WhatsApp, Discord, Google Chat, and Telegram without forcing a chat platform. If Slack is chosen, ask whether to join Lobu's hosted workspace for a quick start, install Lobu into an existing workspace, or use a custom Slack app; then ask whether to test the DM with Lobu, a named channel, or both, and whether people knowledge means conversation participants, bound-channel members, or the full workspace directory.\n- Should anything run on a schedule?\n- Which supported LLM provider credential does the user have?\n\nIf the user gave permission to research and has a public domain, research the company before proposing the design. Summarize its product, customers, workflows, and useful signals, and cite the public sources you used. Then propose one to three entity types, their relationships, the first data source, one or two useful Automations, and suitable interaction channels. Play back a short numbered plan and wait for confirmation before scaffolding anything.\n\n### 3. Discover the surface before choosing how to scaffold\n\nCheck Node is 26.x, then run `lobu context list` and identify the named Lobu Cloud context; do not assume the active context still points to cloud after a local run. If a managed or cloud connector was chosen and there is no session, ask for the login email at that point, explain that Lobu will email an approval link, and run `lobu login --email <confirmed-address> --context <cloud-name>`. The person approving must sign in with that same email; knowing an address never grants access. After a successful login, an empty organization membership list is a tenancy/discovery result, not an authentication failure: call `client.organizations.list()` and explain the result. Never revoke or repeat login with `--force` unless the user separately approves that re-authentication.\n\nUse ClientSDK through Lobu MCP with the explicit cloud context. From the CLI, account discovery works before selecting an active org with `lobu memory run query_sdk '{\"title\":\"Find managed connection providers\",\"script\":\"export default async (_ctx, client) => client.organizations.list()\"}'`; `lobu call` over REST requires an active org. Call `client.organizations.list()` to find public organizations offering managed connections. Call `client.catalog.listInstalled({ kinds: [\"connectors\"] })`; if the connector is not installed, call `client.catalog.listCatalog({ kinds: [\"connectors\"] })`. Inspect the selected entry's `detail.auth_schema`, `detail.options_schema`, `detail.feeds_schema`, and `detail.automation_events` instead of guessing field names. On account-scoped `/mcp`, select an authorized home workspace first with `const home = await client.org(homeSlug)` and call `home.connections.connectManaged`; put the public provider org in `managed_by_org`, rather than selecting that provider org with `client.org`. This call runs against cloud, not the embedded runtime. If a matching live managed offer exists, explain it and call `client.connections.connectManaged` only after consent. Complete the returned user authorization, then run `lobu context use <cloud-name>` immediately before executing its `local_bootstrap_command` from the parent directory where the new project should be created; use `--here` only after entering an empty directory, and do not create a blank Lobu scaffold first. Ask for bring-your-own OAuth credentials only if no managed offer exists or the user prefers their own app.\n\n**If no connector in the catalog matches the data source, do not report \"no integration exists\"** — author a custom connector: write `connectors/<name>.connector.ts` in the project, register it with `connectorFromFile(\"./connectors/<name>.connector.ts\")`, and model it on the [npm downloads example](https://github.com/lobu-ai/lobu/blob/main/examples/lobu-crm/npm-downloads.connector.ts). See [Connector authoring](https://github.com/lobu-ai/lobu/blob/main/docs/connector-authoring.md) for the full contract; the end-to-end entity/event/Automation model is in [Lobu concepts](https://github.com/lobu-ai/lobu/blob/main/docs/CONCEPTS.md).\n\n### 4. Scaffold and build from the confirmed plan\n\nIf managed auth supplied a `local_bootstrap_command`, use the project it generated. Otherwise run `npx @lobu/cli@latest init` with the confirmed name and provider. Postgres is built in, so `lobu run` starts an embedded database; ask for `DATABASE_URL` only if the user chooses external Postgres. Read the generated `AGENTS.md` completely before editing `lobu.config.ts`. Use the canonical reference at `https://github.com/lobu-ai/lobu/blob/main/examples/lobu-crm/lobu.config.ts` when needed; do not assume that example exists in the new project's filesystem. Briefly explain how the chosen feed may use checkpoints to collect incrementally, emits events, builds shared entity memory, and gives both chat and Automations the same governed context.\n\n`feeds_schema.<feed>.eventKinds` are the default Automation trigger catalog for feed connectors: every declared kind is a subscribable event type (`event_type` = the kind slug) for any feed that emits the kind. A feed's first successful non-dry sync establishes its baseline without activation; later inserts of a matching kind activate subscribers. A kind with `updatedEvent: true` also offers `<kind>.updated` for supersedes whose `occurred_at` strictly advances past the previous head. The original kind stays insert-only; unchanged rows, volatile-only updates and same-time reformats stay quiet. Subscribe to both types for new items and later activity. Feed-scoped filtering is not yet available (events dedupe by connection + origin id, so a `feed_key` match would miss origins first seen by another feed). `automation_events` (now derived from eventKinds when a connector declares none) is the trigger picker's list. If no declared kind matches the use case, use a scheduled Automation with a bounded named SQL source and read event text from `payload_text`. Validate the query against the running local schema before relying on it. If `feeds_schema` is empty, do not invent or trigger a feed; chat integrations such as Slack can deliver incoming messages directly. For Slack or Telegram, prefer `defineConnection` with `credentialMode: \"hosted\"` so no bot token is required; `lobu run` prints the exact hosted-workspace join URL, own-workspace install URL when available, and short-lived link command. This hosted chat path requires a cloud session and the agent applied to that cloud workspace; the link targets the cloud agent. It does not create a local Slack data connection or prove local Slack search. Use those returned values instead of constructing URLs. A printed `/lobu link <code>` is one-time: redeem it in the first selected DM or channel. In an installed workspace whose installer is linked to Lobu, bind each additional surface with `/lobu link <agent-id>`; otherwise generate a fresh code for that surface. Mention Lobu in a channel test and verify the App Home separately. Lobu email login and Slack installation are separate: the email link authorizes Lobu CLI access, while an existing-workspace install requires the user or workspace admin to approve Slack's OAuth screen. Never describe Slack consent as an email approval. Use `credentialMode: \"byo\"` only if the user chooses their own app. Tell the user once which remaining secrets are required and add only `secret(\"ENV_NAME\")` placeholders to config. Never open or request permission to read `.env`; inspect `.env.example` when present and declared secret placeholder names only. Never read, print, invent, or paste a real secret into source or chat.\n\nIf the user wants the agent to know people in Slack, ask whether that means conversation participants, members of bound channels, or the full workspace directory. Installing the app proves none of those by itself. Verify the selected scope by inspecting the people or member entities Lobu actually materialized and by asking the agent a roster question. If human-readable names or non-participants are unavailable, identify that exact product gap; never claim the complete workspace directory was synced.\n\n### 5. Prove the complete local path\n\nChange into the generated project directory and verify `pwd` contains the intended `lobu.config.ts`; never run project commands from its parent. Run `npx @lobu/cli@latest validate`, boot with `npx @lobu/cli@latest run`, and verify health and the local Web UI. With the embedded database default, `lobu run` creates and selects the local context and auto-applies the project; with an external `DATABASE_URL`, it does neither, so authenticate and apply to that runtime explicitly. Send a harmless direct chat message without tools.\n\nBefore consent to access provider data, inspect only catalog, connection, auth-profile, and feed metadata. For browser access, inspect the paired device and connection metadata without invoking browser actions. Durable managed OAuth and env-profile credentials stay at the gateway. Do not run a feed or connector dry-run before consent, because a dry-run may still read provider data. Ask explicitly before accessing real provider data. Only after approval, dry-run the connector or feed server-side and trigger the selected feed manually if that connector actually declares one. A feed dry-run records its run but persists no collected events, entities, attachments, checkpoint changes, or feed sync state. Run each Automation once, poll `client.operations.getRun` with its returned `run_id`, and show each completed run plus any declared result event or entity. For a run-result-only or reaction-only Automation, use the completed run and the Automation `view_url` returned by Lobu. For Slack, treat DM, channel mention, App Home, and requested member discovery as four separate checks. Keep actions in approval mode unless the user explicitly approves execution. If any step fails, fix it and rerun that step; do not silently substitute a different path.\n\n### 6. Offer the deployment choice\n\nAfter the local proof, ask the user whether to keep running locally or deploy to Lobu Cloud. Explain that the embedded local runtime and Lobu Cloud are separate targets, and that keeping it local needs no further setup. Only if the user chooses cloud deployment, ask for the login email to identify the deployer, explain that Lobu will email an approval link, and run `lobu login --email <confirmed-address> --context <cloud-name>`; the person approving must sign in with that same email. Because `lobu apply` has no context flag, use `lobu context list` and then `lobu context use <cloud-name>` to select an explicit cloud context before deployment. Run `lobu apply --dry-run` first, show the target organization and exact plan, and wait for confirmation before applying. After apply, use only authoritative `view_url` values and link commands returned by Lobu; never construct URLs. Present the working access choices: Web UI, direct agent chat, API or SDK, MCP, and any channels the user selected.\n\n## Core Model\n\n- **Lobu** is the agent framework, runtime, deployment layer, and memory surface.\n- Keep framework configuration in `lobu.config.ts` (TypeScript, `defineConfig` from `@lobu/cli/config`).\n- Keep agent identity and instructions in `IDENTITY.md`, `SOUL.md`, and `USER.md`.\n- Keep reusable capability bundles in `skills/<name>/SKILL.md` or `agents/<agent>/skills/<name>/SKILL.md`.\n- Use `lobu login` for CLI authentication. Do not use a separate memory login command.\n- Use `lobu connect` for MCP client and skill setup.\n- Use `lobu memory ...` for memory operations, seeding, and direct tool calls.\n\nReference the canonical docs before guessing how a feature works:\n[Lobu concepts](https://github.com/lobu-ai/lobu/blob/main/docs/CONCEPTS.md)\n(entities vs events, identity, end-to-end lifecycle),\n[Automations](https://github.com/lobu-ai/lobu/blob/main/docs/AUTOMATIONS.md)\n(trigger/source/output contract), and\n[Connector authoring](https://github.com/lobu-ai/lobu/blob/main/docs/connector-authoring.md)\n(custom connectors).\n\n## Project Checklist\n\n1. Read `lobu.config.ts` first.\n2. Read the active agent files under `agents/<id>/`.\n3. Check local skills under `skills/` and `agents/<id>/skills/`.\n4. Use `lobu validate` after config changes.\n5. Discover the live SDK and connector surface with `search_sdk`; never guess a method, connector key, feed key, connection id, or operation key.\n6. When prompt or Automation changes, run evals via promptfoo (see `examples/personal-finance/evals/promptfooconfig.yaml`). The in-house `lobu eval` command has been removed.\n\n## Common Commands\n\n```bash\nnpx @lobu/cli@latest init my-agent\nnpx @lobu/cli@latest run\nnpx @lobu/cli@latest validate\nnpx @lobu/cli@latest login\n```\n\n## Authentication\n\n- Interactive (human at a terminal): `lobu login` runs the device-code flow with a browser approval.\n- CI / your own automation: `LOBU_API_TOKEN`, or `lobu login --token <pat>`.\n- Local `lobu run`: the CLI mints credentials automatically over loopback — no prompt.\n- Headless, on a *user's* behalf: `lobu login --email <address>`. The server emails the user a one-click approval link and the CLI polls until they approve, then stores the scoped credential — no TTY, no pre-minted token. This is the auth.md \"user_claimed\" flow.\n\nAn external agent not using this CLI can drive the same flow over HTTP: read `<origin>/auth.md` (linked from the `agent_auth` block in `<origin>/.well-known/oauth-authorization-server`) for the endpoints. Today only the email user_claimed flow exists (no zero-touch ID-JAG). Never fabricate a token.\n\n## Organization Deletion\n\nTreat organization deletion as permanent and restricted to organization owners. The supported path is the **Organization settings** page, opened from that workspace's settings button in the organization switcher. ClientSDK and Lobu CLI intentionally expose no organization-delete method. When asked to delete organizations, identify each exact target and its data impact read-only, surface one production organization at a time for explicit confirmation, then direct an owner to that page or use their logged-in browser only when explicitly authorized. Never invent a hosted URL, call the raw Better Auth route, bypass a failed authorization check, delete organization rows directly, or batch confirmations.\n\nCloud CLI OAuth/PAT credentials are not a Better Auth browser session. A `401` or `403` is a stop signal: report the authorization boundary and leave the organization intact.\n\n<!-- lobu-memory-guidance:start -->\n## Memory Defaults\n\nYour long-term memory is powered by Lobu. Do NOT use local files (memory/, MEMORY.md) for memory.\n- Lobu automatically recalls relevant memories when you receive a message.\n- To save something, call save_memory with the content and an appropriate semantic_type.\n- To search, call search_memory. Results include view_url links to the web interface.\n- NEVER construct Lobu URLs yourself. When the user asks for a link, call search_memory to get the correct view_url.\n- When the user says \"remember this\", save it to Lobu immediately.\n- When a message changes a fact you already stored (an updated preference, status, count, location, or plan), first search_memory for the prior memory to get its id, then save_memory the new value with supersedes_event_id set to that id. This replaces the stale value so future recalls return the current one; the old value stays in history but is hidden from normal search.\n<!-- lobu-memory-guidance:end -->\n\n## Lobu Memory\n\nConfigure project-scoped memory in `lobu.config.ts` by setting the org on `defineConfig` and declaring the schema with the `define*` helpers:\n\n```ts\nimport { defineConfig, defineEntityType } from \"@lobu/cli/config\";\n\nconst ticket = defineEntityType({\n key: \"ticket\",\n name: \"Ticket\",\n properties: {\n subject: {\n type: \"string\",\n title: \"Subject\",\n \"x-table-label\": \"Subject\",\n \"x-table-column\": true,\n },\n },\n});\n\nexport default defineConfig({\n org: \"my-org\",\n orgName: \"My workspace\",\n agents: [/* ... */],\n entities: [ticket],\n});\n```\n\nThe entity schema also renders the record page form. Give every array `items` and every object `properties` (bare ones render as raw JSON), put the label in `title` and help text in `description`, mark derived fields `readOnly: true`, and declare every field an Automation writes.\n\nFor a \"when did this field last change\" timestamp, declare root `metadata_schema[\"x-lobu-stamps\"]: { \"stage_at\": \"stage\" }` instead of writing it from an Automation. The stamp field must be a declared `{ type: \"string\", format: \"date-time\" }` property (not listed in `required`) and the tracked field a declared property. Every writer (agent, SDK, Automation, connector projection, view action, approval) then gets it for free: the server sets `stage_at` when a record is created with `stage` set or when `stage` changes value, and discards any value a caller sends for `stage_at`. `readOnly` alone is presentation only; it is not enforced.\n\nSeed data records still live as YAML under `./data`. Then seed or operate the memory workspace with:\n\n```bash\nlobu login\nlobu memory org set <org-slug>\nlobu memory health --org <org-slug>\nlobu memory seed --org <org-slug>\nlobu memory run search_memory '{\"query\":\"Acme\"}' --org <org-slug>\n```\n\nUse `search_memory` first when the user asks about a specific entity or workspace memory. Use `save_memory` to persist durable memory. To update existing knowledge, search first, then save with `supersedes_event_id` so the old row is tombstoned rather than deleted.\n\n## MCP Client Setup\n\nUse the actual MCP URL for the user's runtime. Never hardcode a hosted URL unless the user explicitly asks for that instance.\n\nCommon setup commands:\n\n```bash\n# Claude Code\nlobu connect claude-code --url <mcp-url>\n\n# Codex\nlobu connect codex --url <mcp-url>\n\n# Antigravity\nlobu connect antigravity --url <mcp-url>\n\n# OpenCode\nlobu connect opencode --url <mcp-url>\n```\n\nRun `lobu connect --url <mcp-url>` without a client id to choose interactively. For ChatGPT, Claude Desktop, Cursor, and other browser-managed clients, the same command applies the safe local configuration it can and prints the exact remaining client handoff. Complete OAuth in the client, not through a separate Lobu CLI login.\n\n## Browser-Authenticated Connectors\n\nFor connectors that need a signed-in browser, pair the Owletto Chrome extension\nand sign in on the source site in that browser. Browser operations run through\nthat paired device; external remote-debugging endpoints and CLI browser-auth\ncapture are no longer supported.\n\nNothing answers a JS dialog (alert, confirm, prompt, beforeunload) on the\nagent's behalf. A browser action it blocks fails, and the failed result's\n`output` carries `tab_id` and `dialog` (`dialog_id`, `type`, `message`). In\n`run_sdk`, catch the `operations.execute` error and read `error.details.output`\nrather than parsing the error text (an uncaught failure returns the same value\nas the `run_sdk` result's `error.details`, and a background run's\n`operations.getRun` returns the same `output`), then answer with the\nconnection's `handle_dialog` operation. An unanswered dialog is handed to the user after two minutes.\n\nTo test a configured feed without writing ingested data, discover the current\nfeed methods with `search_sdk`, then use `client.feeds.trigger({ feed_id, dry_run: true })`\nthrough `run_sdk` or `lobu call run_sdk` (with a `title` arg). Inspect `client.feeds.get({ feed_id })`\nfor the completed run's preview. The dry run uses normal device routing and\nauthorization checks and may access the upstream provider, so obtain consent first.\n\n## Agent-Facing Tool Surface\n\nThe normal MCP surface is intentionally small. Flat administrative tools are not advertised to agents; compose through these tools instead:\n\n- `search_memory` and `save_memory` for direct knowledge recall and persistence.\n- `search_sdk` to discover current ClientSDK methods, signatures, connector feed keys, operations, access requirements, and examples. Pass `mode: \"read\"` when you only need methods safe for `query_sdk`.\n- `query_sdk` for read-only TypeScript and `query_sql` for governed, paginated SQL reads.\n- `run_sdk` for mutations and external operations. Use `lobu call run_sdk --arg title='…' --arg script='…'` from the CLI for the same ClientSDK scripting workflow; `run_sdk`, `query_sdk`, and `query_sql` calls need a short `title` naming them in the activity feed.\n\nSearch before create to avoid duplicates. Prefer a read or dry run before mutations, never fabricate returned URLs or identifiers, and never delete from `events`; supersede or tombstone instead.\n\n## Custom Views\n\nBefore authoring UI, inspect available native entity/event pages, existing views (`client.views.list()` and `client.views.get({ key })`), and the project's shared components and overrides. Honor explicit user designs and reuse UI from the top down:\n\n1. Use the largest existing surface or component that meets the task. Configure its segment, filters, search, saved preset and layout before replacing its UI.\n2. If that surface cannot meet a concrete requirement, compose its exported parts, such as an individual table, board, graph or shared collection controls when available. Preserve shared selection and action handling instead of rebuilding that logic.\n3. If those parts still do not fit, use smaller shared primitives and write custom UI only for the remaining gap. Explain the unmet requirement that forced each step down.\n\nCheck the current exports and target host before choosing an import; native renderer registrations do not imply React exports. Surface a missing export as a platform gap rather than inventing an API or silently copying the native implementation. `@lobu/views/components` currently supplies theme-aware defaults such as `Card`, `DataTable`, filters, charts, links and query-state components. `LoadingState` draws skeleton lines in the host's style; `Skeleton` is a pulsing block to size like the content it stands for (a figure, a row, a chart), so a slow read keeps the page's shape instead of showing text. When exploration needs specialized linked charts, drilldowns, scenario controls or Canvas/SVG, compose a React view from the suitable existing components.\n\nNative JSON templates use the target renderer's registered component names and overrides; inspect what that host actually supplies. React views compose imported components in their own bundle, independently of that native renderer map.\n\nViews are custom React panels attached to entity types, records, events, or the workspace Data hub. They render in the web app and MCP hosts (Claude and other MCP Apps hosts); chat channels get links to views, not the views themselves. Author them in `views/<type>/<key>.tsx` and ship with `lobu apply` (list them via `viewFromFile` in `defineConfig`), or set sources over MCP with `client.views.set` (owner/admin only).\n\nModule shape (the server resolves React, React DOM, `@lobu/views` and `@lobu/views/components`; other dependencies need the CLI path with `node_modules` present):\n\n```tsx\nimport { defineView, tool, useAction, useParams, useQuery } from \"@lobu/views\";\nimport {\n Card,\n DataTable,\n EmptyState,\n ErrorState,\n FilterBar,\n LoadingState,\n SearchField,\n TruncatedNotice,\n} from \"@lobu/views/components\";\n\nexport const view = defineView({\n key: \"pipeline\",\n attach: [{ collection: \"deal\" }],\n params: { stage: { type: \"string\", default: \"open\" } },\n actions: { markWon: { emits: \"deal.won\" } },\n});\n\nexport default function Pipeline() {\n const [params, setParams] = useParams();\n const deals = useQuery(tool(\"manage_entity\", { action: \"list\", entity_type: \"deal\", filters: [{ field: \"stage\", op: \"eq\", value: String(params.stage) }], limit: 100 }));\n const markWon = useAction(\"markWon\");\n const rows = deals.data?.entities ?? [];\n // Keep the filter mounted across query states: an early return on\n // loading/error would unmount the focused input on every keystroke\n // (each keystroke re-queries). Render states inline instead.\n return (\n <Card\n title=\"Pipeline\"\n actions={<button type=\"button\" onClick={() => markWon({})}>Mark won</button>}\n >\n <FilterBar><SearchField label=\"Stage\" value={String(params.stage)} onChange={(v) => setParams({ stage: v })} /></FilterBar>\n {deals.loading && <LoadingState text=\"Loading deals…\" />}\n {deals.error && <ErrorState message={deals.error} errorCode={deals.errorCode} />}\n {!deals.loading && !deals.error && rows.length === 0 && (\n <EmptyState title=\"No deals in this stage.\" />\n )}\n {!deals.loading && !deals.error && rows.length > 0 && (\n <DataTable columns={[{ key: \"name\", header: \"Name\" }]} rows={rows} keyOf={(r) => r.id ?? r.slug} />\n )}\n {deals.truncated && <TruncatedNotice shown={rows.length} />}\n </Card>\n );\n}\n```\n\n`defineView` is the view's only declaration: `key`, optional `name` (defaults to the key) and `description`, `attach`, `params`, `actions` and `resources` are read from it, never passed separately. `views.set` always requires `source_code` containing the entrypoint module, including when retaining multiple files. Write `defineView` out as a literal (no variables, spreads or `${}` templates): the server reads it without running the module.\n\nA view makes no network requests of its own; data comes through `useQuery`. The one exception is images: `resources: [\"https://tile.openstreetmap.org\"]` declares origins the view may load images (map tiles, logos) from. Each entry is a bare `https://` origin with a public hostname (no path, wildcard, localhost or IP), at most 8. The images-only limit is a save-time check: `views.set` renders the view's empty, error and loading states in an offline browser and refuses the save if anything other than an image from a declared origin is requested. It is not enforced at runtime. MCP hosts receive the origins as the MCP Apps `resourceDomains` CSP, which allows scripts, styles, fonts and media from them as well as images, and the Lobu web app applies no runtime CSP to views. Declare only image or tile CDN origins you trust. Hosts that render through the generic `ui://lobu/views` loader use its CSP, which declares no image origins, so declared images may not load there.\n\nFor a multi-file view, `files` maps relative paths to complete source strings and `entrypoint` names the view module. Include all three inputs below; `source_code` must exactly equal `files[entrypoint]`:\n\n```ts\nawait client.views.set({\n source_code: files[entrypoint],\n source_files: { entrypoint, files },\n dependencies: {}, // Local files and the host-provided runtime need no extra packages.\n});\n```\n\n`attach` lists the pages a view appears on, one per entry: `{ record: \"deal\" }` is a card on every deal's page above its activity (`{ record: \"deal\", id: 7 }` pins one record), `{ collection: \"deal\", when? }` a tab on the deal list page, `{ workspace: true }` a Data hub tab, `{ event: \"deal.won\", type? }` one event's page. One view can list several pages and branch on `useScope()` when it answers the same question at each scale. A record card renders with `useHost().displayMode === \"inline\"` inside `container.maxHeight` (the host clips past it): render a summary there with a \"See all\" that calls `requestDisplayMode(\"fullscreen\")`, and the full view when `displayMode` is `\"fullscreen\"` (the peek, a full page, a tab).\n\nWorkspace attachment does not render individual events. For an event presentation, attach to its specific `semantic_type` (event kind), optionally restricted to a linked entity type with `type`; a metadata schema name does not select the view. Avoid binding a specialized renderer to a generic kind such as `summary`. Register a dedicated kind in the workspace's event-kind registry and have its producer emit it. On event pages and event peeks, read `useScope().event` by exact ID and select that ID from the returned lineage; never substitute the latest event or let a URL date param change the subject. A shared workspace/event module should branch on `scope.event`, keeping history selection on its workspace surface. Preserve a readable stored body for fallback and evidence.\n\nBefore reporting a view working, open each attached surface, including an event page and peek when declared. Exercise filtering, drilldown, keyboard navigation, and a narrow pane; check loading, missing/error, and truncated data states. Refresh and reopen an earlier event of the kind to verify the view stays on that event rather than jumping to the newest one. Views render in an iframe, so an empty parent-page DOM is not evidence the view is empty; inspect the frame through an authorized browser or accessibility surface. A successful compile proves only that the bundle was built.\n\nImport reusable UI from **`@lobu/views/components`**. Discover this kit with `search_sdk({ query: \"@lobu/views/components\" })` or a component name. Start with the largest suitable native surface; compose smaller parts only for needs it does not cover:\n\n| Need | Component and minimum input |\n| --- | --- |\n| Complete entity list | `EntityListPage title={title} table={tableProps}` |\n| SQL, computed TypeScript or local rows | `EntityListPage title={title}` with `DataTable columns={columns} rows={rows} keyOf={keyOf}` as children |\n| Complete record body | `EntityRecordPage entity={entity} owner={workspace} schema={schema}` |\n| Entity table or individual fields | `EntityTableView`, `RecordSpecSheet`, `SchemaValue`, `EntityAvatar` |\n| Workspace schema, proposed schema or schema diff | `SchemaGraph`, `SchemaGraph schema={spec}`, `SchemaGraph schema={spec} base=\"workspace\"`, or `SchemaGraph schema={after} base={before}` |\n| Saved resource identity and navigation | `AutomationReference`, `AgentReference`, `ConnectorReference` |\n| Automation instructions, sources, triggers, outputs and code | `AutomationDefinition value={definition}` |\n| Agent identity, models and settings | `AgentDefinition value={definition}` |\n| Connector actions, feeds, schemas and source | `ConnectorDefinition value={definition}` |\n| Current / Proposed comparison | Existing `Tabs` with the same definition component in each panel |\n| Optional technical details | `JsonDiff before={current} after={proposed}` inside collapsed `<details>` |\n\nThe host supplies native JS/CSS, React and live theme. Do not copy product markup or bundle a second React. Exported prop types describe the shared contracts. Use `Button`, `Badge`, `Card`, chart and state components for surrounding UI.\n\n**Page bodies are controlled.** Supply data and slots; they fetch nothing and authorize no writes. `EntityListPage` accepts `title`, optional `actions`/`controls`, and either `table: EntityTableViewProps` or `children`. Its `loading`, `error`, `onRetry` and `empty` affect only results, keeping controls mounted. Native table props include rows, schema, linked lookups, sorting and pagination; honor `metadata.has_more`. For SQL/TypeScript rows use `DataTable`, without inventing entity IDs or types. `EntityRecordPage` renders the native title/avatar and schema fields; `actions`, `details`, `summary`, and `children` supply editing, links, activity and tabs. Default `layout=\"record\"` adapts to width; `layout=\"content\"` retains the header while children own the layout. A `null` title/details/summary hides that slot. Preserve zero and false.\n\n**SchemaGraph is read-only.** It reuses the native schema canvas. Omit props for the mounted workspace schema, pass `schema` for a supplied snapshot, add `base=\"workspace\"` to compare a proposal with the live workspace, or pass another spec as `base`. A spec is `{ entityTypes: [{ slug, name?, description?, metadata_schema?, event_kinds? }], relationshipTypes: [{ slug, name?, metadata_schema?, rules: [{ source_entity_type_slug, target_entity_type_slug }] }] }`. Specs are full snapshots: an omitted type is removed in a diff. Added, removed and changed types/rules remain visible; inspect type details for metadata fields, event kinds and rule changes. Existing entity types open their native pages; unsaved types show details in place. Live reads use the visiting user’s session and permissions through the existing broker; supplied snapshots still render when workspace reads are unavailable. No edits or schema writes are performed. The leaf names match `entitySchema`: list responses use `entity_types` / `relationship_types`; attach `listRules` results to the matching relationship by ID. To apply a reviewed spec, use existing `createType` / `createRelType` (both require `name`) and `addRule({ slug, ...rule })` separately. The graph’s optional name falls back to slug for display only. Hosts without native components throw the standard unavailable-native error.\n\n**References resolve saved identity.** Pass `mode=\"live\"`, mounted `workspace`, optional `appearance=\"inline\" | \"row\"` (default row), and `automationId` (positive decimal string), `agentId`, or `connectorKey` plus optional numeric `connectionId`. Discover IDs first. These reuse product rows and visiting-user permission checks; they accept no authored name/status or mutation callbacks. Invalid selectors, another workspace, missing records and refused reads show unavailable. A connector definition does not imply a connected account. Reads refresh on mount, focus, reconnect and host invalidation, without interval polling.\n\n**Definitions render supplied objects.** All three have the same signature: `{ value: Record<string, unknown> }`. Pass the existing saved definition or complete proposed snapshot, not a patch. Automation fields include `name`, `description`, `prompt`, `sources`, `triggers`, `outputs`, `reaction_script`; Agent fields include `name`, `description`, `identity_md`, `settings`; Connector fields include `name`, `description`, `version`, `actions_schema`, `feeds_schema`, `source_code`. Remaining nested settings stay inspectable. Missing fields differ from empty values. Bodies fetch nothing, execute no supplied code, and add no save/approval controls. Label authored objects as Snapshot or Proposal preview; use a reference for live identity. Never supply credentials.\n\nShow changes as **Current / Proposed**, defaulting to Proposed, with the same native body on both sides. Keep JSON diff optional. Rendering does not save or apply anything and needs no new proposal endpoint. For an existing approval, render its held current/proposed snapshots; do not merge in newer live values. Writes remain on existing declared `useAction` paths or native authorized editor/review pages. An authored preview must not imply a held approval or authority to apply it.\n\n```tsx\nimport {\n Card, ConnectorDefinition, JsonDiff,\n Tabs, TabsList, TabsTrigger, TabsContent,\n} from \"@lobu/views/components\";\n\n// current and proposed are complete definition objects from authorized reads\n// and the requested edit. Use AgentDefinition or AutomationDefinition identically.\n<Card title=\"Connector proposal preview\" description=\"Nothing has been applied.\">\n <Tabs defaultValue=\"proposed\">\n <TabsList label=\"Definition version\">\n <TabsTrigger value=\"current\">Current</TabsTrigger>\n <TabsTrigger value=\"proposed\">Proposed</TabsTrigger>\n </TabsList>\n <TabsContent value=\"current\"><ConnectorDefinition value={current} /></TabsContent>\n <TabsContent value=\"proposed\"><ConnectorDefinition value={proposed} /></TabsContent>\n </Tabs>\n <details><summary>Technical diff</summary><JsonDiff before={current} after={proposed} /></details>\n</Card>\n```\n\nUse `useHost().openRecord({ entity_id, entity_type? }, { mode: \"peek\" })` for a record's native peek. String source keys require the type. The promise reports the actual `{ mode: \"peek\" | \"page\" }`; a host without native peek opens the server-returned record URL. Errors remain errors. `useHost().theme` follows live theme changes; native components inherit the host palette and typography automatically. Use semantic host style variables and avoid hardcoded light/dark colors.\n\nRules that are load-bearing, not style:\n\n- Use structured reads: `useQuery(tool(\"manage_entity\", { action: \"list\", entity_type: type, filters, limit: 100 }))`. The host admits entity `list/get/list_links` and entity-type schema `list/get` reads; tools marked read-only are also available. Use existing tool input/result contracts and preserve server authorization. Send structured arguments, never TypeScript inside a string. `sql` remains available; script-string queries are compatibility support for installed views. `query_sql` allows 500 rows max with a 5 second timeout — branch on the typed `errorCode` (e.g. `UPSTREAM_TIMEOUT`), never on message text, and render `truncated` honestly instead of passing partial data off as complete. Each `query_sql` cell is bounded too: strings keep their first 4,000 Unicode code points plus \"… [truncated]\"; JSON values over 16 KiB become `{ _truncated: true, bytes }` (attachments become null with `attachments_truncated`). `truncatedColumns` names the affected columns. Select smaller elements or fields, for example one array element per row with `jsonb_array_elements(...)`, and paginate as needed; each returned cell is still subject to these limits.\n- Never aggregate history in a view: no `GROUP BY`, `DISTINCT ON`, per-row regexp, or leading-wildcard `LIKE` over `events` or other growing tables. For \"latest state\" views, have an Automation maintain keyed event outputs (each run supersedes the previous event with the same key) and read the current head with `read_knowledge`.\n- `run_sdk` is not exposed to views. Writes go only through declared view actions (`useAction` → `invoke_view_action`). An action declares `emits` (append that event kind, which can activate workspace-triggered Automations), `updates: { entityType, fields }` (write those metadata fields on one record), or both, which commit in one transaction. An `updates` action takes `value: { entity_id, set: { field: value } }`; the view must attach to `entityType`, `set` may only name declared fields, and schema-stamped fields are refused. Pass `{ expected }` as the second argument with the values the view read: a stale read returns 409 `PRECONDITION_FAILED` and writes nothing. The write runs as the clicking user without claiming field ownership, so a human-owned field comes back as `pending_approval` instead of `applied`. Do not add an Automation that only copies an action's event onto the record; declare `updates` instead. Action `value` payloads are capped at 4000 JSON chars — save content first, then pass the id. A subject shown from a superseded event rejects with 409; refetch and ask the user to re-confirm rather than retrying blindly.\n\n ```tsx\n // actions: { markWon: { emits: \"deal.won\", updates: { entityType: \"deal\", fields: [\"stage\"] } } }\n const markWon = useAction(\"markWon\");\n const sent = await markWon({ entity_id: deal.id, set: { stage: \"won\" } }, { expected: { stage: deal.metadata.stage } });\n // sent.result.applied: { entity_id, fields } with server stamps; sent.result.pending_approval when held\n ```\n- Link with `Link` from `@lobu/views/components` (or `useHost().openLink`): `href=\"<type>/<slug>\"` opens that record in the workspace, supported links within the same workspace open in the peek pane, other app links navigate normally, and external URLs open a new tab. A plain `<a href>` goes nowhere inside the sandboxed frame.\n- For several offers, publish one event with a card for each held proposal. Obtain the real pending approval through the existing agent/Automation write method under its normal policy, then read its returned event ID to obtain the canonical review URL. Link each card to that exact review; the host opens it in peek. Each offer has its own run and decision. Use native Current/Proposed fields for updates and the proposed definition for creation. A resource snapshot alone is a preview, not an approval: never fabricate Approve/Reject buttons or imply that a missing resource ID creates anything. Existing settings `?run_id=` links remain compatible; new offers use the proposal review instead of the settings page.\n- Views run in a sandboxed frame with no direct network: no fetch, no third-party calls at runtime. Reuse local React components through relative imports and `source_files: { entrypoint, files }` plus `dependencies: {}` for local-only components with `views.set`, or use `viewFromFile` + `lobu apply`. Extra npm dependencies need the CLI-bundled `compiled_code`; listing `dependencies` alone does not install packages.\n- Never early-return the whole view on loading/error: each filter keystroke re-queries, so an early return unmounts the focused input mid-typing. Keep filters mounted and render query states inline in the results area.\n- Before calling a view verified, exercise the exact compiled artifact and host runtime in a sandboxed browser: representative data, loading, empty and error states, filters, sort/pagination, links/peek, declared actions, light/dark and narrow layouts. Fix failures and rerun. Registration compiles the module and requires an isolated browser check of the exact candidate against bounded empty/error/loading fixtures in light/dark themes and inline/fullscreen modes for every distinct attached scope (at most eight per module; each scope is its own bounded runner request). A failed check returns 422; an unavailable runner returns 503; both preserve the saved view. Fixture validation does not prove successful workspace data or every interaction. Distinguish compiled, browser-verified, stored and deployed; never claim more than the evidence.\n- Params sync to the URL on Lobu hosts only; elsewhere they stay frame-local. `refetch()` re-reads on demand; only Lobu hosts push live data-changed refreshes.\n\n## Connectors, Feeds, and Operations\n\nConnectors are the primary integration path for third-party services. The\nend-to-end model (entities vs events, the run lifecycle) is in\n`docs/CONCEPTS.md`; authoring a new connector when none matches is in\n`docs/connector-authoring.md`. Do not freeze a connector lifecycle in project\ninstructions because it can drift from the deployed SDK:\n\n1. Call `search_sdk` with the service name immediately before acting. It returns installed and installable connectors, declared feed keys, readiness, and the caller-aware live lifecycle. Then, before requesting app credentials, call `client.connections.setupOptions({ connector_key })` against the selected runtime: it discovers verified cloud-managed OAuth and hosted chat alongside local setup, so follow the URLs and instructions it returns. `cloud_status: \"unavailable\"` is a discovery outage, not evidence that managed auth is absent. Options are offers, not connected accounts.\n2. Always follow the methods it returns in order instead of relying on a remembered connect/feed/operation sequence. Repeat discovery after authorization or state changes so the next step reflects the live connector and current caller.\n3. Treat `access: operate` as `mcp:write` and `access: administer` as workspace owner/admin plus `mcp:admin`. If discovery asks for MCP reauthorization or an owner/admin handoff, follow that instruction; never attempt methods it withheld as unavailable.\n\nSource-backed feeds query the provider only through an explicit `client.feeds.readMany({ reads: [...] })` call; `search_memory` stays local and reports unqueried source feeds in `coverage`, while `client.feeds.get` returns metadata without source access. Feeds with `sync` may persist events for search and relational queries. For connector actions, use the live discovery result's operation target and readiness. If readiness is disconnected, follow the returned next action instead of guessing a connection. Surface approval-gated `pending_approval` as a waiting state, not a failure.\n\n## Data Ingestion\n\n- Use `lobu memory seed` for small declarative YAML datasets under `./data`; it processes records sequentially and is not a bulk-backfill path.\n- Use `client.knowledge.save` for schema-less semantic history such as messages, notes, observations, and content. Pass `supersedes_event_id` when replacing an existing fact.\n- Use `client.entities.create` / `client.entities.update` only for strict structured records that match declared entity schemas.\n- For large backfills, send bounded chunks through `run_sdk` / `lobu call run_sdk` and use `Promise.allSettled` so conflicts and partial failures remain visible.\n\n```ts\nexport default async (_ctx, client) => {\n const records = [\n { content: \"...\", semantic_type: \"note\" },\n { content: \"...\", semantic_type: \"observation\" },\n ];\n return Promise.allSettled(records.map((record) => client.knowledge.save(record)));\n};\n```",
|
|
11
|
+
"instructions": "# Lobu\n\nUse this skill when setting up a brand-new Lobu agent from scratch (follow \"Onboarding a New Project\" below) or when running, validating, evaluating, or connecting an existing Lobu project, or operating Lobu memory from a coding agent.\n\nThe `AGENTS.md` generated into a new project is the source of truth for the config API (the `define*` helpers, connectors, auth, Automations, memory) — this skill does not duplicate it. For an existing project, jump to \"Core Model\" + the relevant reference section below.\n\n## Onboarding a New Project\n\nUse this playbook when a new user asks you to build them a Lobu agent from scratch. Set it up end to end: ground yourself in what the user already has, interview, discover, scaffold, prove the complete local path, then offer the deployment choice. Do not call the setup complete until every path the user selected has actually passed end to end. If an external provider, authorization, deployment, or rate limit blocks the proof, name the exact blocker and leave the setup as blocked rather than claiming success.\n\n### 1. Ground yourself in what the user already has\n\nBefore interviewing, look at what already exists so your questions and suggestions are personal rather than a blank slate. This is discovery, not a design decision — do not let it skip the interview.\n\n- Local: run `lobu context list` to see existing contexts (`--json` adds `loggedIn`, which reports stored credentials, not session validity); check the current directory and home for existing Lobu projects (`lobu.config.ts`), configured MCP servers, and CLI auth state. Note what the user already set up.\n- Cloud: if the user has an active session (do not create one just to look), call `client.organizations.list()`, `client.agents.list()` for each org, `client.catalog.listInstalled({ kinds: [\"connectors\"] })`, and `search_memory` for prior knowledge. This reveals existing agents, connectors, and memory you can build on.\n- Tell the user what you are looking at so they can correct you, and let what you find shape the options you offer. Never treat this discovery as an identity signal: orgs, emails, or domains never prove a company or product, and never mention a competitor or third party unless it actually appears in what you found.\n\nDo NOT ask for a login email during the interview. Email is only needed when a managed connector actually requires a session (step 3) or when the user chooses cloud deployment (step 6); ask for it at that point. Treat identity only as identity; never infer a company from an email address or domain.\n\n### 2. Interview with concrete, personalized options\n\nInterview the user one question at a time; wait for each answer, do not guess, and do not batch the questions. Anchor each question in what you found in step 1. Instead of asking \"what agent do you want?\" as a blank slate, summarize what you see and offer two or three concrete alternatives to choose from:\n\n- \"You already have org X with connectors A and B installed and N existing agents. Do you want to (a) add a new agent on top of those, (b) extend one of the existing agents, or (c) start something standalone?\"\n- \"For what it should do, the common shapes are (a) a triage agent that reads incoming chat and files a ticket, (b) a scheduled report that summarizes new activity each morning, (c) a research agent that answers questions from your connected tools. Which fits, or what would you change?\"\n\nOffer a default so the user can answer \"the first one\" — decisive users and undecided users both move faster with a concrete menu.\n\n- What company or product is this for?\n- What does it do, and who does it serve?\n- What is its public domain? (optional for a personal project)\n- Do I have permission to research the public website and other public sources?\n- What is the agent for?\n- What should we call it?\n- Who uses it: just me, my team, or each of my customers?\n- How should it behave, and what may it do unattended versus only with approval?\n- What should it remember? Model this as one to three entity types.\n- Where does its data come from? Pick one connector or custom source to start.\n- Where should people talk to it? Offer Web UI, API or SDK, MCP, Slack, Teams, WhatsApp, Discord, Google Chat, and Telegram without forcing a chat platform. If Slack is chosen, ask whether to join Lobu's hosted workspace for a quick start, install Lobu into an existing workspace, or use a custom Slack app; then ask whether to test the DM with Lobu, a named channel, or both, and whether people knowledge means conversation participants, bound-channel members, or the full workspace directory.\n- Should anything run on a schedule?\n- Which supported LLM provider credential does the user have?\n\nIf the user gave permission to research and has a public domain, research the company before proposing the design. Summarize its product, customers, workflows, and useful signals, and cite the public sources you used. Then propose one to three entity types, their relationships, the first data source, one or two useful Automations, and suitable interaction channels. Play back a short numbered plan and wait for confirmation before scaffolding anything.\n\n### 3. Discover the surface before choosing how to scaffold\n\nCheck Node is 26.x, then run `lobu context list` and identify the named Lobu Cloud context; do not assume the active context still points to cloud after a local run. If a managed or cloud connector was chosen and there is no session, ask for the login email at that point, explain that Lobu will email an approval link, and run `lobu login --email <confirmed-address> --context <cloud-name>`. The person approving must sign in with that same email; knowing an address never grants access. After a successful login, an empty organization membership list is a tenancy/discovery result, not an authentication failure: call `client.organizations.list()` and explain the result. Never revoke or repeat login with `--force` unless the user separately approves that re-authentication.\n\nUse ClientSDK through Lobu MCP with the explicit cloud context. From the CLI, account discovery works before selecting an active org with `lobu memory run query_sdk '{\"title\":\"Find managed connection providers\",\"script\":\"export default async (_ctx, client) => client.organizations.list()\"}'`; `lobu call` over REST requires an active org. Call `client.organizations.list()` to find public organizations offering managed connections. Call `client.catalog.listInstalled({ kinds: [\"connectors\"] })`; if the connector is not installed, call `client.catalog.listCatalog({ kinds: [\"connectors\"] })`. Inspect the selected entry's `detail.auth_schema`, `detail.options_schema`, `detail.feeds_schema`, and `detail.automation_events` instead of guessing field names. On account-scoped `/mcp`, select an authorized home workspace first with `const home = await client.org(homeSlug)` and call `home.connections.connectManaged`; put the public provider org in `managed_by_org`, rather than selecting that provider org with `client.org`. This call runs against cloud, not the embedded runtime. If a matching live managed offer exists, explain it and call `client.connections.connectManaged` only after consent. Complete the returned user authorization, then run `lobu context use <cloud-name>` immediately before executing its `local_bootstrap_command` from the parent directory where the new project should be created; use `--here` only after entering an empty directory, and do not create a blank Lobu scaffold first. Ask for bring-your-own OAuth credentials only if no managed offer exists or the user prefers their own app.\n\n**If no connector in the catalog matches the data source, do not report \"no integration exists\"** — author a custom connector: write `connectors/<name>.connector.ts` in the project, register it with `connectorFromFile(\"./connectors/<name>.connector.ts\")`, and model it on the [npm downloads example](https://github.com/lobu-ai/lobu/blob/main/examples/lobu-crm/npm-downloads.connector.ts). See [Connector authoring](https://github.com/lobu-ai/lobu/blob/main/docs/connector-authoring.md) for the full contract; the end-to-end entity/event/Automation model is in [Lobu concepts](https://github.com/lobu-ai/lobu/blob/main/docs/CONCEPTS.md).\n\n### 4. Scaffold and build from the confirmed plan\n\nIf managed auth supplied a `local_bootstrap_command`, use the project it generated. Otherwise run `npx @lobu/cli@latest init` with the confirmed name and provider. Postgres is built in, so `lobu run` starts an embedded database; ask for `DATABASE_URL` only if the user chooses external Postgres. Read the generated `AGENTS.md` completely before editing `lobu.config.ts`. Use the canonical reference at `https://github.com/lobu-ai/lobu/blob/main/examples/lobu-crm/lobu.config.ts` when needed; do not assume that example exists in the new project's filesystem. Briefly explain how the chosen feed may use checkpoints to collect incrementally, emits events, builds shared entity memory, and gives both chat and Automations the same governed context.\n\n`feeds_schema.<feed>.eventKinds` are the default Automation trigger catalog for feed connectors: every declared kind is a subscribable event type (`event_type` = the kind slug) for any feed that emits the kind. A feed's first successful non-dry sync establishes its baseline without activation; later inserts of a matching kind activate subscribers. A kind with `updatedEvent: true` also offers `<kind>.updated` for supersedes whose `occurred_at` strictly advances past the previous head. The original kind stays insert-only; unchanged rows, volatile-only updates and same-time reformats stay quiet. Subscribe to both types for new items and later activity. Feed-scoped filtering is not yet available (events dedupe by connection + origin id, so a `feed_key` match would miss origins first seen by another feed). `automation_events` (now derived from eventKinds when a connector declares none) is the trigger picker's list. If no declared kind matches the use case, use a scheduled Automation with a bounded named SQL source and read event text from `payload_text`. Validate the query against the running local schema before relying on it. If `feeds_schema` is empty, do not invent or trigger a feed; chat integrations such as Slack can deliver incoming messages directly. For Slack or Telegram, prefer `defineConnection` with `credentialMode: \"hosted\"` so no bot token is required; `lobu run` prints the exact hosted-workspace join URL, own-workspace install URL when available, and short-lived link command. This hosted chat path requires a cloud session and the agent applied to that cloud workspace; the link targets the cloud agent. It does not create a local Slack data connection or prove local Slack search. Use those returned values instead of constructing URLs. A printed `/lobu link <code>` is one-time: redeem it in the first selected DM or channel. In an installed workspace whose installer is linked to Lobu, bind each additional surface with `/lobu link <agent-id>`; otherwise generate a fresh code for that surface. Mention Lobu in a channel test and verify the App Home separately. Lobu email login and Slack installation are separate: the email link authorizes Lobu CLI access, while an existing-workspace install requires the user or workspace admin to approve Slack's OAuth screen. Never describe Slack consent as an email approval. Use `credentialMode: \"byo\"` only if the user chooses their own app. Tell the user once which remaining secrets are required and add only `secret(\"ENV_NAME\")` placeholders to config. Never open or request permission to read `.env`; inspect `.env.example` when present and declared secret placeholder names only. Never read, print, invent, or paste a real secret into source or chat.\n\nIf the user wants the agent to know people in Slack, ask whether that means conversation participants, members of bound channels, or the full workspace directory. Installing the app proves none of those by itself. Verify the selected scope by inspecting the people or member entities Lobu actually materialized and by asking the agent a roster question. If human-readable names or non-participants are unavailable, identify that exact product gap; never claim the complete workspace directory was synced.\n\n### 5. Prove the complete local path\n\nChange into the generated project directory and verify `pwd` contains the intended `lobu.config.ts`; never run project commands from its parent. Run `npx @lobu/cli@latest validate`, boot with `npx @lobu/cli@latest run`, and verify health and the local Web UI. With the embedded database default, `lobu run` creates and selects the local context and auto-applies the project; with an external `DATABASE_URL`, it does neither, so authenticate and apply to that runtime explicitly. Send a harmless direct chat message without tools.\n\nBefore consent to access provider data, inspect only catalog, connection, auth-profile, and feed metadata. For browser access, inspect the paired device and connection metadata without invoking browser actions. Durable managed OAuth and env-profile credentials stay at the gateway. Do not run a feed or connector dry-run before consent, because a dry-run may still read provider data. Ask explicitly before accessing real provider data. Only after approval, dry-run the connector or feed server-side and trigger the selected feed manually if that connector actually declares one. A feed dry-run records its run but persists no collected events, entities, attachments, checkpoint changes, or feed sync state. Run each Automation once, poll `client.operations.getRun` with its returned `run_id`, and show each completed run plus any declared result event or entity. For a run-result-only or reaction-only Automation, use the completed run and the Automation `view_url` returned by Lobu. For Slack, treat DM, channel mention, App Home, and requested member discovery as four separate checks. Keep actions in approval mode unless the user explicitly approves execution. If any step fails, fix it and rerun that step; do not silently substitute a different path.\n\n### 6. Offer the deployment choice\n\nAfter the local proof, ask the user whether to keep running locally or deploy to Lobu Cloud. Explain that the embedded local runtime and Lobu Cloud are separate targets, and that keeping it local needs no further setup. Only if the user chooses cloud deployment, ask for the login email to identify the deployer, explain that Lobu will email an approval link, and run `lobu login --email <confirmed-address> --context <cloud-name>`; the person approving must sign in with that same email. Because `lobu apply` has no context flag, use `lobu context list` and then `lobu context use <cloud-name>` to select an explicit cloud context before deployment. Run `lobu apply --dry-run` first, show the target organization and exact plan, and wait for confirmation before applying. After apply, use only authoritative `view_url` values and link commands returned by Lobu; never construct URLs. Present the working access choices: Web UI, direct agent chat, API or SDK, MCP, and any channels the user selected.\n\n## Core Model\n\n- **Lobu** is the agent framework, runtime, deployment layer, and memory surface.\n- Keep framework configuration in `lobu.config.ts` (TypeScript, `defineConfig` from `@lobu/cli/config`).\n- Keep agent identity and instructions in `IDENTITY.md`, `SOUL.md`, and `USER.md`.\n- Keep reusable capability bundles in `skills/<name>/SKILL.md` or `agents/<agent>/skills/<name>/SKILL.md`.\n- Use `lobu login` for CLI authentication. Do not use a separate memory login command.\n- Use `lobu connect` for MCP client and skill setup.\n- Use `lobu memory ...` for memory operations, seeding, and direct tool calls.\n\nReference the canonical docs before guessing how a feature works:\n[Lobu concepts](https://github.com/lobu-ai/lobu/blob/main/docs/CONCEPTS.md)\n(entities vs events, identity, end-to-end lifecycle),\n[Automations](https://github.com/lobu-ai/lobu/blob/main/docs/AUTOMATIONS.md)\n(trigger/source/output contract), and\n[Connector authoring](https://github.com/lobu-ai/lobu/blob/main/docs/connector-authoring.md)\n(custom connectors).\n\n## Project Checklist\n\n1. Read `lobu.config.ts` first.\n2. Read the active agent files under `agents/<id>/`.\n3. Check local skills under `skills/` and `agents/<id>/skills/`.\n4. Use `lobu validate` after config changes.\n5. Discover the live SDK and connector surface with `search_sdk`; never guess a method, connector key, feed key, connection id, or operation key.\n6. When prompt or Automation changes, run evals via promptfoo (see `examples/personal-finance/evals/promptfooconfig.yaml`). The in-house `lobu eval` command has been removed.\n\n## Common Commands\n\n```bash\nnpx @lobu/cli@latest init my-agent\nnpx @lobu/cli@latest run\nnpx @lobu/cli@latest validate\nnpx @lobu/cli@latest login\n```\n\n## Authentication\n\n- Interactive (human at a terminal): `lobu login` runs the device-code flow with a browser approval.\n- CI / your own automation: `LOBU_API_TOKEN`, or `lobu login --token <pat>`.\n- Local `lobu run`: the CLI mints credentials automatically over loopback — no prompt.\n- Headless, on a *user's* behalf: `lobu login --email <address>`. The server emails the user a one-click approval link and the CLI polls until they approve, then stores the scoped credential — no TTY, no pre-minted token. This is the auth.md \"user_claimed\" flow.\n\nAn external agent not using this CLI can drive the same flow over HTTP: read `<origin>/auth.md` (linked from the `agent_auth` block in `<origin>/.well-known/oauth-authorization-server`) for the endpoints. Today only the email user_claimed flow exists (no zero-touch ID-JAG). Never fabricate a token.\n\n## Organization Deletion\n\nTreat organization deletion as permanent and restricted to organization owners. The supported path is the **Organization settings** page, opened from that workspace's settings button in the organization switcher. ClientSDK and Lobu CLI intentionally expose no organization-delete method. When asked to delete organizations, identify each exact target and its data impact read-only, surface one production organization at a time for explicit confirmation, then direct an owner to that page or use their logged-in browser only when explicitly authorized. Never invent a hosted URL, call the raw Better Auth route, bypass a failed authorization check, delete organization rows directly, or batch confirmations.\n\nCloud CLI OAuth/PAT credentials are not a Better Auth browser session. A `401` or `403` is a stop signal: report the authorization boundary and leave the organization intact.\n\n<!-- lobu-memory-guidance:start -->\n## Memory Defaults\n\nYour long-term memory is powered by Lobu. Do NOT use local files (memory/, MEMORY.md) for memory.\n- Lobu automatically recalls relevant memories when you receive a message.\n- To save something, call save_memory with the content and an appropriate semantic_type.\n- To search, call search_memory. Results include view_url links to the web interface.\n- NEVER construct Lobu URLs yourself. When the user asks for a link, call search_memory to get the correct view_url.\n- When the user says \"remember this\", save it to Lobu immediately.\n- When a message changes a fact you already stored (an updated preference, status, count, location, or plan), first search_memory for the prior memory to get its id, then save_memory the new value with supersedes_event_id set to that id. This replaces the stale value so future recalls return the current one; the old value stays in history but is hidden from normal search.\n<!-- lobu-memory-guidance:end -->\n\n## Lobu Memory\n\nConfigure project-scoped memory in `lobu.config.ts` by setting the org on `defineConfig` and declaring the schema with the `define*` helpers:\n\n```ts\nimport { defineConfig, defineEntityType } from \"@lobu/cli/config\";\n\nconst ticket = defineEntityType({\n key: \"ticket\",\n name: \"Ticket\",\n properties: {\n subject: {\n type: \"string\",\n title: \"Subject\",\n \"x-table-label\": \"Subject\",\n \"x-table-column\": true,\n },\n },\n});\n\nexport default defineConfig({\n org: \"my-org\",\n orgName: \"My workspace\",\n agents: [/* ... */],\n entities: [ticket],\n});\n```\n\nThe entity schema also renders the record page form. Give every array `items` and every object `properties` (bare ones render as raw JSON), put the label in `title` and help text in `description`, mark derived fields `readOnly: true`, and declare every field an Automation writes.\n\nFor a \"when did this field last change\" timestamp, declare root `metadata_schema[\"x-lobu-stamps\"]: { \"stage_at\": \"stage\" }` instead of writing it from an Automation. The stamp field must be a declared `{ type: \"string\", format: \"date-time\" }` property (not listed in `required`) and the tracked field a declared property. Every writer (agent, SDK, Automation, connector projection, view action, approval) then gets it for free: the server sets `stage_at` when a record is created with `stage` set or when `stage` changes value, and discards any value a caller sends for `stage_at`. `readOnly` alone is presentation only; it is not enforced.\n\nSeed data records still live as YAML under `./data`. Then seed or operate the memory workspace with:\n\n```bash\nlobu login\nlobu memory org set <org-slug>\nlobu memory health --org <org-slug>\nlobu memory seed --org <org-slug>\nlobu memory run search_memory '{\"query\":\"Acme\"}' --org <org-slug>\n```\n\nUse `search_memory` first when the user asks about a specific entity or workspace memory. Use `save_memory` to persist durable memory. To update existing knowledge, search first, then save with `supersedes_event_id` so the old row is tombstoned rather than deleted.\n\n### Answering questions about a record\n\nRecent events can contain only counters or timestamp updates; a relevant linked record may hold the investigation, decision, or outcome. Use the existing read APIs to gather that context:\n\n1. Start with `search_memory` to resolve the record and its workspace. Discover the current signatures with `search_sdk`, then use `query_sdk` with the selected workspace's `entities.get` and `knowledge.read`. Event `entity_ids` identify records the event concerns; co-occurrence does not assert a relationship.\n2. When relationships could answer the question, call `entities.listLinks` on the resolved record or relevant event-linked records. Use relationship type and direction to select context relevant to the question, rather than expanding every event. Keep expansion to one hop and fetch at most five distinct related records in total with `entities.get`. Bound link pages too: start with `limit: 20` and inspect at most two pages total; use the returned offset/page metadata for stored records and `next_cursor` for source-backed records. Deduplicate records by workspace, type, and ID/key. If the budget ends while more results remain, say the context is partial.\n3. For stored event evidence in current-state questions, use live heads (`is_superseded: false`), not the first row of an exact-ID read: `content_ids` can return the supersede history before its current head. If no live head is returned, follow the returned pagination for at most two pages total, then report current evidence unavailable if it is still missing. Keep historical versions when the question asks what happened at an earlier time. An event ID identifies a stored version; a source item's stable identity is its connection/source plus `origin_id`.\n4. Preserve the meaning and direction of each relationship. Skip `acl_managed` links for ordinary business context unless the question concerns permissions. An identity association or a shared email address does not by itself verify the same human; a shared support mailbox can represent several people. Neither proves employment or collaboration. Fetch supporting evidence when that distinction matters, and distinguish a stored assertion from a verified source fact.\n5. Cite returned record/event URLs or source links for the answer. Treat `relationship_failures`, `record_failures`, unreadable linked records, and unfinished pages as coverage limits, not proof that no relationship or evidence exists. Respect the selected workspace and caller's access; do not switch workspaces or fall back to raw SQL to bypass a denied read. Manual claims and connector configuration ownership are not automatically supporting event evidence.\n\nFor example, when asked what happened with an issue, follow an explicitly returned investigation/task relationship and read that record's conclusion as well as the issue's recent activity. Report a stored task's conclusion as recorded context; it does not independently prove that a repair is currently deployed. This workflow reads context only; it does not create links or merge records.\n\n## MCP Client Setup\n\nUse the actual MCP URL for the user's runtime. Never hardcode a hosted URL unless the user explicitly asks for that instance.\n\nCommon setup commands:\n\n```bash\n# Claude Code\nlobu connect claude-code --url <mcp-url>\n\n# Codex\nlobu connect codex --url <mcp-url>\n\n# Antigravity\nlobu connect antigravity --url <mcp-url>\n\n# OpenCode\nlobu connect opencode --url <mcp-url>\n```\n\nRun `lobu connect --url <mcp-url>` without a client id to choose interactively. For ChatGPT, Claude Desktop, Cursor, and other browser-managed clients, the same command applies the safe local configuration it can and prints the exact remaining client handoff. Complete OAuth in the client, not through a separate Lobu CLI login.\n\n## Browser-Authenticated Connectors\n\nFor connectors that need a signed-in browser, pair the Owletto Chrome extension\nand sign in on the source site in that browser. Browser operations run through\nthat paired device; external remote-debugging endpoints and CLI browser-auth\ncapture are no longer supported.\n\nNothing answers a JS dialog (alert, confirm, prompt, beforeunload) on the\nagent's behalf. A browser action it blocks fails, and the failed result's\n`output` carries `tab_id` and `dialog` (`dialog_id`, `type`, `message`). In\n`run_sdk`, catch the `operations.execute` error and read `error.details.output`\nrather than parsing the error text (an uncaught failure returns the same value\nas the `run_sdk` result's `error.details`, and a background run's\n`operations.getRun` returns the same `output`), then answer with the\nconnection's `handle_dialog` operation. An unanswered dialog is handed to the user after two minutes.\n\nTo test a configured feed without writing ingested data, discover the current\nfeed methods with `search_sdk`, then use `client.feeds.trigger({ feed_id, dry_run: true })`\nthrough `run_sdk` or `lobu call run_sdk` (with a `title` arg). Inspect `client.feeds.get({ feed_id })`\nfor the completed run's preview. The dry run uses normal device routing and\nauthorization checks and may access the upstream provider, so obtain consent first.\n\n## Agent-Facing Tool Surface\n\nThe normal MCP surface is intentionally small. Flat administrative tools are not advertised to agents; compose through these tools instead:\n\n- `search_memory` and `save_memory` for direct knowledge recall and persistence.\n- `search_sdk` to discover current ClientSDK methods, signatures, connector feed keys, operations, access requirements, and examples. Pass `mode: \"read\"` when you only need methods safe for `query_sdk`.\n- `query_sdk` for read-only TypeScript and `query_sql` for governed, paginated SQL reads.\n- `run_sdk` for mutations and external operations. Use `lobu call run_sdk --arg title='…' --arg script='…'` from the CLI for the same ClientSDK scripting workflow; `run_sdk`, `query_sdk`, and `query_sql` calls need a short `title` naming them in the activity feed.\n\nSearch before create to avoid duplicates. Prefer a read or dry run before mutations, never fabricate returned URLs or identifiers, and never delete from `events`; supersede or tombstone instead.\n\n## Custom Views\n\nBefore authoring UI, inspect available native entity/event pages, existing views (`client.views.list()` and `client.views.get({ key })`), and the project's shared components and overrides. Honor explicit user designs and reuse UI from the top down:\n\n1. Use the largest existing surface or component that meets the task. Configure its segment, filters, search, saved preset and layout before replacing its UI.\n2. If that surface cannot meet a concrete requirement, compose its exported parts, such as an individual table, board, graph or shared collection controls when available. Preserve shared selection and action handling instead of rebuilding that logic.\n3. If those parts still do not fit, use smaller shared primitives and write custom UI only for the remaining gap. Explain the unmet requirement that forced each step down.\n\nCheck the current exports and target host before choosing an import; native renderer registrations do not imply React exports. Surface a missing export as a platform gap rather than inventing an API or silently copying the native implementation. `@lobu/views/components` currently supplies theme-aware defaults such as `Card`, `DataTable`, filters, charts, links and query-state components. `LoadingState` draws skeleton lines in the host's style; `Skeleton` is a pulsing block to size like the content it stands for (a figure, a row, a chart), so a slow read keeps the page's shape instead of showing text. When exploration needs specialized linked charts, drilldowns, scenario controls or Canvas/SVG, compose a React view from the suitable existing components.\n\nNative JSON templates use the target renderer's registered component names and overrides; inspect what that host actually supplies. React views compose imported components in their own bundle, independently of that native renderer map.\n\nViews are custom React panels attached to entity types, records, events, or the workspace Data hub. They render in the web app and MCP hosts (Claude and other MCP Apps hosts); chat channels get links to views, not the views themselves. Author them in `views/<type>/<key>.tsx` and ship with `lobu apply` (list them via `viewFromFile` in `defineConfig`), or set sources over MCP with `client.views.set` (owner/admin only).\n\nModule shape (the server resolves React, React DOM, `@lobu/views` and `@lobu/views/components`; other dependencies need the CLI path with `node_modules` present):\n\n```tsx\nimport { defineView, tool, useAction, useParams, useQuery } from \"@lobu/views\";\nimport {\n Card,\n DataTable,\n EmptyState,\n ErrorState,\n FilterBar,\n LoadingState,\n SearchField,\n TruncatedNotice,\n} from \"@lobu/views/components\";\n\nexport const view = defineView({\n key: \"pipeline\",\n attach: [{ collection: \"deal\" }],\n params: { stage: { type: \"string\", default: \"open\" } },\n actions: { markWon: { emits: \"deal.won\" } },\n});\n\nexport default function Pipeline() {\n const [params, setParams] = useParams();\n const deals = useQuery(tool(\"manage_entity\", { action: \"list\", entity_type: \"deal\", filters: [{ field: \"stage\", op: \"eq\", value: String(params.stage) }], limit: 100 }));\n const markWon = useAction(\"markWon\");\n const rows = deals.data?.entities ?? [];\n // Keep the filter mounted across query states: an early return on\n // loading/error would unmount the focused input on every keystroke\n // (each keystroke re-queries). Render states inline instead.\n return (\n <Card\n title=\"Pipeline\"\n actions={<button type=\"button\" onClick={() => markWon({})}>Mark won</button>}\n >\n <FilterBar><SearchField label=\"Stage\" value={String(params.stage)} onChange={(v) => setParams({ stage: v })} /></FilterBar>\n {deals.loading && <LoadingState text=\"Loading deals…\" />}\n {deals.error && <ErrorState message={deals.error} errorCode={deals.errorCode} />}\n {!deals.loading && !deals.error && rows.length === 0 && (\n <EmptyState title=\"No deals in this stage.\" />\n )}\n {!deals.loading && !deals.error && rows.length > 0 && (\n <DataTable columns={[{ key: \"name\", header: \"Name\" }]} rows={rows} keyOf={(r) => r.id ?? r.slug} />\n )}\n {deals.truncated && <TruncatedNotice shown={rows.length} />}\n </Card>\n );\n}\n```\n\n`defineView` is the view's only declaration: `key`, optional `name` (defaults to the key) and `description`, `attach`, `params`, `actions` and `resources` are read from it, never passed separately. `views.set` always requires `source_code` containing the entrypoint module, including when retaining multiple files. Write `defineView` out as a literal (no variables, spreads or `${}` templates): the server reads it without running the module.\n\nA view makes no network requests of its own; data comes through `useQuery`. The one exception is images: `resources: [\"https://tile.openstreetmap.org\"]` declares origins the view may load images (map tiles, logos) from. Each entry is a bare `https://` origin with a public hostname (no path, wildcard, localhost or IP), at most 8. The images-only limit is a save-time check: `views.set` renders the view's empty, error and loading states in an offline browser and refuses the save if anything other than an image from a declared origin is requested. It is not enforced at runtime. MCP hosts receive the origins as the MCP Apps `resourceDomains` CSP, which allows scripts, styles, fonts and media from them as well as images, and the Lobu web app applies no runtime CSP to views. Declare only image or tile CDN origins you trust. Hosts that render through the generic `ui://lobu/views` loader use its CSP, which declares no image origins, so declared images may not load there.\n\nFor a multi-file view, `files` maps relative paths to complete source strings and `entrypoint` names the view module. Include all three inputs below; `source_code` must exactly equal `files[entrypoint]`:\n\n```ts\nawait client.views.set({\n source_code: files[entrypoint],\n source_files: { entrypoint, files },\n dependencies: {}, // Local files and the host-provided runtime need no extra packages.\n});\n```\n\n`attach` lists the pages a view appears on, one per entry: `{ record: \"deal\" }` is a card on every deal's page above its activity (`{ record: \"deal\", id: 7 }` pins one record), `{ collection: \"deal\", when? }` a tab on the deal list page, `{ workspace: true }` a Data hub tab, `{ event: \"deal.won\", type? }` one event's page. One view can list several pages and branch on `useScope()` when it answers the same question at each scale. A record card renders with `useHost().displayMode === \"inline\"` inside `container.maxHeight` (the host clips past it): render a summary there with a \"See all\" that calls `requestDisplayMode(\"fullscreen\")`, and the full view when `displayMode` is `\"fullscreen\"` (the peek, a full page, a tab).\n\nWorkspace attachment does not render individual events. For an event presentation, attach to its specific `semantic_type` (event kind), optionally restricted to a linked entity type with `type`; a metadata schema name does not select the view. Avoid binding a specialized renderer to a generic kind such as `summary`. Register a dedicated kind in the workspace's event-kind registry and have its producer emit it. On event pages and event peeks, read `useScope().event` by exact ID and select that ID from the returned lineage; never substitute the latest event or let a URL date param change the subject. A shared workspace/event module should branch on `scope.event`, keeping history selection on its workspace surface. Preserve a readable stored body for fallback and evidence.\n\nBefore reporting a view working, open each attached surface, including an event page and peek when declared. Exercise filtering, drilldown, keyboard navigation, and a narrow pane; check loading, missing/error, and truncated data states. Refresh and reopen an earlier event of the kind to verify the view stays on that event rather than jumping to the newest one. Views render in an iframe, so an empty parent-page DOM is not evidence the view is empty; inspect the frame through an authorized browser or accessibility surface. A successful compile proves only that the bundle was built.\n\nImport reusable UI from **`@lobu/views/components`**. Discover this kit with `search_sdk({ query: \"@lobu/views/components\" })` or a component name. Start with the largest suitable native surface; compose smaller parts only for needs it does not cover:\n\n| Need | Component and minimum input |\n| --- | --- |\n| Complete entity list | `EntityListPage title={title} table={tableProps}` |\n| SQL, computed TypeScript or local rows | `EntityListPage title={title}` with `DataTable columns={columns} rows={rows} keyOf={keyOf}` as children |\n| Complete record body | `EntityRecordPage entity={entity} owner={workspace} schema={schema}` |\n| Entity table or individual fields | `EntityTableView`, `RecordSpecSheet`, `SchemaValue`, `EntityAvatar` |\n| Workspace schema, proposed schema or schema diff | `SchemaGraph`, `SchemaGraph schema={spec}`, `SchemaGraph schema={spec} base=\"workspace\"`, or `SchemaGraph schema={after} base={before}` |\n| Saved resource identity and navigation | `AutomationReference`, `AgentReference`, `ConnectorReference` |\n| Automation instructions, sources, triggers, outputs and code | `AutomationDefinition value={definition}` |\n| Agent identity, models and settings | `AgentDefinition value={definition}` |\n| Connector actions, feeds, schemas and source | `ConnectorDefinition value={definition}` |\n| Current / Proposed comparison | Existing `Tabs` with the same definition component in each panel |\n| Optional technical details | `JsonDiff before={current} after={proposed}` inside collapsed `<details>` |\n\nThe host supplies native JS/CSS, React and live theme. Do not copy product markup or bundle a second React. Exported prop types describe the shared contracts. Use `Button`, `Badge`, `Card`, chart and state components for surrounding UI.\n\n**Page bodies are controlled.** Supply data and slots; they fetch nothing and authorize no writes. `EntityListPage` accepts `title`, optional `actions`/`controls`, and either `table: EntityTableViewProps` or `children`. Its `loading`, `error`, `onRetry` and `empty` affect only results, keeping controls mounted. Native table props include rows, schema, linked lookups, sorting and pagination; honor `metadata.has_more`. For SQL/TypeScript rows use `DataTable`, without inventing entity IDs or types. `EntityRecordPage` renders the native title/avatar and schema fields; `actions`, `details`, `summary`, and `children` supply editing, links, activity and tabs. Default `layout=\"record\"` adapts to width; `layout=\"content\"` retains the header while children own the layout. A `null` title/details/summary hides that slot. Preserve zero and false.\n\n**SchemaGraph is read-only.** It reuses the native schema canvas. Omit props for the mounted workspace schema, pass `schema` for a supplied snapshot, add `base=\"workspace\"` to compare a proposal with the live workspace, or pass another spec as `base`. A spec is `{ entityTypes: [{ slug, name?, description?, metadata_schema?, event_kinds? }], relationshipTypes: [{ slug, name?, metadata_schema?, rules: [{ source_entity_type_slug, target_entity_type_slug }] }] }`. Specs are full snapshots: an omitted type is removed in a diff. Added, removed and changed types/rules remain visible; inspect type details for metadata fields, event kinds and rule changes. Existing entity types open their native pages; unsaved types show details in place. Live reads use the visiting user’s session and permissions through the existing broker; supplied snapshots still render when workspace reads are unavailable. No edits or schema writes are performed. The leaf names match `entitySchema`: list responses use `entity_types` / `relationship_types`; attach `listRules` results to the matching relationship by ID. To apply a reviewed spec, use existing `createType` / `createRelType` (both require `name`) and `addRule({ slug, ...rule })` separately. The graph’s optional name falls back to slug for display only. Hosts without native components throw the standard unavailable-native error.\n\n**References resolve saved identity.** Pass `mode=\"live\"`, mounted `workspace`, optional `appearance=\"inline\" | \"row\"` (default row), and `automationId` (positive decimal string), `agentId`, or `connectorKey` plus optional numeric `connectionId`. Discover IDs first. These reuse product rows and visiting-user permission checks; they accept no authored name/status or mutation callbacks. Invalid selectors, another workspace, missing records and refused reads show unavailable. A connector definition does not imply a connected account. Reads refresh on mount, focus, reconnect and host invalidation, without interval polling.\n\n**Definitions render supplied objects.** All three have the same signature: `{ value: Record<string, unknown> }`. Pass the existing saved definition or complete proposed snapshot, not a patch. Automation fields include `name`, `description`, `prompt`, `sources`, `triggers`, `outputs`, `reaction_script`; Agent fields include `name`, `description`, `identity_md`, `settings`; Connector fields include `name`, `description`, `version`, `actions_schema`, `feeds_schema`, `source_code`. Remaining nested settings stay inspectable. Missing fields differ from empty values. Bodies fetch nothing, execute no supplied code, and add no save/approval controls. Label authored objects as Snapshot or Proposal preview; use a reference for live identity. Never supply credentials.\n\nShow changes as **Current / Proposed**, defaulting to Proposed, with the same native body on both sides. Keep JSON diff optional. Rendering does not save or apply anything and needs no new proposal endpoint. For an existing approval, render its held current/proposed snapshots; do not merge in newer live values. Writes remain on existing declared `useAction` paths or native authorized editor/review pages. An authored preview must not imply a held approval or authority to apply it.\n\n```tsx\nimport {\n Card, ConnectorDefinition, JsonDiff,\n Tabs, TabsList, TabsTrigger, TabsContent,\n} from \"@lobu/views/components\";\n\n// current and proposed are complete definition objects from authorized reads\n// and the requested edit. Use AgentDefinition or AutomationDefinition identically.\n<Card title=\"Connector proposal preview\" description=\"Nothing has been applied.\">\n <Tabs defaultValue=\"proposed\">\n <TabsList label=\"Definition version\">\n <TabsTrigger value=\"current\">Current</TabsTrigger>\n <TabsTrigger value=\"proposed\">Proposed</TabsTrigger>\n </TabsList>\n <TabsContent value=\"current\"><ConnectorDefinition value={current} /></TabsContent>\n <TabsContent value=\"proposed\"><ConnectorDefinition value={proposed} /></TabsContent>\n </Tabs>\n <details><summary>Technical diff</summary><JsonDiff before={current} after={proposed} /></details>\n</Card>\n```\n\nUse `useHost().openRecord({ entity_id, entity_type? }, { mode: \"peek\" })` for a record's native peek. String source keys require the type. The promise reports the actual `{ mode: \"peek\" | \"page\" }`; a host without native peek opens the server-returned record URL. Errors remain errors. `useHost().theme` follows live theme changes; native components inherit the host palette and typography automatically. Use semantic host style variables and avoid hardcoded light/dark colors.\n\nRules that are load-bearing, not style:\n\n- Use structured reads: `useQuery(tool(\"manage_entity\", { action: \"list\", entity_type: type, filters, limit: 100 }))`. The host admits entity `list/get/list_links` and entity-type schema `list/get` reads; tools marked read-only are also available. Use existing tool input/result contracts and preserve server authorization. Send structured arguments, never TypeScript inside a string. `sql` remains available; script-string queries are compatibility support for installed views. `query_sql` allows 500 rows max with a 5 second timeout — branch on the typed `errorCode` (e.g. `UPSTREAM_TIMEOUT`), never on message text, and render `truncated` honestly instead of passing partial data off as complete. Each `query_sql` cell is bounded too: strings keep their first 4,000 Unicode code points plus \"… [truncated]\"; JSON values over 16 KiB become `{ _truncated: true, bytes }` (attachments become null with `attachments_truncated`). `truncatedColumns` names the affected columns. Select smaller elements or fields, for example one array element per row with `jsonb_array_elements(...)`, and paginate as needed; each returned cell is still subject to these limits.\n- Never aggregate history in a view: no `GROUP BY`, `DISTINCT ON`, per-row regexp, or leading-wildcard `LIKE` over `events` or other growing tables. For \"latest state\" views, have an Automation maintain keyed event outputs (each run supersedes the previous event with the same key) and read the current head with `read_knowledge`.\n- `run_sdk` is not exposed to views. Writes go only through declared view actions (`useAction` → `invoke_view_action`). An action declares `emits` (append that event kind, which can activate workspace-triggered Automations), `updates: { entityType, fields }` (write those metadata fields on one record), or both, which commit in one transaction. An `updates` action takes `value: { entity_id, set: { field: value } }`; the view must attach to `entityType`, `set` may only name declared fields, and schema-stamped fields are refused. Pass `{ expected }` as the second argument with the values the view read: a stale read returns 409 `PRECONDITION_FAILED` and writes nothing. The write runs as the clicking user without claiming field ownership, so a human-owned field comes back as `pending_approval` instead of `applied`. Do not add an Automation that only copies an action's event onto the record; declare `updates` instead. Action `value` payloads are capped at 4000 JSON chars — save content first, then pass the id. A subject shown from a superseded event rejects with 409; refetch and ask the user to re-confirm rather than retrying blindly.\n\n ```tsx\n // actions: { markWon: { emits: \"deal.won\", updates: { entityType: \"deal\", fields: [\"stage\"] } } }\n const markWon = useAction(\"markWon\");\n const sent = await markWon({ entity_id: deal.id, set: { stage: \"won\" } }, { expected: { stage: deal.metadata.stage } });\n // sent.result.applied: { entity_id, fields } with server stamps; sent.result.pending_approval when held\n ```\n- Link with `Link` from `@lobu/views/components` (or `useHost().openLink`): `href=\"<type>/<slug>\"` opens that record in the workspace, supported links within the same workspace open in the peek pane, other app links navigate normally, and external URLs open a new tab. A plain `<a href>` goes nowhere inside the sandboxed frame.\n- For several offers, publish one event with a card for each held proposal. Obtain the real pending approval through the existing agent/Automation write method under its normal policy, then read its returned event ID to obtain the canonical review URL. Link each card to that exact review; the host opens it in peek. Each offer has its own run and decision. Use native Current/Proposed fields for updates and the proposed definition for creation. A resource snapshot alone is a preview, not an approval: never fabricate Approve/Reject buttons or imply that a missing resource ID creates anything. Existing settings `?run_id=` links remain compatible; new offers use the proposal review instead of the settings page.\n- Views run in a sandboxed frame with no direct network: no fetch, no third-party calls at runtime. Reuse local React components through relative imports and `source_files: { entrypoint, files }` plus `dependencies: {}` for local-only components with `views.set`, or use `viewFromFile` + `lobu apply`. Extra npm dependencies need the CLI-bundled `compiled_code`; listing `dependencies` alone does not install packages.\n- Never early-return the whole view on loading/error: each filter keystroke re-queries, so an early return unmounts the focused input mid-typing. Keep filters mounted and render query states inline in the results area.\n- Before calling a view verified, exercise the exact compiled artifact and host runtime in a sandboxed browser: representative data, loading, empty and error states, filters, sort/pagination, links/peek, declared actions, light/dark and narrow layouts. Fix failures and rerun. Registration compiles the module and requires an isolated browser check of the exact candidate against bounded empty/error/loading fixtures in light/dark themes and inline/fullscreen modes for every distinct attached scope (at most eight per module; each scope is its own bounded runner request). A failed check returns 422; an unavailable runner returns 503; both preserve the saved view. Fixture validation does not prove successful workspace data or every interaction. Distinguish compiled, browser-verified, stored and deployed; never claim more than the evidence.\n- Params sync to the URL on Lobu hosts only; elsewhere they stay frame-local. `refetch()` re-reads on demand; only Lobu hosts push live data-changed refreshes.\n\n## Connectors, Feeds, and Operations\n\nConnectors are the primary integration path for third-party services. The\nend-to-end model (entities vs events, the run lifecycle) is in\n`docs/CONCEPTS.md`; authoring a new connector when none matches is in\n`docs/connector-authoring.md`. Do not freeze a connector lifecycle in project\ninstructions because it can drift from the deployed SDK:\n\n1. Call `search_sdk` with the service name immediately before acting. It returns installed and installable connectors, declared feed keys, readiness, and the caller-aware live lifecycle. Then, before requesting app credentials, call `client.connections.setupOptions({ connector_key })` against the selected runtime: it discovers verified cloud-managed OAuth and hosted chat alongside local setup, so follow the URLs and instructions it returns. `cloud_status: \"unavailable\"` is a discovery outage, not evidence that managed auth is absent. Options are offers, not connected accounts.\n2. Always follow the methods it returns in order instead of relying on a remembered connect/feed/operation sequence. Repeat discovery after authorization or state changes so the next step reflects the live connector and current caller.\n3. Treat `access: operate` as `mcp:write` and `access: administer` as workspace owner/admin plus `mcp:admin`. If discovery asks for MCP reauthorization or an owner/admin handoff, follow that instruction; never attempt methods it withheld as unavailable.\n\nSource-backed feeds query the provider only through an explicit `client.feeds.readMany({ reads: [...] })` call; `search_memory` stays local and reports unqueried source feeds in `coverage`, while `client.feeds.get` returns metadata without source access. Feeds with `sync` may persist events for search and relational queries. For connector actions, use the live discovery result's operation target and readiness. If readiness is disconnected, follow the returned next action instead of guessing a connection. Surface approval-gated `pending_approval` as a waiting state, not a failure.\n\n## Data Ingestion\n\n- Use `lobu memory seed` for small declarative YAML datasets under `./data`; it processes records sequentially and is not a bulk-backfill path.\n- Use `client.knowledge.save` for schema-less semantic history such as messages, notes, observations, and content. Pass `supersedes_event_id` when replacing an existing fact.\n- Use `client.entities.create` / `client.entities.update` only for strict structured records that match declared entity schemas.\n- For large backfills, send bounded chunks through `run_sdk` / `lobu call run_sdk` and use `Promise.allSettled` so conflicts and partial failures remain visible.\n\n```ts\nexport default async (_ctx, client) => {\n const records = [\n { content: \"...\", semantic_type: \"note\" },\n { content: \"...\", semantic_type: \"observation\" },\n ];\n return Promise.allSettled(records.map((record) => client.knowledge.save(record)));\n};\n```",
|
|
12
12
|
"hidden": false
|
|
13
13
|
}
|
|
14
14
|
},
|
package/dist/component.json
CHANGED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
-- migrate:up
|
|
2
|
+
-- lobu:no-quiesce (additive and weaker than the constraint it will replace: every row the running code inserts already satisfies it)
|
|
3
|
+
--
|
|
4
|
+
-- First of three steps that drop events.linked_org_ids, the retired
|
|
5
|
+
-- cross-workspace bridge that nothing has read or written since
|
|
6
|
+
-- 20261114120000. events_unbound_tool_audit names that column, so dropping
|
|
7
|
+
-- the column would silently drop the constraint too. This adds its
|
|
8
|
+
-- replacement, identical except for the linked_org_ids term.
|
|
9
|
+
--
|
|
10
|
+
-- OPERATIONAL COST: catalog-only. ACCESS EXCLUSIVE on events for the catalog
|
|
11
|
+
-- update, bounded by the 5s lock wait. NOT VALID skips the table scan; the
|
|
12
|
+
-- next migration validates under a lock that does not block reads or writes.
|
|
13
|
+
SET LOCAL lock_timeout = '5s';
|
|
14
|
+
|
|
15
|
+
DO $$
|
|
16
|
+
BEGIN
|
|
17
|
+
IF NOT EXISTS (
|
|
18
|
+
SELECT 1 FROM pg_constraint
|
|
19
|
+
WHERE conrelid = 'public.events'::regclass
|
|
20
|
+
AND conname = 'events_unbound_tool_audit_owned'
|
|
21
|
+
) THEN
|
|
22
|
+
ALTER TABLE public.events ADD CONSTRAINT events_unbound_tool_audit_owned CHECK (
|
|
23
|
+
organization_id IS NOT NULL OR (
|
|
24
|
+
semantic_type = 'audit' AND origin_type IS NOT DISTINCT FROM 'tool_invocation'
|
|
25
|
+
AND COALESCE(cardinality(entity_ids), 0) = 0
|
|
26
|
+
AND connector_key IS NULL AND connection_id IS NULL
|
|
27
|
+
AND feed_key IS NULL AND feed_id IS NULL AND run_id IS NULL
|
|
28
|
+
AND automation_id IS NULL AND automation_version_id IS NULL
|
|
29
|
+
AND identity_ns IS NULL AND identity_key IS NULL
|
|
30
|
+
AND supersedes_event_id IS NULL AND superseded_by IS NULL
|
|
31
|
+
AND interaction_type = 'none'
|
|
32
|
+
)
|
|
33
|
+
) NOT VALID;
|
|
34
|
+
END IF;
|
|
35
|
+
END $$;
|
|
36
|
+
|
|
37
|
+
-- migrate:down
|
|
38
|
+
-- lobu:no-quiesce
|
|
39
|
+
SET LOCAL lock_timeout = '5s';
|
|
40
|
+
ALTER TABLE public.events DROP CONSTRAINT IF EXISTS events_unbound_tool_audit_owned;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
-- migrate:up
|
|
2
|
+
-- lobu:no-quiesce (validation changes nothing the running code can observe)
|
|
3
|
+
--
|
|
4
|
+
-- Second step: validate the replacement constraint on its own, so the scan
|
|
5
|
+
-- does not run inside a transaction that also holds ACCESS EXCLUSIVE.
|
|
6
|
+
--
|
|
7
|
+
-- OPERATIONAL COST: one sequential scan of events under SHARE UPDATE
|
|
8
|
+
-- EXCLUSIVE, which blocks neither reads nor writes. Estimated at about 11s on
|
|
9
|
+
-- production (10 GB heap, 8.86M rows), extrapolated from a 3% sample scan that
|
|
10
|
+
-- took 339 ms; not timed end to end. The statement timeout there is 60s. If it
|
|
11
|
+
-- times out, run the statement by hand with `SET statement_timeout = 0` and
|
|
12
|
+
-- record the version.
|
|
13
|
+
-- squawk-ignore prefer-robust-stmts -- a single statement the runner wraps in its own transaction; validating twice is harmless
|
|
14
|
+
ALTER TABLE public.events VALIDATE CONSTRAINT events_unbound_tool_audit_owned;
|
|
15
|
+
|
|
16
|
+
-- migrate:down
|
|
17
|
+
-- lobu:no-quiesce
|
|
18
|
+
-- Validation has nothing to undo; the previous migration's down drops the constraint.
|
|
19
|
+
SELECT 1;
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
-- migrate:up
|
|
2
|
+
-- lobu:no-quiesce -- requires 20261114120000's release to be fully deployed first: code before it inserts and reads the column.
|
|
3
|
+
--
|
|
4
|
+
-- Third step: drop events.linked_org_ids. Event visibility is owner-only
|
|
5
|
+
-- (events.organization_id), so the column, its two GIN indexes
|
|
6
|
+
-- (idx_events_linked_org_ids, idx_events_live_linked_org_ids) and its
|
|
7
|
+
-- projection in current_event_records have no reader or writer left. The
|
|
8
|
+
-- indexes and the old events_unbound_tool_audit constraint go with the column;
|
|
9
|
+
-- the validated replacement takes over the constraint's name.
|
|
10
|
+
--
|
|
11
|
+
-- The view is rebuilt because CREATE OR REPLACE VIEW cannot remove a column.
|
|
12
|
+
-- Table and surviving column grants, including grant options, are read before
|
|
13
|
+
-- the drop and reapplied, so roles granted outside the migrations keep access.
|
|
14
|
+
--
|
|
15
|
+
-- OPERATIONAL COST: catalog-only, no row rewrite. ACCESS EXCLUSIVE on events
|
|
16
|
+
-- and the view until the transaction commits, bounded by the 5s lock wait. Not
|
|
17
|
+
-- timed at production size.
|
|
18
|
+
SET LOCAL lock_timeout = '5s';
|
|
19
|
+
|
|
20
|
+
DO $rebuild$
|
|
21
|
+
DECLARE
|
|
22
|
+
regrants text[];
|
|
23
|
+
stmt text;
|
|
24
|
+
BEGIN
|
|
25
|
+
SELECT COALESCE(array_agg(format(
|
|
26
|
+
'GRANT %s ON public.current_event_records TO %s%s',
|
|
27
|
+
acl.privilege_type,
|
|
28
|
+
CASE WHEN acl.grantee = 0 THEN 'PUBLIC'
|
|
29
|
+
ELSE quote_ident(pg_get_userbyid(acl.grantee)) END,
|
|
30
|
+
CASE WHEN acl.is_grantable THEN ' WITH GRANT OPTION' ELSE '' END)), '{}')
|
|
31
|
+
INTO regrants
|
|
32
|
+
FROM pg_class c
|
|
33
|
+
CROSS JOIN LATERAL aclexplode(c.relacl) acl
|
|
34
|
+
WHERE c.oid = to_regclass('public.current_event_records')
|
|
35
|
+
AND acl.grantee <> c.relowner;
|
|
36
|
+
|
|
37
|
+
SELECT regrants || COALESCE(array_agg(format(
|
|
38
|
+
'GRANT %s (%I) ON public.current_event_records TO %s%s',
|
|
39
|
+
acl.privilege_type,
|
|
40
|
+
a.attname,
|
|
41
|
+
CASE WHEN acl.grantee = 0 THEN 'PUBLIC'
|
|
42
|
+
ELSE quote_ident(pg_get_userbyid(acl.grantee)) END,
|
|
43
|
+
CASE WHEN acl.is_grantable THEN ' WITH GRANT OPTION' ELSE '' END)), '{}')
|
|
44
|
+
INTO regrants
|
|
45
|
+
FROM pg_class c
|
|
46
|
+
JOIN pg_attribute a ON a.attrelid = c.oid
|
|
47
|
+
CROSS JOIN LATERAL aclexplode(a.attacl) acl
|
|
48
|
+
WHERE c.oid = to_regclass('public.current_event_records')
|
|
49
|
+
AND a.attnum > 0 AND NOT a.attisdropped
|
|
50
|
+
AND a.attname <> 'linked_org_ids'
|
|
51
|
+
AND acl.grantee <> c.relowner;
|
|
52
|
+
|
|
53
|
+
DROP VIEW IF EXISTS public.current_event_records;
|
|
54
|
+
|
|
55
|
+
-- squawk-ignore ban-drop-column -- contract phase; nothing reads or writes the column since 20261114120000
|
|
56
|
+
ALTER TABLE public.events DROP COLUMN IF EXISTS linked_org_ids;
|
|
57
|
+
|
|
58
|
+
IF EXISTS (
|
|
59
|
+
SELECT 1 FROM pg_constraint
|
|
60
|
+
WHERE conrelid = 'public.events'::regclass
|
|
61
|
+
AND conname = 'events_unbound_tool_audit_owned'
|
|
62
|
+
) THEN
|
|
63
|
+
ALTER TABLE public.events DROP CONSTRAINT IF EXISTS events_unbound_tool_audit;
|
|
64
|
+
ALTER TABLE public.events
|
|
65
|
+
RENAME CONSTRAINT events_unbound_tool_audit_owned TO events_unbound_tool_audit;
|
|
66
|
+
END IF;
|
|
67
|
+
|
|
68
|
+
CREATE VIEW public.current_event_records WITH (security_invoker = true) AS
|
|
69
|
+
SELECT e.id,
|
|
70
|
+
e.organization_id,
|
|
71
|
+
e.entity_ids,
|
|
72
|
+
e.origin_id,
|
|
73
|
+
e.title,
|
|
74
|
+
e.payload_type,
|
|
75
|
+
e.payload_text,
|
|
76
|
+
e.payload_data,
|
|
77
|
+
e.payload_template,
|
|
78
|
+
e.attachments,
|
|
79
|
+
e.metadata,
|
|
80
|
+
e.score,
|
|
81
|
+
e.author_name,
|
|
82
|
+
e.source_url,
|
|
83
|
+
e.occurred_at,
|
|
84
|
+
e.created_at,
|
|
85
|
+
e.origin_parent_id,
|
|
86
|
+
e.content_length,
|
|
87
|
+
e.search_tsv,
|
|
88
|
+
e.origin_type,
|
|
89
|
+
e.connector_key,
|
|
90
|
+
e.connection_id,
|
|
91
|
+
e.feed_key,
|
|
92
|
+
e.feed_id,
|
|
93
|
+
e.run_id,
|
|
94
|
+
e.semantic_type,
|
|
95
|
+
e.client_id,
|
|
96
|
+
e.created_by,
|
|
97
|
+
e.interaction_type,
|
|
98
|
+
e.interaction_status,
|
|
99
|
+
e.interaction_input_schema,
|
|
100
|
+
e.interaction_input,
|
|
101
|
+
e.interaction_output,
|
|
102
|
+
e.interaction_error,
|
|
103
|
+
e.supersedes_event_id,
|
|
104
|
+
e.identity_ns,
|
|
105
|
+
e.identity_key,
|
|
106
|
+
e.automation_id,
|
|
107
|
+
e.automation_version_id
|
|
108
|
+
FROM public.events e
|
|
109
|
+
WHERE e.superseded_by IS NULL;
|
|
110
|
+
|
|
111
|
+
FOREACH stmt IN ARRAY regrants LOOP
|
|
112
|
+
EXECUTE stmt;
|
|
113
|
+
END LOOP;
|
|
114
|
+
END $rebuild$;
|
|
115
|
+
|
|
116
|
+
-- migrate:down
|
|
117
|
+
-- Forward-only: the column was write-once, computed from other rows at insert,
|
|
118
|
+
-- and nothing read it by the time it was dropped. Restoring an empty column
|
|
119
|
+
-- would serve no code.
|
|
@@ -3211,7 +3211,7 @@ var init_package = __esm({
|
|
|
3211
3211
|
"package.json"() {
|
|
3212
3212
|
package_default = {
|
|
3213
3213
|
name: "@lobu/server",
|
|
3214
|
-
version: "24.11.
|
|
3214
|
+
version: "24.11.1",
|
|
3215
3215
|
private: true,
|
|
3216
3216
|
license: "BUSL-1.1",
|
|
3217
3217
|
type: "module",
|
|
@@ -11409,9 +11409,7 @@ var init_insert_event = __esm({
|
|
|
11409
11409
|
content_length: "version",
|
|
11410
11410
|
search_tsv: "version",
|
|
11411
11411
|
identity_ns: "chain",
|
|
11412
|
-
identity_key: "chain"
|
|
11413
|
-
// Retired: no longer written or read. The entry goes with the column drop.
|
|
11414
|
-
linked_org_ids: "version"
|
|
11412
|
+
identity_key: "chain"
|
|
11415
11413
|
};
|
|
11416
11414
|
INHERITED_COLUMNS = Object.keys(EVENT_SUPERSEDE_RULES).filter((column) => EVENT_SUPERSEDE_RULES[column] !== "version");
|
|
11417
11415
|
AUDIT_IDEMPOTENCY_INDEX = "idx_events_org_idempotency_key";
|
|
@@ -36284,12 +36282,38 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
|
|
|
36284
36282
|
AND ($6::int IS NOT NULL)
|
|
36285
36283
|
AND iwf.run_id = $6::int`;
|
|
36286
36284
|
const branches = [];
|
|
36285
|
+
const vectorScopeCtes = `vector_scope AS MATERIALIZED (
|
|
36286
|
+
SELECT f.id
|
|
36287
|
+
FROM current_event_records f
|
|
36288
|
+
${candidateFilterJoins}
|
|
36289
|
+
WHERE ${standardFiltersSQL}
|
|
36290
|
+
LIMIT ${EXACT_RECALL_SCOPE_LIMIT + 1}
|
|
36291
|
+
),
|
|
36292
|
+
vector_scope_size AS MATERIALIZED (
|
|
36293
|
+
SELECT COUNT(*) AS size FROM vector_scope
|
|
36294
|
+
),
|
|
36295
|
+
`;
|
|
36296
|
+
branches.push(`SELECT scoped.id FROM vector_scope scoped
|
|
36297
|
+
CROSS JOIN LATERAL (
|
|
36298
|
+
SELECT MIN(emb.embedding <=> ${vecParam}) AS dist
|
|
36299
|
+
FROM event_embeddings emb
|
|
36300
|
+
WHERE emb.event_id = scoped.id AND ${modelScopeFor("emb")}
|
|
36301
|
+
) nearest
|
|
36302
|
+
WHERE (SELECT size FROM vector_scope_size) <= ${EXACT_RECALL_SCOPE_LIMIT}
|
|
36303
|
+
AND (1 - nearest.dist) >= ${minSimilarityParam}
|
|
36304
|
+
ORDER BY nearest.dist
|
|
36305
|
+
LIMIT ${CANDIDATE_VECTOR_LIMIT}`);
|
|
36287
36306
|
branches.push(`SELECT id FROM (
|
|
36288
36307
|
SELECT emb.event_id AS id, (emb.embedding <=> ${vecParam}) AS dist
|
|
36289
36308
|
FROM event_embeddings emb
|
|
36290
|
-
JOIN
|
|
36291
|
-
|
|
36292
|
-
|
|
36309
|
+
JOIN LATERAL (
|
|
36310
|
+
SELECT f.id
|
|
36311
|
+
FROM current_event_records f
|
|
36312
|
+
${candidateFilterJoins}
|
|
36313
|
+
WHERE f.id = emb.event_id AND ${standardFiltersSQL}
|
|
36314
|
+
OFFSET 0
|
|
36315
|
+
) visible_event ON true
|
|
36316
|
+
WHERE (SELECT size FROM vector_scope_size) > ${EXACT_RECALL_SCOPE_LIMIT}
|
|
36293
36317
|
AND ${modelScopeFor("emb")}
|
|
36294
36318
|
AND (1 - (emb.embedding <=> ${vecParam})) >= ${minSimilarityParam}
|
|
36295
36319
|
ORDER BY emb.embedding <=> ${vecParam}
|
|
@@ -36315,7 +36339,7 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
|
|
|
36315
36339
|
}
|
|
36316
36340
|
branches.push(textCandidates(`ce.payload_text ILIKE '%' || $1 || '%'`, "ce.id + 0"));
|
|
36317
36341
|
}
|
|
36318
|
-
searchCandidatesCteSql =
|
|
36342
|
+
searchCandidatesCteSql = `${vectorScopeCtes}search_candidates AS (
|
|
36319
36343
|
${branches.map((b) => `(${b})`).join("\n UNION\n ")}
|
|
36320
36344
|
),
|
|
36321
36345
|
`;
|
|
@@ -36509,7 +36533,7 @@ async function searchContentBySingleQuery(sql2, queryText, options, env) {
|
|
|
36509
36533
|
...queryEmbeddingUnavailable && { query_embedding_unavailable: true }
|
|
36510
36534
|
};
|
|
36511
36535
|
}
|
|
36512
|
-
var QUERY_WORD_FREQUENCY_SQL;
|
|
36536
|
+
var EXACT_RECALL_SCOPE_LIMIT, QUERY_WORD_FREQUENCY_SQL;
|
|
36513
36537
|
var init_search_path = __esm({
|
|
36514
36538
|
"src/utils/content-search/search-path.ts"() {
|
|
36515
36539
|
"use strict";
|
|
@@ -36533,6 +36557,7 @@ var init_search_path = __esm({
|
|
|
36533
36557
|
init_types4();
|
|
36534
36558
|
init_entity_types_filter();
|
|
36535
36559
|
init_visibility();
|
|
36560
|
+
EXACT_RECALL_SCOPE_LIMIT = 4096;
|
|
36536
36561
|
QUERY_WORD_FREQUENCY_SQL = `
|
|
36537
36562
|
WITH stats AS MATERIALIZED (
|
|
36538
36563
|
SELECT s.most_common_elems::text::text[] AS elems, s.most_common_elem_freqs AS freqs
|
|
@@ -94415,6 +94440,16 @@ var init_multi_tenant = __esm({
|
|
|
94415
94440
|
401
|
|
94416
94441
|
);
|
|
94417
94442
|
}
|
|
94443
|
+
if (isPat && !authInfo.organizationId && (requestedOrgId || isMcpRoute || !isUnscopedRoute)) {
|
|
94444
|
+
return c.json(
|
|
94445
|
+
{
|
|
94446
|
+
error: "invalid_token",
|
|
94447
|
+
error_description: "PAT is not scoped to an organization \u2014 re-mint via `lobu token`"
|
|
94448
|
+
},
|
|
94449
|
+
401,
|
|
94450
|
+
{ "WWW-Authenticate": bearerChallenge("invalid_token") }
|
|
94451
|
+
);
|
|
94452
|
+
}
|
|
94418
94453
|
if (!isPat && authInfo.resource) {
|
|
94419
94454
|
const requestedResource = isMcpRoute ? getMcpResourceForRequest(publicMcpRequestUrl(c.req.raw)) : null;
|
|
94420
94455
|
if (!requestedResource || authInfo.resource !== requestedResource) {
|
|
@@ -169214,7 +169249,7 @@ var LOBU_SKILL_MARKDOWN;
|
|
|
169214
169249
|
var init_lobu_skill_generated = __esm({
|
|
169215
169250
|
"src/skills/lobu-skill.generated.ts"() {
|
|
169216
169251
|
"use strict";
|
|
169217
|
-
LOBU_SKILL_MARKDOWN = '---\nname: lobu\ndescription: "Set up new Lobu agents end to end and operate existing Lobu projects and memory: interview, scaffold, validate, authenticate, connect feeds, execute operations, and test Automations."\n---\n\n# Lobu\n\nUse this skill when setting up a brand-new Lobu agent from scratch (follow "Onboarding a New Project" below) or when running, validating, evaluating, or connecting an existing Lobu project, or operating Lobu memory from a coding agent.\n\nThe `AGENTS.md` generated into a new project is the source of truth for the config API (the `define*` helpers, connectors, auth, Automations, memory) \u2014 this skill does not duplicate it. For an existing project, jump to "Core Model" + the relevant reference section below.\n\n## Onboarding a New Project\n\nUse this playbook when a new user asks you to build them a Lobu agent from scratch. Set it up end to end: ground yourself in what the user already has, interview, discover, scaffold, prove the complete local path, then offer the deployment choice. Do not call the setup complete until every path the user selected has actually passed end to end. If an external provider, authorization, deployment, or rate limit blocks the proof, name the exact blocker and leave the setup as blocked rather than claiming success.\n\n### 1. Ground yourself in what the user already has\n\nBefore interviewing, look at what already exists so your questions and suggestions are personal rather than a blank slate. This is discovery, not a design decision \u2014 do not let it skip the interview.\n\n- Local: run `lobu context list` to see existing contexts (`--json` adds `loggedIn`, which reports stored credentials, not session validity); check the current directory and home for existing Lobu projects (`lobu.config.ts`), configured MCP servers, and CLI auth state. Note what the user already set up.\n- Cloud: if the user has an active session (do not create one just to look), call `client.organizations.list()`, `client.agents.list()` for each org, `client.catalog.listInstalled({ kinds: ["connectors"] })`, and `search_memory` for prior knowledge. This reveals existing agents, connectors, and memory you can build on.\n- Tell the user what you are looking at so they can correct you, and let what you find shape the options you offer. Never treat this discovery as an identity signal: orgs, emails, or domains never prove a company or product, and never mention a competitor or third party unless it actually appears in what you found.\n\nDo NOT ask for a login email during the interview. Email is only needed when a managed connector actually requires a session (step 3) or when the user chooses cloud deployment (step 6); ask for it at that point. Treat identity only as identity; never infer a company from an email address or domain.\n\n### 2. Interview with concrete, personalized options\n\nInterview the user one question at a time; wait for each answer, do not guess, and do not batch the questions. Anchor each question in what you found in step 1. Instead of asking "what agent do you want?" as a blank slate, summarize what you see and offer two or three concrete alternatives to choose from:\n\n- "You already have org X with connectors A and B installed and N existing agents. Do you want to (a) add a new agent on top of those, (b) extend one of the existing agents, or (c) start something standalone?"\n- "For what it should do, the common shapes are (a) a triage agent that reads incoming chat and files a ticket, (b) a scheduled report that summarizes new activity each morning, (c) a research agent that answers questions from your connected tools. Which fits, or what would you change?"\n\nOffer a default so the user can answer "the first one" \u2014 decisive users and undecided users both move faster with a concrete menu.\n\n- What company or product is this for?\n- What does it do, and who does it serve?\n- What is its public domain? (optional for a personal project)\n- Do I have permission to research the public website and other public sources?\n- What is the agent for?\n- What should we call it?\n- Who uses it: just me, my team, or each of my customers?\n- How should it behave, and what may it do unattended versus only with approval?\n- What should it remember? Model this as one to three entity types.\n- Where does its data come from? Pick one connector or custom source to start.\n- Where should people talk to it? Offer Web UI, API or SDK, MCP, Slack, Teams, WhatsApp, Discord, Google Chat, and Telegram without forcing a chat platform. If Slack is chosen, ask whether to join Lobu\'s hosted workspace for a quick start, install Lobu into an existing workspace, or use a custom Slack app; then ask whether to test the DM with Lobu, a named channel, or both, and whether people knowledge means conversation participants, bound-channel members, or the full workspace directory.\n- Should anything run on a schedule?\n- Which supported LLM provider credential does the user have?\n\nIf the user gave permission to research and has a public domain, research the company before proposing the design. Summarize its product, customers, workflows, and useful signals, and cite the public sources you used. Then propose one to three entity types, their relationships, the first data source, one or two useful Automations, and suitable interaction channels. Play back a short numbered plan and wait for confirmation before scaffolding anything.\n\n### 3. Discover the surface before choosing how to scaffold\n\nCheck Node is 26.x, then run `lobu context list` and identify the named Lobu Cloud context; do not assume the active context still points to cloud after a local run. If a managed or cloud connector was chosen and there is no session, ask for the login email at that point, explain that Lobu will email an approval link, and run `lobu login --email <confirmed-address> --context <cloud-name>`. The person approving must sign in with that same email; knowing an address never grants access. After a successful login, an empty organization membership list is a tenancy/discovery result, not an authentication failure: call `client.organizations.list()` and explain the result. Never revoke or repeat login with `--force` unless the user separately approves that re-authentication.\n\nUse ClientSDK through Lobu MCP with the explicit cloud context. From the CLI, account discovery works before selecting an active org with `lobu memory run query_sdk \'{"title":"Find managed connection providers","script":"export default async (_ctx, client) => client.organizations.list()"}\'`; `lobu call` over REST requires an active org. Call `client.organizations.list()` to find public organizations offering managed connections. Call `client.catalog.listInstalled({ kinds: ["connectors"] })`; if the connector is not installed, call `client.catalog.listCatalog({ kinds: ["connectors"] })`. Inspect the selected entry\'s `detail.auth_schema`, `detail.options_schema`, `detail.feeds_schema`, and `detail.automation_events` instead of guessing field names. On account-scoped `/mcp`, select an authorized home workspace first with `const home = await client.org(homeSlug)` and call `home.connections.connectManaged`; put the public provider org in `managed_by_org`, rather than selecting that provider org with `client.org`. This call runs against cloud, not the embedded runtime. If a matching live managed offer exists, explain it and call `client.connections.connectManaged` only after consent. Complete the returned user authorization, then run `lobu context use <cloud-name>` immediately before executing its `local_bootstrap_command` from the parent directory where the new project should be created; use `--here` only after entering an empty directory, and do not create a blank Lobu scaffold first. Ask for bring-your-own OAuth credentials only if no managed offer exists or the user prefers their own app.\n\n**If no connector in the catalog matches the data source, do not report "no integration exists"** \u2014 author a custom connector: write `connectors/<name>.connector.ts` in the project, register it with `connectorFromFile("./connectors/<name>.connector.ts")`, and model it on the [npm downloads example](https://github.com/lobu-ai/lobu/blob/main/examples/lobu-crm/npm-downloads.connector.ts). See [Connector authoring](https://github.com/lobu-ai/lobu/blob/main/docs/connector-authoring.md) for the full contract; the end-to-end entity/event/Automation model is in [Lobu concepts](https://github.com/lobu-ai/lobu/blob/main/docs/CONCEPTS.md).\n\n### 4. Scaffold and build from the confirmed plan\n\nIf managed auth supplied a `local_bootstrap_command`, use the project it generated. Otherwise run `npx @lobu/cli@latest init` with the confirmed name and provider. Postgres is built in, so `lobu run` starts an embedded database; ask for `DATABASE_URL` only if the user chooses external Postgres. Read the generated `AGENTS.md` completely before editing `lobu.config.ts`. Use the canonical reference at `https://github.com/lobu-ai/lobu/blob/main/examples/lobu-crm/lobu.config.ts` when needed; do not assume that example exists in the new project\'s filesystem. Briefly explain how the chosen feed may use checkpoints to collect incrementally, emits events, builds shared entity memory, and gives both chat and Automations the same governed context.\n\n`feeds_schema.<feed>.eventKinds` are the default Automation trigger catalog for feed connectors: every declared kind is a subscribable event type (`event_type` = the kind slug) for any feed that emits the kind. A feed\'s first successful non-dry sync establishes its baseline without activation; later inserts of a matching kind activate subscribers. A kind with `updatedEvent: true` also offers `<kind>.updated` for supersedes whose `occurred_at` strictly advances past the previous head. The original kind stays insert-only; unchanged rows, volatile-only updates and same-time reformats stay quiet. Subscribe to both types for new items and later activity. Feed-scoped filtering is not yet available (events dedupe by connection + origin id, so a `feed_key` match would miss origins first seen by another feed). `automation_events` (now derived from eventKinds when a connector declares none) is the trigger picker\'s list. If no declared kind matches the use case, use a scheduled Automation with a bounded named SQL source and read event text from `payload_text`. Validate the query against the running local schema before relying on it. If `feeds_schema` is empty, do not invent or trigger a feed; chat integrations such as Slack can deliver incoming messages directly. For Slack or Telegram, prefer `defineConnection` with `credentialMode: "hosted"` so no bot token is required; `lobu run` prints the exact hosted-workspace join URL, own-workspace install URL when available, and short-lived link command. This hosted chat path requires a cloud session and the agent applied to that cloud workspace; the link targets the cloud agent. It does not create a local Slack data connection or prove local Slack search. Use those returned values instead of constructing URLs. A printed `/lobu link <code>` is one-time: redeem it in the first selected DM or channel. In an installed workspace whose installer is linked to Lobu, bind each additional surface with `/lobu link <agent-id>`; otherwise generate a fresh code for that surface. Mention Lobu in a channel test and verify the App Home separately. Lobu email login and Slack installation are separate: the email link authorizes Lobu CLI access, while an existing-workspace install requires the user or workspace admin to approve Slack\'s OAuth screen. Never describe Slack consent as an email approval. Use `credentialMode: "byo"` only if the user chooses their own app. Tell the user once which remaining secrets are required and add only `secret("ENV_NAME")` placeholders to config. Never open or request permission to read `.env`; inspect `.env.example` when present and declared secret placeholder names only. Never read, print, invent, or paste a real secret into source or chat.\n\nIf the user wants the agent to know people in Slack, ask whether that means conversation participants, members of bound channels, or the full workspace directory. Installing the app proves none of those by itself. Verify the selected scope by inspecting the people or member entities Lobu actually materialized and by asking the agent a roster question. If human-readable names or non-participants are unavailable, identify that exact product gap; never claim the complete workspace directory was synced.\n\n### 5. Prove the complete local path\n\nChange into the generated project directory and verify `pwd` contains the intended `lobu.config.ts`; never run project commands from its parent. Run `npx @lobu/cli@latest validate`, boot with `npx @lobu/cli@latest run`, and verify health and the local Web UI. With the embedded database default, `lobu run` creates and selects the local context and auto-applies the project; with an external `DATABASE_URL`, it does neither, so authenticate and apply to that runtime explicitly. Send a harmless direct chat message without tools.\n\nBefore consent to access provider data, inspect only catalog, connection, auth-profile, and feed metadata. For browser access, inspect the paired device and connection metadata without invoking browser actions. Durable managed OAuth and env-profile credentials stay at the gateway. Do not run a feed or connector dry-run before consent, because a dry-run may still read provider data. Ask explicitly before accessing real provider data. Only after approval, dry-run the connector or feed server-side and trigger the selected feed manually if that connector actually declares one. A feed dry-run records its run but persists no collected events, entities, attachments, checkpoint changes, or feed sync state. Run each Automation once, poll `client.operations.getRun` with its returned `run_id`, and show each completed run plus any declared result event or entity. For a run-result-only or reaction-only Automation, use the completed run and the Automation `view_url` returned by Lobu. For Slack, treat DM, channel mention, App Home, and requested member discovery as four separate checks. Keep actions in approval mode unless the user explicitly approves execution. If any step fails, fix it and rerun that step; do not silently substitute a different path.\n\n### 6. Offer the deployment choice\n\nAfter the local proof, ask the user whether to keep running locally or deploy to Lobu Cloud. Explain that the embedded local runtime and Lobu Cloud are separate targets, and that keeping it local needs no further setup. Only if the user chooses cloud deployment, ask for the login email to identify the deployer, explain that Lobu will email an approval link, and run `lobu login --email <confirmed-address> --context <cloud-name>`; the person approving must sign in with that same email. Because `lobu apply` has no context flag, use `lobu context list` and then `lobu context use <cloud-name>` to select an explicit cloud context before deployment. Run `lobu apply --dry-run` first, show the target organization and exact plan, and wait for confirmation before applying. After apply, use only authoritative `view_url` values and link commands returned by Lobu; never construct URLs. Present the working access choices: Web UI, direct agent chat, API or SDK, MCP, and any channels the user selected.\n\n## Core Model\n\n- **Lobu** is the agent framework, runtime, deployment layer, and memory surface.\n- Keep framework configuration in `lobu.config.ts` (TypeScript, `defineConfig` from `@lobu/cli/config`).\n- Keep agent identity and instructions in `IDENTITY.md`, `SOUL.md`, and `USER.md`.\n- Keep reusable capability bundles in `skills/<name>/SKILL.md` or `agents/<agent>/skills/<name>/SKILL.md`.\n- Use `lobu login` for CLI authentication. Do not use a separate memory login command.\n- Use `lobu connect` for MCP client and skill setup.\n- Use `lobu memory ...` for memory operations, seeding, and direct tool calls.\n\nReference the canonical docs before guessing how a feature works:\n[Lobu concepts](https://github.com/lobu-ai/lobu/blob/main/docs/CONCEPTS.md)\n(entities vs events, identity, end-to-end lifecycle),\n[Automations](https://github.com/lobu-ai/lobu/blob/main/docs/AUTOMATIONS.md)\n(trigger/source/output contract), and\n[Connector authoring](https://github.com/lobu-ai/lobu/blob/main/docs/connector-authoring.md)\n(custom connectors).\n\n## Project Checklist\n\n1. Read `lobu.config.ts` first.\n2. Read the active agent files under `agents/<id>/`.\n3. Check local skills under `skills/` and `agents/<id>/skills/`.\n4. Use `lobu validate` after config changes.\n5. Discover the live SDK and connector surface with `search_sdk`; never guess a method, connector key, feed key, connection id, or operation key.\n6. When prompt or Automation changes, run evals via promptfoo (see `examples/personal-finance/evals/promptfooconfig.yaml`). The in-house `lobu eval` command has been removed.\n\n## Common Commands\n\n```bash\nnpx @lobu/cli@latest init my-agent\nnpx @lobu/cli@latest run\nnpx @lobu/cli@latest validate\nnpx @lobu/cli@latest login\n```\n\n## Authentication\n\n- Interactive (human at a terminal): `lobu login` runs the device-code flow with a browser approval.\n- CI / your own automation: `LOBU_API_TOKEN`, or `lobu login --token <pat>`.\n- Local `lobu run`: the CLI mints credentials automatically over loopback \u2014 no prompt.\n- Headless, on a *user\'s* behalf: `lobu login --email <address>`. The server emails the user a one-click approval link and the CLI polls until they approve, then stores the scoped credential \u2014 no TTY, no pre-minted token. This is the auth.md "user_claimed" flow.\n\nAn external agent not using this CLI can drive the same flow over HTTP: read `<origin>/auth.md` (linked from the `agent_auth` block in `<origin>/.well-known/oauth-authorization-server`) for the endpoints. Today only the email user_claimed flow exists (no zero-touch ID-JAG). Never fabricate a token.\n\n## Organization Deletion\n\nTreat organization deletion as permanent and restricted to organization owners. The supported path is the **Organization settings** page, opened from that workspace\'s settings button in the organization switcher. ClientSDK and Lobu CLI intentionally expose no organization-delete method. When asked to delete organizations, identify each exact target and its data impact read-only, surface one production organization at a time for explicit confirmation, then direct an owner to that page or use their logged-in browser only when explicitly authorized. Never invent a hosted URL, call the raw Better Auth route, bypass a failed authorization check, delete organization rows directly, or batch confirmations.\n\nCloud CLI OAuth/PAT credentials are not a Better Auth browser session. A `401` or `403` is a stop signal: report the authorization boundary and leave the organization intact.\n\n<!-- lobu-memory-guidance:start -->\n## Memory Defaults\n\nYour long-term memory is powered by Lobu. Do NOT use local files (memory/, MEMORY.md) for memory.\n- Lobu automatically recalls relevant memories when you receive a message.\n- To save something, call save_memory with the content and an appropriate semantic_type.\n- To search, call search_memory. Results include view_url links to the web interface.\n- NEVER construct Lobu URLs yourself. When the user asks for a link, call search_memory to get the correct view_url.\n- When the user says "remember this", save it to Lobu immediately.\n- When a message changes a fact you already stored (an updated preference, status, count, location, or plan), first search_memory for the prior memory to get its id, then save_memory the new value with supersedes_event_id set to that id. This replaces the stale value so future recalls return the current one; the old value stays in history but is hidden from normal search.\n<!-- lobu-memory-guidance:end -->\n\n## Lobu Memory\n\nConfigure project-scoped memory in `lobu.config.ts` by setting the org on `defineConfig` and declaring the schema with the `define*` helpers:\n\n```ts\nimport { defineConfig, defineEntityType } from "@lobu/cli/config";\n\nconst ticket = defineEntityType({\n key: "ticket",\n name: "Ticket",\n properties: {\n subject: {\n type: "string",\n title: "Subject",\n "x-table-label": "Subject",\n "x-table-column": true,\n },\n },\n});\n\nexport default defineConfig({\n org: "my-org",\n orgName: "My workspace",\n agents: [/* ... */],\n entities: [ticket],\n});\n```\n\nThe entity schema also renders the record page form. Give every array `items` and every object `properties` (bare ones render as raw JSON), put the label in `title` and help text in `description`, mark derived fields `readOnly: true`, and declare every field an Automation writes.\n\nFor a "when did this field last change" timestamp, declare root `metadata_schema["x-lobu-stamps"]: { "stage_at": "stage" }` instead of writing it from an Automation. The stamp field must be a declared `{ type: "string", format: "date-time" }` property (not listed in `required`) and the tracked field a declared property. Every writer (agent, SDK, Automation, connector projection, view action, approval) then gets it for free: the server sets `stage_at` when a record is created with `stage` set or when `stage` changes value, and discards any value a caller sends for `stage_at`. `readOnly` alone is presentation only; it is not enforced.\n\nSeed data records still live as YAML under `./data`. Then seed or operate the memory workspace with:\n\n```bash\nlobu login\nlobu memory org set <org-slug>\nlobu memory health --org <org-slug>\nlobu memory seed --org <org-slug>\nlobu memory run search_memory \'{"query":"Acme"}\' --org <org-slug>\n```\n\nUse `search_memory` first when the user asks about a specific entity or workspace memory. Use `save_memory` to persist durable memory. To update existing knowledge, search first, then save with `supersedes_event_id` so the old row is tombstoned rather than deleted.\n\n## MCP Client Setup\n\nUse the actual MCP URL for the user\'s runtime. Never hardcode a hosted URL unless the user explicitly asks for that instance.\n\nCommon setup commands:\n\n```bash\n# Claude Code\nlobu connect claude-code --url <mcp-url>\n\n# Codex\nlobu connect codex --url <mcp-url>\n\n# Antigravity\nlobu connect antigravity --url <mcp-url>\n\n# OpenCode\nlobu connect opencode --url <mcp-url>\n```\n\nRun `lobu connect --url <mcp-url>` without a client id to choose interactively. For ChatGPT, Claude Desktop, Cursor, and other browser-managed clients, the same command applies the safe local configuration it can and prints the exact remaining client handoff. Complete OAuth in the client, not through a separate Lobu CLI login.\n\n## Browser-Authenticated Connectors\n\nFor connectors that need a signed-in browser, pair the Owletto Chrome extension\nand sign in on the source site in that browser. Browser operations run through\nthat paired device; external remote-debugging endpoints and CLI browser-auth\ncapture are no longer supported.\n\nNothing answers a JS dialog (alert, confirm, prompt, beforeunload) on the\nagent\'s behalf. A browser action it blocks fails, and the failed result\'s\n`output` carries `tab_id` and `dialog` (`dialog_id`, `type`, `message`). In\n`run_sdk`, catch the `operations.execute` error and read `error.details.output`\nrather than parsing the error text (an uncaught failure returns the same value\nas the `run_sdk` result\'s `error.details`, and a background run\'s\n`operations.getRun` returns the same `output`), then answer with the\nconnection\'s `handle_dialog` operation. An unanswered dialog is handed to the user after two minutes.\n\nTo test a configured feed without writing ingested data, discover the current\nfeed methods with `search_sdk`, then use `client.feeds.trigger({ feed_id, dry_run: true })`\nthrough `run_sdk` or `lobu call run_sdk` (with a `title` arg). Inspect `client.feeds.get({ feed_id })`\nfor the completed run\'s preview. The dry run uses normal device routing and\nauthorization checks and may access the upstream provider, so obtain consent first.\n\n## Agent-Facing Tool Surface\n\nThe normal MCP surface is intentionally small. Flat administrative tools are not advertised to agents; compose through these tools instead:\n\n- `search_memory` and `save_memory` for direct knowledge recall and persistence.\n- `search_sdk` to discover current ClientSDK methods, signatures, connector feed keys, operations, access requirements, and examples. Pass `mode: "read"` when you only need methods safe for `query_sdk`.\n- `query_sdk` for read-only TypeScript and `query_sql` for governed, paginated SQL reads.\n- `run_sdk` for mutations and external operations. Use `lobu call run_sdk --arg title=\'\u2026\' --arg script=\'\u2026\'` from the CLI for the same ClientSDK scripting workflow; `run_sdk`, `query_sdk`, and `query_sql` calls need a short `title` naming them in the activity feed.\n\nSearch before create to avoid duplicates. Prefer a read or dry run before mutations, never fabricate returned URLs or identifiers, and never delete from `events`; supersede or tombstone instead.\n\n## Custom Views\n\nBefore authoring UI, inspect available native entity/event pages, existing views (`client.views.list()` and `client.views.get({ key })`), and the project\'s shared components and overrides. Honor explicit user designs and reuse UI from the top down:\n\n1. Use the largest existing surface or component that meets the task. Configure its segment, filters, search, saved preset and layout before replacing its UI.\n2. If that surface cannot meet a concrete requirement, compose its exported parts, such as an individual table, board, graph or shared collection controls when available. Preserve shared selection and action handling instead of rebuilding that logic.\n3. If those parts still do not fit, use smaller shared primitives and write custom UI only for the remaining gap. Explain the unmet requirement that forced each step down.\n\nCheck the current exports and target host before choosing an import; native renderer registrations do not imply React exports. Surface a missing export as a platform gap rather than inventing an API or silently copying the native implementation. `@lobu/views/components` currently supplies theme-aware defaults such as `Card`, `DataTable`, filters, charts, links and query-state components. `LoadingState` draws skeleton lines in the host\'s style; `Skeleton` is a pulsing block to size like the content it stands for (a figure, a row, a chart), so a slow read keeps the page\'s shape instead of showing text. When exploration needs specialized linked charts, drilldowns, scenario controls or Canvas/SVG, compose a React view from the suitable existing components.\n\nNative JSON templates use the target renderer\'s registered component names and overrides; inspect what that host actually supplies. React views compose imported components in their own bundle, independently of that native renderer map.\n\nViews are custom React panels attached to entity types, records, events, or the workspace Data hub. They render in the web app and MCP hosts (Claude and other MCP Apps hosts); chat channels get links to views, not the views themselves. Author them in `views/<type>/<key>.tsx` and ship with `lobu apply` (list them via `viewFromFile` in `defineConfig`), or set sources over MCP with `client.views.set` (owner/admin only).\n\nModule shape (the server resolves React, React DOM, `@lobu/views` and `@lobu/views/components`; other dependencies need the CLI path with `node_modules` present):\n\n```tsx\nimport { defineView, tool, useAction, useParams, useQuery } from "@lobu/views";\nimport {\n Card,\n DataTable,\n EmptyState,\n ErrorState,\n FilterBar,\n LoadingState,\n SearchField,\n TruncatedNotice,\n} from "@lobu/views/components";\n\nexport const view = defineView({\n key: "pipeline",\n attach: [{ collection: "deal" }],\n params: { stage: { type: "string", default: "open" } },\n actions: { markWon: { emits: "deal.won" } },\n});\n\nexport default function Pipeline() {\n const [params, setParams] = useParams();\n const deals = useQuery(tool("manage_entity", { action: "list", entity_type: "deal", filters: [{ field: "stage", op: "eq", value: String(params.stage) }], limit: 100 }));\n const markWon = useAction("markWon");\n const rows = deals.data?.entities ?? [];\n // Keep the filter mounted across query states: an early return on\n // loading/error would unmount the focused input on every keystroke\n // (each keystroke re-queries). Render states inline instead.\n return (\n <Card\n title="Pipeline"\n actions={<button type="button" onClick={() => markWon({})}>Mark won</button>}\n >\n <FilterBar><SearchField label="Stage" value={String(params.stage)} onChange={(v) => setParams({ stage: v })} /></FilterBar>\n {deals.loading && <LoadingState text="Loading deals\u2026" />}\n {deals.error && <ErrorState message={deals.error} errorCode={deals.errorCode} />}\n {!deals.loading && !deals.error && rows.length === 0 && (\n <EmptyState title="No deals in this stage." />\n )}\n {!deals.loading && !deals.error && rows.length > 0 && (\n <DataTable columns={[{ key: "name", header: "Name" }]} rows={rows} keyOf={(r) => r.id ?? r.slug} />\n )}\n {deals.truncated && <TruncatedNotice shown={rows.length} />}\n </Card>\n );\n}\n```\n\n`defineView` is the view\'s only declaration: `key`, optional `name` (defaults to the key) and `description`, `attach`, `params`, `actions` and `resources` are read from it, never passed separately. `views.set` always requires `source_code` containing the entrypoint module, including when retaining multiple files. Write `defineView` out as a literal (no variables, spreads or `${}` templates): the server reads it without running the module.\n\nA view makes no network requests of its own; data comes through `useQuery`. The one exception is images: `resources: ["https://tile.openstreetmap.org"]` declares origins the view may load images (map tiles, logos) from. Each entry is a bare `https://` origin with a public hostname (no path, wildcard, localhost or IP), at most 8. The images-only limit is a save-time check: `views.set` renders the view\'s empty, error and loading states in an offline browser and refuses the save if anything other than an image from a declared origin is requested. It is not enforced at runtime. MCP hosts receive the origins as the MCP Apps `resourceDomains` CSP, which allows scripts, styles, fonts and media from them as well as images, and the Lobu web app applies no runtime CSP to views. Declare only image or tile CDN origins you trust. Hosts that render through the generic `ui://lobu/views` loader use its CSP, which declares no image origins, so declared images may not load there.\n\nFor a multi-file view, `files` maps relative paths to complete source strings and `entrypoint` names the view module. Include all three inputs below; `source_code` must exactly equal `files[entrypoint]`:\n\n```ts\nawait client.views.set({\n source_code: files[entrypoint],\n source_files: { entrypoint, files },\n dependencies: {}, // Local files and the host-provided runtime need no extra packages.\n});\n```\n\n`attach` lists the pages a view appears on, one per entry: `{ record: "deal" }` is a card on every deal\'s page above its activity (`{ record: "deal", id: 7 }` pins one record), `{ collection: "deal", when? }` a tab on the deal list page, `{ workspace: true }` a Data hub tab, `{ event: "deal.won", type? }` one event\'s page. One view can list several pages and branch on `useScope()` when it answers the same question at each scale. A record card renders with `useHost().displayMode === "inline"` inside `container.maxHeight` (the host clips past it): render a summary there with a "See all" that calls `requestDisplayMode("fullscreen")`, and the full view when `displayMode` is `"fullscreen"` (the peek, a full page, a tab).\n\nWorkspace attachment does not render individual events. For an event presentation, attach to its specific `semantic_type` (event kind), optionally restricted to a linked entity type with `type`; a metadata schema name does not select the view. Avoid binding a specialized renderer to a generic kind such as `summary`. Register a dedicated kind in the workspace\'s event-kind registry and have its producer emit it. On event pages and event peeks, read `useScope().event` by exact ID and select that ID from the returned lineage; never substitute the latest event or let a URL date param change the subject. A shared workspace/event module should branch on `scope.event`, keeping history selection on its workspace surface. Preserve a readable stored body for fallback and evidence.\n\nBefore reporting a view working, open each attached surface, including an event page and peek when declared. Exercise filtering, drilldown, keyboard navigation, and a narrow pane; check loading, missing/error, and truncated data states. Refresh and reopen an earlier event of the kind to verify the view stays on that event rather than jumping to the newest one. Views render in an iframe, so an empty parent-page DOM is not evidence the view is empty; inspect the frame through an authorized browser or accessibility surface. A successful compile proves only that the bundle was built.\n\nImport reusable UI from **`@lobu/views/components`**. Discover this kit with `search_sdk({ query: "@lobu/views/components" })` or a component name. Start with the largest suitable native surface; compose smaller parts only for needs it does not cover:\n\n| Need | Component and minimum input |\n| --- | --- |\n| Complete entity list | `EntityListPage title={title} table={tableProps}` |\n| SQL, computed TypeScript or local rows | `EntityListPage title={title}` with `DataTable columns={columns} rows={rows} keyOf={keyOf}` as children |\n| Complete record body | `EntityRecordPage entity={entity} owner={workspace} schema={schema}` |\n| Entity table or individual fields | `EntityTableView`, `RecordSpecSheet`, `SchemaValue`, `EntityAvatar` |\n| Workspace schema, proposed schema or schema diff | `SchemaGraph`, `SchemaGraph schema={spec}`, `SchemaGraph schema={spec} base="workspace"`, or `SchemaGraph schema={after} base={before}` |\n| Saved resource identity and navigation | `AutomationReference`, `AgentReference`, `ConnectorReference` |\n| Automation instructions, sources, triggers, outputs and code | `AutomationDefinition value={definition}` |\n| Agent identity, models and settings | `AgentDefinition value={definition}` |\n| Connector actions, feeds, schemas and source | `ConnectorDefinition value={definition}` |\n| Current / Proposed comparison | Existing `Tabs` with the same definition component in each panel |\n| Optional technical details | `JsonDiff before={current} after={proposed}` inside collapsed `<details>` |\n\nThe host supplies native JS/CSS, React and live theme. Do not copy product markup or bundle a second React. Exported prop types describe the shared contracts. Use `Button`, `Badge`, `Card`, chart and state components for surrounding UI.\n\n**Page bodies are controlled.** Supply data and slots; they fetch nothing and authorize no writes. `EntityListPage` accepts `title`, optional `actions`/`controls`, and either `table: EntityTableViewProps` or `children`. Its `loading`, `error`, `onRetry` and `empty` affect only results, keeping controls mounted. Native table props include rows, schema, linked lookups, sorting and pagination; honor `metadata.has_more`. For SQL/TypeScript rows use `DataTable`, without inventing entity IDs or types. `EntityRecordPage` renders the native title/avatar and schema fields; `actions`, `details`, `summary`, and `children` supply editing, links, activity and tabs. Default `layout="record"` adapts to width; `layout="content"` retains the header while children own the layout. A `null` title/details/summary hides that slot. Preserve zero and false.\n\n**SchemaGraph is read-only.** It reuses the native schema canvas. Omit props for the mounted workspace schema, pass `schema` for a supplied snapshot, add `base="workspace"` to compare a proposal with the live workspace, or pass another spec as `base`. A spec is `{ entityTypes: [{ slug, name?, description?, metadata_schema?, event_kinds? }], relationshipTypes: [{ slug, name?, metadata_schema?, rules: [{ source_entity_type_slug, target_entity_type_slug }] }] }`. Specs are full snapshots: an omitted type is removed in a diff. Added, removed and changed types/rules remain visible; inspect type details for metadata fields, event kinds and rule changes. Existing entity types open their native pages; unsaved types show details in place. Live reads use the visiting user\u2019s session and permissions through the existing broker; supplied snapshots still render when workspace reads are unavailable. No edits or schema writes are performed. The leaf names match `entitySchema`: list responses use `entity_types` / `relationship_types`; attach `listRules` results to the matching relationship by ID. To apply a reviewed spec, use existing `createType` / `createRelType` (both require `name`) and `addRule({ slug, ...rule })` separately. The graph\u2019s optional name falls back to slug for display only. Hosts without native components throw the standard unavailable-native error.\n\n**References resolve saved identity.** Pass `mode="live"`, mounted `workspace`, optional `appearance="inline" | "row"` (default row), and `automationId` (positive decimal string), `agentId`, or `connectorKey` plus optional numeric `connectionId`. Discover IDs first. These reuse product rows and visiting-user permission checks; they accept no authored name/status or mutation callbacks. Invalid selectors, another workspace, missing records and refused reads show unavailable. A connector definition does not imply a connected account. Reads refresh on mount, focus, reconnect and host invalidation, without interval polling.\n\n**Definitions render supplied objects.** All three have the same signature: `{ value: Record<string, unknown> }`. Pass the existing saved definition or complete proposed snapshot, not a patch. Automation fields include `name`, `description`, `prompt`, `sources`, `triggers`, `outputs`, `reaction_script`; Agent fields include `name`, `description`, `identity_md`, `settings`; Connector fields include `name`, `description`, `version`, `actions_schema`, `feeds_schema`, `source_code`. Remaining nested settings stay inspectable. Missing fields differ from empty values. Bodies fetch nothing, execute no supplied code, and add no save/approval controls. Label authored objects as Snapshot or Proposal preview; use a reference for live identity. Never supply credentials.\n\nShow changes as **Current / Proposed**, defaulting to Proposed, with the same native body on both sides. Keep JSON diff optional. Rendering does not save or apply anything and needs no new proposal endpoint. For an existing approval, render its held current/proposed snapshots; do not merge in newer live values. Writes remain on existing declared `useAction` paths or native authorized editor/review pages. An authored preview must not imply a held approval or authority to apply it.\n\n```tsx\nimport {\n Card, ConnectorDefinition, JsonDiff,\n Tabs, TabsList, TabsTrigger, TabsContent,\n} from "@lobu/views/components";\n\n// current and proposed are complete definition objects from authorized reads\n// and the requested edit. Use AgentDefinition or AutomationDefinition identically.\n<Card title="Connector proposal preview" description="Nothing has been applied.">\n <Tabs defaultValue="proposed">\n <TabsList label="Definition version">\n <TabsTrigger value="current">Current</TabsTrigger>\n <TabsTrigger value="proposed">Proposed</TabsTrigger>\n </TabsList>\n <TabsContent value="current"><ConnectorDefinition value={current} /></TabsContent>\n <TabsContent value="proposed"><ConnectorDefinition value={proposed} /></TabsContent>\n </Tabs>\n <details><summary>Technical diff</summary><JsonDiff before={current} after={proposed} /></details>\n</Card>\n```\n\nUse `useHost().openRecord({ entity_id, entity_type? }, { mode: "peek" })` for a record\'s native peek. String source keys require the type. The promise reports the actual `{ mode: "peek" | "page" }`; a host without native peek opens the server-returned record URL. Errors remain errors. `useHost().theme` follows live theme changes; native components inherit the host palette and typography automatically. Use semantic host style variables and avoid hardcoded light/dark colors.\n\nRules that are load-bearing, not style:\n\n- Use structured reads: `useQuery(tool("manage_entity", { action: "list", entity_type: type, filters, limit: 100 }))`. The host admits entity `list/get/list_links` and entity-type schema `list/get` reads; tools marked read-only are also available. Use existing tool input/result contracts and preserve server authorization. Send structured arguments, never TypeScript inside a string. `sql` remains available; script-string queries are compatibility support for installed views. `query_sql` allows 500 rows max with a 5 second timeout \u2014 branch on the typed `errorCode` (e.g. `UPSTREAM_TIMEOUT`), never on message text, and render `truncated` honestly instead of passing partial data off as complete. Each `query_sql` cell is bounded too: strings keep their first 4,000 Unicode code points plus "\u2026 [truncated]"; JSON values over 16 KiB become `{ _truncated: true, bytes }` (attachments become null with `attachments_truncated`). `truncatedColumns` names the affected columns. Select smaller elements or fields, for example one array element per row with `jsonb_array_elements(...)`, and paginate as needed; each returned cell is still subject to these limits.\n- Never aggregate history in a view: no `GROUP BY`, `DISTINCT ON`, per-row regexp, or leading-wildcard `LIKE` over `events` or other growing tables. For "latest state" views, have an Automation maintain keyed event outputs (each run supersedes the previous event with the same key) and read the current head with `read_knowledge`.\n- `run_sdk` is not exposed to views. Writes go only through declared view actions (`useAction` \u2192 `invoke_view_action`). An action declares `emits` (append that event kind, which can activate workspace-triggered Automations), `updates: { entityType, fields }` (write those metadata fields on one record), or both, which commit in one transaction. An `updates` action takes `value: { entity_id, set: { field: value } }`; the view must attach to `entityType`, `set` may only name declared fields, and schema-stamped fields are refused. Pass `{ expected }` as the second argument with the values the view read: a stale read returns 409 `PRECONDITION_FAILED` and writes nothing. The write runs as the clicking user without claiming field ownership, so a human-owned field comes back as `pending_approval` instead of `applied`. Do not add an Automation that only copies an action\'s event onto the record; declare `updates` instead. Action `value` payloads are capped at 4000 JSON chars \u2014 save content first, then pass the id. A subject shown from a superseded event rejects with 409; refetch and ask the user to re-confirm rather than retrying blindly.\n\n ```tsx\n // actions: { markWon: { emits: "deal.won", updates: { entityType: "deal", fields: ["stage"] } } }\n const markWon = useAction("markWon");\n const sent = await markWon({ entity_id: deal.id, set: { stage: "won" } }, { expected: { stage: deal.metadata.stage } });\n // sent.result.applied: { entity_id, fields } with server stamps; sent.result.pending_approval when held\n ```\n- Link with `Link` from `@lobu/views/components` (or `useHost().openLink`): `href="<type>/<slug>"` opens that record in the workspace, supported links within the same workspace open in the peek pane, other app links navigate normally, and external URLs open a new tab. A plain `<a href>` goes nowhere inside the sandboxed frame.\n- For several offers, publish one event with a card for each held proposal. Obtain the real pending approval through the existing agent/Automation write method under its normal policy, then read its returned event ID to obtain the canonical review URL. Link each card to that exact review; the host opens it in peek. Each offer has its own run and decision. Use native Current/Proposed fields for updates and the proposed definition for creation. A resource snapshot alone is a preview, not an approval: never fabricate Approve/Reject buttons or imply that a missing resource ID creates anything. Existing settings `?run_id=` links remain compatible; new offers use the proposal review instead of the settings page.\n- Views run in a sandboxed frame with no direct network: no fetch, no third-party calls at runtime. Reuse local React components through relative imports and `source_files: { entrypoint, files }` plus `dependencies: {}` for local-only components with `views.set`, or use `viewFromFile` + `lobu apply`. Extra npm dependencies need the CLI-bundled `compiled_code`; listing `dependencies` alone does not install packages.\n- Never early-return the whole view on loading/error: each filter keystroke re-queries, so an early return unmounts the focused input mid-typing. Keep filters mounted and render query states inline in the results area.\n- Before calling a view verified, exercise the exact compiled artifact and host runtime in a sandboxed browser: representative data, loading, empty and error states, filters, sort/pagination, links/peek, declared actions, light/dark and narrow layouts. Fix failures and rerun. Registration compiles the module and requires an isolated browser check of the exact candidate against bounded empty/error/loading fixtures in light/dark themes and inline/fullscreen modes for every distinct attached scope (at most eight per module; each scope is its own bounded runner request). A failed check returns 422; an unavailable runner returns 503; both preserve the saved view. Fixture validation does not prove successful workspace data or every interaction. Distinguish compiled, browser-verified, stored and deployed; never claim more than the evidence.\n- Params sync to the URL on Lobu hosts only; elsewhere they stay frame-local. `refetch()` re-reads on demand; only Lobu hosts push live data-changed refreshes.\n\n## Connectors, Feeds, and Operations\n\nConnectors are the primary integration path for third-party services. The\nend-to-end model (entities vs events, the run lifecycle) is in\n`docs/CONCEPTS.md`; authoring a new connector when none matches is in\n`docs/connector-authoring.md`. Do not freeze a connector lifecycle in project\ninstructions because it can drift from the deployed SDK:\n\n1. Call `search_sdk` with the service name immediately before acting. It returns installed and installable connectors, declared feed keys, readiness, and the caller-aware live lifecycle. Then, before requesting app credentials, call `client.connections.setupOptions({ connector_key })` against the selected runtime: it discovers verified cloud-managed OAuth and hosted chat alongside local setup, so follow the URLs and instructions it returns. `cloud_status: "unavailable"` is a discovery outage, not evidence that managed auth is absent. Options are offers, not connected accounts.\n2. Always follow the methods it returns in order instead of relying on a remembered connect/feed/operation sequence. Repeat discovery after authorization or state changes so the next step reflects the live connector and current caller.\n3. Treat `access: operate` as `mcp:write` and `access: administer` as workspace owner/admin plus `mcp:admin`. If discovery asks for MCP reauthorization or an owner/admin handoff, follow that instruction; never attempt methods it withheld as unavailable.\n\nSource-backed feeds query the provider only through an explicit `client.feeds.readMany({ reads: [...] })` call; `search_memory` stays local and reports unqueried source feeds in `coverage`, while `client.feeds.get` returns metadata without source access. Feeds with `sync` may persist events for search and relational queries. For connector actions, use the live discovery result\'s operation target and readiness. If readiness is disconnected, follow the returned next action instead of guessing a connection. Surface approval-gated `pending_approval` as a waiting state, not a failure.\n\n## Data Ingestion\n\n- Use `lobu memory seed` for small declarative YAML datasets under `./data`; it processes records sequentially and is not a bulk-backfill path.\n- Use `client.knowledge.save` for schema-less semantic history such as messages, notes, observations, and content. Pass `supersedes_event_id` when replacing an existing fact.\n- Use `client.entities.create` / `client.entities.update` only for strict structured records that match declared entity schemas.\n- For large backfills, send bounded chunks through `run_sdk` / `lobu call run_sdk` and use `Promise.allSettled` so conflicts and partial failures remain visible.\n\n```ts\nexport default async (_ctx, client) => {\n const records = [\n { content: "...", semantic_type: "note" },\n { content: "...", semantic_type: "observation" },\n ];\n return Promise.allSettled(records.map((record) => client.knowledge.save(record)));\n};\n```\n';
|
|
169252
|
+
LOBU_SKILL_MARKDOWN = '---\nname: lobu\ndescription: "Set up new Lobu agents end to end and operate existing Lobu projects and memory: interview, scaffold, validate, authenticate, connect feeds, execute operations, and test Automations."\n---\n\n# Lobu\n\nUse this skill when setting up a brand-new Lobu agent from scratch (follow "Onboarding a New Project" below) or when running, validating, evaluating, or connecting an existing Lobu project, or operating Lobu memory from a coding agent.\n\nThe `AGENTS.md` generated into a new project is the source of truth for the config API (the `define*` helpers, connectors, auth, Automations, memory) \u2014 this skill does not duplicate it. For an existing project, jump to "Core Model" + the relevant reference section below.\n\n## Onboarding a New Project\n\nUse this playbook when a new user asks you to build them a Lobu agent from scratch. Set it up end to end: ground yourself in what the user already has, interview, discover, scaffold, prove the complete local path, then offer the deployment choice. Do not call the setup complete until every path the user selected has actually passed end to end. If an external provider, authorization, deployment, or rate limit blocks the proof, name the exact blocker and leave the setup as blocked rather than claiming success.\n\n### 1. Ground yourself in what the user already has\n\nBefore interviewing, look at what already exists so your questions and suggestions are personal rather than a blank slate. This is discovery, not a design decision \u2014 do not let it skip the interview.\n\n- Local: run `lobu context list` to see existing contexts (`--json` adds `loggedIn`, which reports stored credentials, not session validity); check the current directory and home for existing Lobu projects (`lobu.config.ts`), configured MCP servers, and CLI auth state. Note what the user already set up.\n- Cloud: if the user has an active session (do not create one just to look), call `client.organizations.list()`, `client.agents.list()` for each org, `client.catalog.listInstalled({ kinds: ["connectors"] })`, and `search_memory` for prior knowledge. This reveals existing agents, connectors, and memory you can build on.\n- Tell the user what you are looking at so they can correct you, and let what you find shape the options you offer. Never treat this discovery as an identity signal: orgs, emails, or domains never prove a company or product, and never mention a competitor or third party unless it actually appears in what you found.\n\nDo NOT ask for a login email during the interview. Email is only needed when a managed connector actually requires a session (step 3) or when the user chooses cloud deployment (step 6); ask for it at that point. Treat identity only as identity; never infer a company from an email address or domain.\n\n### 2. Interview with concrete, personalized options\n\nInterview the user one question at a time; wait for each answer, do not guess, and do not batch the questions. Anchor each question in what you found in step 1. Instead of asking "what agent do you want?" as a blank slate, summarize what you see and offer two or three concrete alternatives to choose from:\n\n- "You already have org X with connectors A and B installed and N existing agents. Do you want to (a) add a new agent on top of those, (b) extend one of the existing agents, or (c) start something standalone?"\n- "For what it should do, the common shapes are (a) a triage agent that reads incoming chat and files a ticket, (b) a scheduled report that summarizes new activity each morning, (c) a research agent that answers questions from your connected tools. Which fits, or what would you change?"\n\nOffer a default so the user can answer "the first one" \u2014 decisive users and undecided users both move faster with a concrete menu.\n\n- What company or product is this for?\n- What does it do, and who does it serve?\n- What is its public domain? (optional for a personal project)\n- Do I have permission to research the public website and other public sources?\n- What is the agent for?\n- What should we call it?\n- Who uses it: just me, my team, or each of my customers?\n- How should it behave, and what may it do unattended versus only with approval?\n- What should it remember? Model this as one to three entity types.\n- Where does its data come from? Pick one connector or custom source to start.\n- Where should people talk to it? Offer Web UI, API or SDK, MCP, Slack, Teams, WhatsApp, Discord, Google Chat, and Telegram without forcing a chat platform. If Slack is chosen, ask whether to join Lobu\'s hosted workspace for a quick start, install Lobu into an existing workspace, or use a custom Slack app; then ask whether to test the DM with Lobu, a named channel, or both, and whether people knowledge means conversation participants, bound-channel members, or the full workspace directory.\n- Should anything run on a schedule?\n- Which supported LLM provider credential does the user have?\n\nIf the user gave permission to research and has a public domain, research the company before proposing the design. Summarize its product, customers, workflows, and useful signals, and cite the public sources you used. Then propose one to three entity types, their relationships, the first data source, one or two useful Automations, and suitable interaction channels. Play back a short numbered plan and wait for confirmation before scaffolding anything.\n\n### 3. Discover the surface before choosing how to scaffold\n\nCheck Node is 26.x, then run `lobu context list` and identify the named Lobu Cloud context; do not assume the active context still points to cloud after a local run. If a managed or cloud connector was chosen and there is no session, ask for the login email at that point, explain that Lobu will email an approval link, and run `lobu login --email <confirmed-address> --context <cloud-name>`. The person approving must sign in with that same email; knowing an address never grants access. After a successful login, an empty organization membership list is a tenancy/discovery result, not an authentication failure: call `client.organizations.list()` and explain the result. Never revoke or repeat login with `--force` unless the user separately approves that re-authentication.\n\nUse ClientSDK through Lobu MCP with the explicit cloud context. From the CLI, account discovery works before selecting an active org with `lobu memory run query_sdk \'{"title":"Find managed connection providers","script":"export default async (_ctx, client) => client.organizations.list()"}\'`; `lobu call` over REST requires an active org. Call `client.organizations.list()` to find public organizations offering managed connections. Call `client.catalog.listInstalled({ kinds: ["connectors"] })`; if the connector is not installed, call `client.catalog.listCatalog({ kinds: ["connectors"] })`. Inspect the selected entry\'s `detail.auth_schema`, `detail.options_schema`, `detail.feeds_schema`, and `detail.automation_events` instead of guessing field names. On account-scoped `/mcp`, select an authorized home workspace first with `const home = await client.org(homeSlug)` and call `home.connections.connectManaged`; put the public provider org in `managed_by_org`, rather than selecting that provider org with `client.org`. This call runs against cloud, not the embedded runtime. If a matching live managed offer exists, explain it and call `client.connections.connectManaged` only after consent. Complete the returned user authorization, then run `lobu context use <cloud-name>` immediately before executing its `local_bootstrap_command` from the parent directory where the new project should be created; use `--here` only after entering an empty directory, and do not create a blank Lobu scaffold first. Ask for bring-your-own OAuth credentials only if no managed offer exists or the user prefers their own app.\n\n**If no connector in the catalog matches the data source, do not report "no integration exists"** \u2014 author a custom connector: write `connectors/<name>.connector.ts` in the project, register it with `connectorFromFile("./connectors/<name>.connector.ts")`, and model it on the [npm downloads example](https://github.com/lobu-ai/lobu/blob/main/examples/lobu-crm/npm-downloads.connector.ts). See [Connector authoring](https://github.com/lobu-ai/lobu/blob/main/docs/connector-authoring.md) for the full contract; the end-to-end entity/event/Automation model is in [Lobu concepts](https://github.com/lobu-ai/lobu/blob/main/docs/CONCEPTS.md).\n\n### 4. Scaffold and build from the confirmed plan\n\nIf managed auth supplied a `local_bootstrap_command`, use the project it generated. Otherwise run `npx @lobu/cli@latest init` with the confirmed name and provider. Postgres is built in, so `lobu run` starts an embedded database; ask for `DATABASE_URL` only if the user chooses external Postgres. Read the generated `AGENTS.md` completely before editing `lobu.config.ts`. Use the canonical reference at `https://github.com/lobu-ai/lobu/blob/main/examples/lobu-crm/lobu.config.ts` when needed; do not assume that example exists in the new project\'s filesystem. Briefly explain how the chosen feed may use checkpoints to collect incrementally, emits events, builds shared entity memory, and gives both chat and Automations the same governed context.\n\n`feeds_schema.<feed>.eventKinds` are the default Automation trigger catalog for feed connectors: every declared kind is a subscribable event type (`event_type` = the kind slug) for any feed that emits the kind. A feed\'s first successful non-dry sync establishes its baseline without activation; later inserts of a matching kind activate subscribers. A kind with `updatedEvent: true` also offers `<kind>.updated` for supersedes whose `occurred_at` strictly advances past the previous head. The original kind stays insert-only; unchanged rows, volatile-only updates and same-time reformats stay quiet. Subscribe to both types for new items and later activity. Feed-scoped filtering is not yet available (events dedupe by connection + origin id, so a `feed_key` match would miss origins first seen by another feed). `automation_events` (now derived from eventKinds when a connector declares none) is the trigger picker\'s list. If no declared kind matches the use case, use a scheduled Automation with a bounded named SQL source and read event text from `payload_text`. Validate the query against the running local schema before relying on it. If `feeds_schema` is empty, do not invent or trigger a feed; chat integrations such as Slack can deliver incoming messages directly. For Slack or Telegram, prefer `defineConnection` with `credentialMode: "hosted"` so no bot token is required; `lobu run` prints the exact hosted-workspace join URL, own-workspace install URL when available, and short-lived link command. This hosted chat path requires a cloud session and the agent applied to that cloud workspace; the link targets the cloud agent. It does not create a local Slack data connection or prove local Slack search. Use those returned values instead of constructing URLs. A printed `/lobu link <code>` is one-time: redeem it in the first selected DM or channel. In an installed workspace whose installer is linked to Lobu, bind each additional surface with `/lobu link <agent-id>`; otherwise generate a fresh code for that surface. Mention Lobu in a channel test and verify the App Home separately. Lobu email login and Slack installation are separate: the email link authorizes Lobu CLI access, while an existing-workspace install requires the user or workspace admin to approve Slack\'s OAuth screen. Never describe Slack consent as an email approval. Use `credentialMode: "byo"` only if the user chooses their own app. Tell the user once which remaining secrets are required and add only `secret("ENV_NAME")` placeholders to config. Never open or request permission to read `.env`; inspect `.env.example` when present and declared secret placeholder names only. Never read, print, invent, or paste a real secret into source or chat.\n\nIf the user wants the agent to know people in Slack, ask whether that means conversation participants, members of bound channels, or the full workspace directory. Installing the app proves none of those by itself. Verify the selected scope by inspecting the people or member entities Lobu actually materialized and by asking the agent a roster question. If human-readable names or non-participants are unavailable, identify that exact product gap; never claim the complete workspace directory was synced.\n\n### 5. Prove the complete local path\n\nChange into the generated project directory and verify `pwd` contains the intended `lobu.config.ts`; never run project commands from its parent. Run `npx @lobu/cli@latest validate`, boot with `npx @lobu/cli@latest run`, and verify health and the local Web UI. With the embedded database default, `lobu run` creates and selects the local context and auto-applies the project; with an external `DATABASE_URL`, it does neither, so authenticate and apply to that runtime explicitly. Send a harmless direct chat message without tools.\n\nBefore consent to access provider data, inspect only catalog, connection, auth-profile, and feed metadata. For browser access, inspect the paired device and connection metadata without invoking browser actions. Durable managed OAuth and env-profile credentials stay at the gateway. Do not run a feed or connector dry-run before consent, because a dry-run may still read provider data. Ask explicitly before accessing real provider data. Only after approval, dry-run the connector or feed server-side and trigger the selected feed manually if that connector actually declares one. A feed dry-run records its run but persists no collected events, entities, attachments, checkpoint changes, or feed sync state. Run each Automation once, poll `client.operations.getRun` with its returned `run_id`, and show each completed run plus any declared result event or entity. For a run-result-only or reaction-only Automation, use the completed run and the Automation `view_url` returned by Lobu. For Slack, treat DM, channel mention, App Home, and requested member discovery as four separate checks. Keep actions in approval mode unless the user explicitly approves execution. If any step fails, fix it and rerun that step; do not silently substitute a different path.\n\n### 6. Offer the deployment choice\n\nAfter the local proof, ask the user whether to keep running locally or deploy to Lobu Cloud. Explain that the embedded local runtime and Lobu Cloud are separate targets, and that keeping it local needs no further setup. Only if the user chooses cloud deployment, ask for the login email to identify the deployer, explain that Lobu will email an approval link, and run `lobu login --email <confirmed-address> --context <cloud-name>`; the person approving must sign in with that same email. Because `lobu apply` has no context flag, use `lobu context list` and then `lobu context use <cloud-name>` to select an explicit cloud context before deployment. Run `lobu apply --dry-run` first, show the target organization and exact plan, and wait for confirmation before applying. After apply, use only authoritative `view_url` values and link commands returned by Lobu; never construct URLs. Present the working access choices: Web UI, direct agent chat, API or SDK, MCP, and any channels the user selected.\n\n## Core Model\n\n- **Lobu** is the agent framework, runtime, deployment layer, and memory surface.\n- Keep framework configuration in `lobu.config.ts` (TypeScript, `defineConfig` from `@lobu/cli/config`).\n- Keep agent identity and instructions in `IDENTITY.md`, `SOUL.md`, and `USER.md`.\n- Keep reusable capability bundles in `skills/<name>/SKILL.md` or `agents/<agent>/skills/<name>/SKILL.md`.\n- Use `lobu login` for CLI authentication. Do not use a separate memory login command.\n- Use `lobu connect` for MCP client and skill setup.\n- Use `lobu memory ...` for memory operations, seeding, and direct tool calls.\n\nReference the canonical docs before guessing how a feature works:\n[Lobu concepts](https://github.com/lobu-ai/lobu/blob/main/docs/CONCEPTS.md)\n(entities vs events, identity, end-to-end lifecycle),\n[Automations](https://github.com/lobu-ai/lobu/blob/main/docs/AUTOMATIONS.md)\n(trigger/source/output contract), and\n[Connector authoring](https://github.com/lobu-ai/lobu/blob/main/docs/connector-authoring.md)\n(custom connectors).\n\n## Project Checklist\n\n1. Read `lobu.config.ts` first.\n2. Read the active agent files under `agents/<id>/`.\n3. Check local skills under `skills/` and `agents/<id>/skills/`.\n4. Use `lobu validate` after config changes.\n5. Discover the live SDK and connector surface with `search_sdk`; never guess a method, connector key, feed key, connection id, or operation key.\n6. When prompt or Automation changes, run evals via promptfoo (see `examples/personal-finance/evals/promptfooconfig.yaml`). The in-house `lobu eval` command has been removed.\n\n## Common Commands\n\n```bash\nnpx @lobu/cli@latest init my-agent\nnpx @lobu/cli@latest run\nnpx @lobu/cli@latest validate\nnpx @lobu/cli@latest login\n```\n\n## Authentication\n\n- Interactive (human at a terminal): `lobu login` runs the device-code flow with a browser approval.\n- CI / your own automation: `LOBU_API_TOKEN`, or `lobu login --token <pat>`.\n- Local `lobu run`: the CLI mints credentials automatically over loopback \u2014 no prompt.\n- Headless, on a *user\'s* behalf: `lobu login --email <address>`. The server emails the user a one-click approval link and the CLI polls until they approve, then stores the scoped credential \u2014 no TTY, no pre-minted token. This is the auth.md "user_claimed" flow.\n\nAn external agent not using this CLI can drive the same flow over HTTP: read `<origin>/auth.md` (linked from the `agent_auth` block in `<origin>/.well-known/oauth-authorization-server`) for the endpoints. Today only the email user_claimed flow exists (no zero-touch ID-JAG). Never fabricate a token.\n\n## Organization Deletion\n\nTreat organization deletion as permanent and restricted to organization owners. The supported path is the **Organization settings** page, opened from that workspace\'s settings button in the organization switcher. ClientSDK and Lobu CLI intentionally expose no organization-delete method. When asked to delete organizations, identify each exact target and its data impact read-only, surface one production organization at a time for explicit confirmation, then direct an owner to that page or use their logged-in browser only when explicitly authorized. Never invent a hosted URL, call the raw Better Auth route, bypass a failed authorization check, delete organization rows directly, or batch confirmations.\n\nCloud CLI OAuth/PAT credentials are not a Better Auth browser session. A `401` or `403` is a stop signal: report the authorization boundary and leave the organization intact.\n\n<!-- lobu-memory-guidance:start -->\n## Memory Defaults\n\nYour long-term memory is powered by Lobu. Do NOT use local files (memory/, MEMORY.md) for memory.\n- Lobu automatically recalls relevant memories when you receive a message.\n- To save something, call save_memory with the content and an appropriate semantic_type.\n- To search, call search_memory. Results include view_url links to the web interface.\n- NEVER construct Lobu URLs yourself. When the user asks for a link, call search_memory to get the correct view_url.\n- When the user says "remember this", save it to Lobu immediately.\n- When a message changes a fact you already stored (an updated preference, status, count, location, or plan), first search_memory for the prior memory to get its id, then save_memory the new value with supersedes_event_id set to that id. This replaces the stale value so future recalls return the current one; the old value stays in history but is hidden from normal search.\n<!-- lobu-memory-guidance:end -->\n\n## Lobu Memory\n\nConfigure project-scoped memory in `lobu.config.ts` by setting the org on `defineConfig` and declaring the schema with the `define*` helpers:\n\n```ts\nimport { defineConfig, defineEntityType } from "@lobu/cli/config";\n\nconst ticket = defineEntityType({\n key: "ticket",\n name: "Ticket",\n properties: {\n subject: {\n type: "string",\n title: "Subject",\n "x-table-label": "Subject",\n "x-table-column": true,\n },\n },\n});\n\nexport default defineConfig({\n org: "my-org",\n orgName: "My workspace",\n agents: [/* ... */],\n entities: [ticket],\n});\n```\n\nThe entity schema also renders the record page form. Give every array `items` and every object `properties` (bare ones render as raw JSON), put the label in `title` and help text in `description`, mark derived fields `readOnly: true`, and declare every field an Automation writes.\n\nFor a "when did this field last change" timestamp, declare root `metadata_schema["x-lobu-stamps"]: { "stage_at": "stage" }` instead of writing it from an Automation. The stamp field must be a declared `{ type: "string", format: "date-time" }` property (not listed in `required`) and the tracked field a declared property. Every writer (agent, SDK, Automation, connector projection, view action, approval) then gets it for free: the server sets `stage_at` when a record is created with `stage` set or when `stage` changes value, and discards any value a caller sends for `stage_at`. `readOnly` alone is presentation only; it is not enforced.\n\nSeed data records still live as YAML under `./data`. Then seed or operate the memory workspace with:\n\n```bash\nlobu login\nlobu memory org set <org-slug>\nlobu memory health --org <org-slug>\nlobu memory seed --org <org-slug>\nlobu memory run search_memory \'{"query":"Acme"}\' --org <org-slug>\n```\n\nUse `search_memory` first when the user asks about a specific entity or workspace memory. Use `save_memory` to persist durable memory. To update existing knowledge, search first, then save with `supersedes_event_id` so the old row is tombstoned rather than deleted.\n\n### Answering questions about a record\n\nRecent events can contain only counters or timestamp updates; a relevant linked record may hold the investigation, decision, or outcome. Use the existing read APIs to gather that context:\n\n1. Start with `search_memory` to resolve the record and its workspace. Discover the current signatures with `search_sdk`, then use `query_sdk` with the selected workspace\'s `entities.get` and `knowledge.read`. Event `entity_ids` identify records the event concerns; co-occurrence does not assert a relationship.\n2. When relationships could answer the question, call `entities.listLinks` on the resolved record or relevant event-linked records. Use relationship type and direction to select context relevant to the question, rather than expanding every event. Keep expansion to one hop and fetch at most five distinct related records in total with `entities.get`. Bound link pages too: start with `limit: 20` and inspect at most two pages total; use the returned offset/page metadata for stored records and `next_cursor` for source-backed records. Deduplicate records by workspace, type, and ID/key. If the budget ends while more results remain, say the context is partial.\n3. For stored event evidence in current-state questions, use live heads (`is_superseded: false`), not the first row of an exact-ID read: `content_ids` can return the supersede history before its current head. If no live head is returned, follow the returned pagination for at most two pages total, then report current evidence unavailable if it is still missing. Keep historical versions when the question asks what happened at an earlier time. An event ID identifies a stored version; a source item\'s stable identity is its connection/source plus `origin_id`.\n4. Preserve the meaning and direction of each relationship. Skip `acl_managed` links for ordinary business context unless the question concerns permissions. An identity association or a shared email address does not by itself verify the same human; a shared support mailbox can represent several people. Neither proves employment or collaboration. Fetch supporting evidence when that distinction matters, and distinguish a stored assertion from a verified source fact.\n5. Cite returned record/event URLs or source links for the answer. Treat `relationship_failures`, `record_failures`, unreadable linked records, and unfinished pages as coverage limits, not proof that no relationship or evidence exists. Respect the selected workspace and caller\'s access; do not switch workspaces or fall back to raw SQL to bypass a denied read. Manual claims and connector configuration ownership are not automatically supporting event evidence.\n\nFor example, when asked what happened with an issue, follow an explicitly returned investigation/task relationship and read that record\'s conclusion as well as the issue\'s recent activity. Report a stored task\'s conclusion as recorded context; it does not independently prove that a repair is currently deployed. This workflow reads context only; it does not create links or merge records.\n\n## MCP Client Setup\n\nUse the actual MCP URL for the user\'s runtime. Never hardcode a hosted URL unless the user explicitly asks for that instance.\n\nCommon setup commands:\n\n```bash\n# Claude Code\nlobu connect claude-code --url <mcp-url>\n\n# Codex\nlobu connect codex --url <mcp-url>\n\n# Antigravity\nlobu connect antigravity --url <mcp-url>\n\n# OpenCode\nlobu connect opencode --url <mcp-url>\n```\n\nRun `lobu connect --url <mcp-url>` without a client id to choose interactively. For ChatGPT, Claude Desktop, Cursor, and other browser-managed clients, the same command applies the safe local configuration it can and prints the exact remaining client handoff. Complete OAuth in the client, not through a separate Lobu CLI login.\n\n## Browser-Authenticated Connectors\n\nFor connectors that need a signed-in browser, pair the Owletto Chrome extension\nand sign in on the source site in that browser. Browser operations run through\nthat paired device; external remote-debugging endpoints and CLI browser-auth\ncapture are no longer supported.\n\nNothing answers a JS dialog (alert, confirm, prompt, beforeunload) on the\nagent\'s behalf. A browser action it blocks fails, and the failed result\'s\n`output` carries `tab_id` and `dialog` (`dialog_id`, `type`, `message`). In\n`run_sdk`, catch the `operations.execute` error and read `error.details.output`\nrather than parsing the error text (an uncaught failure returns the same value\nas the `run_sdk` result\'s `error.details`, and a background run\'s\n`operations.getRun` returns the same `output`), then answer with the\nconnection\'s `handle_dialog` operation. An unanswered dialog is handed to the user after two minutes.\n\nTo test a configured feed without writing ingested data, discover the current\nfeed methods with `search_sdk`, then use `client.feeds.trigger({ feed_id, dry_run: true })`\nthrough `run_sdk` or `lobu call run_sdk` (with a `title` arg). Inspect `client.feeds.get({ feed_id })`\nfor the completed run\'s preview. The dry run uses normal device routing and\nauthorization checks and may access the upstream provider, so obtain consent first.\n\n## Agent-Facing Tool Surface\n\nThe normal MCP surface is intentionally small. Flat administrative tools are not advertised to agents; compose through these tools instead:\n\n- `search_memory` and `save_memory` for direct knowledge recall and persistence.\n- `search_sdk` to discover current ClientSDK methods, signatures, connector feed keys, operations, access requirements, and examples. Pass `mode: "read"` when you only need methods safe for `query_sdk`.\n- `query_sdk` for read-only TypeScript and `query_sql` for governed, paginated SQL reads.\n- `run_sdk` for mutations and external operations. Use `lobu call run_sdk --arg title=\'\u2026\' --arg script=\'\u2026\'` from the CLI for the same ClientSDK scripting workflow; `run_sdk`, `query_sdk`, and `query_sql` calls need a short `title` naming them in the activity feed.\n\nSearch before create to avoid duplicates. Prefer a read or dry run before mutations, never fabricate returned URLs or identifiers, and never delete from `events`; supersede or tombstone instead.\n\n## Custom Views\n\nBefore authoring UI, inspect available native entity/event pages, existing views (`client.views.list()` and `client.views.get({ key })`), and the project\'s shared components and overrides. Honor explicit user designs and reuse UI from the top down:\n\n1. Use the largest existing surface or component that meets the task. Configure its segment, filters, search, saved preset and layout before replacing its UI.\n2. If that surface cannot meet a concrete requirement, compose its exported parts, such as an individual table, board, graph or shared collection controls when available. Preserve shared selection and action handling instead of rebuilding that logic.\n3. If those parts still do not fit, use smaller shared primitives and write custom UI only for the remaining gap. Explain the unmet requirement that forced each step down.\n\nCheck the current exports and target host before choosing an import; native renderer registrations do not imply React exports. Surface a missing export as a platform gap rather than inventing an API or silently copying the native implementation. `@lobu/views/components` currently supplies theme-aware defaults such as `Card`, `DataTable`, filters, charts, links and query-state components. `LoadingState` draws skeleton lines in the host\'s style; `Skeleton` is a pulsing block to size like the content it stands for (a figure, a row, a chart), so a slow read keeps the page\'s shape instead of showing text. When exploration needs specialized linked charts, drilldowns, scenario controls or Canvas/SVG, compose a React view from the suitable existing components.\n\nNative JSON templates use the target renderer\'s registered component names and overrides; inspect what that host actually supplies. React views compose imported components in their own bundle, independently of that native renderer map.\n\nViews are custom React panels attached to entity types, records, events, or the workspace Data hub. They render in the web app and MCP hosts (Claude and other MCP Apps hosts); chat channels get links to views, not the views themselves. Author them in `views/<type>/<key>.tsx` and ship with `lobu apply` (list them via `viewFromFile` in `defineConfig`), or set sources over MCP with `client.views.set` (owner/admin only).\n\nModule shape (the server resolves React, React DOM, `@lobu/views` and `@lobu/views/components`; other dependencies need the CLI path with `node_modules` present):\n\n```tsx\nimport { defineView, tool, useAction, useParams, useQuery } from "@lobu/views";\nimport {\n Card,\n DataTable,\n EmptyState,\n ErrorState,\n FilterBar,\n LoadingState,\n SearchField,\n TruncatedNotice,\n} from "@lobu/views/components";\n\nexport const view = defineView({\n key: "pipeline",\n attach: [{ collection: "deal" }],\n params: { stage: { type: "string", default: "open" } },\n actions: { markWon: { emits: "deal.won" } },\n});\n\nexport default function Pipeline() {\n const [params, setParams] = useParams();\n const deals = useQuery(tool("manage_entity", { action: "list", entity_type: "deal", filters: [{ field: "stage", op: "eq", value: String(params.stage) }], limit: 100 }));\n const markWon = useAction("markWon");\n const rows = deals.data?.entities ?? [];\n // Keep the filter mounted across query states: an early return on\n // loading/error would unmount the focused input on every keystroke\n // (each keystroke re-queries). Render states inline instead.\n return (\n <Card\n title="Pipeline"\n actions={<button type="button" onClick={() => markWon({})}>Mark won</button>}\n >\n <FilterBar><SearchField label="Stage" value={String(params.stage)} onChange={(v) => setParams({ stage: v })} /></FilterBar>\n {deals.loading && <LoadingState text="Loading deals\u2026" />}\n {deals.error && <ErrorState message={deals.error} errorCode={deals.errorCode} />}\n {!deals.loading && !deals.error && rows.length === 0 && (\n <EmptyState title="No deals in this stage." />\n )}\n {!deals.loading && !deals.error && rows.length > 0 && (\n <DataTable columns={[{ key: "name", header: "Name" }]} rows={rows} keyOf={(r) => r.id ?? r.slug} />\n )}\n {deals.truncated && <TruncatedNotice shown={rows.length} />}\n </Card>\n );\n}\n```\n\n`defineView` is the view\'s only declaration: `key`, optional `name` (defaults to the key) and `description`, `attach`, `params`, `actions` and `resources` are read from it, never passed separately. `views.set` always requires `source_code` containing the entrypoint module, including when retaining multiple files. Write `defineView` out as a literal (no variables, spreads or `${}` templates): the server reads it without running the module.\n\nA view makes no network requests of its own; data comes through `useQuery`. The one exception is images: `resources: ["https://tile.openstreetmap.org"]` declares origins the view may load images (map tiles, logos) from. Each entry is a bare `https://` origin with a public hostname (no path, wildcard, localhost or IP), at most 8. The images-only limit is a save-time check: `views.set` renders the view\'s empty, error and loading states in an offline browser and refuses the save if anything other than an image from a declared origin is requested. It is not enforced at runtime. MCP hosts receive the origins as the MCP Apps `resourceDomains` CSP, which allows scripts, styles, fonts and media from them as well as images, and the Lobu web app applies no runtime CSP to views. Declare only image or tile CDN origins you trust. Hosts that render through the generic `ui://lobu/views` loader use its CSP, which declares no image origins, so declared images may not load there.\n\nFor a multi-file view, `files` maps relative paths to complete source strings and `entrypoint` names the view module. Include all three inputs below; `source_code` must exactly equal `files[entrypoint]`:\n\n```ts\nawait client.views.set({\n source_code: files[entrypoint],\n source_files: { entrypoint, files },\n dependencies: {}, // Local files and the host-provided runtime need no extra packages.\n});\n```\n\n`attach` lists the pages a view appears on, one per entry: `{ record: "deal" }` is a card on every deal\'s page above its activity (`{ record: "deal", id: 7 }` pins one record), `{ collection: "deal", when? }` a tab on the deal list page, `{ workspace: true }` a Data hub tab, `{ event: "deal.won", type? }` one event\'s page. One view can list several pages and branch on `useScope()` when it answers the same question at each scale. A record card renders with `useHost().displayMode === "inline"` inside `container.maxHeight` (the host clips past it): render a summary there with a "See all" that calls `requestDisplayMode("fullscreen")`, and the full view when `displayMode` is `"fullscreen"` (the peek, a full page, a tab).\n\nWorkspace attachment does not render individual events. For an event presentation, attach to its specific `semantic_type` (event kind), optionally restricted to a linked entity type with `type`; a metadata schema name does not select the view. Avoid binding a specialized renderer to a generic kind such as `summary`. Register a dedicated kind in the workspace\'s event-kind registry and have its producer emit it. On event pages and event peeks, read `useScope().event` by exact ID and select that ID from the returned lineage; never substitute the latest event or let a URL date param change the subject. A shared workspace/event module should branch on `scope.event`, keeping history selection on its workspace surface. Preserve a readable stored body for fallback and evidence.\n\nBefore reporting a view working, open each attached surface, including an event page and peek when declared. Exercise filtering, drilldown, keyboard navigation, and a narrow pane; check loading, missing/error, and truncated data states. Refresh and reopen an earlier event of the kind to verify the view stays on that event rather than jumping to the newest one. Views render in an iframe, so an empty parent-page DOM is not evidence the view is empty; inspect the frame through an authorized browser or accessibility surface. A successful compile proves only that the bundle was built.\n\nImport reusable UI from **`@lobu/views/components`**. Discover this kit with `search_sdk({ query: "@lobu/views/components" })` or a component name. Start with the largest suitable native surface; compose smaller parts only for needs it does not cover:\n\n| Need | Component and minimum input |\n| --- | --- |\n| Complete entity list | `EntityListPage title={title} table={tableProps}` |\n| SQL, computed TypeScript or local rows | `EntityListPage title={title}` with `DataTable columns={columns} rows={rows} keyOf={keyOf}` as children |\n| Complete record body | `EntityRecordPage entity={entity} owner={workspace} schema={schema}` |\n| Entity table or individual fields | `EntityTableView`, `RecordSpecSheet`, `SchemaValue`, `EntityAvatar` |\n| Workspace schema, proposed schema or schema diff | `SchemaGraph`, `SchemaGraph schema={spec}`, `SchemaGraph schema={spec} base="workspace"`, or `SchemaGraph schema={after} base={before}` |\n| Saved resource identity and navigation | `AutomationReference`, `AgentReference`, `ConnectorReference` |\n| Automation instructions, sources, triggers, outputs and code | `AutomationDefinition value={definition}` |\n| Agent identity, models and settings | `AgentDefinition value={definition}` |\n| Connector actions, feeds, schemas and source | `ConnectorDefinition value={definition}` |\n| Current / Proposed comparison | Existing `Tabs` with the same definition component in each panel |\n| Optional technical details | `JsonDiff before={current} after={proposed}` inside collapsed `<details>` |\n\nThe host supplies native JS/CSS, React and live theme. Do not copy product markup or bundle a second React. Exported prop types describe the shared contracts. Use `Button`, `Badge`, `Card`, chart and state components for surrounding UI.\n\n**Page bodies are controlled.** Supply data and slots; they fetch nothing and authorize no writes. `EntityListPage` accepts `title`, optional `actions`/`controls`, and either `table: EntityTableViewProps` or `children`. Its `loading`, `error`, `onRetry` and `empty` affect only results, keeping controls mounted. Native table props include rows, schema, linked lookups, sorting and pagination; honor `metadata.has_more`. For SQL/TypeScript rows use `DataTable`, without inventing entity IDs or types. `EntityRecordPage` renders the native title/avatar and schema fields; `actions`, `details`, `summary`, and `children` supply editing, links, activity and tabs. Default `layout="record"` adapts to width; `layout="content"` retains the header while children own the layout. A `null` title/details/summary hides that slot. Preserve zero and false.\n\n**SchemaGraph is read-only.** It reuses the native schema canvas. Omit props for the mounted workspace schema, pass `schema` for a supplied snapshot, add `base="workspace"` to compare a proposal with the live workspace, or pass another spec as `base`. A spec is `{ entityTypes: [{ slug, name?, description?, metadata_schema?, event_kinds? }], relationshipTypes: [{ slug, name?, metadata_schema?, rules: [{ source_entity_type_slug, target_entity_type_slug }] }] }`. Specs are full snapshots: an omitted type is removed in a diff. Added, removed and changed types/rules remain visible; inspect type details for metadata fields, event kinds and rule changes. Existing entity types open their native pages; unsaved types show details in place. Live reads use the visiting user\u2019s session and permissions through the existing broker; supplied snapshots still render when workspace reads are unavailable. No edits or schema writes are performed. The leaf names match `entitySchema`: list responses use `entity_types` / `relationship_types`; attach `listRules` results to the matching relationship by ID. To apply a reviewed spec, use existing `createType` / `createRelType` (both require `name`) and `addRule({ slug, ...rule })` separately. The graph\u2019s optional name falls back to slug for display only. Hosts without native components throw the standard unavailable-native error.\n\n**References resolve saved identity.** Pass `mode="live"`, mounted `workspace`, optional `appearance="inline" | "row"` (default row), and `automationId` (positive decimal string), `agentId`, or `connectorKey` plus optional numeric `connectionId`. Discover IDs first. These reuse product rows and visiting-user permission checks; they accept no authored name/status or mutation callbacks. Invalid selectors, another workspace, missing records and refused reads show unavailable. A connector definition does not imply a connected account. Reads refresh on mount, focus, reconnect and host invalidation, without interval polling.\n\n**Definitions render supplied objects.** All three have the same signature: `{ value: Record<string, unknown> }`. Pass the existing saved definition or complete proposed snapshot, not a patch. Automation fields include `name`, `description`, `prompt`, `sources`, `triggers`, `outputs`, `reaction_script`; Agent fields include `name`, `description`, `identity_md`, `settings`; Connector fields include `name`, `description`, `version`, `actions_schema`, `feeds_schema`, `source_code`. Remaining nested settings stay inspectable. Missing fields differ from empty values. Bodies fetch nothing, execute no supplied code, and add no save/approval controls. Label authored objects as Snapshot or Proposal preview; use a reference for live identity. Never supply credentials.\n\nShow changes as **Current / Proposed**, defaulting to Proposed, with the same native body on both sides. Keep JSON diff optional. Rendering does not save or apply anything and needs no new proposal endpoint. For an existing approval, render its held current/proposed snapshots; do not merge in newer live values. Writes remain on existing declared `useAction` paths or native authorized editor/review pages. An authored preview must not imply a held approval or authority to apply it.\n\n```tsx\nimport {\n Card, ConnectorDefinition, JsonDiff,\n Tabs, TabsList, TabsTrigger, TabsContent,\n} from "@lobu/views/components";\n\n// current and proposed are complete definition objects from authorized reads\n// and the requested edit. Use AgentDefinition or AutomationDefinition identically.\n<Card title="Connector proposal preview" description="Nothing has been applied.">\n <Tabs defaultValue="proposed">\n <TabsList label="Definition version">\n <TabsTrigger value="current">Current</TabsTrigger>\n <TabsTrigger value="proposed">Proposed</TabsTrigger>\n </TabsList>\n <TabsContent value="current"><ConnectorDefinition value={current} /></TabsContent>\n <TabsContent value="proposed"><ConnectorDefinition value={proposed} /></TabsContent>\n </Tabs>\n <details><summary>Technical diff</summary><JsonDiff before={current} after={proposed} /></details>\n</Card>\n```\n\nUse `useHost().openRecord({ entity_id, entity_type? }, { mode: "peek" })` for a record\'s native peek. String source keys require the type. The promise reports the actual `{ mode: "peek" | "page" }`; a host without native peek opens the server-returned record URL. Errors remain errors. `useHost().theme` follows live theme changes; native components inherit the host palette and typography automatically. Use semantic host style variables and avoid hardcoded light/dark colors.\n\nRules that are load-bearing, not style:\n\n- Use structured reads: `useQuery(tool("manage_entity", { action: "list", entity_type: type, filters, limit: 100 }))`. The host admits entity `list/get/list_links` and entity-type schema `list/get` reads; tools marked read-only are also available. Use existing tool input/result contracts and preserve server authorization. Send structured arguments, never TypeScript inside a string. `sql` remains available; script-string queries are compatibility support for installed views. `query_sql` allows 500 rows max with a 5 second timeout \u2014 branch on the typed `errorCode` (e.g. `UPSTREAM_TIMEOUT`), never on message text, and render `truncated` honestly instead of passing partial data off as complete. Each `query_sql` cell is bounded too: strings keep their first 4,000 Unicode code points plus "\u2026 [truncated]"; JSON values over 16 KiB become `{ _truncated: true, bytes }` (attachments become null with `attachments_truncated`). `truncatedColumns` names the affected columns. Select smaller elements or fields, for example one array element per row with `jsonb_array_elements(...)`, and paginate as needed; each returned cell is still subject to these limits.\n- Never aggregate history in a view: no `GROUP BY`, `DISTINCT ON`, per-row regexp, or leading-wildcard `LIKE` over `events` or other growing tables. For "latest state" views, have an Automation maintain keyed event outputs (each run supersedes the previous event with the same key) and read the current head with `read_knowledge`.\n- `run_sdk` is not exposed to views. Writes go only through declared view actions (`useAction` \u2192 `invoke_view_action`). An action declares `emits` (append that event kind, which can activate workspace-triggered Automations), `updates: { entityType, fields }` (write those metadata fields on one record), or both, which commit in one transaction. An `updates` action takes `value: { entity_id, set: { field: value } }`; the view must attach to `entityType`, `set` may only name declared fields, and schema-stamped fields are refused. Pass `{ expected }` as the second argument with the values the view read: a stale read returns 409 `PRECONDITION_FAILED` and writes nothing. The write runs as the clicking user without claiming field ownership, so a human-owned field comes back as `pending_approval` instead of `applied`. Do not add an Automation that only copies an action\'s event onto the record; declare `updates` instead. Action `value` payloads are capped at 4000 JSON chars \u2014 save content first, then pass the id. A subject shown from a superseded event rejects with 409; refetch and ask the user to re-confirm rather than retrying blindly.\n\n ```tsx\n // actions: { markWon: { emits: "deal.won", updates: { entityType: "deal", fields: ["stage"] } } }\n const markWon = useAction("markWon");\n const sent = await markWon({ entity_id: deal.id, set: { stage: "won" } }, { expected: { stage: deal.metadata.stage } });\n // sent.result.applied: { entity_id, fields } with server stamps; sent.result.pending_approval when held\n ```\n- Link with `Link` from `@lobu/views/components` (or `useHost().openLink`): `href="<type>/<slug>"` opens that record in the workspace, supported links within the same workspace open in the peek pane, other app links navigate normally, and external URLs open a new tab. A plain `<a href>` goes nowhere inside the sandboxed frame.\n- For several offers, publish one event with a card for each held proposal. Obtain the real pending approval through the existing agent/Automation write method under its normal policy, then read its returned event ID to obtain the canonical review URL. Link each card to that exact review; the host opens it in peek. Each offer has its own run and decision. Use native Current/Proposed fields for updates and the proposed definition for creation. A resource snapshot alone is a preview, not an approval: never fabricate Approve/Reject buttons or imply that a missing resource ID creates anything. Existing settings `?run_id=` links remain compatible; new offers use the proposal review instead of the settings page.\n- Views run in a sandboxed frame with no direct network: no fetch, no third-party calls at runtime. Reuse local React components through relative imports and `source_files: { entrypoint, files }` plus `dependencies: {}` for local-only components with `views.set`, or use `viewFromFile` + `lobu apply`. Extra npm dependencies need the CLI-bundled `compiled_code`; listing `dependencies` alone does not install packages.\n- Never early-return the whole view on loading/error: each filter keystroke re-queries, so an early return unmounts the focused input mid-typing. Keep filters mounted and render query states inline in the results area.\n- Before calling a view verified, exercise the exact compiled artifact and host runtime in a sandboxed browser: representative data, loading, empty and error states, filters, sort/pagination, links/peek, declared actions, light/dark and narrow layouts. Fix failures and rerun. Registration compiles the module and requires an isolated browser check of the exact candidate against bounded empty/error/loading fixtures in light/dark themes and inline/fullscreen modes for every distinct attached scope (at most eight per module; each scope is its own bounded runner request). A failed check returns 422; an unavailable runner returns 503; both preserve the saved view. Fixture validation does not prove successful workspace data or every interaction. Distinguish compiled, browser-verified, stored and deployed; never claim more than the evidence.\n- Params sync to the URL on Lobu hosts only; elsewhere they stay frame-local. `refetch()` re-reads on demand; only Lobu hosts push live data-changed refreshes.\n\n## Connectors, Feeds, and Operations\n\nConnectors are the primary integration path for third-party services. The\nend-to-end model (entities vs events, the run lifecycle) is in\n`docs/CONCEPTS.md`; authoring a new connector when none matches is in\n`docs/connector-authoring.md`. Do not freeze a connector lifecycle in project\ninstructions because it can drift from the deployed SDK:\n\n1. Call `search_sdk` with the service name immediately before acting. It returns installed and installable connectors, declared feed keys, readiness, and the caller-aware live lifecycle. Then, before requesting app credentials, call `client.connections.setupOptions({ connector_key })` against the selected runtime: it discovers verified cloud-managed OAuth and hosted chat alongside local setup, so follow the URLs and instructions it returns. `cloud_status: "unavailable"` is a discovery outage, not evidence that managed auth is absent. Options are offers, not connected accounts.\n2. Always follow the methods it returns in order instead of relying on a remembered connect/feed/operation sequence. Repeat discovery after authorization or state changes so the next step reflects the live connector and current caller.\n3. Treat `access: operate` as `mcp:write` and `access: administer` as workspace owner/admin plus `mcp:admin`. If discovery asks for MCP reauthorization or an owner/admin handoff, follow that instruction; never attempt methods it withheld as unavailable.\n\nSource-backed feeds query the provider only through an explicit `client.feeds.readMany({ reads: [...] })` call; `search_memory` stays local and reports unqueried source feeds in `coverage`, while `client.feeds.get` returns metadata without source access. Feeds with `sync` may persist events for search and relational queries. For connector actions, use the live discovery result\'s operation target and readiness. If readiness is disconnected, follow the returned next action instead of guessing a connection. Surface approval-gated `pending_approval` as a waiting state, not a failure.\n\n## Data Ingestion\n\n- Use `lobu memory seed` for small declarative YAML datasets under `./data`; it processes records sequentially and is not a bulk-backfill path.\n- Use `client.knowledge.save` for schema-less semantic history such as messages, notes, observations, and content. Pass `supersedes_event_id` when replacing an existing fact.\n- Use `client.entities.create` / `client.entities.update` only for strict structured records that match declared entity schemas.\n- For large backfills, send bounded chunks through `run_sdk` / `lobu call run_sdk` and use `Promise.allSettled` so conflicts and partial failures remain visible.\n\n```ts\nexport default async (_ctx, client) => {\n const records = [\n { content: "...", semantic_type: "note" },\n { content: "...", semantic_type: "observation" },\n ];\n return Promise.allSettled(records.map((record) => client.knowledge.save(record)));\n};\n```\n';
|
|
169218
169253
|
}
|
|
169219
169254
|
});
|
|
169220
169255
|
|
|
@@ -188561,6 +188596,11 @@ async function runWorkspacePurgeTask(payload, ctx) {
|
|
|
188561
188596
|
await batch(
|
|
188562
188597
|
"organization",
|
|
188563
188598
|
(tx) => withAclPrivilege(tx, async () => {
|
|
188599
|
+
await tx`SELECT id FROM organization WHERE id = ${organizationId} FOR UPDATE`;
|
|
188600
|
+
await tx`
|
|
188601
|
+
UPDATE personal_access_tokens SET revoked_at = NOW(), updated_at = NOW()
|
|
188602
|
+
WHERE organization_id = ${organizationId} AND revoked_at IS NULL
|
|
188603
|
+
`;
|
|
188564
188604
|
const deleted = await tx`DELETE FROM organization WHERE id = ${organizationId}`;
|
|
188565
188605
|
return deleted.count;
|
|
188566
188606
|
})
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lobu/runtime-server",
|
|
3
|
-
"version": "24.11.
|
|
3
|
+
"version": "24.11.1",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@lobu/runtime-server",
|
|
9
|
-
"version": "24.11.
|
|
9
|
+
"version": "24.11.1",
|
|
10
10
|
"license": "BUSL-1.1",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@agentclientprotocol/sdk": "1.4.0",
|
|
@@ -11497,7 +11497,7 @@
|
|
|
11497
11497
|
},
|
|
11498
11498
|
"vendor/connector-sdk": {
|
|
11499
11499
|
"name": "@lobu/connector-sdk",
|
|
11500
|
-
"version": "24.11.
|
|
11500
|
+
"version": "24.11.1",
|
|
11501
11501
|
"license": "BUSL-1.1",
|
|
11502
11502
|
"dependencies": {
|
|
11503
11503
|
"@lobu/core": "file:../core",
|
|
@@ -11512,7 +11512,7 @@
|
|
|
11512
11512
|
},
|
|
11513
11513
|
"vendor/core": {
|
|
11514
11514
|
"name": "@lobu/core",
|
|
11515
|
-
"version": "24.11.
|
|
11515
|
+
"version": "24.11.1",
|
|
11516
11516
|
"license": "Apache-2.0",
|
|
11517
11517
|
"dependencies": {
|
|
11518
11518
|
"@opentelemetry/api": "^1.9.0",
|
|
@@ -11557,7 +11557,7 @@
|
|
|
11557
11557
|
},
|
|
11558
11558
|
"vendor/views": {
|
|
11559
11559
|
"name": "@lobu/views",
|
|
11560
|
-
"version": "24.11.
|
|
11560
|
+
"version": "24.11.1",
|
|
11561
11561
|
"license": "Apache-2.0",
|
|
11562
11562
|
"dependencies": {
|
|
11563
11563
|
"@lobu/core": "file:../core"
|
package/package.json
CHANGED
package/vendor/core/package.json
CHANGED