@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
@@ -0,0 +1,60 @@
1
+ export interface ViewReapplySet {
2
+ configPath: string;
3
+ files: string[];
4
+ }
5
+ /**
6
+ * Resolve the current reapply set for `cwd`: the config file plus every
7
+ * listed view's entry and import graph. Throws the config loader's
8
+ * ValidationError when `lobu.config.ts` is missing or malformed — the caller
9
+ * treats that as "no reapply loop", never as fatal.
10
+ */
11
+ export declare function collectViewReapplySet(cwd: string): Promise<ViewReapplySet>;
12
+ export interface ViewReapplyEvents {
13
+ /** A reapply file changed (debounced): re-apply, then rebuild the set. */
14
+ onChange: () => Promise<void>;
15
+ /** Log line for operator-visible reapply state. */
16
+ onLog?: (message: string) => void;
17
+ }
18
+ /**
19
+ * Reapply `set.files` on change and call `onChange` after 750 ms quiet.
20
+ * Returns `close` plus `update`.
21
+ *
22
+ * One coordinator lives for the whole loop: `update` replaces only the
23
+ * native `fs.watch` subscriptions (so a new import joins the set after an
24
+ * apply) and preserves the pending timer, the in-flight apply and the dirty
25
+ * flag. Closing the coordinator on every apply instead would clear a timer
26
+ * scheduled by a save that landed mid-apply, silently discarding it.
27
+ * `close` is terminal: it clears the timer, drops the subscriptions, and
28
+ * stops the finally handler from scheduling anything further.
29
+ *
30
+ * Concurrent change bursts collapse into one call; a change DURING a
31
+ * re-apply schedules exactly one follow-up, so rapid saves never stack
32
+ * applies. When `update` adds a file that was not watched before, one
33
+ * follow-up is requested through the same dirty/schedule mechanism: a save
34
+ * to that file may have landed after the apply read it but before its new
35
+ * subscription existed, so no file subscription could have observed it. The
36
+ * same holds when an existing path changes native file identity (an atomic
37
+ * rename replaces the inode while the old Node per-file subscription stays
38
+ * attached to the replaced file). The baseline advances at fire time to the
39
+ * disk state the apply is about to read, so the triggering save itself never
40
+ * reconciles; only a save that lands DURING the apply does. The next
41
+ * stable graph and unchanged identities add nothing and schedule nothing
42
+ * further.
43
+ *
44
+ * Native file identity for a watched path (`dev:ino:size:mtimeMs`). An
45
+ * atomic rename replaces the inode at the same path while the old Node
46
+ * per-file subscription stays attached to the replaced file, so path
47
+ * equality alone cannot detect the swap. `dev:ino` alone is insufficient:
48
+ * Linux (overlayfs/tmpfs) reuses a freed inode number immediately, so two
49
+ * rapid atomic renames can alias back to the same `dev:ino`, and a
50
+ * truncate-in-place save keeps the same `dev:ino` with new bytes. `size`
51
+ * plus `mtimeMs` (sub-millisecond float, distinct even ~0.3 ms apart)
52
+ * disambiguate both. A missing file maps to null so a later reappearance
53
+ * also reconciles.
54
+ */
55
+ export declare function fileIdentity(path: string): string | null;
56
+ export declare function startViewReapply(set: ViewReapplySet, events: ViewReapplyEvents): {
57
+ close: () => void;
58
+ update: (next: ViewReapplySet) => void;
59
+ };
60
+ //# sourceMappingURL=view-reapply.d.ts.map
@@ -0,0 +1,182 @@
1
+ /**
2
+ * `lobu run` view reapply loop: re-apply the project when a view file, one of
3
+ * its imports, or `lobu.config.ts` changes — so Claude Code in a checkout sees
4
+ * the edited view locally within ~2 s of saving.
5
+ *
6
+ * The reapply set is exactly the listed view files + their import graph (from
7
+ * the esbuild metafile, the same bundler apply uses) + the config file
8
+ * (reloaded through jiti on every apply, so config edits take effect without
9
+ * a restart). Per-file `fs.watch` calls: no recursive directory walk, no
10
+ * editor-tempfile noise. Resolved fresh after every apply, so a new import
11
+ * joins the set on the next save.
12
+ */
13
+ import { statSync, watch } from "node:fs";
14
+ import { loadProjectConfig } from "./apply/desired-state.js";
15
+ import { collectViewWatchFiles } from "./view-bundler.js";
16
+ /**
17
+ * Resolve the current reapply set for `cwd`: the config file plus every
18
+ * listed view's entry and import graph. Throws the config loader's
19
+ * ValidationError when `lobu.config.ts` is missing or malformed — the caller
20
+ * treats that as "no reapply loop", never as fatal.
21
+ */
22
+ export async function collectViewReapplySet(cwd) {
23
+ const { project, configPath } = await loadProjectConfig(cwd);
24
+ const files = new Set([configPath]);
25
+ for (const src of project.views ?? []) {
26
+ const rel = src.path.trim();
27
+ if (!rel || rel.startsWith("/") || rel.includes("\\"))
28
+ continue;
29
+ const { resolve } = await import("node:path");
30
+ const abs = resolve(cwd, rel);
31
+ for (const file of await collectViewWatchFiles(abs))
32
+ files.add(file);
33
+ }
34
+ return { configPath, files: [...files].sort() };
35
+ }
36
+ /**
37
+ * Reapply `set.files` on change and call `onChange` after 750 ms quiet.
38
+ * Returns `close` plus `update`.
39
+ *
40
+ * One coordinator lives for the whole loop: `update` replaces only the
41
+ * native `fs.watch` subscriptions (so a new import joins the set after an
42
+ * apply) and preserves the pending timer, the in-flight apply and the dirty
43
+ * flag. Closing the coordinator on every apply instead would clear a timer
44
+ * scheduled by a save that landed mid-apply, silently discarding it.
45
+ * `close` is terminal: it clears the timer, drops the subscriptions, and
46
+ * stops the finally handler from scheduling anything further.
47
+ *
48
+ * Concurrent change bursts collapse into one call; a change DURING a
49
+ * re-apply schedules exactly one follow-up, so rapid saves never stack
50
+ * applies. When `update` adds a file that was not watched before, one
51
+ * follow-up is requested through the same dirty/schedule mechanism: a save
52
+ * to that file may have landed after the apply read it but before its new
53
+ * subscription existed, so no file subscription could have observed it. The
54
+ * same holds when an existing path changes native file identity (an atomic
55
+ * rename replaces the inode while the old Node per-file subscription stays
56
+ * attached to the replaced file). The baseline advances at fire time to the
57
+ * disk state the apply is about to read, so the triggering save itself never
58
+ * reconciles; only a save that lands DURING the apply does. The next
59
+ * stable graph and unchanged identities add nothing and schedule nothing
60
+ * further.
61
+ *
62
+ * Native file identity for a watched path (`dev:ino:size:mtimeMs`). An
63
+ * atomic rename replaces the inode at the same path while the old Node
64
+ * per-file subscription stays attached to the replaced file, so path
65
+ * equality alone cannot detect the swap. `dev:ino` alone is insufficient:
66
+ * Linux (overlayfs/tmpfs) reuses a freed inode number immediately, so two
67
+ * rapid atomic renames can alias back to the same `dev:ino`, and a
68
+ * truncate-in-place save keeps the same `dev:ino` with new bytes. `size`
69
+ * plus `mtimeMs` (sub-millisecond float, distinct even ~0.3 ms apart)
70
+ * disambiguate both. A missing file maps to null so a later reappearance
71
+ * also reconciles.
72
+ */
73
+ export function fileIdentity(path) {
74
+ try {
75
+ const st = statSync(path);
76
+ return `${st.dev}:${st.ino}:${st.size}:${st.mtimeMs}`;
77
+ }
78
+ catch {
79
+ return null;
80
+ }
81
+ }
82
+ export function startViewReapply(set, events) {
83
+ let subs = [];
84
+ let timer = null;
85
+ let applying = false;
86
+ let dirty = false;
87
+ let closed = false;
88
+ let watchedFiles = new Set(set.files);
89
+ let watchedIdentities = new Map(set.files.map((file) => [file, fileIdentity(file)]));
90
+ const fire = () => {
91
+ timer = null;
92
+ if (closed)
93
+ return;
94
+ if (applying) {
95
+ dirty = true;
96
+ return;
97
+ }
98
+ // Advance the identity baseline to the disk state this apply is about to
99
+ // read. The triggering save landed before the debounce expired, so it is
100
+ // already on disk and will be deployed by this apply: without this, its
101
+ // own size/mtime diff versus the last post-apply baseline would look like
102
+ // an unobserved mid-apply save and schedule a spurious no-op follow-up
103
+ // (every truncate-in-place save keeps its inode). Post-apply `update`
104
+ // then reconciles only saves that landed DURING the apply, including an
105
+ // atomic rename the old per-file subscription could not observe — even
106
+ // when Linux reuses the freed inode number and `dev:ino` aliases.
107
+ for (const file of watchedFiles) {
108
+ watchedIdentities.set(file, fileIdentity(file));
109
+ }
110
+ applying = true;
111
+ events
112
+ .onChange()
113
+ .catch((err) => {
114
+ events.onLog?.(`view re-apply failed: ${err instanceof Error ? err.message : String(err)}`);
115
+ })
116
+ .finally(() => {
117
+ applying = false;
118
+ if (closed)
119
+ return;
120
+ if (dirty) {
121
+ dirty = false;
122
+ schedule();
123
+ }
124
+ });
125
+ };
126
+ const schedule = () => {
127
+ if (closed || timer)
128
+ return;
129
+ timer = setTimeout(fire, 750);
130
+ };
131
+ const subscribe = (files) => {
132
+ for (const sub of subs)
133
+ sub.close();
134
+ subs = [];
135
+ for (const file of files) {
136
+ try {
137
+ subs.push(watch(file, { persistent: true }, schedule));
138
+ }
139
+ catch {
140
+ // Tempfile/impl races (deleted between collect and reapply): the next
141
+ // successful apply rebuilds the set; a missing file never kills `run`.
142
+ }
143
+ }
144
+ };
145
+ subscribe(set.files);
146
+ return {
147
+ update: (next) => {
148
+ if (closed)
149
+ return;
150
+ const nextIdentities = new Map(next.files.map((file) => [file, fileIdentity(file)]));
151
+ let reconcile = next.files.some((file) => !watchedFiles.has(file));
152
+ if (!reconcile) {
153
+ for (const file of next.files) {
154
+ if (nextIdentities.get(file) !== watchedIdentities.get(file)) {
155
+ reconcile = true;
156
+ break;
157
+ }
158
+ }
159
+ }
160
+ watchedFiles = new Set(next.files);
161
+ watchedIdentities = nextIdentities;
162
+ subscribe(next.files);
163
+ if (reconcile) {
164
+ if (applying)
165
+ dirty = true;
166
+ else
167
+ schedule();
168
+ }
169
+ },
170
+ close: () => {
171
+ closed = true;
172
+ if (timer) {
173
+ clearTimeout(timer);
174
+ timer = null;
175
+ }
176
+ for (const sub of subs)
177
+ sub.close();
178
+ subs = [];
179
+ },
180
+ };
181
+ }
182
+ //# sourceMappingURL=view-reapply.js.map
@@ -1,4 +1,5 @@
1
1
  import { type Credentials } from "../internal/credentials.js";
2
+ import type { DependencySession } from "./_lib/ensure-deps-installed.js";
2
3
  interface DevOptions {
3
4
  port?: string;
4
5
  quiet?: boolean;
@@ -92,11 +93,19 @@ export declare function shouldRefuseSharedDatabaseUrl(input: {
92
93
  */
93
94
  export declare function devCommand(cwd: string, options?: DevOptions): Promise<void>;
94
95
  /**
95
- * Whether `lobu run` should auto-apply the project. True only when:
96
- * - the backend is embedded (never auto-mutate an external/prod DB), AND
97
- * - local sign-in registered and credentialed the selected context, AND
98
- * - the project actually has a `lobu.config.ts` to apply.
96
+ * Re-apply the project's view files + their import graph (and `lobu.config.ts`
97
+ * itself) on change. The reapply set is rebuilt after every apply
98
+ * so a new import joins on the next save; the config reloads through jiti on
99
+ * each apply, so config edits take effect without restarting `lobu run`.
100
+ *
101
+ * Best-effort: setup failure only logs (a project with no `views:` still gets
102
+ * the config reapplied on edit, so adding the first view starts working with
103
+ * no restart). The reapply graph is imported lazily for the same module-load
104
+ * reason as the auto-apply above.
99
105
  */
106
+ export declare function startViewReapplyLoop(cwd: string, gatewayUrl: string, localOrgSlug?: string, dependencySession?: DependencySession): Promise<{
107
+ close: () => void;
108
+ }>;
100
109
  export declare function shouldAutoApplyLocalProject(opts: {
101
110
  mode: "external" | "embedded";
102
111
  localContextReady: boolean;
@@ -119,7 +128,7 @@ export declare function autoApplyLocalProject(cwd: string, gatewayUrl: string, l
119
128
  yes: boolean;
120
129
  url: string;
121
130
  org?: string;
122
- }) => Promise<unknown>): Promise<void>;
131
+ }) => Promise<unknown>, dependencySession?: DependencySession): Promise<void>;
123
132
  /**
124
133
  * Walk up from `startDir` looking for the Lobu monorepo workspace root: a
125
134
  * `package.json` with a non-empty `workspaces` field AND a
@@ -8,13 +8,13 @@ import { isChatPlatform } from "@lobu/core";
8
8
  import chalk from "chalk";
9
9
  import ora from "ora";
10
10
  import { resolveApiClient } from "../internal/api-client.js";
11
- import { agentApiBase } from "../internal/gateway-url.js";
12
11
  import { addContext, getCurrentContextName, getServerConfig, loadContextConfig, setActiveOrg, setCurrentContext, } from "../internal/context.js";
13
12
  import { saveCredentials } from "../internal/credentials.js";
13
+ import { agentApiBase } from "../internal/gateway-url.js";
14
14
  import { parseEnvContent } from "../internal/index.js";
15
- import { prepareRuntime } from "../internal/runtime-components.js";
16
15
  import { checkNodeSupport } from "../internal/node-version.js";
17
16
  import { loadProjectLink } from "../internal/project-link.js";
17
+ import { prepareRuntime } from "../internal/runtime-components.js";
18
18
  import { loadProjectConfig } from "./_lib/apply/desired-state.js";
19
19
  function connectorRefKey(ref) {
20
20
  return typeof ref === "string" ? ref : new ref().definition.key;
@@ -295,7 +295,17 @@ export async function devCommand(cwd, options = {}) {
295
295
  localContextReady,
296
296
  hasLobuConfig,
297
297
  })) {
298
- await autoApplyLocalProject(cwd, gatewayUrl, localOrgSlug);
298
+ const dependencySession = new Map();
299
+ await autoApplyLocalProject(cwd, gatewayUrl, localOrgSlug, undefined, dependencySession);
300
+ // Watch the project's listed view files + their import graph (and the
301
+ // config itself) and re-apply on change, so an edited view shows up
302
+ // locally within ~2 s of saving. Best-effort like the apply above: a
303
+ // project with no views, or a watch setup failure, only logs.
304
+ // Lazy-imported so the reapply graph (esbuild, jiti) stays out of
305
+ // `lobu run`'s module-load path — same rule as the auto-apply above.
306
+ void startViewReapplyLoop(cwd, gatewayUrl, localOrgSlug, dependencySession).catch(() => {
307
+ // startViewReapplyLoop logs its own diagnostics; never crash `run`.
308
+ });
299
309
  }
300
310
  // Mint hosted-chat link codes only AFTER the gateway is reachable and the
301
311
  // project is applied. printPreviewInstructions POSTs /preview/claims; if
@@ -328,11 +338,48 @@ export async function devCommand(cwd, options = {}) {
328
338
  });
329
339
  }
330
340
  /**
331
- * Whether `lobu run` should auto-apply the project. True only when:
332
- * - the backend is embedded (never auto-mutate an external/prod DB), AND
333
- * - local sign-in registered and credentialed the selected context, AND
334
- * - the project actually has a `lobu.config.ts` to apply.
341
+ * Re-apply the project's view files + their import graph (and `lobu.config.ts`
342
+ * itself) on change. The reapply set is rebuilt after every apply
343
+ * so a new import joins on the next save; the config reloads through jiti on
344
+ * each apply, so config edits take effect without restarting `lobu run`.
345
+ *
346
+ * Best-effort: setup failure only logs (a project with no `views:` still gets
347
+ * the config reapplied on edit, so adding the first view starts working with
348
+ * no restart). The reapply graph is imported lazily for the same module-load
349
+ * reason as the auto-apply above.
335
350
  */
351
+ export async function startViewReapplyLoop(cwd, gatewayUrl, localOrgSlug, dependencySession = new Map()) {
352
+ const noop = { close: () => undefined };
353
+ try {
354
+ const { collectViewReapplySet, startViewReapply } = await import("./_lib/view-reapply.js");
355
+ let set = await collectViewReapplySet(cwd);
356
+ const viewFiles = set.files.length - 1;
357
+ if (viewFiles > 0) {
358
+ console.log(chalk.dim(` watching ${viewFiles} view file${viewFiles === 1 ? "" : "s"} (re-apply on save)`));
359
+ }
360
+ const onLog = (message) => console.warn(chalk.dim(` (${message})`));
361
+ const current = startViewReapply(set, { onLog, onChange });
362
+ async function onChange() {
363
+ console.log(chalk.dim("\n views changed — re-applying…"));
364
+ await autoApplyLocalProject(cwd, gatewayUrl, localOrgSlug, undefined, dependencySession);
365
+ try {
366
+ set = await collectViewReapplySet(cwd);
367
+ }
368
+ catch {
369
+ // Keep the last good paths, but reopen subscriptions after an
370
+ // atomic save replaces a file that currently does not parse.
371
+ }
372
+ // In-place subscription swap on the same coordinator: a save recorded
373
+ // while this apply ran keeps its pending timer and still deploys.
374
+ current.update(set);
375
+ }
376
+ return { close: () => current.close() };
377
+ }
378
+ catch (err) {
379
+ console.warn(chalk.dim(` (view reapply off: ${err instanceof Error ? err.message : String(err)})`));
380
+ return noop;
381
+ }
382
+ }
336
383
  export function shouldAutoApplyLocalProject(opts) {
337
384
  return (opts.mode === "embedded" && opts.localContextReady && opts.hasLobuConfig);
338
385
  }
@@ -350,7 +397,7 @@ export function shouldAutoApplyLocalProject(opts) {
350
397
  */
351
398
  export async function autoApplyLocalProject(cwd, gatewayUrl, localOrgSlug,
352
399
  // Test seam — defaults to the lazily-imported applyCommand.
353
- applyImpl) {
400
+ applyImpl, dependencySession) {
354
401
  try {
355
402
  const applyCommand = applyImpl ?? (await import("./_lib/apply/apply-cmd.js")).applyCommand;
356
403
  // Pin the apply to the embedded server's URL. `resolveApiTarget` matches
@@ -361,6 +408,7 @@ applyImpl) {
361
408
  // cloud org can't redirect this local apply to a slug that doesn't exist
362
409
  // here — that previously 404'd and silently applied nothing.
363
410
  await applyCommand({
411
+ ...(dependencySession ? { dependencySession } : {}),
364
412
  cwd,
365
413
  yes: true,
366
414
  url: gatewayUrl,
@@ -34,5 +34,5 @@ export declare function initCommand(cwd?: string, projectNameArg?: string, optio
34
34
  * Warn-don't-fail: a broken/missing installer must not abort the scaffold, so
35
35
  * the failure is returned as a warning string for the caller to print.
36
36
  */
37
- export declare function installScaffoldedProjectDeps(projectDir: string, stdio?: "inherit" | "pipe"): string | null;
37
+ export declare function installScaffoldedProjectDeps(projectDir: string, stdio?: "inherit" | "pipe"): Promise<string | null>;
38
38
  //# sourceMappingURL=init.d.ts.map
@@ -278,7 +278,7 @@ export async function initCommand(cwd = process.cwd(), projectNameArg, options =
278
278
  }
279
279
  else {
280
280
  console.log(chalk.dim("\nInstalling project dependencies (this may take a few minutes)..."));
281
- const depsWarning = installScaffoldedProjectDeps(projectDir, "inherit");
281
+ const depsWarning = await installScaffoldedProjectDeps(projectDir, "inherit");
282
282
  if (depsWarning)
283
283
  console.log(chalk.yellow(`\n⚠ ${depsWarning}`));
284
284
  else
@@ -608,7 +608,7 @@ export async function initCommand(cwd = process.cwd(), projectNameArg, options =
608
608
  }
609
609
  else {
610
610
  console.log(chalk.dim("\nInstalling project dependencies (this may take a few minutes)..."));
611
- depsWarning = installScaffoldedProjectDeps(projectDir, "inherit");
611
+ depsWarning = await installScaffoldedProjectDeps(projectDir, "inherit");
612
612
  }
613
613
  if (depsWarning) {
614
614
  console.log(chalk.yellow(`\n⚠ ${depsWarning}`));
@@ -760,9 +760,9 @@ async function generateLobuConfig(projectDir, options) {
760
760
  * Warn-don't-fail: a broken/missing installer must not abort the scaffold, so
761
761
  * the failure is returned as a warning string for the caller to print.
762
762
  */
763
- export function installScaffoldedProjectDeps(projectDir, stdio = "pipe") {
763
+ export async function installScaffoldedProjectDeps(projectDir, stdio = "pipe") {
764
764
  try {
765
- installProjectDeps(projectDir, { stdio });
765
+ await installProjectDeps(projectDir, { stdio });
766
766
  return null;
767
767
  }
768
768
  catch (error) {
@@ -213,6 +213,9 @@ export async function loginCommand(options) {
213
213
  tokenEndpoint: discovery.tokenEndpoint,
214
214
  revocationEndpoint: discovery.revocationEndpoint,
215
215
  userinfoEndpoint: discovery.userinfoEndpoint,
216
+ // Record the audience the issuer bound this grant to (RFC 8707, echoed
217
+ // on the token response). Refresh must replay it verbatim.
218
+ ...(tokens.resource ? { resource: tokens.resource } : {}),
216
219
  };
217
220
  await saveCredentials({
218
221
  accessToken: tokens.accessToken,
@@ -176,14 +176,6 @@ export interface EntityType {
176
176
  onMatch: "auto_merge" | "review";
177
177
  }>;
178
178
  };
179
- /**
180
- * Default view template (render-DSL root node, optionally with a `data_sources`
181
- * key) for this entity type's detail page. Applied declaratively and
182
- * git-audited. Under `prune`, omitting it clears any existing template (the
183
- * page falls back to the schema-derived default); without prune, omitting it
184
- * leaves a UI-authored template untouched.
185
- */
186
- viewTemplate?: Record<string, unknown>;
187
179
  metadata?: Record<string, unknown>;
188
180
  /**
189
181
  * Present only for DERIVED types — a read-only SQL view (`{ sql }`). Omitted ⇒
@@ -407,6 +399,24 @@ export interface ConnectorSource {
407
399
  * so the connector module is never imported during config eval.
408
400
  */
409
401
  export declare function connectorFromFile<_Connector extends ConnectorClassExport = ConnectorClassExport>(path: string): ConnectorSource;
402
+ export interface ViewSource {
403
+ readonly kind: "viewSource";
404
+ /** Path to a view module (`views/<type>/<key>.tsx`), relative to the config file. */
405
+ path: string;
406
+ }
407
+ /**
408
+ * Reference a Lobu view module to bundle + ship at apply time.
409
+ *
410
+ * The module declares itself with `export const view = defineView({ key,
411
+ * attach, params, actions })` from `@lobu/views` plus a default-export
412
+ * component (hooks inside, no document access); the `attach` line in the
413
+ * file says where it appears, the folder is only a convention. `lobu apply`
414
+ * bundles the module where the project's node_modules exists (relative files
415
+ * and npm deps resolved) and ships source + bundle + extracted metadata;
416
+ * `lobu run` watches the listed files and re-applies on change. Explicit
417
+ * list, no directory auto-discovery — mirroring `connectorFromFile`.
418
+ */
419
+ export declare function viewFromFile(path: string): ViewSource;
410
420
  /**
411
421
  * The shape an Automation reaction module's default export must satisfy:
412
422
  * `export default async (ctx, client, params?) => …`. Used to type-check the
@@ -810,6 +820,13 @@ export interface Project {
810
820
  * auto-discovery; only listed connectors are uploaded.
811
821
  */
812
822
  connectors?: ConnectorSource[];
823
+ /**
824
+ * Local view modules (`views/<type>/<key>.tsx`) to bundle and ship, built
825
+ * with {@link viewFromFile}. Explicit list, no directory auto-discovery;
826
+ * only listed views are uploaded. The module's `defineView` says where it
827
+ * appears; `lobu run` watches the listed files and their import graph.
828
+ */
829
+ views?: ViewSource[];
813
830
  }
814
831
  export declare function defineConfig(config: Omit<Project, "kind">): Project;
815
832
  //# sourceMappingURL=define.d.ts.map
@@ -72,6 +72,15 @@ function deriveRequired(required, properties) {
72
72
  }
73
73
  export function defineEntityType(config) {
74
74
  const { required, properties, ...rest } = config;
75
+ // View templates were retired with the server tool: a stale config must fail
76
+ // loudly here, not silently drop the declaration or die later on a removed
77
+ // tool call.
78
+ if (rest.viewTemplate !== undefined) {
79
+ const key = typeof rest.key === "string"
80
+ ? rest.key
81
+ : "unknown";
82
+ throw new Error(`Entity type '${key}' declares 'viewTemplate', which was retired and removed: delete 'viewTemplate' from lobu.config.ts (detail pages fall back to the schema default).`);
83
+ }
75
84
  const resolvedRequired = deriveRequired(required, properties);
76
85
  return {
77
86
  ...rest,
@@ -115,6 +124,21 @@ export function defineConnection(config) {
115
124
  export function connectorFromFile(path) {
116
125
  return { kind: "connectorSource", path };
117
126
  }
127
+ /**
128
+ * Reference a Lobu view module to bundle + ship at apply time.
129
+ *
130
+ * The module declares itself with `export const view = defineView({ key,
131
+ * attach, params, actions })` from `@lobu/views` plus a default-export
132
+ * component (hooks inside, no document access); the `attach` line in the
133
+ * file says where it appears, the folder is only a convention. `lobu apply`
134
+ * bundles the module where the project's node_modules exists (relative files
135
+ * and npm deps resolved) and ships source + bundle + extracted metadata;
136
+ * `lobu run` watches the listed files and re-applies on change. Explicit
137
+ * list, no directory auto-discovery — mirroring `connectorFromFile`.
138
+ */
139
+ export function viewFromFile(path) {
140
+ return { kind: "viewSource", path };
141
+ }
118
142
  /** Execute a local TypeScript job directly, with the owning agent's SDK permissions. */
119
143
  export function scriptFromFile(path, params) {
120
144
  return { kind: "scriptSource", path, ...(params ? { params } : {}) };
@@ -44,11 +44,8 @@ export default defineConnector({
44
44
  // Fetch data, transform to events...
45
45
  const events: EventEnvelope[] = [];
46
46
 
47
- return {
48
- events,
49
- checkpoint: { last_sync_at: new Date().toISOString() },
50
- metadata: { query, items_found: events.length },
51
- };
47
+ await ctx.commit(events, { last_sync_at: new Date().toISOString() });
48
+ return { status: 'complete', metadata: { query, items_found: events.length } };
52
49
  },
53
50
  },
54
51
  },
@@ -234,10 +231,11 @@ feeds: {
234
231
  issue: { description: 'An issue changed' },
235
232
  },
236
233
  // Incremental materialization for local search and Automations.
237
- sync: async (ctx) => ({
238
- events: await fetchChangedIssues(ctx.config.project, ctx.checkpoint),
239
- checkpoint: { synced_at: new Date().toISOString() },
240
- }),
234
+ sync: async (ctx) => {
235
+ const events = await fetchChangedIssues(ctx.config.project, ctx.checkpoint);
236
+ await ctx.commit(events, { synced_at: new Date().toISOString() });
237
+ return { status: 'complete' };
238
+ },
241
239
  // Direct source read with native filtering and pagination.
242
240
  read: async (ctx) => {
243
241
  const page = await queryIssues({
@@ -258,7 +256,8 @@ A feed's `eventKinds` are also the **default Automation trigger catalog**. The f
258
256
 
259
257
  The worker calls the selected feed's `sync` handler for scheduled,
260
258
  webhook-triggered, and manually triggered sync runs. It receives a `SyncContext`
261
- and returns a `SyncResult`.
259
+ stores events through `ctx.commit`, and returns a `SyncResult` saying whether
260
+ the source is caught up.
262
261
 
263
262
  ### SyncContext
264
263
 
@@ -271,8 +270,9 @@ interface SyncContext {
271
270
  credentials: SyncCredentials | null; // OAuth/session credentials; env_keys are in config
272
271
  entityIds: number[]; // Linked entity IDs
273
272
  sessionState?: Record<string, unknown>; // Browser session state (cookies, tokens)
274
- emitEvents?: (events: EventEnvelope[]) => Promise<void>; // Stream events mid-sync
275
- updateCheckpoint?: (cp: Record<string, unknown>) => Promise<void>; // Save progress mid-sync
273
+ // Store a page, then move its checkpoint; resolves once both are durable.
274
+ // `null` stores the events and leaves the checkpoint where it is.
275
+ commit: (events: EventEnvelope[], checkpoint: Record<string, unknown> | null) => Promise<void>;
276
276
  }
277
277
  ```
278
278
 
@@ -280,8 +280,7 @@ interface SyncContext {
280
280
 
281
281
  ```typescript
282
282
  interface SyncResult {
283
- events: EventEnvelope[]; // Events to ingest
284
- checkpoint: Record<string, unknown> | null; // Updated checkpoint to persist
283
+ status: 'complete' | 'more'; // Caught up, or stopped early with work left (reruns now)
285
284
  auth_update?: Record<string, unknown>; // Updated session state (browser cookies, etc.)
286
285
  metadata?: {
287
286
  items_found?: number;
@@ -320,7 +319,7 @@ Use checkpoints to implement incremental sync. Common patterns:
320
319
  - **Timestamp-based**: Store `last_sync_at` and use it as a `since` filter on the next sync (see `github.ts`)
321
320
  - **ID-based**: Store a list of seen IDs for deduplication, trimmed to a max size to prevent unbounded growth (see `rss.ts`)
322
321
 
323
- For long-running syncs, use `ctx.emitEvents()` to stream event batches to the platform as they're collected, and `ctx.updateCheckpoint()` to persist progress. If the sync crashes mid-way, the next run resumes from the last saved checkpoint.
322
+ Commit as you go: call `await ctx.commit(events, checkpoint)` once per source page, with the checkpoint that resumes after that page, and await it before fetching the next. A large commit may be transported in chunks, but its checkpoint moves only with the final chunk; if the run is killed or crashes mid-way, replay may supersede already-stored events, and no checkpoint ever covers events that were not stored. A pass that stops early at a budget (pages, rows, time) returns `{ status: 'more' }` so the next run starts immediately; `more` is only honored when the pass moved the checkpoint, so a pass that makes no progress falls back to the schedule instead of looping.
324
323
 
325
324
  ## Reading from the Source
326
325
 
@@ -527,7 +526,7 @@ Connectors can also be installed manually via `client.connections.installConnect
527
526
 
528
527
  1. For fleet workers and embedded-mode hosts (worker + gateway share a host), the gateway sends only `connector_key` in the worker-poll response — both runtimes have the `.ts` source on disk, and the worker compiles locally via the shared pipeline at `@lobu/connector-worker/compile`. For DB-only / device workers without source on disk, the gateway sends `compiled_code` inline.
529
528
  2. The bundle is self-contained — the SDK and every pure-JS dependency are inlined — and is evaluated inside a V8 isolate in the worker process. The isolate has no module loader, so a bundle that still `require()`s a Node builtin is rejected before it runs.
530
- 3. Host and guest speak the SDK shapes (`SyncContext` / `ActionContext` / `AuthContext` in, `SyncResult` / `ActionResult` / `AuthResult` out, no envelope) across named host capabilities. Sync events stream up as the connector emits them.
529
+ 3. Host and guest speak the SDK shapes (`SyncContext` / `ActionContext` / `AuthContext` in, `SyncResult` / `ActionResult` / `AuthResult` out, no envelope) across named host capabilities. Sync pages and their checkpoints cross the `ctx.commit` capability together.
531
530
  4. `IsolateExecutor` defaults to a 10-minute wall clock and a 512 MB heap for every run; interactive auth runs disable the fixed timeout while waiting for the user.
532
531
  5. The guest has no filesystem, no ambient environment, and no socket of its own: everything it can reach is a named capability the host granted — `fetch` and, for the DB connectors, a host-dialled TCP socket — plus the explicit values supplied in `job.env`.
533
532
  6. Connection credentials and config flow through the typed job context (`ctx.credentials`, `ctx.config`, or auth's `previousCredentials`). The worker API token is never forwarded to connector code. `ctx.credentials.accessToken` is a per-run placeholder the host resolves at the wire (see "`oauth` - OAuth providers" above); `ctx.config` and `previousCredentials` still carry real values.