@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
@@ -1,29 +1,18 @@
1
- /**
2
- * Shared structural types + tiny helpers used across the apply pipeline
3
- * (desired-state IR, wire client, diff, apply-cmd).
4
- *
5
- * Only shapes that are genuinely IDENTICAL on both sides of the wire belong
6
- * here — anything that encodes a server-specific response shape stays a
7
- * `Remote*` type in client.ts.
8
- */
9
1
  export function isRecord(value) {
10
2
  return typeof value === "object" && value !== null && !Array.isArray(value);
11
3
  }
12
- /** Apply declared model/executor fields while preserving unmanaged execution options. */
13
- export function automationExecutionConfig(model, remote, executor) {
14
- if (executor) {
15
- if (model != null)
16
- throw new Error("Script Automations do not use a model override.");
17
- return { executor };
18
- }
19
- if (model === undefined && executor === undefined)
4
+ /** Preserve omitted options; replacing a legacy definition must be explicit. */
5
+ export function automationExecutionConfig(model, remote, declared) {
6
+ if (declared !== undefined)
7
+ return declared;
8
+ if (model === undefined)
20
9
  return remote ?? null;
10
+ if (remote?.executor)
11
+ throw new Error("Clear the legacy executor explicitly with executionConfig before changing its model.");
21
12
  const config = { ...remote };
22
- if (executor === null)
23
- delete config.executor;
24
13
  if (model === null)
25
14
  delete config.model;
26
- else if (model !== undefined)
15
+ else
27
16
  config.model = model;
28
17
  return Object.keys(config).length > 0 ? config : null;
29
18
  }
@@ -12,6 +12,7 @@ import { addContext, getCurrentContextName, getServerConfig, loadContextConfig,
12
12
  import { saveCredentials } from "../internal/credentials.js";
13
13
  import { agentApiBase } from "../internal/gateway-url.js";
14
14
  import { parseEnvContent } from "../internal/index.js";
15
+ import { resolveNode26Binary } from "../internal/node-binary.js";
15
16
  import { checkNodeSupport } from "../internal/node-version.js";
16
17
  import { loadProjectLink } from "../internal/project-link.js";
17
18
  import { prepareRuntime } from "../internal/runtime-components.js";
@@ -105,13 +106,21 @@ export function shouldRefuseSharedDatabaseUrl(input) {
105
106
  */
106
107
  export async function devCommand(cwd, options = {}) {
107
108
  const spinner = ora("Validating environment...").start();
108
- // The server also warns on Node 25, but only after the CLI's boot output.
109
- // Surface the sandbox limitation before validation so it is hard to miss.
109
+ // The backend loads isolated-vm, whose native build is Node-26-only. Fail
110
+ // before validation so an unsupported (or Bun-hosted) launch is obvious.
110
111
  const nodeSupport = checkNodeSupport();
111
- if (nodeSupport.ok && !nodeSupport.sandbox) {
112
- spinner.warn(chalk.yellow(`Node ${process.versions.node}: the agent-code sandbox (query_sdk / run_sdk) is unavailable.`));
113
- console.warn(chalk.dim(" isolated-vm has no Node 25 build. Use Node 24 (LTS) or 26+ to enable the sandbox.\n"));
114
- spinner.start("Validating environment...");
112
+ if (!nodeSupport.ok) {
113
+ spinner.fail(chalk.red(nodeSupport.reason));
114
+ console.error(chalk.dim(` ${nodeSupport.why}\n`));
115
+ process.exit(1);
116
+ }
117
+ let nodeBinary;
118
+ try {
119
+ nodeBinary = resolveNode26Binary();
120
+ }
121
+ catch (error) {
122
+ spinner.fail(chalk.red(error instanceof Error ? error.message : String(error)));
123
+ process.exit(1);
115
124
  }
116
125
  const envPath = join(cwd, ".env");
117
126
  let envVars = {};
@@ -256,7 +265,12 @@ export async function devCommand(cwd, options = {}) {
256
265
  GATEWAY_PORT: String(portNum),
257
266
  ...(logLevel ? { LOG_LEVEL: logLevel } : {}),
258
267
  };
259
- const child = spawn(process.execPath, [bundlePath], {
268
+ // Never `process.execPath`: when the CLI itself was launched through Bun,
269
+ // that is Bun, which cannot dlopen the V8 isolated-vm addon. `nodeBinary`
270
+ // is a verified Node 26 binary (the current process when it already is one).
271
+ // `--no-node-snapshot` is isolated-vm's upstream launch requirement on
272
+ // Node 20+.
273
+ const child = spawn(nodeBinary, ["--no-node-snapshot", bundlePath], {
260
274
  cwd,
261
275
  env: childEnv,
262
276
  stdio: "inherit",
@@ -56,14 +56,7 @@ function checkNodeVersion() {
56
56
  return {
57
57
  name: "node",
58
58
  status: "fail",
59
- detail: `${version} (needs >=${MIN_NODE_MAJOR})`,
60
- };
61
- }
62
- if (!support.sandbox) {
63
- return {
64
- name: "node",
65
- status: "warn",
66
- detail: `${version} (SDK sandbox unavailable; use 24 LTS or 26+)`,
59
+ detail: `${version} (needs ${MIN_NODE_MAJOR}.x)`,
67
60
  };
68
61
  }
69
62
  return { name: "node", status: "ok", detail: version };
@@ -521,11 +521,10 @@ export async function initCommand(cwd = process.cwd(), projectNameArg, options =
521
521
  WORKER_DISALLOWED_DOMAINS: answers.disallowedDomains,
522
522
  };
523
523
  await renderTemplate(".env.tmpl", variables, join(projectDir, ".env"));
524
- // Pin Node 22 for nvm / fnm / mise / asdf / volta — Lobu refuses to boot
525
- // on Node 25+ (isolated-vm has no prebuilt). Homebrew's `node` now
526
- // resolves to 26, so without these files a fresh `lobu run` fails.
527
- await writeFile(join(projectDir, ".nvmrc"), "22\n");
528
- await writeFile(join(projectDir, ".node-version"), "22\n");
524
+ // Pin Node 26 for nvm / fnm / mise / asdf / volta — Lobu's gateway and
525
+ // worker load the Node-26-only isolated-vm native build.
526
+ await writeFile(join(projectDir, ".nvmrc"), "26\n");
527
+ await writeFile(join(projectDir, ".node-version"), "26\n");
529
528
  // `.env` carries ENCRYPTION_KEY + provider API keys / OAuth tokens
530
529
  // appended via setLocalEnvValue below. Tighten now so the initial
531
530
  // write isn't world-readable on multi-user hosts (default umask 022).
@@ -9,7 +9,9 @@
9
9
  * Automation reactions) live in their own modules; these objects only declare
10
10
  * config and references.
11
11
  */
12
- import type { AutomationEventTrigger, AutomationScheduleTrigger, AutomationWorkspaceEventTrigger, ConnectorClass, ConnectorRuntime, CollectionPresentation, Dimension, EventSet, Measure, ReactionClient, AutomationScriptContext, ReactionContext, Segment } from "@lobu/connector-sdk";
12
+ import type { AutomationEventTrigger, AutomationScheduleTrigger, AutomationScriptContext, AutomationWorkspaceEventTrigger, CollectionPresentation, ConnectorClass, ConnectorRuntime, Dimension, EventSet, Measure, ReactionClient, ReactionContext, Segment } from "@lobu/connector-sdk";
13
+ import type { AgentSettingsPatch } from "@lobu/core/contracts/agent-settings";
14
+ import type { AutomationExecutionConfig } from "@lobu/core/contracts/tools/manage-automations";
13
15
  import { type StringOptions, type TOptional, type TSchema, type TString } from "@sinclair/typebox";
14
16
  import type { SecretRef } from "./secret.js";
15
17
  /** A connector referenced by its key, or by the class produced by `defineConnector`. */
@@ -428,17 +430,11 @@ export declare function viewFromFile(path: string): ViewSource;
428
430
  * `<Handler>` generic on {@link reactionFromFile} against the referenced module.
429
431
  */
430
432
  export type ReactionHandler = (ctx: ReactionContext, client: ReactionClient, params?: Record<string, unknown>) => Promise<unknown>;
431
- export type AutomationScriptHandler = (ctx: AutomationScriptContext, client: ReactionClient, params?: Record<string, unknown>) => Promise<unknown>;
432
- export interface ScriptSource {
433
- readonly kind: "scriptSource";
434
- path: string;
435
- params?: Record<string, unknown>;
436
- }
437
- /** Execute a local TypeScript job directly, with the owning agent's SDK permissions. */
438
- export declare function scriptFromFile<_Handler extends AutomationScriptHandler = AutomationScriptHandler>(path: string, params?: Record<string, unknown>): ScriptSource;
433
+ /** Optional preparation export in an Automation reaction module. */
434
+ export type PreparationHandler = (ctx: AutomationScriptContext, client: ReactionClient) => Promise<Record<string, Record<string, unknown>[]>>;
439
435
  /**
440
- * A local reaction source file to compile + run in a sandboxed isolate when the
441
- * Automation fires. Built with {@link reactionFromFile} and set on
436
+ * A local lifecycle module: optional `prepare` before the native agent and/or
437
+ * a default completion reaction, both run in the shared sandbox. Built with {@link reactionFromFile} and set on
442
438
  * {@link Automation.reaction}. Like {@link ConnectorSource}, this carries only the
443
439
  * path as plain data — the handler module is NOT imported at config-eval time;
444
440
  * `lobu apply` reads the raw source and the server compiles it.
@@ -449,7 +445,10 @@ export interface ReactionSource {
449
445
  path: string;
450
446
  }
451
447
  /**
452
- * Reference a local reaction source file to compile + ship at apply time.
448
+ * Reference a local lifecycle module to compile + ship at apply time.
449
+ * A preparation-only module needs no generic: `reactionFromFile("./prepare.ts")`.
450
+ * Its `prepare` export returns named arrays of records, saved per run and read
451
+ * by the agent through `knowledge.read({ automation_id, run_id }).sources`.
453
452
  *
454
453
  * Pass the handler's module type via the generic for go-to-def / rename and a
455
454
  * `tsc` error if the module's default export drifts from {@link ReactionHandler}:
@@ -462,7 +461,7 @@ export interface ReactionSource {
462
461
  * The `import type` is erased at compile time (zero runtime cost; jiti drops it),
463
462
  * so the handler module is never imported during config eval.
464
463
  */
465
- export declare function reactionFromFile<_Handler extends ReactionHandler = ReactionHandler>(path: string): ReactionSource;
464
+ export declare function reactionFromFile<_Handler extends (...args: never[]) => Promise<unknown> = ReactionHandler>(path: string): ReactionSource;
466
465
  export interface AutomationEntityOutput {
467
466
  /** Stored entity type (a config handle or slug). */
468
467
  entity: EntityType | string;
@@ -505,10 +504,10 @@ export interface Automation {
505
504
  readonly kind: "automation";
506
505
  /** Stable slug — diff key. */
507
506
  slug: string;
508
- /** Owning agent (handle or id). Every Automation belongs to exactly one agent. */
509
- agent: Agent | string;
510
- /** Script job or agent execution. Omitted preserves the stored executor; "agent" clears a script executor. */
511
- executor?: ScriptSource | "agent";
507
+ /** Managed agent identity. Omit for device-only or external analysis. */
508
+ agent?: Agent | string | null;
509
+ /** Canonical execution options. Omit to preserve; null clears. Cannot overlap the model helper. */
510
+ executionConfig?: AutomationExecutionConfig | null;
512
511
  name?: string;
513
512
  description?: string;
514
513
  /**
@@ -536,7 +535,7 @@ export interface Automation {
536
535
  * action for a declarative project.
537
536
  *
538
537
  * Supply {@link Automation.prompt}, `skills`, a {@link Automation.reaction}
539
- * script, or an {@link Automation.executor} script. Any one is required for schedule triggers, event
538
+ * script. Any one is required for schedule triggers, event
540
539
  * triggers with execution `"window"`, and Automations with no triggers
541
540
  * (manual runs); an event trigger with execution `"turn"` may omit all
542
541
  * instruction sources, since the incoming event is the content and a built-in
@@ -565,7 +564,7 @@ export interface Automation {
565
564
  tags?: string[];
566
565
  /** LLM guidance for the Automation's downstream reaction agent. */
567
566
  reactionsGuidance?: string;
568
- /** Agent-kind override for firings (e.g. "background", "notifier"). */
567
+ /** Agent runtime override for firings. */
569
568
  agentKind?: string;
570
569
  /**
571
570
  * UUID pinning this Automation's runs to a specific device worker. Only
@@ -579,16 +578,14 @@ export interface Automation {
579
578
  */
580
579
  model?: string | null;
581
580
  /**
582
- * A sibling `.ts` reaction script (`./reactions/foo.reaction.ts`) compiled +
583
- * run in a sandboxed isolate when the Automation fires, built with
584
- * {@link reactionFromFile}. The script must `export default async (ctx,
585
- * client, params?) => …` ({@link ReactionHandler}). Kept in its own file (not
586
- * inline) so your IDE type-checks it; the path must stay under the config
587
- * directory.
581
+ * A sibling TypeScript module, built with {@link reactionFromFile}. Export
582
+ * `prepare` to save named sources before analysis and/or a default handler
583
+ * for completion. Without prompt, skills, input schema or declared outputs,
584
+ * the module runs as code without a model. The path stays under the config
585
+ * directory so it can be typechecked and bundled portably.
588
586
  *
589
587
  * Omit to preserve a previously installed reaction. Set explicitly to `null`
590
- * to remove it — required when switching a reaction-driven Automation to a
591
- * script executor so the same work is not performed twice.
588
+ * to remove it after the remaining definition has its required instructions.
592
589
  */
593
590
  reaction?: ReactionSource | null;
594
591
  }
@@ -673,7 +670,7 @@ export interface ProviderConfig {
673
670
  key?: string | SecretRef;
674
671
  }
675
672
  /** Modalities an org inference provider may declare a capability block for. */
676
- export type InferenceModality = "text" | "image" | "stt" | "tts" | "embedding";
673
+ export type InferenceModality = "text" | "image" | "stt" | "tts";
677
674
  /**
678
675
  * Per-modality upstream override for an {@link OrgProvider}. Omit a modality
679
676
  * entirely to keep the provider's static (built-in) semantics for it. All fields
@@ -719,6 +716,8 @@ export interface Agent {
719
716
  id: string;
720
717
  name?: string;
721
718
  description?: string;
719
+ /** Canonical settings. Omitted keys stay unmanaged; supplied settings replace their stored value. */
720
+ settings?: AgentSettingsPatch;
722
721
  /**
723
722
  * Agent directory holding `SOUL.md` / `IDENTITY.md` / `USER.md`. Relative to
724
723
  * the config file; defaults to `./agents/<id>`. (Skills are referenced
@@ -163,12 +163,11 @@ export function connectorFromFile(path) {
163
163
  export function viewFromFile(path) {
164
164
  return { kind: "viewSource", path };
165
165
  }
166
- /** Execute a local TypeScript job directly, with the owning agent's SDK permissions. */
167
- export function scriptFromFile(path, params) {
168
- return { kind: "scriptSource", path, ...(params ? { params } : {}) };
169
- }
170
166
  /**
171
- * Reference a local reaction source file to compile + ship at apply time.
167
+ * Reference a local lifecycle module to compile + ship at apply time.
168
+ * A preparation-only module needs no generic: `reactionFromFile("./prepare.ts")`.
169
+ * Its `prepare` export returns named arrays of records, saved per run and read
170
+ * by the agent through `knowledge.read({ automation_id, run_id }).sources`.
172
171
  *
173
172
  * Pass the handler's module type via the generic for go-to-def / rename and a
174
173
  * `tsc` error if the module's default export drifts from {@link ReactionHandler}:
@@ -166,63 +166,91 @@ function escapeLike(term: string): string {
166
166
  return term.replace(/[\\%_]/g, (c) => `\\${c}`);
167
167
  }
168
168
 
169
+ /** Opening `$$` / `$tag$` of a dollar-quoted string, matched at `lastIndex`. */
170
+ const DOLLAR_QUOTE_RE = /\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$/y;
171
+
169
172
  /**
170
- * True if `sql` has a `LIMIT`/`OFFSET` keyword at paren-depth 0 (a TOP-level
171
- * one), scanning past string literals, quoted identifiers, and comments so a
172
- * `'limit'` literal or a `"limit"` column never false-matches. An inner LIMIT
173
- * inside a subquery sits at depth > 0 and is allowed. Works without the AST, so
174
- * it gates both the parseable and the token-fallback paths identically.
173
+ * Blank out string literals, quoted identifiers, dollar-quoted strings and
174
+ * comments (same length, so positions survive) so the structural checks only
175
+ * see executable tokens — a `';'`, `':name'`, `'$1'` or `"limit"` inside a
176
+ * literal must never trip them. Unterminated literals/comments mask to the end;
177
+ * Postgres reports those itself.
175
178
  */
176
- function hasTopLevelLimitOrOffset(sql: string): boolean {
179
+ function executableSql(sql: string): string {
177
180
  const n = sql.length;
178
- let depth = 0;
181
+ let result = '';
179
182
  let i = 0;
180
183
  while (i < n) {
184
+ const start = i;
181
185
  const c = sql[i];
182
- if (c === "'") {
183
- i++;
184
- while (i < n && sql[i] !== "'") i++;
185
- i++;
186
- continue;
187
- }
188
- if (c === '"') {
189
- i++;
190
- while (i < n && sql[i] !== '"') i++;
186
+ if (c === "'" || c === '"') {
187
+ // E'…' strings escape with backslash; plain ones only double the quote.
188
+ const backslashEscapes =
189
+ c === "'" &&
190
+ /[eE]/.test(sql[i - 1] ?? '') &&
191
+ !/[A-Za-z0-9_$]/.test(sql[i - 2] ?? '');
191
192
  i++;
192
- continue;
193
- }
194
- if (c === '-' && sql[i + 1] === '-') {
195
- i += 2;
193
+ while (i < n) {
194
+ if (backslashEscapes && sql[i] === '\\') {
195
+ i += 2;
196
+ continue;
197
+ }
198
+ if (sql[i++] === c) {
199
+ if (sql[i] !== c) break;
200
+ i++;
201
+ }
202
+ }
203
+ } else if (c === '$' && !/[A-Za-z0-9_$]/.test(sql[i - 1] ?? '')) {
204
+ DOLLAR_QUOTE_RE.lastIndex = i;
205
+ const delimiter = DOLLAR_QUOTE_RE.exec(sql)?.[0];
206
+ if (!delimiter) {
207
+ result += c;
208
+ i++;
209
+ continue;
210
+ }
211
+ const end = sql.indexOf(delimiter, i + delimiter.length);
212
+ i = end < 0 ? n : end + delimiter.length;
213
+ } else if (c === '-' && sql[i + 1] === '-') {
196
214
  while (i < n && sql[i] !== '\n') i++;
197
- continue;
198
- }
199
- if (c === '/' && sql[i + 1] === '*') {
215
+ } else if (c === '/' && sql[i + 1] === '*') {
216
+ let depth = 1;
200
217
  i += 2;
201
- while (i < n && !(sql[i] === '*' && sql[i + 1] === '/')) i++;
202
- i += 2;
203
- continue;
204
- }
205
- if (c === '(') {
206
- depth++;
207
- i++;
208
- continue;
209
- }
210
- if (c === ')') {
211
- if (depth > 0) depth--;
218
+ while (i < n && depth > 0) {
219
+ if (sql[i] === '/' && sql[i + 1] === '*') {
220
+ depth++;
221
+ i += 2;
222
+ } else if (sql[i] === '*' && sql[i + 1] === '/') {
223
+ depth--;
224
+ i += 2;
225
+ } else {
226
+ i++;
227
+ }
228
+ }
229
+ } else {
230
+ result += c;
212
231
  i++;
213
232
  continue;
214
233
  }
215
- if (/[A-Za-z_]/.test(c)) {
216
- let j = i + 1;
217
- while (j < n && /[A-Za-z0-9_$]/.test(sql[j])) j++;
218
- if (depth === 0) {
219
- const word = sql.slice(i, j).toLowerCase();
220
- if (word === 'limit' || word === 'offset') return true;
221
- }
222
- i = j;
223
- continue;
234
+ result += ' '.repeat(Math.min(i, n) - start);
235
+ }
236
+ return result;
237
+ }
238
+
239
+ /**
240
+ * True if `sql` (already masked by executableSql) has a LIMIT/OFFSET keyword
241
+ * at paren-depth 0. An inner LIMIT inside a subquery sits at depth > 0 and is
242
+ * allowed.
243
+ */
244
+ function hasTopLevelLimitOrOffset(sql: string): boolean {
245
+ let depth = 0;
246
+ for (const [token] of sql.matchAll(/[A-Za-z_][A-Za-z0-9_$]*|[()]/g)) {
247
+ if (token === '(') {
248
+ depth++;
249
+ } else if (token === ')') {
250
+ depth = Math.max(0, depth - 1);
251
+ } else if (depth === 0 && /^(limit|offset)$/i.test(token)) {
252
+ return true;
224
253
  }
225
- i++;
226
254
  }
227
255
  return false;
228
256
  }
@@ -253,18 +281,19 @@ function queryValidationError(message: string) {
253
281
  function validateReadOnlySelect(raw: string): string {
254
282
  const stripped = raw.trim().replace(/;\s*$/, '');
255
283
  if (!stripped) throw queryValidationError('query is empty');
256
- if (stripped.includes(';')) {
284
+ const executable = executableSql(stripped);
285
+ if (executable.includes(';')) {
257
286
  throw queryValidationError('query must be a single statement (no embedded ";").');
258
287
  }
259
- if (/\$\d/.test(stripped) || /(^|[^:]):[A-Za-z_]/.test(stripped)) {
288
+ if (/\$\d/.test(executable) || /(^|[^:]):[A-Za-z_]/.test(executable)) {
260
289
  throw queryValidationError('query must not contain bind parameters ($1, :name).');
261
290
  }
262
291
  // Allow a leading "(" for "(SELECT …) UNION …" / parenthesized selects.
263
- const head = stripped.replace(/^\s*\(+\s*/, '');
292
+ const head = executable.replace(/^\s*\(+\s*/, '').trimStart();
264
293
  if (!/^(select|with)\b/i.test(head)) {
265
294
  throw queryValidationError('query must be a single read-only SELECT (or WITH … SELECT).');
266
295
  }
267
- if (hasTopLevelLimitOrOffset(stripped)) {
296
+ if (hasTopLevelLimitOrOffset(executable)) {
268
297
  throw queryValidationError(
269
298
  'query must not include a top-level LIMIT/OFFSET — the connector adds pagination automatically (an inner LIMIT inside a subquery is fine).',
270
299
  );
@@ -20,6 +20,7 @@ interface OrganizationInfo {
20
20
  /** HTTP verbs the CLI's REST clients issue. */
21
21
  export type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
22
22
  export interface RequestWithStatusOptions {
23
+ headers?: Record<string, string>;
23
24
  okStatuses?: number[];
24
25
  /** Send `Accept: application/json` (default). Off matches the apply client. */
25
26
  sendAccept?: boolean;
@@ -47,6 +48,7 @@ export declare class ApiClient {
47
48
  requestWithStatus<T>(method: HttpMethod, path: string, body?: unknown, options?: RequestWithStatusOptions): Promise<{
48
49
  status: number;
49
50
  body: T;
51
+ headers: Headers;
50
52
  }>;
51
53
  request<T>(method: HttpMethod, path: string, body?: unknown, options?: {
52
54
  okStatuses?: number[];
@@ -25,6 +25,7 @@ export class ApiClient {
25
25
  const url = path.startsWith("http") ? path : `${this.apiBaseUrl}${path}`;
26
26
  const headers = {
27
27
  ...this.extraHeaders,
28
+ ...options.headers,
28
29
  Authorization: `Bearer ${this.token}`,
29
30
  };
30
31
  if (options.sendAccept !== false)
@@ -48,7 +49,11 @@ export class ApiClient {
48
49
  const { message, code } = extractApiError(parsed, response.status, response.statusText);
49
50
  throw new ApiError(`${method} ${path} failed: ${message}`, response.status, code);
50
51
  }
51
- return { status: response.status, body: parsed };
52
+ return {
53
+ status: response.status,
54
+ body: parsed,
55
+ headers: response.headers,
56
+ };
52
57
  }
53
58
  async request(method, path, body, options = {}) {
54
59
  const { body: parsed } = await this.requestWithStatus(method, path, body, options);
@@ -0,0 +1,22 @@
1
+ export interface ResolveNode26Deps {
2
+ /** The CLI process's own executable — Bun when the CLI was launched via Bun. */
3
+ execPath: string;
4
+ versions: {
5
+ node?: string;
6
+ bun?: string;
7
+ };
8
+ platform: NodeJS.Platform;
9
+ env: NodeJS.ProcessEnv;
10
+ run: (command: string, args: string[]) => string;
11
+ }
12
+ /**
13
+ * Resolve the Node 26 binary that must host the backend.
14
+ *
15
+ * `lobu run` may itself be launched through Bun (for example `bunx @lobu/cli`),
16
+ * where `process.execPath` is Bun — a runtime that cannot load the V8
17
+ * isolated-vm addon. Never hand that executable to the server: use the current
18
+ * process only when it is genuinely Node 26, otherwise verify a `node` on PATH
19
+ * and fail fast with an actionable message.
20
+ */
21
+ export declare function resolveNode26Binary(deps?: ResolveNode26Deps): string;
22
+ //# sourceMappingURL=node-binary.d.ts.map
@@ -0,0 +1,73 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { delimiter, join } from "node:path";
3
+ const REQUIRED_NODE_MAJOR = 26;
4
+ const defaultDeps = {
5
+ execPath: process.execPath,
6
+ versions: process.versions,
7
+ platform: process.platform,
8
+ env: process.env,
9
+ run: (command, args) => execFileSync(command, args, {
10
+ encoding: "utf8",
11
+ timeout: 5_000,
12
+ stdio: ["ignore", "pipe", "ignore"],
13
+ }).trim(),
14
+ };
15
+ function majorOf(version) {
16
+ return Number.parseInt(version?.split(".")[0] ?? "", 10);
17
+ }
18
+ function probeNode(binary, run) {
19
+ try {
20
+ const raw = run(binary, [
21
+ "-p",
22
+ "JSON.stringify({node:process.versions.node,bun:process.versions.bun??null})",
23
+ ]);
24
+ const parsed = JSON.parse(raw);
25
+ if (typeof parsed.node !== "string")
26
+ return null;
27
+ return { node: parsed.node, bun: parsed.bun ?? null };
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ }
33
+ function pathCandidates(platform, env) {
34
+ const names = platform === "win32"
35
+ ? (env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM")
36
+ .split(";")
37
+ .filter(Boolean)
38
+ .map((ext) => `node${ext.toLowerCase()}`)
39
+ : ["node"];
40
+ const dirs = (env.PATH ?? "")
41
+ .split(platform === "win32" ? ";" : delimiter)
42
+ .filter(Boolean);
43
+ return dirs.flatMap((dir) => names.map((name) => join(dir, name)));
44
+ }
45
+ function isNode26(probe) {
46
+ return (probe !== null &&
47
+ probe.bun === null &&
48
+ majorOf(probe.node) === REQUIRED_NODE_MAJOR);
49
+ }
50
+ /**
51
+ * Resolve the Node 26 binary that must host the backend.
52
+ *
53
+ * `lobu run` may itself be launched through Bun (for example `bunx @lobu/cli`),
54
+ * where `process.execPath` is Bun — a runtime that cannot load the V8
55
+ * isolated-vm addon. Never hand that executable to the server: use the current
56
+ * process only when it is genuinely Node 26, otherwise verify a `node` on PATH
57
+ * and fail fast with an actionable message.
58
+ */
59
+ export function resolveNode26Binary(deps = defaultDeps) {
60
+ if (deps.versions.bun === undefined &&
61
+ majorOf(deps.versions.node) === REQUIRED_NODE_MAJOR) {
62
+ return deps.execPath;
63
+ }
64
+ for (const candidate of pathCandidates(deps.platform, deps.env)) {
65
+ if (isNode26(probeNode(candidate, deps.run)))
66
+ return candidate;
67
+ }
68
+ const current = deps.versions.bun
69
+ ? `Bun ${deps.versions.bun}`
70
+ : `Node ${deps.versions.node ?? "unknown"}`;
71
+ throw new Error(`Lobu's gateway must run on Node.js ${REQUIRED_NODE_MAJOR}.x — this CLI is running on ${current} and no Node ${REQUIRED_NODE_MAJOR} binary was found on PATH. Install Node ${REQUIRED_NODE_MAJOR} (nvm install ${REQUIRED_NODE_MAJOR} && nvm use ${REQUIRED_NODE_MAJOR}) and re-run.`);
72
+ }
73
+ //# sourceMappingURL=node-binary.js.map
@@ -1,23 +1,18 @@
1
1
  /**
2
2
  * Single source of truth for the CLI's Node-version policy.
3
3
  *
4
- * Lobu's SDK sandbox (query_sdk / run_sdk) uses isolated-vm, whose native addon
5
- * is tied to each Node line's V8 ABI: isolated-vm@6 covers Node 22–24, the
6
- * aliased isolated-vm@7 covers Node 26+. Node 25 is an EOL non-LTS line upstream
7
- * skipped, so it boots but has no sandbox build. Below 22 nothing works — the
8
- * bundled server's deps (undici) reference globals absent on
9
- * old Node and crash on load.
4
+ * Lobu's gateway and worker load isolated-vm, whose native addon is tied to a
5
+ * single Node major's V8 ABI. This repo ships one isolated-vm 7 build and runs
6
+ * it on Node 26 only; Node 27 and later need a matching addon build before they
7
+ * can be supported.
10
8
  *
11
- * The `bin/lobu.js` entrypoint carries an inline copy of the MIN threshold
12
- * because it must run with zero imports (before the bundle loads); keep it and
9
+ * The `bin/lobu.js` entrypoint carries an inline copy of the same major because
10
+ * it must run with zero imports (before the bundle loads); keep it and
13
11
  * packages/server/src/utils/assert-node-version.ts in sync with this file.
14
12
  */
15
- export declare const MIN_NODE_MAJOR = 22;
16
- /** True when isolated-vm has a build for this Node major (sandbox works). */
17
- export declare function sandboxAvailableForNode(major: number): boolean;
13
+ export declare const MIN_NODE_MAJOR = 26;
18
14
  type NodeSupport = {
19
15
  ok: true;
20
- sandbox: boolean;
21
16
  } | {
22
17
  ok: false;
23
18
  reason: string;