@lobu/runtime-device 21.2.1 → 22.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 (196) hide show
  1. package/dist/component.json +1 -1
  2. package/dist/dependencies.bun.lock +91 -83
  3. package/npm-shrinkwrap.json +492 -438
  4. package/package.json +12 -2
  5. package/vendor/cli/dist/commands/_lib/apply/apply-cmd.js +5 -6
  6. package/vendor/cli/dist/commands/_lib/apply/client.d.ts +1 -0
  7. package/vendor/cli/dist/commands/_lib/apply/client.js +26 -7
  8. package/vendor/cli/dist/commands/_lib/apply/desired-state.d.ts +9 -1
  9. package/vendor/cli/dist/commands/_lib/apply/diff.d.ts +1 -0
  10. package/vendor/cli/dist/commands/_lib/apply/diff.js +46 -4
  11. package/vendor/cli/dist/commands/_lib/apply/map-config.js +18 -38
  12. package/vendor/cli/dist/commands/_lib/init-from-org/bootstrap.js +5 -17
  13. package/vendor/cli/dist/commands/init.d.ts +0 -2
  14. package/vendor/cli/dist/commands/init.js +0 -27
  15. package/vendor/cli/dist/commands/login.d.ts +17 -0
  16. package/vendor/cli/dist/commands/login.js +43 -17
  17. package/vendor/cli/dist/commands/memory/_lib/errors.d.ts +0 -8
  18. package/vendor/cli/dist/commands/memory/_lib/errors.js +0 -12
  19. package/vendor/cli/dist/commands/memory/_lib/mcp.js +6 -6
  20. package/vendor/cli/dist/commands/memory/_lib/seed-cmd.js +4 -10
  21. package/vendor/cli/dist/config/define.d.ts +21 -15
  22. package/vendor/cli/dist/config/define.js +2 -2
  23. package/vendor/cli/dist/connectors/README.md +7 -5
  24. package/vendor/cli/dist/connectors/_google/actions.ts +270 -0
  25. package/vendor/cli/dist/connectors/_google/discovery/calendar_v3.json +1 -0
  26. package/vendor/cli/dist/connectors/_google/discovery/chat_v1.json +1 -0
  27. package/vendor/cli/dist/connectors/_google/discovery/docs_v1.json +1 -0
  28. package/vendor/cli/dist/connectors/_google/discovery/drive_v3.json +1 -0
  29. package/vendor/cli/dist/connectors/_google/discovery/gmail_v1.json +1 -0
  30. package/vendor/cli/dist/connectors/_google/discovery/people_v1.json +1 -0
  31. package/vendor/cli/dist/connectors/_google/discovery/sheets_v4.json +1 -0
  32. package/vendor/cli/dist/connectors/_google/discovery/tasks_v1.json +1 -0
  33. package/vendor/cli/dist/connectors/_google/discovery/youtube_v3.json +1 -0
  34. package/vendor/cli/dist/connectors/_google/discovery.ts +442 -0
  35. package/vendor/cli/dist/connectors/_google/errors.ts +91 -0
  36. package/vendor/cli/dist/connectors/_google/list-feed.ts +223 -0
  37. package/vendor/cli/dist/connectors/_google/policies.ts +127 -0
  38. package/vendor/cli/dist/connectors/agentid.ts +43 -0
  39. package/vendor/cli/dist/connectors/chat-user-identity.ts +2 -1
  40. package/vendor/cli/dist/connectors/github-automation-events.ts +9 -0
  41. package/vendor/cli/dist/connectors/github-identity.ts +28 -3
  42. package/vendor/cli/dist/connectors/github.ts +101 -59
  43. package/vendor/cli/dist/connectors/google_calendar.ts +207 -719
  44. package/vendor/cli/dist/connectors/google_drive.ts +16 -2
  45. package/vendor/cli/dist/connectors/google_gmail.ts +51 -33
  46. package/vendor/cli/dist/connectors/herdr.ts +406 -0
  47. package/vendor/cli/dist/connectors/jira.ts +6 -6
  48. package/vendor/cli/dist/connectors/linear.ts +7 -4
  49. package/vendor/cli/dist/connectors/postgres.ts +27 -2
  50. package/vendor/cli/dist/connectors/tiktok-inbox-page.js +230 -0
  51. package/vendor/cli/dist/connectors/tiktok-web-page.js +211 -0
  52. package/vendor/cli/dist/connectors/tiktok_web.ts +286 -0
  53. package/vendor/cli/dist/connectors/whatsapp-web-adapter.js +228 -10
  54. package/vendor/cli/dist/connectors/whatsapp-web-helpers.ts +47 -14
  55. package/vendor/cli/dist/connectors/whatsapp-web-identity.ts +121 -0
  56. package/vendor/cli/dist/connectors/whatsapp_web.ts +170 -29
  57. package/vendor/cli/dist/connectors/x.ts +276 -136
  58. package/vendor/cli/dist/index.js +1 -37
  59. package/vendor/cli/dist/internal/context.d.ts +10 -0
  60. package/vendor/cli/dist/internal/context.js +26 -16
  61. package/vendor/cli/dist/internal/node-version.d.ts +1 -1
  62. package/vendor/cli/dist/internal/node-version.js +1 -1
  63. package/vendor/cli/dist/internal/oauth.d.ts +3 -1
  64. package/vendor/cli/dist/internal/oauth.js +4 -3
  65. package/vendor/cli/dist/internal/runtime-components.d.ts +9 -0
  66. package/vendor/cli/dist/internal/runtime-components.js +67 -2
  67. package/vendor/cli/dist/mac-auth.js +17 -1
  68. package/vendor/cli/dist/providers.json +1 -1
  69. package/vendor/cli/dist/runtime-components.json +4 -4
  70. package/vendor/cli/dist/templates/AGENTS.md.tmpl +11 -4
  71. package/vendor/cli/dist/templates/README.md.tmpl +1 -1
  72. package/vendor/cli/dist/vendor/ora/.bun-tag-fde20e9a6df212fa +0 -0
  73. package/vendor/cli/dist/vendor/ora/index.d.ts +332 -0
  74. package/vendor/cli/dist/vendor/ora/index.js +424 -0
  75. package/vendor/cli/dist/vendor/ora/license +9 -0
  76. package/vendor/cli/dist/vendor/ora/package.json +64 -0
  77. package/vendor/cli/dist/vendor/ora/readme.md +329 -0
  78. package/vendor/cli/package.json +2 -2
  79. package/vendor/connector-sdk/dist/browser-requirement.d.ts +36 -0
  80. package/vendor/connector-sdk/dist/browser-requirement.js +60 -0
  81. package/vendor/connector-sdk/dist/connector-runtime.d.ts +3 -1
  82. package/vendor/connector-sdk/dist/connector-runtime.js +10 -0
  83. package/vendor/connector-sdk/dist/connector-types.d.ts +159 -45
  84. package/vendor/connector-sdk/dist/define-connector.d.ts +4 -2
  85. package/vendor/connector-sdk/dist/define-connector.js +3 -0
  86. package/vendor/connector-sdk/dist/index.d.ts +5 -2
  87. package/vendor/connector-sdk/dist/index.js +1 -0
  88. package/vendor/connector-sdk/dist/reaction-client-types.d.ts +16 -21
  89. package/vendor/connector-sdk/dist/reaction-client-types.typecheck.d.ts +5 -0
  90. package/vendor/connector-sdk/package.json +5 -1
  91. package/vendor/connector-worker/dist/agent-turn/guest-entry.js +31 -27
  92. package/vendor/connector-worker/dist/agent-turn/guest.bundle.js +131 -185
  93. package/vendor/connector-worker/dist/agent-turn/memory.d.ts +3 -2
  94. package/vendor/connector-worker/dist/agent-turn/memory.js +3 -20
  95. package/vendor/connector-worker/dist/agent-turn/types.d.ts +3 -15
  96. package/vendor/connector-worker/dist/agent-turn/workspace.d.ts +2 -2
  97. package/vendor/connector-worker/dist/agent-turn/workspace.js +2 -4
  98. package/vendor/connector-worker/dist/daemon/action-monitor.d.ts +12 -0
  99. package/vendor/connector-worker/dist/daemon/action-monitor.js +25 -0
  100. package/vendor/connector-worker/dist/daemon/agent-turn.js +0 -9
  101. package/vendor/connector-worker/dist/daemon/builtins/index.d.ts +12 -0
  102. package/vendor/connector-worker/dist/daemon/builtins/index.js +61 -1
  103. package/vendor/connector-worker/dist/daemon/builtins/os-shell.d.ts +2 -1
  104. package/vendor/connector-worker/dist/daemon/builtins/os-shell.js +40 -27
  105. package/vendor/connector-worker/dist/daemon/client.d.ts +5 -1
  106. package/vendor/connector-worker/dist/daemon/client.js +3 -0
  107. package/vendor/connector-worker/dist/daemon/device-concurrency.d.ts +8 -0
  108. package/vendor/connector-worker/dist/daemon/device-concurrency.js +13 -0
  109. package/vendor/connector-worker/dist/daemon/executor.d.ts +1 -1
  110. package/vendor/connector-worker/dist/daemon/executor.js +48 -117
  111. package/vendor/connector-worker/dist/daemon/log.d.ts +2 -0
  112. package/vendor/connector-worker/dist/daemon/log.js +23 -2
  113. package/vendor/connector-worker/dist/daemon/mac-device-daemon.d.ts +20 -4
  114. package/vendor/connector-worker/dist/daemon/mac-device-daemon.js +53 -13
  115. package/vendor/connector-worker/dist/daemon/native-bridge/client.d.ts +6 -0
  116. package/vendor/connector-worker/dist/daemon/native-bridge/client.js +15 -0
  117. package/vendor/connector-worker/dist/daemon/native-bridge/executor.js +2 -0
  118. package/vendor/connector-worker/dist/daemon/native-bridge/protocol.d.ts +1 -1
  119. package/vendor/connector-worker/dist/daemon/native-bridge/protocol.js +1 -0
  120. package/vendor/connector-worker/dist/daemon/poll-loop.d.ts +3 -0
  121. package/vendor/connector-worker/dist/daemon/poll-loop.js +5 -1
  122. package/vendor/connector-worker/dist/daemon/start.d.ts +1 -0
  123. package/vendor/connector-worker/dist/daemon/start.js +12 -5
  124. package/vendor/connector-worker/dist/executor/interface.d.ts +34 -2
  125. package/vendor/connector-worker/dist/executor/isolate.js +66 -15
  126. package/vendor/connector-worker/dist/executor/redact.d.ts +1 -0
  127. package/vendor/connector-worker/dist/executor/redact.js +97 -26
  128. package/vendor/connector-worker/dist/executor/runtime.d.ts +7 -0
  129. package/vendor/connector-worker/dist/executor/runtime.js +26 -0
  130. package/vendor/connector-worker/dist/isolate/bridge.js +3 -1
  131. package/vendor/connector-worker/dist/mac-device-daemon.js +10 -3
  132. package/vendor/connector-worker/package.json +2 -2
  133. package/vendor/core/dist/agent-policy.js +1 -1
  134. package/vendor/core/dist/agent-store.d.ts +2 -0
  135. package/vendor/core/dist/agent-tooling.d.ts +1 -1
  136. package/vendor/core/dist/agent-tooling.js +1 -1
  137. package/vendor/core/dist/capabilities.js +2 -0
  138. package/vendor/core/dist/contracts/agent-settings.d.ts +0 -11
  139. package/vendor/core/dist/contracts/agent-settings.js +1 -7
  140. package/vendor/core/dist/contracts/tools/collection-presentation.d.ts +93 -0
  141. package/vendor/core/dist/contracts/tools/collection-presentation.js +88 -0
  142. package/vendor/core/dist/contracts/tools/collection-selection.d.ts +47 -0
  143. package/vendor/core/dist/contracts/tools/collection-selection.js +74 -0
  144. package/vendor/core/dist/contracts/tools/manage-agents.d.ts +10 -4
  145. package/vendor/core/dist/contracts/tools/manage-auth-profiles.d.ts +1 -1
  146. package/vendor/core/dist/contracts/tools/manage-auth-profiles.js +5 -1
  147. package/vendor/core/dist/contracts/tools/manage-automations.d.ts +19 -4
  148. package/vendor/core/dist/contracts/tools/manage-automations.js +25 -8
  149. package/vendor/core/dist/contracts/tools/manage-connections.d.ts +1 -0
  150. package/vendor/core/dist/contracts/tools/manage-connections.js +3 -0
  151. package/vendor/core/dist/contracts/tools/manage-entity-schema.d.ts +11 -0
  152. package/vendor/core/dist/contracts/tools/manage-entity-schema.js +42 -3
  153. package/vendor/core/dist/contracts/tools/manage-entity.d.ts +181 -152
  154. package/vendor/core/dist/contracts/tools/manage-entity.js +118 -162
  155. package/vendor/core/dist/contracts/tools/manage-operations.d.ts +41 -3
  156. package/vendor/core/dist/contracts/tools/manage-operations.js +40 -2
  157. package/vendor/core/dist/contracts/tools/manage-views.d.ts +182 -7
  158. package/vendor/core/dist/contracts/tools/manage-views.js +49 -13
  159. package/vendor/core/dist/contracts/tools/read-knowledge.d.ts +11 -2
  160. package/vendor/core/dist/contracts/tools/read-knowledge.js +23 -3
  161. package/vendor/core/dist/contracts/tools/save-memory.d.ts +3 -6
  162. package/vendor/core/dist/contracts/tools/save-memory.js +2 -6
  163. package/vendor/core/dist/contracts/tools/view-attach.d.ts +2 -1
  164. package/vendor/core/dist/contracts/tools/view-attach.js +7 -2
  165. package/vendor/core/dist/contracts/worker/protocol.d.ts +122 -28
  166. package/vendor/core/dist/contracts/worker/protocol.js +81 -17
  167. package/vendor/core/dist/index.d.ts +3 -4
  168. package/vendor/core/dist/index.js +3 -6
  169. package/vendor/core/dist/json-template.d.ts +6 -10
  170. package/vendor/core/dist/json-template.js +5 -9
  171. package/vendor/core/dist/logger.js +11 -5
  172. package/vendor/core/dist/shell-safety.d.ts +9 -0
  173. package/vendor/core/dist/shell-safety.js +154 -0
  174. package/vendor/core/dist/suggestions.d.ts +1 -1
  175. package/vendor/core/dist/suggestions.js +1 -1
  176. package/vendor/core/dist/tool-trace-summary.d.ts +1 -1
  177. package/vendor/core/dist/tool-trace-summary.js +1 -1
  178. package/vendor/core/dist/types.d.ts +1 -3
  179. package/vendor/core/dist/utils/diagnostic-scrubber.d.ts +7 -0
  180. package/vendor/core/dist/utils/{sentry-scrubber.js → diagnostic-scrubber.js} +25 -53
  181. package/vendor/core/dist/worker/auth.d.ts +44 -6
  182. package/vendor/core/dist/worker/auth.js +44 -11
  183. package/vendor/core/package.json +15 -6
  184. package/vendor/ora/.bun-tag-fde20e9a6df212fa +0 -0
  185. package/vendor/ora/index.d.ts +332 -0
  186. package/vendor/ora/index.js +424 -0
  187. package/vendor/ora/license +9 -0
  188. package/vendor/ora/package.json +53 -0
  189. package/vendor/ora/readme.md +329 -0
  190. package/vendor/cli/dist/commands/telemetry.d.ts +0 -10
  191. package/vendor/cli/dist/commands/telemetry.js +0 -66
  192. package/vendor/core/dist/sentry.d.ts +0 -26
  193. package/vendor/core/dist/sentry.js +0 -133
  194. package/vendor/core/dist/tool-policy.d.ts +0 -74
  195. package/vendor/core/dist/tool-policy.js +0 -305
  196. package/vendor/core/dist/utils/sentry-scrubber.d.ts +0 -29
@@ -29,13 +29,5 @@ export declare function isFailedToolPayload(tool: string | undefined, result: un
29
29
  * `` `in ${path}` ``.
30
30
  */
31
31
  export declare function parseJsonObject(raw: string, label: string): Record<string, unknown>;
32
- /**
33
- * Extra guidance for a failed tool call. A 405 on `POST /api/{org}/{tool}` means
34
- * the request reached a host that does not serve the tool API. The usual cause
35
- * is a context with no `memoryUrl`: the CLI then falls back to the default cloud
36
- * MCP host instead of the context's own `url`, and that host answers 405 with an
37
- * empty body, which on its own gives no hint about the wrong host.
38
- */
39
- export declare function wrongHostHint(status: number): string;
40
32
  export {};
41
33
  //# sourceMappingURL=errors.d.ts.map
@@ -63,16 +63,4 @@ export function parseJsonObject(raw, label) {
63
63
  }
64
64
  return parsed;
65
65
  }
66
- /**
67
- * Extra guidance for a failed tool call. A 405 on `POST /api/{org}/{tool}` means
68
- * the request reached a host that does not serve the tool API. The usual cause
69
- * is a context with no `memoryUrl`: the CLI then falls back to the default cloud
70
- * MCP host instead of the context's own `url`, and that host answers 405 with an
71
- * empty body, which on its own gives no hint about the wrong host.
72
- */
73
- export function wrongHostHint(status) {
74
- if (status !== 405)
75
- return "";
76
- return " A 405 usually means this host does not serve the tool API. If the active context has no memoryUrl, the CLI used the default https://lobu.ai/mcp host; set memoryUrl on the context to the host that serves /api/{org}/{tool}.";
77
- }
78
66
  //# sourceMappingURL=errors.js.map
@@ -1,6 +1,7 @@
1
1
  import { MCP_PROTOCOL_VERSION } from "@lobu/core";
2
+ import { toolApiOriginForMcpUrl } from "../../../internal/context.js";
2
3
  import { extractApiError } from "../../../internal/http.js";
3
- import { ApiError, wrongHostHint } from "./errors.js";
4
+ import { ApiError } from "./errors.js";
4
5
  import { getUsableToken, orgFromMcpUrl, resolveServerUrl, } from "./memory-auth.js";
5
6
  const JSON_MCP_ACCEPT = "application/json";
6
7
  function uniqueStrings(values) {
@@ -98,7 +99,7 @@ async function mcpFetch(mcpUrl, body, sessionId, protocolVersion, contextName) {
98
99
  : " without an access token";
99
100
  const hint = res.status === 401
100
101
  ? `${authContext}. Try --context <name> or run \`lobu context use <name>\`.`
101
- : `${authContext}${wrongHostHint(res.status)}`;
102
+ : authContext;
102
103
  throw new ApiError(`MCP request failed via ${usedUrl}: ${res.status} ${res.statusText}${hint}`, res.status);
103
104
  }
104
105
  const raw = await res.text();
@@ -147,7 +148,7 @@ export async function mcpRpc(mcpUrl, method, params, contextName) {
147
148
  return data.result;
148
149
  }
149
150
  /**
150
- * Shared REST-proxy call against `{origin}/api/{orgSlug}/{path}`, reusing the
151
+ * Shared REST-proxy call against `{tool API origin}/api/{orgSlug}/{path}`, reusing the
151
152
  * same auth resolution and localhost/docker-host fallback as `mcpRpc`. Returns
152
153
  * the raw handler result as parsed JSON (no MCP envelope). Throws `ApiError` on
153
154
  * non-2xx, surfacing the server's `{ error }` message when present.
@@ -168,8 +169,7 @@ async function restCall(mcpUrl, path, opts, contextName) {
168
169
  if (!orgSlug) {
169
170
  throw new ApiError(opts.noOrgMessage(mcpUrl));
170
171
  }
171
- const baseUrl = new URL(mcpUrl).origin;
172
- const endpoint = `${baseUrl}/api/${orgSlug}/${path}`;
172
+ const endpoint = `${toolApiOriginForMcpUrl(mcpUrl)}/api/${orgSlug}/${path}`;
173
173
  const { response: res, usedUrl } = await fetchMcpWithFallback(endpoint, {
174
174
  method: opts.method,
175
175
  headers,
@@ -191,7 +191,7 @@ async function restCall(mcpUrl, path, opts, contextName) {
191
191
  : " without an access token";
192
192
  const hint = res.status === 401
193
193
  ? `${authContext}. Try --context <name> or run \`lobu context use <name>\`.`
194
- : `${authContext}${wrongHostHint(res.status)}`;
194
+ : authContext;
195
195
  throw new ApiError(`${opts.failureLabel} failed via ${usedUrl}: ${message}${hint}`, res.status);
196
196
  }
197
197
  return (raw.length > 0 ? JSON.parse(raw) : {});
@@ -3,8 +3,9 @@ import { basename, dirname, join, resolve } from "node:path";
3
3
  import { parse as parseYaml } from "yaml";
4
4
  import { loadDesiredStateFromConfig } from "../../_lib/apply/desired-state.js";
5
5
  import { isPlatformOwnedRelationshipSlug } from "../../_lib/platform-owned-types.js";
6
- import { ApiError, ValidationError, wrongHostHint } from "./errors.js";
6
+ import { ApiError, ValidationError } from "./errors.js";
7
7
  import { getSessionForOrg, getUsableToken, mcpUrlForOrg, orgFromMcpUrl, resolveOrg, resolveServerUrl, } from "./memory-auth.js";
8
+ import { toolApiOriginForMcpUrl } from "../../../internal/context.js";
8
9
  import { printError, printText } from "../../../internal/output.js";
9
10
  import { validateDataRecord, } from "./schema.js";
10
11
  function readYamlFilesRecursive(dir, prefix = "") {
@@ -75,13 +76,6 @@ function loadDataRecords(dataPath) {
75
76
  recordType: data.type,
76
77
  }));
77
78
  }
78
- function deriveApiBaseUrl(mcpUrl) {
79
- const url = new URL(mcpUrl);
80
- url.pathname = "";
81
- url.search = "";
82
- url.hash = "";
83
- return url.toString().replace(/\/+$/, "");
84
- }
85
79
  export async function callTool(ctx, toolName, args) {
86
80
  const url = `${ctx.apiBaseUrl}/api/${ctx.orgSlug}/${toolName}`;
87
81
  const res = await fetch(url, {
@@ -106,7 +100,7 @@ export async function callTool(ctx, toolName, args) {
106
100
  : `HTTP ${res.status} ${res.statusText}`.trim();
107
101
  throw new ApiError(res.ok
108
102
  ? `Invalid JSON from ${toolName} via ${url}: ${detail}`
109
- : `${toolName} failed via ${url}: ${detail}${wrongHostHint(res.status)}`, res.status);
103
+ : `${toolName} failed via ${url}: ${detail}`, res.status);
110
104
  }
111
105
  if (!res.ok) {
112
106
  const msg = typeof parsed.error === "string" ? parsed.error : `HTTP ${res.status}`;
@@ -368,7 +362,7 @@ export async function seedMemoryWorkspace(opts = {}) {
368
362
  const { layout, state } = await resolveProjectLayout(opts.path);
369
363
  const orgOverride = opts.org || layout.org;
370
364
  const { token, mcpUrl, orgSlug } = await resolveAuth(opts.url, orgOverride, opts.context);
371
- const apiBaseUrl = deriveApiBaseUrl(mcpUrl);
365
+ const apiBaseUrl = toolApiOriginForMcpUrl(mcpUrl);
372
366
  const dryRun = opts.dryRun ?? false;
373
367
  const ctx = { apiBaseUrl, orgSlug, token, dryRun };
374
368
  printText(`Seeding org: ${orgSlug}${dryRun ? " (dry-run)" : ""}`);
@@ -9,7 +9,7 @@
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, Dimension, EventSet, Measure, ReactionClient, AutomationScriptContext, ReactionContext, Segment } from "@lobu/connector-sdk";
12
+ import type { AutomationEventTrigger, AutomationScheduleTrigger, AutomationWorkspaceEventTrigger, ConnectorClass, ConnectorRuntime, CollectionPresentation, Dimension, EventSet, Measure, ReactionClient, AutomationScriptContext, ReactionContext, Segment } from "@lobu/connector-sdk";
13
13
  import { type StringOptions, type TOptional, type TSchema, type TString } from "@sinclair/typebox";
14
14
  import type { SecretRef } from "./secret.js";
15
15
  /** A connector referenced by its key, or by the class produced by `defineConnector`. */
@@ -52,6 +52,8 @@ export interface EntityEventKind {
52
52
  /**
53
53
  * Optional authored render template (render-DSL root node). When omitted,
54
54
  * events of this kind render a default field card built from `metadataSchema`.
55
+ * It renders the event card only; build an interactive dashboard as a
56
+ * React view (`defineView`) attached with `{ event_kind }`.
55
57
  */
56
58
  jsonTemplate?: Record<string, unknown>;
57
59
  /**
@@ -78,8 +80,8 @@ export interface EntityWriteRow<Fields = Record<string, unknown>> {
78
80
  /** `{ ...committed, ...patch }`, i.e. the row as it would commit. */
79
81
  next: Partial<Fields> & Record<string, unknown>;
80
82
  /**
81
- * Deletes and merges use the existing row-shaped contract: they arrive as
82
- * `op: "update"` with `$deleted` or `$merged_into` changing respectively.
83
+ * Deletes use the existing row-shaped contract: they arrive as
84
+ * `op: "update"` with `$deleted` changing.
83
85
  */
84
86
  op: "create" | "update";
85
87
  /**
@@ -146,6 +148,8 @@ export interface EntityType {
146
148
  * placement, and per-field optionality; raw JSON Schema objects stay valid.
147
149
  */
148
150
  properties?: Record<string, unknown>;
151
+ /** Collection presets, table defaults and a read-only facet query. */
152
+ collection?: CollectionPresentation;
149
153
  /**
150
154
  * Event kinds (semantic types) valid for events linked to this entity type,
151
155
  * keyed by semantic_type. Declares each kind's metadata contract + optional
@@ -162,18 +166,18 @@ export interface EntityType {
162
166
  /**
163
167
  * Entity-resolution policy (the `x-lobu-resolution` metadata_schema key the
164
168
  * server reads to decide whether duplicate entities sharing a normalized
165
- * identity auto-merge or queue human review). Declared here so the policy is
169
+ * identity auto-link or queue human review). Declared here so the policy is
166
170
  * git-audited like the rest of the schema; `lobu apply` folds it into the
167
171
  * type's metadata_schema. A rule's `fields` are metadata keys or identity
168
172
  * namespaces (e.g. `email`), `normalizer` is `email` | `phone` | `exact`, and
169
- * `onMatch` is `auto_merge` | `review`. When the key is absent, `person`
170
- * falls back to email/phone review rules; other entity types have no rules.
173
+ * `onMatch` is `auto_link` | `review`. A type without an explicit policy
174
+ * has no matching rules. Association preserves each record and its ID.
171
175
  */
172
176
  resolutionPolicy?: {
173
177
  rules: Array<{
174
178
  fields: string[];
175
179
  normalizer: "email" | "phone" | "exact";
176
- onMatch: "auto_merge" | "review";
180
+ onMatch: "auto_link" | "review";
177
181
  }>;
178
182
  };
179
183
  metadata?: Record<string, unknown>;
@@ -238,6 +242,7 @@ export interface FieldOptions extends StringOptions {
238
242
  }
239
243
  export declare function defineEntityType(config: Omit<EntityType, "kind">): EntityType;
240
244
  export interface RelationshipType {
245
+ purpose?: "identity";
241
246
  readonly kind: "relationshipType";
242
247
  key: string;
243
248
  name?: string;
@@ -475,6 +480,15 @@ export interface AutomationEntityOutput {
475
480
  export interface AutomationEventOutput {
476
481
  /** Semantic type assigned to every standard event draft in this output. */
477
482
  event: string;
483
+ /**
484
+ * Optional one to four metadata fields forming one exact composite identity
485
+ * tuple, scoped to the semantic type (not the Automation, so a migration can
486
+ * seed rows the Automation later adopts). Every draft must contain every
487
+ * field in `metadata` as a non-blank string, safe integer, or boolean.
488
+ * Field order is significant. When set, each run supersedes the current
489
+ * event carrying the same key values. Omit for append-only per-item logs.
490
+ */
491
+ key?: string[];
478
492
  }
479
493
  export type AutomationOutput = AutomationEntityOutput | AutomationEventOutput;
480
494
  /**
@@ -700,13 +714,6 @@ export interface NetworkConfig {
700
714
  /** Domains explicitly blocked (takes precedence over `allowed`). */
701
715
  denied?: string[];
702
716
  }
703
- /** Worker-side tool permissions. */
704
- export interface ToolsConfig {
705
- allowed?: string[];
706
- denied?: string[];
707
- /** Reject tool calls that aren't in `allowed`. */
708
- strict?: boolean;
709
- }
710
717
  export interface Agent {
711
718
  readonly kind: "agent";
712
719
  id: string;
@@ -726,7 +733,6 @@ export interface Agent {
726
733
  skills?: Skill[];
727
734
  providers?: ProviderConfig[];
728
735
  network?: NetworkConfig;
729
- tools?: ToolsConfig;
730
736
  /** Guardrails enabled for this agent, by registered name. */
731
737
  guardrails?: string[];
732
738
  /** Nix packages provisioned into the worker environment. */
@@ -263,8 +263,8 @@ export function context(query) {
263
263
  */
264
264
  export const UNRESOLVED_MODEL_SUFFIX = "__unresolved__";
265
265
  export function defineAgent(config) {
266
- if (config.tools && "preApproved" in config.tools) {
267
- throw new Error(`Agent '${config.id}' declares removed 'tools.preApproved'. Delete it from your config; connector approvals are managed in Settings → Policies.`);
266
+ if ("tools" in config) {
267
+ throw new Error(`Agent '${config.id}' declares removed 'tools' settings. Delete this block; action permissions are managed in Settings → Policies.`);
268
268
  }
269
269
  return { ...config, kind: "agent" };
270
270
  }
@@ -197,16 +197,18 @@ type ConnectorFeedSpec = {
197
197
  metadataSchema?: object;
198
198
  }>;
199
199
  } & (
200
- | { sync: FeedSyncHandler; read?: FeedReadHandler }
201
- | { sync?: FeedSyncHandler; read: FeedReadHandler }
200
+ | { sync: FeedSyncHandler; read?: FeedReadHandler; observe?: never }
201
+ | { sync?: never; read: FeedReadHandler; observe?: (ctx: FeedObserveContext) => Promise<void> }
202
202
  );
203
203
  ```
204
204
 
205
205
  The record key becomes the feed key. A `sync` handler publishes
206
206
  `operations: ['sync']`, a `read` handler publishes `['read']`, and defining both
207
- publishes `['sync', 'read']`. Metadata-only device or MCP connector definitions
208
- declare `operations` explicitly because their executable handlers live outside
209
- the connector process.
207
+ publishes `['sync', 'read']`. An optional `observe(ctx): Promise<void>` hook
208
+ attaches browser listeners for a read-only trigger feed. It returns no data
209
+ and does not add a public operation; notifications use existing subscriptions.
210
+ Metadata-only device or MCP connector definitions declare `operations`
211
+ explicitly because their executable handlers live outside the connector process.
210
212
 
211
213
  `configSchema` describes the persisted feed instance, not one operation. Its
212
214
  top-level `required` fields are therefore enforced for read-only, sync-only,
@@ -0,0 +1,270 @@
1
+ /**
2
+ * Connector actions compiled from a pinned Google Discovery document.
3
+ *
4
+ * One action per Discovery method, executed by one generic `execute`. What
5
+ * Discovery cannot say is supplied per API by a small {@link GoogleApiPolicy}:
6
+ * which scopes the connector may ask for, which methods stay hidden, which
7
+ * POSTs only read, and parameter defaults such as Gmail's `userId: 'me'`.
8
+ */
9
+ import {
10
+ type ActionContext,
11
+ type ActionDefinition,
12
+ type ActionResult,
13
+ type ConnectorFile,
14
+ downloadSizeError,
15
+ fileDownloadOutput,
16
+ type HttpClient,
17
+ } from '@lobu/connector-sdk';
18
+ import {
19
+ buildGoogleRequest,
20
+ type DiscoveryDocument,
21
+ type DiscoveryMethod,
22
+ discoveryMethods,
23
+ methodInputSchema,
24
+ methodParameters,
25
+ type UploadMedia,
26
+ } from './discovery';
27
+ import { classifyGoogleError, type GoogleError } from './errors';
28
+
29
+ export interface GoogleApiPolicy {
30
+ /**
31
+ * Scopes this connector may request, narrowest first. Discovery lists the
32
+ * scopes that can EACH authorize a method (any-of); a method requires the
33
+ * first ladder scope it accepts. A method that accepts none is not exposed.
34
+ */
35
+ scopeLadder: string[];
36
+ /**
37
+ * Rungs every connection is granted at connect time (the auth method's
38
+ * `requiredScopes`); the narrowest rung when omitted. A method one of them
39
+ * authorizes requires it rather than a narrower rung the connection lacks.
40
+ */
41
+ connectScopes?: string[];
42
+ /** Exact method ids never exposed. */
43
+ blockedMethods?: string[];
44
+ /** Method id prefixes never exposed. */
45
+ blockedPrefixes?: string[];
46
+ /** Non-GET methods that only read, e.g. `calendar.freebusy.query`. */
47
+ readMethods?: string[];
48
+ /** Non-DELETE methods that destroy data irreversibly, e.g. `calendar.calendars.clear`. */
49
+ destructiveMethods?: string[];
50
+ /** Filled when the caller omits the parameter, e.g. `{ userId: 'me' }`. */
51
+ defaults?: Record<string, unknown>;
52
+ }
53
+
54
+ /**
55
+ * Push-channel plumbing. A `watch` call registers a callback URL with Google
56
+ * and must be paired with renewal and teardown, which the connector owns
57
+ * through its webhook lifecycle — never something an agent invokes ad hoc.
58
+ */
59
+ const CHANNEL_METHOD = /\.(watch|(?:channels|users)\.stop)$/;
60
+
61
+ type SkipReason = 'blocked' | 'channel' | 'deprecated' | 'scope_outside_ladder';
62
+
63
+ interface ActionTarget {
64
+ method: DiscoveryMethod;
65
+ /** The policy defaults this method takes, applied under the caller's input. */
66
+ defaults: Record<string, unknown>;
67
+ /**
68
+ * The response is file bytes: `alt` asks for them with `alt=media` (Drive
69
+ * `files.get`, whose plain response is JSON metadata); `body` is a method
70
+ * that only ever answers with bytes (Drive `files.export`).
71
+ */
72
+ download?: 'alt' | 'body';
73
+ }
74
+
75
+ export interface CompiledGoogleApi {
76
+ doc: DiscoveryDocument;
77
+ actions: Record<string, ActionDefinition>;
78
+ targets: Map<string, ActionTarget>;
79
+ skipped: Array<{ methodId: string; reason: SkipReason }>;
80
+ }
81
+
82
+ /** `calendar.events.list` → `events_list`. */
83
+ function actionKeyFor(doc: DiscoveryDocument, methodId: string): string {
84
+ return methodId.replace(`${doc.name}.`, '').replace(/\./g, '_');
85
+ }
86
+
87
+ function connectScopes(policy: GoogleApiPolicy): string[] {
88
+ return policy.connectScopes ?? policy.scopeLadder.slice(0, 1);
89
+ }
90
+
91
+ /**
92
+ * The OAuth method's scope fields. Only `optionalScopes` can be requested as an
93
+ * upgrade later, so every rung a compiled action may require is listed there.
94
+ */
95
+ export function oauthScopes(policy: GoogleApiPolicy): { requiredScopes: string[]; optionalScopes: string[] } {
96
+ const required = connectScopes(policy);
97
+ return { requiredScopes: required, optionalScopes: policy.scopeLadder.filter((s) => !required.includes(s)) };
98
+ }
99
+
100
+ function pickScope(accepted: string[] | undefined, policy: GoogleApiPolicy): string | null | undefined {
101
+ if (!accepted || accepted.length === 0) return null; // public method: no scope needed
102
+ const granted = connectScopes(policy).find((scope) => accepted.includes(scope));
103
+ return granted ?? policy.scopeLadder.find((scope) => accepted.includes(scope));
104
+ }
105
+
106
+ export function compileGoogleActions(doc: DiscoveryDocument, policy: GoogleApiPolicy): CompiledGoogleApi {
107
+ const compiled: CompiledGoogleApi = { doc, actions: {}, targets: new Map(), skipped: [] };
108
+ const blocked = (id: string) =>
109
+ policy.blockedMethods?.includes(id) || policy.blockedPrefixes?.some((p) => id.startsWith(p));
110
+
111
+ for (const method of discoveryMethods(doc)) {
112
+ const skip = (reason: SkipReason) => compiled.skipped.push({ methodId: method.id, reason });
113
+ if (blocked(method.id)) {
114
+ skip('blocked');
115
+ continue;
116
+ }
117
+ if (CHANNEL_METHOD.test(method.id)) {
118
+ skip('channel');
119
+ continue;
120
+ }
121
+ if (method.deprecated) {
122
+ skip('deprecated');
123
+ continue;
124
+ }
125
+ const scope = pickScope(method.scopes, policy);
126
+ if (scope === undefined) {
127
+ skip('scope_outside_ladder');
128
+ continue;
129
+ }
130
+
131
+ const isRead = method.httpMethod === 'GET' || policy.readMethods?.includes(method.id) === true;
132
+ const defaults = Object.fromEntries(
133
+ methodParameters(method)
134
+ .filter(([name]) => policy.defaults && name in policy.defaults)
135
+ .map(([name]) => [name, policy.defaults?.[name]])
136
+ );
137
+ const key = actionKeyFor(doc, method.id);
138
+ const base: ActionDefinition = {
139
+ key,
140
+ name: method.id,
141
+ description: method.description,
142
+ kind: isRead ? 'read' : 'write',
143
+ ...(scope ? { requiredScopes: [scope] } : {}),
144
+ annotations: isRead
145
+ ? { readOnlyHint: true, idempotentHint: true }
146
+ : {
147
+ openWorldHint: true,
148
+ ...(method.httpMethod === 'DELETE' || policy.destructiveMethods?.includes(method.id)
149
+ ? { destructiveHint: true }
150
+ : {}),
151
+ ...(method.httpMethod === 'PUT' ? { idempotentHint: true } : {}),
152
+ },
153
+ inputSchema: methodInputSchema(doc, method, defaults),
154
+ };
155
+ compiled.actions[key] = base;
156
+ const bytesOnly = method.supportsMediaDownload && !method.response;
157
+ compiled.targets.set(key, { method, defaults, ...(bytesOnly ? { download: 'body' as const } : {}) });
158
+
159
+ if (method.supportsMediaDownload && method.response) {
160
+ const mediaKey = `${key}_media`;
161
+ compiled.actions[mediaKey] = {
162
+ ...base,
163
+ key: mediaKey,
164
+ name: `${method.id} (media)`,
165
+ description: `Download the content bytes of ${method.id} (alt=media) as an attachment.`,
166
+ kind: 'read',
167
+ annotations: { readOnlyHint: true, idempotentHint: true },
168
+ };
169
+ compiled.targets.set(mediaKey, { method, defaults, download: 'alt' });
170
+ }
171
+ }
172
+ return compiled;
173
+ }
174
+
175
+ const MAX_RATE_LIMIT_ATTEMPTS = 3;
176
+
177
+ export async function executeGoogleAction(
178
+ compiled: CompiledGoogleApi,
179
+ ctx: ActionContext,
180
+ http: HttpClient,
181
+ sleep: (ms: number) => Promise<void> = (ms) => new Promise((r) => setTimeout(r, ms))
182
+ ): Promise<ActionResult> {
183
+ const target = compiled.targets.get(ctx.actionKey);
184
+ if (!target) return { success: false, error: `Unknown action: ${ctx.actionKey}` };
185
+ const action = compiled.actions[ctx.actionKey];
186
+ const { media, ...input } = { ...target.defaults, ...ctx.input };
187
+
188
+ try {
189
+ const request = buildGoogleRequest(compiled.doc, target.method, input, {
190
+ ...(target.download === 'alt' ? { media: 'download' as const } : {}),
191
+ ...(media === undefined ? {} : { upload: uploadMedia(media, target.method) }),
192
+ });
193
+ for (let attempt = 1; ; attempt++) {
194
+ const response = await http.raw(request.url, {
195
+ method: request.method,
196
+ headers: request.headers,
197
+ body: request.body,
198
+ idempotent: action.kind === 'read',
199
+ });
200
+ if (response.ok) {
201
+ if (target.download) return await downloadResult(response, String(input.fileId ?? input.id ?? target.method.id));
202
+ return { success: true, output: jsonOutput(await response.text()) };
203
+ }
204
+
205
+ const error = classifyGoogleError(response.status, await response.text());
206
+ // The SDK throws after retrying 429/5xx. Google also reports per-user rate
207
+ // limits as 403 `rateLimitExceeded`, which only the body identifies.
208
+ if (response.status === 403 && error.code === 'rate_limited' && attempt < MAX_RATE_LIMIT_ATTEMPTS) {
209
+ await sleep(2 ** attempt * 500);
210
+ continue;
211
+ }
212
+ return actionFailure(target.method.id, error);
213
+ }
214
+ } catch (error) {
215
+ // The SDK client throws its HttpStatusError for 429/5xx once its own
216
+ // retries are spent. Read the fields, not `instanceof`: the class reaches
217
+ // this module through more than one copy of the SDK (bundles, test mocks).
218
+ const { status, bodyText } = (error ?? {}) as { status?: unknown; bodyText?: unknown };
219
+ if (typeof status === 'number') {
220
+ return actionFailure(target.method.id, classifyGoogleError(status, typeof bodyText === 'string' ? bodyText : ''));
221
+ }
222
+ return { success: false, error: error instanceof Error ? error.message : String(error) };
223
+ }
224
+ }
225
+
226
+ function actionFailure(methodId: string, error: GoogleError): ActionResult {
227
+ return {
228
+ success: false,
229
+ error: `${methodId} failed (${error.status} ${error.code}): ${error.message}`,
230
+ output: { error_code: error.code, http_status: error.status, retryable: error.retryable },
231
+ };
232
+ }
233
+
234
+ /** The server hands a resolved file input over as base64; Google wants the bytes. */
235
+ function uploadMedia(media: unknown, method: DiscoveryMethod): UploadMedia {
236
+ const file = media as Partial<ConnectorFile> | null;
237
+ if (typeof file?.base64 !== 'string' || typeof file.content_type !== 'string') {
238
+ throw new Error(`${method.id}: \`media\` must be a file input (run_sdk ctx.files or a Lobu file reference).`);
239
+ }
240
+ return { bytes: Buffer.from(file.base64, 'base64'), contentType: file.content_type };
241
+ }
242
+
243
+ /**
244
+ * File bytes as an attachment. Refused before reading when Google declares a
245
+ * size over the connector limit, and again after, for responses that do not:
246
+ * an isolate buffers the whole body, so an unbounded read is an OOM.
247
+ */
248
+ async function downloadResult(response: Response, label: string): Promise<ActionResult> {
249
+ const declared = Number(response.headers.get('content-length'));
250
+ const tooBig = downloadSizeError(Number.isFinite(declared) && declared > 0 ? declared : undefined, label);
251
+ if (tooBig) {
252
+ await response.body?.cancel();
253
+ return { success: false, error: tooBig };
254
+ }
255
+ const bytes = new Uint8Array(await response.arrayBuffer());
256
+ const receivedTooBig = downloadSizeError(bytes.length, label);
257
+ if (receivedTooBig) return { success: false, error: receivedTooBig };
258
+ const mimeType = response.headers.get('content-type')?.split(';')[0]?.trim() || 'application/octet-stream';
259
+ return { success: true, output: fileDownloadOutput({ bytes, filename: label, mimeType }) };
260
+ }
261
+
262
+ /** Google answers JSON; an empty body (DELETE) is `{}`, anything else is kept as text. */
263
+ function jsonOutput(text: string): Record<string, unknown> {
264
+ if (!text) return {};
265
+ try {
266
+ return JSON.parse(text) as Record<string, unknown>;
267
+ } catch {
268
+ return { content: text };
269
+ }
270
+ }