@lobu/runtime-device 20.1.0 → 21.0.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 (121) hide show
  1. package/dist/component.json +1 -1
  2. package/dist/dependencies.bun.lock +46 -40
  3. package/npm-shrinkwrap.json +283 -237
  4. package/package.json +1 -1
  5. package/vendor/cli/dist/commands/_lib/apply/apply-cmd.d.ts +7 -2
  6. package/vendor/cli/dist/commands/_lib/apply/apply-cmd.js +77 -75
  7. package/vendor/cli/dist/commands/_lib/apply/client.d.ts +40 -25
  8. package/vendor/cli/dist/commands/_lib/apply/client.js +31 -39
  9. package/vendor/cli/dist/commands/_lib/apply/deployment.d.ts +1 -1
  10. package/vendor/cli/dist/commands/_lib/apply/deployment.js +2 -2
  11. package/vendor/cli/dist/commands/_lib/apply/desired-state.d.ts +47 -11
  12. package/vendor/cli/dist/commands/_lib/apply/desired-state.js +106 -7
  13. package/vendor/cli/dist/commands/_lib/apply/diff.d.ts +14 -6
  14. package/vendor/cli/dist/commands/_lib/apply/diff.js +42 -23
  15. package/vendor/cli/dist/commands/_lib/apply/map-config.js +2 -3
  16. package/vendor/cli/dist/commands/_lib/apply/render.js +2 -0
  17. package/vendor/cli/dist/commands/_lib/apply/rollback-cmd.js +3 -3
  18. package/vendor/cli/dist/commands/_lib/connector-loader.d.ts +5 -1
  19. package/vendor/cli/dist/commands/_lib/connector-loader.js +1 -1
  20. package/vendor/cli/dist/commands/_lib/ensure-deps-installed.d.ts +15 -26
  21. package/vendor/cli/dist/commands/_lib/ensure-deps-installed.js +227 -136
  22. package/vendor/cli/dist/commands/_lib/view-bundler.d.ts +33 -0
  23. package/vendor/cli/dist/commands/_lib/view-bundler.js +207 -0
  24. package/vendor/cli/dist/commands/_lib/view-reapply.d.ts +60 -0
  25. package/vendor/cli/dist/commands/_lib/view-reapply.js +182 -0
  26. package/vendor/cli/dist/commands/dev.d.ts +14 -5
  27. package/vendor/cli/dist/commands/dev.js +56 -8
  28. package/vendor/cli/dist/commands/init.d.ts +1 -1
  29. package/vendor/cli/dist/commands/init.js +4 -4
  30. package/vendor/cli/dist/commands/login.js +3 -0
  31. package/vendor/cli/dist/config/define.d.ts +25 -8
  32. package/vendor/cli/dist/config/define.js +24 -0
  33. package/vendor/cli/dist/connectors/README.md +15 -16
  34. package/vendor/cli/dist/connectors/chat-user-identity.ts +41 -0
  35. package/vendor/cli/dist/connectors/github.ts +15 -9
  36. package/vendor/cli/dist/connectors/google-identity.ts +11 -0
  37. package/vendor/cli/dist/connectors/google_calendar.ts +21 -31
  38. package/vendor/cli/dist/connectors/google_drive.ts +106 -131
  39. package/vendor/cli/dist/connectors/google_gmail.ts +53 -30
  40. package/vendor/cli/dist/connectors/hackernews.ts +2 -5
  41. package/vendor/cli/dist/connectors/jira.ts +62 -27
  42. package/vendor/cli/dist/connectors/linear.ts +55 -21
  43. package/vendor/cli/dist/connectors/microsoft_outlook.ts +151 -110
  44. package/vendor/cli/dist/connectors/postgres.ts +19 -11
  45. package/vendor/cli/dist/connectors/producthunt.ts +8 -6
  46. package/vendor/cli/dist/connectors/reddit.ts +2 -2
  47. package/vendor/cli/dist/connectors/rss.ts +2 -2
  48. package/vendor/cli/dist/connectors/slack-identity.ts +19 -0
  49. package/vendor/cli/dist/connectors/whatsapp_web.ts +5 -4
  50. package/vendor/cli/dist/connectors/x.ts +32 -17
  51. package/vendor/cli/dist/connectors/youtube.ts +18 -5
  52. package/vendor/cli/dist/internal/connector-compiler.d.ts +1 -1
  53. package/vendor/cli/dist/internal/connector-compiler.js +216 -17
  54. package/vendor/cli/dist/internal/credentials.js +5 -1
  55. package/vendor/cli/dist/internal/oauth.d.ts +15 -1
  56. package/vendor/cli/dist/internal/oauth.js +9 -1
  57. package/vendor/cli/dist/runtime-components.json +4 -4
  58. package/vendor/cli/package.json +2 -1
  59. package/vendor/connector-sdk/dist/connector-runtime.d.ts +4 -6
  60. package/vendor/connector-sdk/dist/connector-runtime.js +3 -5
  61. package/vendor/connector-sdk/dist/connector-types.d.ts +28 -13
  62. package/vendor/connector-sdk/dist/define-connector.d.ts +4 -1
  63. package/vendor/connector-sdk/dist/define-connector.js +4 -1
  64. package/vendor/connector-sdk/dist/http-client.d.ts +18 -7
  65. package/vendor/connector-sdk/dist/http-client.js +15 -13
  66. package/vendor/connector-sdk/dist/index.d.ts +1 -1
  67. package/vendor/connector-sdk/dist/retry.d.ts +15 -3
  68. package/vendor/connector-sdk/dist/retry.js +40 -64
  69. package/vendor/connector-sdk/package.json +1 -1
  70. package/vendor/connector-worker/dist/agent-turn/guest-entry.js +122 -10
  71. package/vendor/connector-worker/dist/agent-turn/guest.bundle.js +78 -10
  72. package/vendor/connector-worker/dist/agent-turn/types.d.ts +34 -4
  73. package/vendor/connector-worker/dist/compile/index.d.ts +21 -2
  74. package/vendor/connector-worker/dist/compile/index.js +41 -8
  75. package/vendor/connector-worker/dist/compile/source-capture.d.ts +10 -0
  76. package/vendor/connector-worker/dist/compile/source-capture.js +108 -0
  77. package/vendor/connector-worker/dist/daemon/agent-turn.js +97 -10
  78. package/vendor/connector-worker/dist/daemon/automation-process.d.ts +32 -0
  79. package/vendor/connector-worker/dist/daemon/automation-process.js +102 -1
  80. package/vendor/connector-worker/dist/daemon/automation.d.ts +1 -1
  81. package/vendor/connector-worker/dist/daemon/builtins/index.js +8 -0
  82. package/vendor/connector-worker/dist/daemon/builtins/os-shell.d.ts +13 -1
  83. package/vendor/connector-worker/dist/daemon/builtins/os-shell.js +28 -2
  84. package/vendor/connector-worker/dist/daemon/executor.d.ts +0 -1
  85. package/vendor/connector-worker/dist/daemon/executor.js +42 -51
  86. package/vendor/connector-worker/dist/daemon/start.js +5 -1
  87. package/vendor/connector-worker/dist/executor/interface.d.ts +12 -8
  88. package/vendor/connector-worker/dist/executor/isolate.js +45 -28
  89. package/vendor/connector-worker/dist/self-check/index.js +15 -13
  90. package/vendor/connector-worker/package.json +1 -1
  91. package/vendor/core/dist/agent-policy.js +3 -0
  92. package/vendor/core/dist/connector-query-errors.d.ts +3 -3
  93. package/vendor/core/dist/connector-query-errors.js +8 -3
  94. package/vendor/core/dist/contracts/tools/manage-connections.d.ts +24 -0
  95. package/vendor/core/dist/contracts/tools/manage-connections.js +13 -0
  96. package/vendor/core/dist/contracts/tools/manage-entity-schema.d.ts +15 -25
  97. package/vendor/core/dist/contracts/tools/manage-entity-schema.js +3 -5
  98. package/vendor/core/dist/contracts/tools/manage-feeds.d.ts +11 -0
  99. package/vendor/core/dist/contracts/tools/manage-feeds.js +12 -1
  100. package/vendor/core/dist/contracts/tools/manage-operations.d.ts +47 -6
  101. package/vendor/core/dist/contracts/tools/manage-operations.js +36 -1
  102. package/vendor/core/dist/contracts/tools/manage-views.d.ts +293 -0
  103. package/vendor/core/dist/contracts/tools/manage-views.js +203 -0
  104. package/vendor/core/dist/contracts/tools/source-files-schema.d.ts +7 -0
  105. package/vendor/core/dist/contracts/tools/source-files-schema.js +19 -0
  106. package/vendor/core/dist/contracts/tools/source-files.d.ts +14 -0
  107. package/vendor/core/dist/contracts/tools/source-files.js +55 -0
  108. package/vendor/core/dist/contracts/tools/view-content-hash.d.ts +37 -0
  109. package/vendor/core/dist/contracts/tools/view-content-hash.js +58 -0
  110. package/vendor/core/dist/contracts/tools/view-path.d.ts +18 -0
  111. package/vendor/core/dist/contracts/tools/view-path.js +24 -0
  112. package/vendor/core/dist/contracts/worker/protocol.d.ts +73 -8
  113. package/vendor/core/dist/contracts/worker/protocol.js +58 -9
  114. package/vendor/core/dist/credentials.d.ts +16 -1
  115. package/vendor/core/dist/credentials.js +10 -1
  116. package/vendor/core/dist/reserved.d.ts +3 -3
  117. package/vendor/core/dist/reserved.js +9 -1
  118. package/vendor/core/dist/utils/secret-redaction.js +2 -0
  119. package/vendor/core/package.json +25 -5
  120. package/vendor/core/dist/contracts/tools/manage-view-templates.d.ts +0 -165
  121. package/vendor/core/dist/contracts/tools/manage-view-templates.js +0 -130
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lobu/runtime-device",
3
- "version": "20.1.0",
3
+ "version": "21.0.0",
4
4
  "type": "module",
5
5
  "license": "BUSL-1.1",
6
6
  "repository": {
@@ -1,7 +1,9 @@
1
+ import { type DependencySession } from "../ensure-deps-installed.js";
1
2
  import { type ApplyClient, type RemoteConnectorDefinition } from "./client.js";
2
- import { type DesiredState, type DesiredAutomation } from "./desired-state.js";
3
+ import { type DesiredAutomation, type DesiredState } from "./desired-state.js";
3
4
  import { type DiffPlan, type RemoteSnapshot } from "./diff.js";
4
5
  interface ApplyOptions {
6
+ dependencySession?: DependencySession;
5
7
  cwd?: string;
6
8
  dryRun?: boolean;
7
9
  yes?: boolean;
@@ -34,7 +36,7 @@ export declare function resolveAutomationConnectionRefs(automations: DesiredAuto
34
36
  * UTF-8 text only after the (bounded) body is in hand. Exported for testing.
35
37
  */
36
38
  export declare function readBoundedBody(res: Response, maxBytes: number, onOverflow: () => never): Promise<string>;
37
- export declare function fetchRemoteSnapshot(client: ApplyClient, state: DesiredState, only?: "agents" | "memory", prune?: boolean, orgId?: string): Promise<RemoteSnapshot>;
39
+ export declare function fetchRemoteSnapshot(client: ApplyClient, state: DesiredState, only?: "agents" | "memory", prune?: boolean): Promise<RemoteSnapshot>;
38
40
  /**
39
41
  * Validate connection / auth-profile config against the connector definitions
40
42
  * the server knows about. When `skipSchemaForConnectorKeys` is given, those
@@ -74,6 +76,9 @@ interface ApplyContext {
74
76
  state: DesiredState;
75
77
  plan: DiffPlan;
76
78
  remote: RemoteSnapshot;
79
+ /** Origin the apply targets (for printing per-view shell URLs). */
80
+ apiBaseUrl: string;
81
+ orgSlug: string;
77
82
  }
78
83
  /**
79
84
  * Push provider API keys into the org's `inference_providers` store — the
@@ -6,12 +6,13 @@ import { parseEnvContent } from "../../../internal/env-file.js";
6
6
  import { printError, printText } from "../../../internal/output.js";
7
7
  import { loadProjectLink } from "../../../internal/project-link.js";
8
8
  import { ApiError, ValidationError } from "../../memory/_lib/errors.js";
9
+ import { withProjectDependencies, } from "../ensure-deps-installed.js";
9
10
  import { resolveApplyClient, } from "./client.js";
10
11
  import { buildAttributionAndOwned, buildCountsByKind, buildDeploymentManifest, collectGitInfo, computeManifestHash, loadBaselineFromManifest, mintApplyId, toBaseline, } from "./deployment.js";
11
12
  import { loadDesiredStateFromConfig, normalizeConnectionConfigScope, resolveConnectorSchemas, validateAuthProfileAgainstConnector, validateConnectionAgainstConnector, } from "./desired-state.js";
12
13
  import { buildUpdatePayload, computeDiff, UPDATE_FIELD_TABLES, } from "./diff.js";
13
- import { confirmCustomConnectors, confirmDeletions, confirmPlan, } from "./prompt.js";
14
14
  import { hydrateManagedConnectorCatalog, isManagedCloudTarget, loadManagedCloudConnectorCatalog, } from "./managed-connector-catalog.js";
15
+ import { confirmCustomConnectors, confirmDeletions, confirmPlan, } from "./prompt.js";
15
16
  import { renderBlockedReport, renderMissingSecrets, renderPlan, renderPostApplyPunchList, renderProgress, } from "./render.js";
16
17
  import { automationExecutionConfig, declaredConnectorKeys, referencedConnectorKeys, } from "./shared.js";
17
18
  /** Resolve declarative connection slugs to the integer API contract. */
@@ -196,7 +197,7 @@ function hasDesiredConnectors(state) {
196
197
  state.connectors.authProfiles.length > 0 ||
197
198
  state.connectors.connections.length > 0);
198
199
  }
199
- export async function fetchRemoteSnapshot(client, state, only, prune = false, orgId) {
200
+ export async function fetchRemoteSnapshot(client, state, only, prune = false) {
200
201
  const agents = only === "memory" ? [] : await client.listAgents();
201
202
  const agentSettings = new Map();
202
203
  if (only !== "memory") {
@@ -208,38 +209,8 @@ export async function fetchRemoteSnapshot(client, state, only, prune = false, or
208
209
  }
209
210
  }
210
211
  const entityTypes = only === "agents" ? [] : await client.listEntityTypes();
211
- // View templates are fetched per-type, NOT streamed in the entity-type list
212
- // (the UI/bootstrap calls that endpoint). Fetch for config-declared types
213
- // (a declared template, or under prune so an omitted one is a removal) AND,
214
- // under prune, for remote-only candidates whose owned/unchanged delete
215
- // classification must see the real template — otherwise an unhydrated
216
- // `undefined` compares equal to a stale baseline and a UI-authored template
217
- // edit is misclassified as unchanged and auto-deleted. Bounded to the org's
218
- // own entity-type set.
219
- if (entityTypes.length > 0) {
220
- const desiredBySlug = new Map(state.memorySchema.entityTypes.map((e) => [e.slug, e]));
221
- for (const remote of entityTypes) {
222
- const desired = desiredBySlug.get(remote.slug);
223
- // The list also surfaces public types owned by OTHER orgs. Fetch a
224
- // template only for types this org owns: the fetch resolves by slug in
225
- // THIS org, so a foreign public type whose local slug is absent (or
226
- // soft-deleted) would 404 and abort the whole apply.
227
- if (orgId !== undefined &&
228
- remote.organization_id !== undefined &&
229
- remote.organization_id !== orgId) {
230
- continue;
231
- }
232
- // Declared template → always. Otherwise only under prune, where an
233
- // omitted template is a removal (declared types) and an unhydrated
234
- // `undefined` would make a UI-authored template look unchanged since the
235
- // baseline (remote-only delete candidates).
236
- if (desired?.viewTemplate === undefined && !prune)
237
- continue;
238
- const tpl = await client.getEntityTypeViewTemplate(remote.slug);
239
- if (tpl)
240
- remote.viewTemplate = tpl;
241
- }
242
- }
212
+ // View templates are retired with the server tool: no per-type hydration.
213
+ // (It called the removed manage_view_templates, which aborts the apply.)
243
214
  const relationshipTypes = only === "agents" ? [] : await client.listRelationshipTypes();
244
215
  // The relationship-type `list` action omits rules, so the diff would compare
245
216
  // desired rules against an always-empty remote and churn a perpetual "rules
@@ -288,6 +259,9 @@ export async function fetchRemoteSnapshot(client, state, only, prune = false, or
288
259
  // Org-owned inference providers are org-scoped (neither agents nor memory), so
289
260
  // only a full apply reconciles them. The list drives create/update/drift.
290
261
  const inferenceProviders = only === undefined ? await client.listInferenceProviders() : [];
262
+ // Views are org-scoped modules (neither agents nor memory): a full apply
263
+ // reconciles them against `manage_views list` (metadata only).
264
+ const views = only === undefined ? await client.listViews() : [];
291
265
  return {
292
266
  agents,
293
267
  agentSettings,
@@ -299,6 +273,7 @@ export async function fetchRemoteSnapshot(client, state, only, prune = false, or
299
273
  connections,
300
274
  feedsByConnectionId,
301
275
  inferenceProviders,
276
+ views,
302
277
  };
303
278
  }
304
279
  // ── Connector definition install (runs INSIDE executePlan, after confirm) ──
@@ -329,23 +304,15 @@ async function installConnectorDefinitions(client, state, catalog, plan) {
329
304
  continue;
330
305
  let result;
331
306
  if (def.sourcePath) {
332
- // Local `*.connector.ts`: compile on the CLI, where the project's
333
- // node_modules is available, so esbuild can bundle the connector's
334
- // declared npm deps (the server only receives the artifact). Native deps
335
- // ride `runtime.nix.packages` and are provisioned at run time. Compile
336
- // `sourcePath` (the actual `.ts`), not `sourceFile` (an error-message
337
- // label that may point at a `type: connector` YAML doc).
338
- //
339
- // Lazy-imported (cached by the loader) so the heavy connector-compile
340
- // graph (esbuild + connector-worker + SDK) stays out of apply-cmd's
341
- // module-load path — see the dynamic-import allow-list in AGENTS.md.
342
- const { ensureProjectDepsInstalled } = await import("../ensure-deps-installed.js");
343
- const { compileConnectorForIsolateFromFile } = await import("../connector-loader.js");
344
- ensureProjectDepsInstalled(def.sourcePath, printText);
345
- const compiledCode = await compileConnectorForIsolateFromFile(def.sourcePath);
307
+ const artifact = def.compiledArtifact;
308
+ if (!artifact) {
309
+ throw new Error(`Local connector was not prepared: ${def.sourcePath}`);
310
+ }
346
311
  result = await client.installConnector({
347
- sourceCode: compiledCode,
348
- compiled: true,
312
+ sourceCode: artifact.sourceFiles.files[artifact.sourceFiles.entrypoint],
313
+ compiledCode: artifact.compiledCode,
314
+ sourceFiles: artifact.sourceFiles,
315
+ dependencies: artifact.dependencies,
349
316
  });
350
317
  }
351
318
  else if (def.sourceCode !== undefined) {
@@ -564,21 +531,6 @@ export async function executePlan(ctx, pendingAuth) {
564
531
  }, clearFacets,
565
532
  // Outside prune, keep UI-added property keys when rebuilding the schema.
566
533
  !(ctx.state.prune ?? false));
567
- // View template is a separate, version-appending tool. Reconcile it only on
568
- // create (when declared) or a flagged change — never every run, so the
569
- // version history doesn't churn. Declared ⇒ set; omitted-under-prune ⇒ clear.
570
- const tpl = row.desired.viewTemplate;
571
- const templateChanged = row.verb === "create"
572
- ? tpl !== undefined
573
- : (row.changedFields?.includes("viewTemplate") ?? false);
574
- if (templateChanged) {
575
- if (tpl !== undefined) {
576
- await ctx.client.setEntityTypeViewTemplate(row.desired.slug, tpl);
577
- }
578
- else {
579
- await ctx.client.clearEntityTypeViewTemplate(row.desired.slug);
580
- }
581
- }
582
534
  printText(renderProgress(row.verb, "entity-type", row.id));
583
535
  }
584
536
  // 1) Relationship types before connector definitions: server preflight
@@ -604,6 +556,30 @@ export async function executePlan(ctx, pendingAuth) {
604
556
  printText(chalk.yellow(`Warning: ${warning}`));
605
557
  }
606
558
  }
559
+ // 2b) Views — shipped from the load-time bundle (source + browser bundle +
560
+ // metadata extracted from the module itself, hashed with the server's
561
+ // function). No re-bundling here: the diff already compared the exact
562
+ // hash the server will compute.
563
+ for (const row of rowsByKind("view")) {
564
+ if (row.kind !== "view")
565
+ continue;
566
+ if (!row.desired)
567
+ continue;
568
+ const result = await ctx.client.setView({
569
+ key: row.id,
570
+ name: row.desired.key,
571
+ source_code: row.desired.sourceCode,
572
+ compiled_code: row.desired.compiledCode,
573
+ source_files: row.desired.sourceFiles,
574
+ dependencies: row.desired.dependencies,
575
+ attach: row.desired.attach,
576
+ params: row.desired.params,
577
+ actions: row.desired.actions,
578
+ });
579
+ const kb = (Buffer.byteLength(row.desired.compiledCode, "utf8") / 1024).toFixed(0);
580
+ printText(renderProgress(row.verb, "view", row.id, `${result.written ? "(pushed" : "(unchanged"}, ${kb} KB)`));
581
+ printText(chalk.dim(` → ${ctx.apiBaseUrl}/api/${ctx.orgSlug}/views/${row.id}/shell`));
582
+ }
607
583
  // 3) Agents
608
584
  for (const row of rowsByKind("agent")) {
609
585
  if (row.kind !== "agent")
@@ -958,6 +934,7 @@ async function deleteRemovedDefinitions(ctx) {
958
934
  return;
959
935
  const automationIdBySlug = new Map(ctx.remote.automations.map((w) => [w.slug, w.automation_id]));
960
936
  const steps = [
937
+ ["view", (id) => ctx.client.removeView(id)],
961
938
  [
962
939
  "automation",
963
940
  async (id) => {
@@ -1041,14 +1018,39 @@ async function postDeploymentSummarySafe(client, summary) {
1041
1018
  }
1042
1019
  export async function applyCommand(opts = {}) {
1043
1020
  const cwd = opts.cwd ?? process.cwd();
1044
- const fetchImpl = opts.fetchImpl ?? fetch;
1045
- // Auto-load `.env` from the project dir so secret()/$VAR refs in
1046
- // lobu.config.ts resolve without the user having to `set -a; source .env`.
1047
- // Mirrors `lobu dev`. Existing process.env values win (don't clobber shell).
1021
+ // Auto-load `.env` so secret()/$VAR refs in lobu.config.ts resolve without
1022
+ // `set -a; source .env`. Mirrors `lobu dev`; existing process.env values win.
1048
1023
  await loadProjectEnvFile(cwd);
1049
- // Load desired state from the TypeScript entrypoint (lobu.config.ts).
1050
- const loadArgs = { cwd, ...(opts.only ? { only: opts.only } : {}) };
1051
- const { state, configPath, warnings } = await loadDesiredStateFromConfig(loadArgs);
1024
+ const prepared = await withProjectDependencies(cwd, {
1025
+ mode: opts.dryRun ? "read" : "frozen",
1026
+ session: opts.dependencySession ?? new Map(),
1027
+ log: printText,
1028
+ }, async () => {
1029
+ const prepared = await loadDesiredStateFromConfig({
1030
+ cwd,
1031
+ ...(opts.only ? { only: opts.only } : {}),
1032
+ });
1033
+ if (!opts.dryRun) {
1034
+ for (const def of prepared.state.connectors.definitions) {
1035
+ if (!def.sourcePath)
1036
+ continue;
1037
+ // Preserve the existing lazy compiler load: its heavy esbuild/worker
1038
+ // graph is needed only for local connectors. Compile under the
1039
+ // dependency lock; release before prompts or remote apply requests.
1040
+ const { compileConnectorArtifactFromFile } = await import("../connector-loader.js");
1041
+ if (!def.sourceRoot)
1042
+ throw new Error("Local connector is missing its project root");
1043
+ def.compiledArtifact = await compileConnectorArtifactFromFile(def.sourcePath, def.sourceRoot);
1044
+ }
1045
+ }
1046
+ return prepared;
1047
+ });
1048
+ await applyProject(opts, prepared);
1049
+ }
1050
+ async function applyProject(opts, prepared) {
1051
+ const cwd = opts.cwd ?? process.cwd();
1052
+ const fetchImpl = opts.fetchImpl ?? fetch;
1053
+ const { state, configPath, warnings } = prepared;
1052
1054
  printText(chalk.dim(`Config: ${configPath}`));
1053
1055
  for (const warning of warnings) {
1054
1056
  printText(chalk.yellow(`Warning: ${warning}`));
@@ -1179,7 +1181,7 @@ export async function applyCommand(opts = {}) {
1179
1181
  // this (current/stale) catalog — "create" when the key isn't installed,
1180
1182
  // "update" when it is. Connector defs are NOT installed here; that happens in
1181
1183
  // `executePlan`, AFTER plan confirmation.
1182
- const remote = await fetchRemoteSnapshot(client, state, opts.only, prune, resolvedOrg?.id);
1184
+ const remote = await fetchRemoteSnapshot(client, state, opts.only, prune);
1183
1185
  if (!opts.only && !(await isManagedCloudTarget(apiBaseUrl))) {
1184
1186
  remote.connectorDefinitions = await hydrateManagedConnectorCatalog(state, remote.connectorDefinitions, (managedOrg) => loadManagedCloudConnectorCatalog(managedOrg, fetchImpl));
1185
1187
  }
@@ -1361,7 +1363,7 @@ export async function applyCommand(opts = {}) {
1361
1363
  // constraint anymore — the order is kept for stable output only.
1362
1364
  if (hasResourceWork) {
1363
1365
  printText(chalk.bold("\nApplying:"));
1364
- const executed = await executePlan({ client, state, plan, remote }, pendingAuth);
1366
+ const executed = await executePlan({ client, state, plan, remote, apiBaseUrl, orgSlug }, pendingAuth);
1365
1367
  connectorVersions = executed.connectorVersions;
1366
1368
  }
1367
1369
  // Provider keys live outside the resource diff (idempotent PUT), so push
@@ -1400,7 +1402,7 @@ export async function applyCommand(opts = {}) {
1400
1402
  // so owned gets real incarnation ids (pre-apply remote has none for creates).
1401
1403
  if (!applyErr && hasResourceWork && plan.counts.create > 0) {
1402
1404
  try {
1403
- const postRemote = await fetchRemoteSnapshot(client, state, opts.only, prune, resolvedOrg?.id);
1405
+ const postRemote = await fetchRemoteSnapshot(client, state, opts.only, prune);
1404
1406
  baselineRecordForRecording = recordableBaseline(postRemote);
1405
1407
  if (!opts.only) {
1406
1408
  pins = {
@@ -1,6 +1,7 @@
1
1
  import type { EntityMetrics } from "@lobu/connector-sdk";
2
2
  import type { AgentSettings } from "@lobu/core";
3
3
  import type { InstallConnectorInput } from "@lobu/core/contracts/tools/manage-connections";
4
+ import type { SourceDependencies, SourceFiles } from "@lobu/core/contracts/tools/source-files";
4
5
  import type { InferenceCapabilityBlock, InferenceModality } from "../../../config/define.js";
5
6
  import { ApiError } from "../../memory/_lib/errors.js";
6
7
  import type { DeploymentSummary } from "./deployment.js";
@@ -58,13 +59,6 @@ export interface RemoteEntityType {
58
59
  properties?: Record<string, unknown>;
59
60
  /** Event kinds keyed by semantic_type (mirrors {@link DesiredEntityType.eventKinds}); hoisted from the row's `event_kinds`. */
60
61
  eventKinds?: Record<string, unknown>;
61
- /**
62
- * Current default view template (mirrors {@link DesiredEntityType.viewTemplate}).
63
- * NOT returned by the entity-type list (kept off that hot path); apply-cmd
64
- * fetches it per relevant type via {@link ApplyClient.getEntityTypeViewTemplate}
65
- * and attaches it before diffing.
66
- */
67
- viewTemplate?: Record<string, unknown>;
68
62
  /** Present only for derived types (mirrors {@link DesiredEntityType.backing}). */
69
63
  backing?: EntityBacking;
70
64
  /** Declared metrics (mirrors {@link DesiredEntityType.metrics}); hoisted from the row's `metrics_config`. */
@@ -120,6 +114,29 @@ export interface RemoteInferenceProvider {
120
114
  status: string;
121
115
  createdAt: string;
122
116
  }
117
+ /** An applied view as `manage_views list` reports it (metadata, never bundles). */
118
+ export interface RemoteView {
119
+ key: string;
120
+ name: string;
121
+ content_hash: string;
122
+ attach: Array<Record<string, unknown>>;
123
+ last_writer: string;
124
+ updated_at: string;
125
+ }
126
+ export interface SetViewPayload {
127
+ key: string;
128
+ name?: string;
129
+ description?: string;
130
+ source_code: string;
131
+ compiled_code?: string;
132
+ source_files?: SourceFiles;
133
+ dependencies?: SourceDependencies;
134
+ attach: Array<Record<string, unknown>>;
135
+ params: Record<string, unknown>;
136
+ actions: Record<string, {
137
+ emits: string;
138
+ }>;
139
+ }
123
140
  export interface RemoteAutomation {
124
141
  slug: string;
125
142
  name?: string;
@@ -235,6 +252,9 @@ type CliInstallConnectorPayload = {
235
252
  sourceUrl?: InstallConnectorInput["source_url"];
236
253
  sourceUri?: InstallConnectorInput["source_uri"];
237
254
  compiled?: InstallConnectorInput["compiled"];
255
+ compiledCode?: InstallConnectorInput["compiled_code"];
256
+ sourceFiles?: InstallConnectorInput["source_files"];
257
+ dependencies?: InstallConnectorInput["dependencies"];
238
258
  };
239
259
  /**
240
260
  * Result of ensuring an auth profile exists. For interactive kinds
@@ -349,6 +369,19 @@ export declare class ApplyClient {
349
369
  rotateInferenceProviderKey(slug: string, value: string): Promise<void>;
350
370
  /** Soft-delete an org inference provider. */
351
371
  deleteInferenceProvider(slug: string): Promise<void>;
372
+ /** Applied views (metadata only — the list never returns bundles). */
373
+ listViews(): Promise<RemoteView[]>;
374
+ /**
375
+ * Store a view: source + CLI-bundled browser bundle + metadata extracted
376
+ * from the module itself. Returns whether a write happened (same
377
+ * executable artifact is a server-side no-op).
378
+ */
379
+ setView(payload: SetViewPayload): Promise<{
380
+ written: boolean;
381
+ content_hash: string;
382
+ }>;
383
+ /** Delete an applied view by key (prune-gated removal). */
384
+ removeView(key: string): Promise<void>;
352
385
  listEntityTypes(): Promise<RemoteEntityType[]>;
353
386
  /**
354
387
  * The `manage_entity_schema` admin tool exposes separate `create` / `update`
@@ -395,24 +428,6 @@ export declare class ApplyClient {
395
428
  * properties alone are the full schema.
396
429
  */
397
430
  preserveRemoteOnlyProperties?: boolean): Promise<UpsertEntityTypeResult>;
398
- /**
399
- * Fetch an entity type's current default view template (`null` if none).
400
- * Apply uses this to diff ONLY the types it needs (declared templates, plus
401
- * every config type under prune) — the template is deliberately NOT returned
402
- * by the entity-type list, which the UI/bootstrap also calls.
403
- */
404
- getEntityTypeViewTemplate(slug: string): Promise<Record<string, unknown> | null>;
405
- /**
406
- * Set the entity type's default view template. A separate, version-appending
407
- * tool from the schema upsert, so apply calls this ONLY on create or a changed
408
- * template (see apply-cmd) — never every run, which would churn the history.
409
- */
410
- setEntityTypeViewTemplate(slug: string, jsonTemplate: Record<string, unknown>): Promise<void>;
411
- /**
412
- * Clear the entity type's default view template (prune-gated removal). Nulls
413
- * the current-version pointer server-side; history rows stay for rollback.
414
- */
415
- clearEntityTypeViewTemplate(slug: string): Promise<void>;
416
431
  listRelationshipTypes(): Promise<RemoteRelationshipType[]>;
417
432
  /**
418
433
  * Fetch a relationship type's rules (the `list` action omits them, so the
@@ -286,6 +286,34 @@ export class ApplyClient {
286
286
  async deleteInferenceProvider(slug) {
287
287
  await this.request("DELETE", `/api/${this.orgSlug}/agents/inference-providers/${encodeURIComponent(slug)}`);
288
288
  }
289
+ // ── Views ─────────────────────────────────────────────────────────────────
290
+ /** Applied views (metadata only — the list never returns bundles). */
291
+ async listViews() {
292
+ const { body } = await this.request("POST", `/api/${this.orgSlug}/manage_views`, { action: "list" });
293
+ return body.views ?? [];
294
+ }
295
+ /**
296
+ * Store a view: source + CLI-bundled browser bundle + metadata extracted
297
+ * from the module itself. Returns whether a write happened (same
298
+ * executable artifact is a server-side no-op).
299
+ */
300
+ async setView(payload) {
301
+ const { body } = await this.request("POST", `/api/${this.orgSlug}/manage_views`, {
302
+ action: "set",
303
+ ...payload,
304
+ });
305
+ return {
306
+ written: body.written ?? false,
307
+ content_hash: body.view?.content_hash ?? "",
308
+ };
309
+ }
310
+ /** Delete an applied view by key (prune-gated removal). */
311
+ async removeView(key) {
312
+ await this.request("POST", `/api/${this.orgSlug}/manage_views`, {
313
+ action: "remove",
314
+ key,
315
+ });
316
+ }
289
317
  // ── Memory schema ─────────────────────────────────────────────────────────
290
318
  async listEntityTypes() {
291
319
  const { body } = await this.request("POST", `/api/${this.orgSlug}/manage_entity_schema`, {
@@ -457,45 +485,6 @@ export class ApplyClient {
457
485
  }
458
486
  return this.upsertSchemaResource("entity_type", payload);
459
487
  }
460
- /**
461
- * Fetch an entity type's current default view template (`null` if none).
462
- * Apply uses this to diff ONLY the types it needs (declared templates, plus
463
- * every config type under prune) — the template is deliberately NOT returned
464
- * by the entity-type list, which the UI/bootstrap also calls.
465
- */
466
- async getEntityTypeViewTemplate(slug) {
467
- const { body } = await this.request("POST", `/api/${this.orgSlug}/manage_view_templates`, {
468
- action: "get",
469
- resource_type: "entity_type",
470
- resource_id: slug,
471
- });
472
- return body.default_tab?.current?.json_template ?? null;
473
- }
474
- /**
475
- * Set the entity type's default view template. A separate, version-appending
476
- * tool from the schema upsert, so apply calls this ONLY on create or a changed
477
- * template (see apply-cmd) — never every run, which would churn the history.
478
- */
479
- async setEntityTypeViewTemplate(slug, jsonTemplate) {
480
- await this.request("POST", `/api/${this.orgSlug}/manage_view_templates`, {
481
- action: "set",
482
- resource_type: "entity_type",
483
- resource_id: slug,
484
- json_template: jsonTemplate,
485
- change_notes: "lobu apply",
486
- });
487
- }
488
- /**
489
- * Clear the entity type's default view template (prune-gated removal). Nulls
490
- * the current-version pointer server-side; history rows stay for rollback.
491
- */
492
- async clearEntityTypeViewTemplate(slug) {
493
- await this.request("POST", `/api/${this.orgSlug}/manage_view_templates`, {
494
- action: "clear",
495
- resource_type: "entity_type",
496
- resource_id: slug,
497
- });
498
- }
499
488
  async listRelationshipTypes() {
500
489
  const { body } = await this.request("POST", `/api/${this.orgSlug}/manage_entity_schema`, {
501
490
  schema_type: "relationship_type",
@@ -784,6 +773,9 @@ export class ApplyClient {
784
773
  ? {
785
774
  source_code: payload.sourceCode,
786
775
  compiled: payload.compiled ?? false,
776
+ compiled_code: payload.compiledCode,
777
+ source_files: payload.sourceFiles,
778
+ dependencies: payload.dependencies,
787
779
  }
788
780
  : {}),
789
781
  ...(payload.sourceUrl ? { source_url: payload.sourceUrl } : {}),
@@ -95,7 +95,7 @@ export declare function toBaseline(record: BaselineRecord | null): Baseline;
95
95
  * The post-apply attribution snapshot + owned identities. Attribution records
96
96
  * the effective entity/rel/Automation state AFTER a successful apply — config's
97
97
  * declared values merged with preserved unmanaged facets (eventKinds /
98
- * viewTemplate / schemaExtras the config never declared) from the pre-apply
98
+ * schemaExtras the config never declared) from the pre-apply
99
99
  * remote — so `remote == attribution` means "unchanged since last apply".
100
100
  *
101
101
  * Under `prune`, omitted clearable facets are cleared by executePlan, so the
@@ -133,7 +133,7 @@ export function toBaseline(record) {
133
133
  * The post-apply attribution snapshot + owned identities. Attribution records
134
134
  * the effective entity/rel/Automation state AFTER a successful apply — config's
135
135
  * declared values merged with preserved unmanaged facets (eventKinds /
136
- * viewTemplate / schemaExtras the config never declared) from the pre-apply
136
+ * schemaExtras the config never declared) from the pre-apply
137
137
  * remote — so `remote == attribution` means "unchanged since last apply".
138
138
  *
139
139
  * Under `prune`, omitted clearable facets are cleared by executePlan, so the
@@ -266,7 +266,7 @@ export function buildDeploymentManifest(state, connectorVersions, baseline) {
266
266
  connectors: {
267
267
  ...connectors,
268
268
  // Keep the declaration shape for display/diff labels; drop the bytes.
269
- definitions: definitions.map(({ sourceCode: _sourceCode, ...def }) => def),
269
+ definitions: definitions.map(({ sourceCode: _sourceCode, sourceRoot: _sourceRoot, compiledArtifact: _compiledArtifact, ...def }) => def),
270
270
  },
271
271
  },
272
272
  connector_versions: connectorVersions,
@@ -1,6 +1,7 @@
1
1
  import type { ConnectorDefinition, EntityMetrics } from "@lobu/connector-sdk";
2
2
  import type { AgentSettings } from "@lobu/core";
3
3
  import type { AutomationEventTrigger, AutomationScheduleTrigger, AutomationWorkspaceEventTrigger } from "@lobu/core/contracts/tools/manage-automations";
4
+ import type { RetainedSource } from "@lobu/core/contracts/tools/source-files";
4
5
  import type { InferenceCapabilityBlock, InferenceModality, Project } from "../../../config/index.js";
5
6
  import { type AutomationSource, type EntityBacking, type RelationshipRule } from "./shared.js";
6
7
  export interface DesiredAgentMetadata {
@@ -37,14 +38,6 @@ export interface DesiredEntityType {
37
38
  sourcePath: string;
38
39
  sourceCode: string;
39
40
  };
40
- /**
41
- * Default view template (render-DSL root node) for this type's detail page.
42
- * Present only when declared. Applied via manage_view_templates set/clear and
43
- * diffed against the remote current default (which apply-cmd fetches per
44
- * relevant type — NOT streamed in the entity-type list). Prune-aware: under
45
- * prune an absent template clears the remote one; otherwise it is left alone.
46
- */
47
- viewTemplate?: Record<string, unknown>;
48
41
  metadata?: Record<string, unknown>;
49
42
  /**
50
43
  * Present only for derived (SQL-view-backed) entity types; absent ⇒ stored
@@ -208,17 +201,54 @@ export interface DesiredConnectorDefinition {
208
201
  declaredKeyHint?: string;
209
202
  /** Local `.ts` path (absolute) — mutually exclusive with `sourceUrl`. */
210
203
  sourcePath?: string;
204
+ /** Project boundary for collecting local source; never sent to the server. */
205
+ sourceRoot?: string;
211
206
  /** Remote URL — mutually exclusive with `sourcePath`. */
212
207
  sourceUrl?: string;
213
208
  /**
214
- * Raw TypeScript source read from `sourcePath`, pushed verbatim to the
215
- * server (which compiles, extracts metadata, and returns the real `key`).
216
- * Absent when `sourceUrl` is used.
209
+ * Raw TypeScript source used for static inspection. Local sources are
210
+ * compiled before upload; remote sources are compiled by the server.
217
211
  */
218
212
  sourceCode?: string;
213
+ /** Artifact and author files prepared while project dependencies are locked. */
214
+ compiledArtifact?: RetainedSource & {
215
+ compiledCode: string;
216
+ };
219
217
  /** For error messages — the `.connector.ts` file or `type: connector` doc. */
220
218
  sourceFile: string;
221
219
  }
220
+ /** One `viewFromFile` entry, bundled at load (apply reuses the artifacts). */
221
+ export interface DesiredView extends RetainedSource {
222
+ /**
223
+ * View key, re-derived from the module's own `defineView({ key })` at bundle
224
+ * time. The bundle pass refuses a mismatch with nothing to fall back to: a
225
+ * key is required, so the plan, the bundle and the action agree.
226
+ */
227
+ key: string;
228
+ /** Absolute path to the module. */
229
+ sourcePath: string;
230
+ /** Raw module source, pushed verbatim beside the bundle. */
231
+ sourceCode: string;
232
+ /**
233
+ * sha256 of source plus declared metadata plus the compiled artifact's
234
+ * digest, via the shared `@lobu/core/contracts/tools/view-content-hash` —
235
+ * the SAME function the server hashes with, so the diff's noop means the
236
+ * server will no-write. The bundle is an input (not just a payload)
237
+ * because it carries the relative imports and view npm deps the entry
238
+ * source alone does not name.
239
+ */
240
+ contentHash: string;
241
+ /** Config-relative path for messages. */
242
+ sourceFile: string;
243
+ /** Browser IIFE bundle (react, bridge, relative files, view npm deps). */
244
+ compiledCode: string;
245
+ /** Metadata extracted from the module itself. */
246
+ attach: Array<Record<string, unknown>>;
247
+ params: Record<string, unknown>;
248
+ actions: Record<string, {
249
+ emits: string;
250
+ }>;
251
+ }
222
252
  export interface DesiredAgent {
223
253
  metadata: DesiredAgentMetadata;
224
254
  /**
@@ -290,6 +320,12 @@ export interface DesiredState {
290
320
  authProfiles: DesiredAuthProfile[];
291
321
  connections: DesiredConnection[];
292
322
  };
323
+ /**
324
+ * View modules declared via `viewFromFile`. The key is provisional — read
325
+ * from the `defineView({ key })` literal when present, else derived from the
326
+ * path — and apply re-derives it from the bundle, refusing a mismatch.
327
+ */
328
+ views: DesiredView[];
293
329
  /**
294
330
  * Names of env vars referenced via `secret()` / `$VAR` (provider keys,
295
331
  * auth-profile + mcp credentials). The CLI surfaces these before mutating