@lobu/runtime-device 24.3.0 → 24.5.0

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.
Files changed (96) hide show
  1. package/dist/component.json +1 -1
  2. package/dist/dependencies.bun.lock +66 -68
  3. package/dist/verify.mjs +1 -1
  4. package/npm-shrinkwrap.json +165 -181
  5. package/package.json +2 -2
  6. package/vendor/cli/dist/bundled-skills/lobu/SKILL.md +23 -5
  7. package/vendor/cli/dist/bundled-skills/lobu-connect/SKILL.md +6 -0
  8. package/vendor/cli/dist/commands/_lib/apply/apply-cmd.js +20 -13
  9. package/vendor/cli/dist/commands/_lib/apply/client.d.ts +48 -100
  10. package/vendor/cli/dist/commands/_lib/apply/client.js +76 -27
  11. package/vendor/cli/dist/commands/_lib/apply/deployment.js +1 -1
  12. package/vendor/cli/dist/commands/_lib/apply/desired-state.d.ts +7 -11
  13. package/vendor/cli/dist/commands/_lib/apply/desired-state.js +9 -40
  14. package/vendor/cli/dist/commands/_lib/apply/diff.d.ts +4 -4
  15. package/vendor/cli/dist/commands/_lib/apply/diff.js +37 -33
  16. package/vendor/cli/dist/commands/_lib/apply/map-config.d.ts +1 -1
  17. package/vendor/cli/dist/commands/_lib/apply/map-config.js +79 -92
  18. package/vendor/cli/dist/commands/_lib/apply/shared.d.ts +3 -6
  19. package/vendor/cli/dist/commands/_lib/apply/shared.js +8 -19
  20. package/vendor/cli/dist/commands/dev.js +21 -7
  21. package/vendor/cli/dist/commands/doctor.js +1 -8
  22. package/vendor/cli/dist/commands/init.js +4 -5
  23. package/vendor/cli/dist/config/define.d.ts +27 -28
  24. package/vendor/cli/dist/config/define.js +4 -5
  25. package/vendor/cli/dist/connectors/postgres.ts +77 -48
  26. package/vendor/cli/dist/internal/api-client.d.ts +2 -0
  27. package/vendor/cli/dist/internal/api-client.js +6 -1
  28. package/vendor/cli/dist/internal/node-binary.d.ts +22 -0
  29. package/vendor/cli/dist/internal/node-binary.js +73 -0
  30. package/vendor/cli/dist/internal/node-version.d.ts +7 -12
  31. package/vendor/cli/dist/internal/node-version.js +16 -20
  32. package/vendor/cli/dist/runtime-components.json +4 -4
  33. package/vendor/cli/dist/templates/AGENTS.md.tmpl +2 -2
  34. package/vendor/cli/package.json +2 -2
  35. package/vendor/connector-sdk/dist/reaction-client-types.d.ts +8 -2
  36. package/vendor/connector-sdk/dist/reaction-sdk.d.ts +5 -1
  37. package/vendor/connector-sdk/package.json +1 -1
  38. package/vendor/connector-worker/dist/daemon/acp-adapters/claude.js +1 -1
  39. package/vendor/connector-worker/dist/daemon/agent-turn.js +69 -3
  40. package/vendor/connector-worker/dist/daemon/client.d.ts +25 -8
  41. package/vendor/connector-worker/dist/daemon/client.js +32 -4
  42. package/vendor/connector-worker/dist/daemon/log.js +2 -1
  43. package/vendor/connector-worker/dist/daemon/mac-device-daemon.js +7 -1
  44. package/vendor/connector-worker/dist/daemon/poll-loop.d.ts +17 -0
  45. package/vendor/connector-worker/dist/daemon/poll-loop.js +101 -13
  46. package/vendor/connector-worker/dist/daemon/resource-admission.d.ts +19 -0
  47. package/vendor/connector-worker/dist/daemon/resource-admission.js +59 -0
  48. package/vendor/connector-worker/dist/daemon/resources.d.ts +20 -0
  49. package/vendor/connector-worker/dist/daemon/resources.js +163 -0
  50. package/vendor/connector-worker/dist/daemon/start.js +29 -4
  51. package/vendor/connector-worker/dist/daemon/worker.d.ts +2 -0
  52. package/vendor/connector-worker/dist/daemon/worker.js +4 -0
  53. package/vendor/connector-worker/dist/executor/select.d.ts +1 -1
  54. package/vendor/connector-worker/dist/executor/select.js +1 -1
  55. package/vendor/connector-worker/dist/isolate/ivm-types.d.ts +1 -2
  56. package/vendor/connector-worker/dist/isolate/ivm-types.js +1 -2
  57. package/vendor/connector-worker/dist/isolate/load.d.ts +10 -12
  58. package/vendor/connector-worker/dist/isolate/load.js +23 -27
  59. package/vendor/connector-worker/dist/self-check/index.d.ts +2 -2
  60. package/vendor/connector-worker/dist/self-check/index.js +2 -2
  61. package/vendor/connector-worker/package.json +3 -4
  62. package/vendor/core/dist/contracts/agent-settings.d.ts +61 -6
  63. package/vendor/core/dist/contracts/agent-settings.js +10 -7
  64. package/vendor/core/dist/contracts/tools/manage-agents.d.ts +473 -98
  65. package/vendor/core/dist/contracts/tools/manage-agents.js +111 -2
  66. package/vendor/core/dist/contracts/tools/manage-automations.d.ts +21 -18
  67. package/vendor/core/dist/contracts/tools/manage-automations.js +15 -15
  68. package/vendor/core/dist/contracts/tools/manage-entity-schema.js +2 -2
  69. package/vendor/core/dist/contracts/tools/manage-entity.d.ts +45 -20
  70. package/vendor/core/dist/contracts/tools/manage-entity.js +17 -5
  71. package/vendor/core/dist/contracts/tools/manage-inference-providers.d.ts +445 -0
  72. package/vendor/core/dist/contracts/tools/manage-inference-providers.js +133 -0
  73. package/vendor/core/dist/contracts/tools/manage-views.d.ts +4 -4
  74. package/vendor/core/dist/contracts/tools/manage-views.js +5 -3
  75. package/vendor/core/dist/contracts/worker/device-automation.js +4 -2
  76. package/vendor/core/dist/error-report.d.ts +73 -0
  77. package/vendor/core/dist/error-report.js +346 -0
  78. package/vendor/core/dist/index.d.ts +4 -1
  79. package/vendor/core/dist/index.js +7 -1
  80. package/vendor/core/dist/logger.js +15 -6
  81. package/vendor/core/dist/otel-fetch.d.ts +19 -0
  82. package/vendor/core/dist/otel-fetch.js +96 -0
  83. package/vendor/core/dist/otel.d.ts +22 -2
  84. package/vendor/core/dist/otel.js +95 -48
  85. package/vendor/core/dist/reserved.d.ts +1 -1
  86. package/vendor/core/dist/reserved.js +6 -4
  87. package/vendor/core/dist/tool-result.d.ts +8 -0
  88. package/vendor/core/dist/tool-result.js +61 -0
  89. package/vendor/core/dist/trace-context.d.ts +12 -0
  90. package/vendor/core/dist/trace-context.js +50 -0
  91. package/vendor/core/dist/utils/diagnostic-scrubber.js +1 -1
  92. package/vendor/core/dist/worker/auth.js +4 -0
  93. package/vendor/core/package.json +6 -1
  94. /package/vendor/cli/dist/vendor/ora/{.bun-tag-fde20e9a6df212fa → .bun-tag-77bb9b258a474a18} +0 -0
  95. /package/vendor/ora/{.bun-tag-fde20e9a6df212fa → .bun-tag-77bb9b258a474a18} +0 -0
  96. /package/vendor/postgres/{.bun-tag-22d644c2873790db → .bun-tag-c81dacd34e959a7a} +0 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lobu/runtime-device",
3
- "version": "24.3.0",
3
+ "version": "24.5.0",
4
4
  "type": "module",
5
5
  "license": "BUSL-1.1",
6
6
  "repository": {
@@ -14,7 +14,7 @@
14
14
  "npm-shrinkwrap.json"
15
15
  ],
16
16
  "engines": {
17
- "node": ">=22 <25 || >=26"
17
+ "node": ">=26 <27"
18
18
  },
19
19
  "overrides": {
20
20
  "sharp": "^0.35.3"
@@ -50,7 +50,7 @@ If the user gave permission to research and has a public domain, research the co
50
50
 
51
51
  ### 3. Discover the surface before choosing how to scaffold
52
52
 
53
- Check Node is 22-24 or 26+ (only Node 25 is unsupported), 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.
53
+ Check 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.
54
54
 
55
55
  Use 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.
56
56
 
@@ -236,9 +236,17 @@ Search before create to avoid duplicates. Prefer a read or dry run before mutati
236
236
 
237
237
  ## Custom Views
238
238
 
239
- When a user would benefit from exploring data, offer or build an interactive view: linked charts, searchable tables, filters, drilldowns, scenario controls, or a Canvas/SVG visualization. Prefer an existing view when it already answers the question. Views are ordinary React, so authors can compose their own components; the default components are a starting point.
239
+ Before 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:
240
240
 
241
- Views 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 single-file sources over MCP with `manage_views` (owner/admin only).
241
+ 1. Use the largest existing surface or component that meets the task. Configure its segment, filters, search, saved preset and layout before replacing its UI.
242
+ 2. 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.
243
+ 3. 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.
244
+
245
+ Check 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. When exploration needs specialized linked charts, drilldowns, scenario controls or Canvas/SVG, compose a React view from the suitable existing components.
246
+
247
+ Native 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.
248
+
249
+ Views 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).
242
250
 
243
251
  Module shape (the server resolves React, React DOM, `@lobu/views` and `@lobu/views/components`; other dependencies need the CLI path with `node_modules` present):
244
252
 
@@ -292,7 +300,17 @@ export default function Pipeline() {
292
300
  }
293
301
  ```
294
302
 
295
- `defineView` is the view's only declaration: `key`, optional `name` (defaults to the key) and `description`, `attach`, `params` and `actions` are read from it, never passed separately, so `manage_views` `set` takes just the source. Write it out as a literal (no variables, spreads or `${}` templates): the server reads it without running the module.
303
+ `defineView` is the view's only declaration: `key`, optional `name` (defaults to the key) and `description`, `attach`, `params` and `actions` 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.
304
+
305
+ For 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]`:
306
+
307
+ ```ts
308
+ await client.views.set({
309
+ source_code: files[entrypoint],
310
+ source_files: { entrypoint, files },
311
+ dependencies: {}, // Local files and the host-provided runtime need no extra packages.
312
+ });
313
+ ```
296
314
 
297
315
  `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).
298
316
 
@@ -306,7 +324,7 @@ Rules that are load-bearing, not style:
306
324
  - 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`.
307
325
  - Writes go only through declared view actions (`useAction` → `invoke_view_action`), which emit the declared event kind and can activate workspace-triggered Automations. 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.
308
326
  - Link with `Link` from `@lobu/views/components` (or `useHost().openLink`): `href="<type>/<slug>"` opens that record in the workspace, a full URL opens a new tab. A plain `<a href>` goes nowhere inside the sandboxed frame.
309
- - Views run in a sandboxed frame with no direct network: no fetch, no third-party calls at runtime. Bundle shared code via the CLI path; the MCP `manage_views` path compiles `react` + `@lobu/views` (+components) only.
327
+ - 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.
310
328
  - 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.
311
329
  - 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.
312
330
 
@@ -30,3 +30,9 @@ If Lobu authentication is required, let the host complete OAuth in the user's br
30
30
  Local Automation delivery is a separate opt-in setup and is not enabled by installing Lobu here.
31
31
 
32
32
  Before requesting connector app credentials, discover `connections.setupOptions` with `search_sdk` and call it in the selected workspace. It returns verified managed OAuth, hosted cloud chat, and local setup choices. Follow the returned URL and instructions; an unavailable cloud lookup is not proof that no managed offer exists. On account-scoped MCP, select an authorized home workspace before calling `connections.connectManaged` against cloud; the provider org is its `managed_by_org` argument. Managed OAuth can support local execution. Hosted Slack chat targets a cloud agent and does not connect an independent embedded runtime.
33
+
34
+ ## Interactive views
35
+
36
+ Before building UI, inspect available native entity/event pages, existing views with `views.list` / `views.get`, and project components and overrides. Honor explicit user designs and reuse what fits. Discover `views.set` or `@lobu/views/components` with `search_sdk`: the kit supplies defaults such as `Card`, `DataTable`, filters, charts and query states; custom React components remain supported.
37
+
38
+ Read **Custom Views** in the connected runtime's full Lobu skill before authoring: the `skill://lobu` MCP resource or `<runtime-origin>/api/skill/lobu` ([Lobu Cloud](https://app.lobu.ai/api/skill/lobu)). It covers attachments, bounded reads, actions, bundling, and browser verification. Use the selected runtime's guide so the contract matches its deployment.
@@ -205,7 +205,7 @@ export async function fetchRemoteSnapshot(client, state, only, prune = false) {
205
205
  const remoteAgentIds = new Set(agents.map((a) => a.agentId));
206
206
  const targetAgentIds = desiredAgentIds.filter((id) => remoteAgentIds.has(id));
207
207
  for (const agentId of targetAgentIds) {
208
- agentSettings.set(agentId, await client.getAgentSettings(agentId));
208
+ agentSettings.set(agentId, await client.getAgentSettings(agentId, agents.find((agent) => agent.agentId === agentId)));
209
209
  }
210
210
  }
211
211
  const entityTypes = only === "agents" ? [] : await client.listEntityTypes();
@@ -302,6 +302,14 @@ async function installConnectorDefinitions(client, state, catalog, plan) {
302
302
  const def = row.desired;
303
303
  if (!def)
304
304
  continue;
305
+ const key = def.key ?? def.declaredKeyHint;
306
+ const remote = catalog.find((entry) => entry.installed && entry.key === key);
307
+ if (row.verb === "update" && !remote?.version) {
308
+ throw new ApiError(`Cannot safely update connector '${key}': its active version is missing. Refresh the catalog and retry.`);
309
+ }
310
+ const target = row.verb === "update" && remote?.version
311
+ ? { connector_key: remote.key, expected_version: remote.version }
312
+ : undefined;
305
313
  let result;
306
314
  if (def.sourcePath) {
307
315
  const artifact = def.compiledArtifact;
@@ -313,16 +321,16 @@ async function installConnectorDefinitions(client, state, catalog, plan) {
313
321
  compiledCode: artifact.compiledCode,
314
322
  sourceFiles: artifact.sourceFiles,
315
323
  dependencies: artifact.dependencies,
316
- });
324
+ }, target);
317
325
  }
318
326
  else if (def.sourceCode !== undefined) {
319
327
  // `source_url` connector: source was fetched into `sourceCode` and has no
320
328
  // local project/node_modules to bundle against — upload it raw and let
321
329
  // the gateway compile it (the pre-existing path).
322
- result = await client.installConnector({ sourceCode: def.sourceCode });
330
+ result = await client.installConnector({ sourceCode: def.sourceCode }, target);
323
331
  }
324
332
  else {
325
- result = await client.installConnector({ sourceUrl: def.sourceUrl });
333
+ result = await client.installConnector({ sourceUrl: def.sourceUrl }, target);
326
334
  }
327
335
  if (result.connectorKey) {
328
336
  locallySuppliedKeys.add(result.connectorKey);
@@ -641,8 +649,8 @@ export async function executePlan(ctx, pendingAuth) {
641
649
  min_cooldown_seconds: w.minCooldownSeconds,
642
650
  tags: w.tags,
643
651
  agent_kind: w.agentKind,
644
- execution_config: w.model !== undefined || w.executor !== undefined
645
- ? automationExecutionConfig(w.model, undefined, w.executor)
652
+ execution_config: w.executionConfig !== undefined || w.model !== undefined
653
+ ? automationExecutionConfig(w.model, undefined, w.executionConfig)
646
654
  : undefined,
647
655
  outputs: w.outputs,
648
656
  });
@@ -672,7 +680,7 @@ export async function executePlan(ctx, pendingAuth) {
672
680
  // update reaches the server. Push first (idempotent, no drift signal
673
681
  // because it's not returned by Automation lists) so the rule sees it.
674
682
  // Removal (`reaction: null`) is handled in step (b2) below, after the
675
- // executor install — never here.
683
+ // scalar updates — never here.
676
684
  if (w.reactionScript) {
677
685
  await ctx.client.setReactionScript(automationId, w.reactionScript.sourceCode);
678
686
  }
@@ -701,15 +709,14 @@ export async function executePlan(ctx, pendingAuth) {
701
709
  : {}),
702
710
  ...(scalarForUpdate.includes("execution_config")
703
711
  ? {
704
- execution_config: automationExecutionConfig(w.model, remote?.execution_config, w.executor),
712
+ execution_config: automationExecutionConfig(w.model, remote?.execution_config, w.executionConfig),
705
713
  }
706
714
  : {}),
707
715
  });
708
716
  }
709
- // b2) Reaction removal — AFTER the scalar updates above so a stored
710
- // script executor is installed first. An explicit `reaction: null`
711
- // clears the row via set_reaction_script(""), so a reaction-driven
712
- // job switching to a script executor never runs both paths.
717
+ // b2) Explicit module removal follows scalar updates so the remaining
718
+ // definition is validated with its final owner and execution settings.
719
+ // `reaction: null` clears the row via set_reaction_script("").
713
720
  // Omitted reactions are never touched: the diff only reports
714
721
  // `reaction_script` when declared.
715
722
  if (changed.has("reaction_script") && w.reactionScript === null) {
@@ -726,7 +733,7 @@ export async function executePlan(ctx, pendingAuth) {
726
733
  ? { name: w.name }
727
734
  : {}),
728
735
  ...(versionBound.has("description")
729
- ? { description: w.description ?? null }
736
+ ? { description: w.description ?? "" }
730
737
  : {}),
731
738
  ...(versionBound.has("prompt") ? { prompt: w.prompt } : {}),
732
739
  ...(versionBound.has("skills")
@@ -1,8 +1,12 @@
1
1
  import type { EntityMetrics } from "@lobu/connector-sdk";
2
- import type { AgentSettings } from "@lobu/core";
3
- import type { InstallConnectorInput } from "@lobu/core/contracts/tools/manage-connections";
4
- import type { SourceDependencies, SourceFiles } from "@lobu/core/contracts/tools/source-files";
5
- import type { InferenceCapabilityBlock, InferenceModality } from "../../../config/define.js";
2
+ import { type AgentSettings } from "@lobu/core";
3
+ import type { FlatActionInput } from "@lobu/core/contracts/tools/action-input";
4
+ import type { AuthProfileCreateInput, AuthProfileUpdateInput } from "@lobu/core/contracts/tools/manage-auth-profiles";
5
+ import type { LegacyAutomationExecutionConfig, ManageAutomationsArgs } from "@lobu/core/contracts/tools/manage-automations";
6
+ import type { ConnectionCreateInput, ConnectionUpdateInput, InstallConnectorInput, UpdateConnectorSourceInput } from "@lobu/core/contracts/tools/manage-connections";
7
+ import type { FeedCreateInput, FeedUpdateInput } from "@lobu/core/contracts/tools/manage-feeds";
8
+ import type { InferenceCapabilityBlock, InferenceModality, InferenceProviderCreateInput } from "@lobu/core/contracts/tools/manage-inference-providers";
9
+ import type { ViewSetInput } from "@lobu/core/contracts/tools/manage-views";
6
10
  import { ApiError } from "../../memory/_lib/errors.js";
7
11
  import type { DeploymentSummary } from "./deployment.js";
8
12
  import type { DesiredAgentMetadata, DesiredEntityType, DesiredRelationshipType } from "./desired-state.js";
@@ -124,12 +128,7 @@ export interface RemoteView {
124
128
  last_writer: string;
125
129
  updated_at: string;
126
130
  }
127
- export interface SetViewPayload {
128
- source_code: string;
129
- compiled_code?: string;
130
- source_files?: SourceFiles;
131
- dependencies?: SourceDependencies;
132
- }
131
+ export type SetViewPayload = ViewSetInput;
133
132
  export interface RemoteAutomation {
134
133
  slug: string;
135
134
  name?: string;
@@ -138,8 +137,8 @@ export interface RemoteAutomation {
138
137
  triggers?: import("@lobu/core/contracts/tools/manage-automations").AutomationTrigger[];
139
138
  device_worker_id?: string | null;
140
139
  goal_id?: number | null;
141
- agent_kind?: string | null;
142
- execution_config?: Record<string, unknown> | null;
140
+ agent_kind?: ManageAutomationsArgs["agent_kind"];
141
+ execution_config?: LegacyAutomationExecutionConfig | null;
143
142
  min_cooldown_seconds?: number | null;
144
143
  tags?: string[] | null;
145
144
  sources?: AutomationSource[] | null;
@@ -220,18 +219,17 @@ export interface RemoteFeed {
220
219
  * diff's changed-field list rather than listing every field unconditionally.
221
220
  */
222
221
  export interface UpdateConnectionPayload {
223
- name?: string;
224
- authProfileSlug?: string | null;
225
- appAuthProfileSlug?: string | null;
226
- config?: Record<string, unknown>;
227
- deviceWorkerId?: string | null;
222
+ name?: ConnectionUpdateInput["display_name"];
223
+ authProfileSlug?: ConnectionUpdateInput["auth_profile_slug"];
224
+ appAuthProfileSlug?: ConnectionUpdateInput["app_auth_profile_slug"];
225
+ config?: NonNullable<ConnectionUpdateInput["config"]>;
226
+ deviceWorkerId?: ConnectionUpdateInput["device_worker_id"];
228
227
  }
229
228
  /** The mutable fields of a feed update — same absent-means-unwritten rule. */
230
229
  export interface UpdateFeedPayload {
231
- name?: string;
232
- /** Cron string, or null to clear (manual-only). */
233
- schedule?: string | null;
234
- config?: Record<string, unknown>;
230
+ name?: FeedUpdateInput["display_name"];
231
+ schedule?: FeedUpdateInput["schedule"];
232
+ config?: NonNullable<FeedUpdateInput["config"]>;
235
233
  }
236
234
  interface InstallConnectorResult {
237
235
  connectorKey: string;
@@ -287,6 +285,7 @@ interface ApplyClientConfig {
287
285
  export declare class ApplyClient {
288
286
  private readonly orgSlug;
289
287
  private readonly http;
288
+ private readonly agentRevisions;
290
289
  constructor(cfg: ApplyClientConfig, fetchImpl?: typeof fetch);
291
290
  /**
292
291
  * Delegates the fetch/parse/non-ok-error pipeline to the shared
@@ -317,11 +316,8 @@ export declare class ApplyClient {
317
316
  * to the org-scoped IDs issue.
318
317
  */
319
318
  upsertAgent(agent: DesiredAgentMetadata): Promise<RemoteAgent>;
320
- patchAgentMetadata(agentId: string, agent: {
321
- name?: string;
322
- description?: string;
323
- }): Promise<void>;
324
- getAgentSettings(agentId: string): Promise<AgentSettings | null>;
319
+ patchAgentMetadata(agentId: string, updates: Partial<DesiredAgentMetadata>): Promise<void>;
320
+ getAgentSettings(agentId: string, metadata?: RemoteAgent): Promise<AgentSettings | null>;
325
321
  patchAgentSettings(agentId: string, settings: Partial<AgentSettings>): Promise<void>;
326
322
  /**
327
323
  * Record this apply run as a deployment (`POST /api/<org>/deployments`).
@@ -344,13 +340,7 @@ export declare class ApplyClient {
344
340
  /** List the org's inference providers (never returns the api key). */
345
341
  listInferenceProviders(): Promise<RemoteInferenceProvider[]>;
346
342
  /** Create an org inference provider. 409 (surfaced as ApiError) on slug conflict. */
347
- createInferenceProvider(body: {
348
- slug: string;
349
- kind: string;
350
- displayName?: string;
351
- apiKey: string;
352
- capabilities?: Partial<Record<InferenceModality, InferenceCapabilityBlock>>;
353
- }): Promise<RemoteInferenceProvider>;
343
+ createInferenceProvider(body: InferenceProviderCreateInput): Promise<RemoteInferenceProvider>;
354
344
  /** Upsert one modality's capability block (`{ base_url?, model?, models_endpoint? }`). */
355
345
  updateInferenceProviderCapabilities(slug: string, modality: InferenceModality, block: InferenceCapabilityBlock): Promise<void>;
356
346
  /**
@@ -453,26 +443,8 @@ export declare class ApplyClient {
453
443
  * Create an Automation owned by `agentId`. Duplicate-slug surfaces as a
454
444
  * structured error the caller swallows for idempotency.
455
445
  */
456
- createAutomation(payload: {
457
- slug: string;
458
- agentId: string;
459
- name?: string;
460
- description?: string;
461
- prompt: string;
462
- skills?: Array<{
463
- name: string;
464
- content: string;
465
- }>;
466
- reaction_script?: string;
467
- triggers?: import("@lobu/core/contracts/tools/manage-automations").AutomationTrigger[];
468
- sources?: AutomationSource[];
469
- reactions_guidance?: string;
470
- device_worker_id?: string;
471
- min_cooldown_seconds?: number;
472
- tags?: string[];
473
- agent_kind?: string;
474
- execution_config?: Record<string, unknown> | null;
475
- outputs?: Record<string, unknown> | null;
446
+ createAutomation(payload: FlatActionInput<ManageAutomationsArgs, "slug" | "name" | "description" | "prompt" | "skills" | "reaction_script" | "triggers" | "sources" | "reactions_guidance" | "device_worker_id" | "min_cooldown_seconds" | "tags" | "agent_kind" | "execution_config" | "outputs", "slug" | "prompt"> & {
447
+ agentId: ManageAutomationsArgs["managed_agent_id"];
476
448
  }): Promise<{
477
449
  automation_id?: string;
478
450
  }>;
@@ -485,38 +457,14 @@ export declare class ApplyClient {
485
457
  * `null` clears nullable fields (device_worker_id, agent_kind) per the
486
458
  * server contract.
487
459
  */
488
- updateAutomation(payload: {
489
- automation_id: string;
490
- triggers?: import("@lobu/core/contracts/tools/manage-automations").AutomationTrigger[];
491
- managed_agent_id?: string;
492
- device_worker_id?: string | null;
493
- min_cooldown_seconds?: number;
494
- tags?: string[];
495
- agent_kind?: string | null;
496
- execution_config?: Record<string, unknown> | null;
497
- }): Promise<void>;
460
+ updateAutomation(payload: FlatActionInput<ManageAutomationsArgs, "automation_id" | "triggers" | "managed_agent_id" | "device_worker_id" | "min_cooldown_seconds" | "tags" | "agent_kind" | "execution_config", "automation_id">): Promise<void>;
498
461
  /**
499
462
  * Create a new automation_versions row carrying the version-bound fields, then
500
463
  * upgrade the automation's `current_version_id` to that new version. Server
501
464
  * inherits unset fields from the previous version row.
502
465
  * name/description/prompt/sources are version-owned (update rejects them).
503
466
  */
504
- createAutomationVersion(payload: {
505
- automation_id: string;
506
- name?: string;
507
- description?: string | null;
508
- prompt?: string;
509
- skills?: Array<{
510
- name: string;
511
- content: string;
512
- }>;
513
- sources?: AutomationSource[];
514
- outputs?: Record<string, unknown> | null;
515
- reactions_guidance?: string;
516
- change_notes?: string;
517
- /** When set, written atomically with the new version (set_as_current). */
518
- triggers?: import("@lobu/core/contracts/tools/manage-automations").AutomationTrigger[];
519
- }): Promise<{
467
+ createAutomationVersion(payload: FlatActionInput<ManageAutomationsArgs, "automation_id" | "name" | "description" | "prompt" | "skills" | "sources" | "outputs" | "reactions_guidance" | "change_notes" | "triggers", "automation_id">): Promise<{
520
468
  version?: number;
521
469
  }>;
522
470
  /**
@@ -541,7 +489,7 @@ export declare class ApplyClient {
541
489
  * connector by id or pass connector source; server returns the resolved
542
490
  * connectorKey plus updated.
543
491
  */
544
- installConnector(payload: CliInstallConnectorPayload): Promise<InstallConnectorResult>;
492
+ installConnector(payload: CliInstallConnectorPayload, target?: Required<Pick<UpdateConnectorSourceInput, "connector_key" | "expected_version">>): Promise<InstallConnectorResult>;
545
493
  uninstallConnector(connectorKey: string): Promise<void>;
546
494
  /**
547
495
  * Re-activate a retained connector version (org-local pointer flip — the
@@ -552,16 +500,16 @@ export declare class ApplyClient {
552
500
  listAuthProfiles(): Promise<RemoteAuthProfile[]>;
553
501
  getAuthProfileBySlug(slug: string): Promise<RemoteAuthProfile | null>;
554
502
  createAuthProfile(payload: {
555
- slug: string;
556
- connector: string;
557
- kind: string;
558
- name?: string;
559
- credentials?: Record<string, string>;
503
+ slug: NonNullable<AuthProfileCreateInput["slug"]>;
504
+ connector: AuthProfileCreateInput["connector_key"];
505
+ kind: AuthProfileCreateInput["profile_kind"];
506
+ name?: AuthProfileCreateInput["display_name"];
507
+ credentials?: AuthProfileCreateInput["credentials"];
560
508
  }): Promise<EnsureAuthProfileResult>;
561
509
  updateAuthProfile(payload: {
562
- slug: string;
563
- name?: string;
564
- credentials?: Record<string, string>;
510
+ slug: AuthProfileUpdateInput["auth_profile_slug"];
511
+ name?: AuthProfileUpdateInput["display_name"];
512
+ credentials?: AuthProfileUpdateInput["credentials"];
565
513
  }): Promise<EnsureAuthProfileResult>;
566
514
  /** Re-issue a connect token for an existing interactive-auth profile. */
567
515
  reconnectAuthProfile(slug: string): Promise<string | undefined>;
@@ -586,23 +534,23 @@ export declare class ApplyClient {
586
534
  changed: boolean;
587
535
  }>;
588
536
  createConnection(payload: {
589
- slug: string;
590
- connector: string;
591
- name?: string;
592
- authProfileSlug?: string;
593
- appAuthProfileSlug?: string;
594
- config?: Record<string, unknown>;
595
- deviceWorkerId?: string;
537
+ slug: NonNullable<ConnectionCreateInput["slug"]>;
538
+ connector: ConnectionCreateInput["connector_key"];
539
+ name?: ConnectionCreateInput["display_name"];
540
+ authProfileSlug?: ConnectionCreateInput["auth_profile_slug"];
541
+ appAuthProfileSlug?: ConnectionCreateInput["app_auth_profile_slug"];
542
+ config?: ConnectionCreateInput["config"];
543
+ deviceWorkerId?: ConnectionCreateInput["device_worker_id"];
596
544
  }): Promise<RemoteConnection>;
597
545
  updateConnection(connectionId: number, payload: UpdateConnectionPayload): Promise<RemoteConnection>;
598
546
  listFeeds(connectionId: number): Promise<RemoteFeed[]>;
599
547
  createFeed(payload: {
600
- connectionId: number;
601
- feedKey: string;
602
- name?: string;
548
+ connectionId: FeedCreateInput["connection_id"];
549
+ feedKey: FeedCreateInput["feed_key"];
550
+ name?: FeedCreateInput["display_name"];
603
551
  /** Cron string, or null for manual-only. */
604
- schedule?: string | null;
605
- config?: Record<string, unknown>;
552
+ schedule?: FeedCreateInput["schedule"];
553
+ config?: FeedCreateInput["config"];
606
554
  }): Promise<RemoteFeed>;
607
555
  updateFeed(feedId: number, payload: UpdateFeedPayload): Promise<RemoteFeed>;
608
556
  }
@@ -1,3 +1,4 @@
1
+ import { getToolResultFailure, isPendingToolApproval, } from "@lobu/core";
1
2
  import { ApiClient } from "../../../internal/api-client.js";
2
3
  import { resolveApiClient } from "../../../internal/index.js";
3
4
  import { ApiError } from "../../memory/_lib/errors.js";
@@ -105,6 +106,7 @@ function hoistEntityTypeSchema(row) {
105
106
  export class ApplyClient {
106
107
  orgSlug;
107
108
  http;
109
+ agentRevisions = new Map();
108
110
  constructor(cfg, fetchImpl = fetch) {
109
111
  this.orgSlug = cfg.orgSlug;
110
112
  this.http = new ApiClient(cfg.apiBaseUrl, cfg.token, fetchImpl, {
@@ -123,8 +125,13 @@ export class ApplyClient {
123
125
  * same outcome the local pipeline did. `Content-Type: application/json` is
124
126
  * sent on every request (no `Accept`) to mirror the previous wire shape.
125
127
  */
126
- async request(method, path, body, okStatuses = [200, 201, 204]) {
127
- const { status, body: raw } = await this.http.requestWithStatus(method, path, body, { okStatuses, sendAccept: false, alwaysJsonContentType: true });
128
+ async request(method, path, body, okStatuses = [200, 201, 204], headers) {
129
+ const { status, body: raw, headers: responseHeaders, } = await this.http.requestWithStatus(method, path, body, {
130
+ okStatuses,
131
+ sendAccept: false,
132
+ alwaysJsonContentType: true,
133
+ headers,
134
+ });
128
135
  let parsed;
129
136
  if (raw === undefined) {
130
137
  parsed = {};
@@ -135,10 +142,15 @@ export class ApplyClient {
135
142
  else {
136
143
  parsed = { value: raw };
137
144
  }
138
- if (typeof parsed.error === "string" && parsed.error.length > 0) {
139
- throw new ApiError(`${method} ${path} returned error: ${parsed.error}`, status);
145
+ if (isPendingToolApproval(parsed)) {
146
+ const run = parsed.run_id != null ? ` (run ${parsed.run_id})` : "";
147
+ throw new ApiError(`Configuration change requires approval${run}. This apply is incomplete; approve the pending change before retrying.`, status, "approval_pending");
148
+ }
149
+ const failure = getToolResultFailure(`${method} ${path}`, parsed);
150
+ if (failure) {
151
+ throw new ApiError(`${method} ${path} returned error: ${failure.message}`, status);
140
152
  }
141
- return { status, body: parsed };
153
+ return { status, body: parsed, headers: responseHeaders };
142
154
  }
143
155
  // ── Organization ──────────────────────────────────────────────────────────
144
156
  /**
@@ -186,12 +198,31 @@ export class ApplyClient {
186
198
  `/api/${this.orgSlug}/agents`, agent, [200, 201]);
187
199
  return body;
188
200
  }
189
- async patchAgentMetadata(agentId, agent) {
190
- await this.request("PATCH", `/api/${this.orgSlug}/agents/${encodeURIComponent(agentId)}`, agent);
201
+ async patchAgentMetadata(agentId, updates) {
202
+ const revision = this.agentRevisions.get(agentId);
203
+ const { headers } = await this.request("PATCH", `/api/${this.orgSlug}/agents/${encodeURIComponent(agentId)}`, updates, undefined, revision ? { "If-Match": revision } : undefined);
204
+ const next = headers.get("etag");
205
+ if (next)
206
+ this.agentRevisions.set(agentId, next);
191
207
  }
192
- async getAgentSettings(agentId) {
208
+ async getAgentSettings(agentId, metadata) {
193
209
  try {
194
- const { body } = await this.request("GET", `/api/${this.orgSlug}/agents/${encodeURIComponent(agentId)}/config`);
210
+ // Apply needs metadata and settings from one revision. Bootstrap callers
211
+ // that only read settings retain the smaller /config response.
212
+ const path = `/api/${this.orgSlug}/agents/${encodeURIComponent(agentId)}`;
213
+ if (metadata) {
214
+ const { body, headers } = await this.request("GET", path);
215
+ const revision = headers.get("etag");
216
+ if (revision)
217
+ this.agentRevisions.set(agentId, revision);
218
+ metadata.name = body.name;
219
+ metadata.description = body.description;
220
+ return body.settings;
221
+ }
222
+ const { body, headers } = await this.request("GET", `${path}/config`);
223
+ const revision = headers.get("etag");
224
+ if (revision)
225
+ this.agentRevisions.set(agentId, revision);
195
226
  return body;
196
227
  }
197
228
  catch (err) {
@@ -201,7 +232,8 @@ export class ApplyClient {
201
232
  }
202
233
  }
203
234
  async patchAgentSettings(agentId, settings) {
204
- await this.request("PATCH", `/api/${this.orgSlug}/agents/${encodeURIComponent(agentId)}/config`, settings);
235
+ const revision = this.agentRevisions.get(agentId);
236
+ await this.request("PATCH", `/api/${this.orgSlug}/agents/${encodeURIComponent(agentId)}/config`, settings, undefined, revision ? { "If-Match": revision } : undefined);
205
237
  }
206
238
  /**
207
239
  * Record this apply run as a deployment (`POST /api/<org>/deployments`).
@@ -770,25 +802,42 @@ export class ApplyClient {
770
802
  * connector by id or pass connector source; server returns the resolved
771
803
  * connectorKey plus updated.
772
804
  */
773
- async installConnector(payload) {
774
- const body = await this.connectionsTool({
775
- action: "install_connector",
776
- ...(payload.connectorId ? { connector_id: payload.connectorId } : {}),
777
- ...(payload.sourceCode !== undefined
778
- ? {
779
- source_code: payload.sourceCode,
780
- compiled: payload.compiled ?? false,
781
- compiled_code: payload.compiledCode,
782
- source_files: payload.sourceFiles,
783
- dependencies: payload.dependencies,
784
- }
785
- : {}),
786
- ...(payload.sourceUrl ? { source_url: payload.sourceUrl } : {}),
787
- ...(payload.sourceUri ? { source_uri: payload.sourceUri } : {}),
788
- });
805
+ async installConnector(payload, target) {
806
+ if (target && payload.sourceCode === undefined) {
807
+ throw new ApiError("Updating an installed connector requires its prepared source code.");
808
+ }
809
+ const artifact = {
810
+ compiled: payload.compiled ?? false,
811
+ compiled_code: payload.compiledCode,
812
+ source_files: payload.sourceFiles,
813
+ dependencies: payload.dependencies,
814
+ };
815
+ const body = await this.connectionsTool(target
816
+ ? {
817
+ action: "update_connector_source",
818
+ ...target,
819
+ source_code: payload.sourceCode,
820
+ ...artifact,
821
+ }
822
+ : {
823
+ action: "install_connector",
824
+ ...(payload.connectorId
825
+ ? { connector_id: payload.connectorId }
826
+ : {}),
827
+ ...(payload.sourceCode !== undefined
828
+ ? {
829
+ source_code: payload.sourceCode,
830
+ ...artifact,
831
+ }
832
+ : {}),
833
+ ...(payload.sourceUrl ? { source_url: payload.sourceUrl } : {}),
834
+ ...(payload.sourceUri ? { source_uri: payload.sourceUri } : {}),
835
+ });
789
836
  return {
790
837
  connectorKey: body.connector_key ?? "",
791
- updated: body.updated ?? false,
838
+ updated: target
839
+ ? body.version !== target.expected_version
840
+ : (body.updated ?? false),
792
841
  ...(body.version ? { version: body.version } : {}),
793
842
  };
794
843
  }
@@ -205,7 +205,7 @@ export function buildAttributionAndOwned(state, remote, orgId, prune = false) {
205
205
  // The three-way baseline must record the effective execution_config after
206
206
  // apply (including preserved remote keys), or a later model edit is
207
207
  // misclassified as "remote moved" blocking drift instead of an update.
208
- execution_config: automationExecutionConfig(d.model, r?.execution_config, d.executor),
208
+ execution_config: automationExecutionConfig(d.model, r?.execution_config, d.executionConfig),
209
209
  outputs: p.outputs,
210
210
  };
211
211
  });