@lobu/runtime-device 24.1.0 → 24.2.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 (159) hide show
  1. package/dist/component.json +1 -1
  2. package/dist/dependencies.bun.lock +26 -28
  3. package/npm-shrinkwrap.json +155 -172
  4. package/package.json +1 -1
  5. package/vendor/cli/dist/bundled-skills/lobu/SKILL.md +14 -5
  6. package/vendor/cli/dist/chrome-extension/accessibility-tree.js +834 -0
  7. package/vendor/cli/dist/chrome-extension/ambient-context.js +53 -0
  8. package/vendor/cli/dist/chrome-extension/auth-refresh.js +167 -0
  9. package/vendor/cli/dist/chrome-extension/automation-run.js +13 -0
  10. package/vendor/cli/dist/chrome-extension/background.js +1155 -0
  11. package/vendor/cli/dist/chrome-extension/bridge.js +140 -0
  12. package/vendor/cli/dist/chrome-extension/browser-origin-policy.js +62 -0
  13. package/vendor/cli/dist/chrome-extension/browser-recovery.js +260 -0
  14. package/vendor/cli/dist/chrome-extension/browser-url-sanitizer.js +284 -0
  15. package/vendor/cli/dist/chrome-extension/completion-response.js +12 -0
  16. package/vendor/cli/dist/chrome-extension/config.js +144 -0
  17. package/vendor/cli/dist/chrome-extension/connector-manifests/chrome.json +1516 -0
  18. package/vendor/cli/dist/chrome-extension/connector-manifests/chrome_bookmarks.json +84 -0
  19. package/vendor/cli/dist/chrome-extension/connector-manifests/chrome_downloads.json +86 -0
  20. package/vendor/cli/dist/chrome-extension/connector-manifests/chrome_history.json +78 -0
  21. package/vendor/cli/dist/chrome-extension/connector-manifests.js +1767 -0
  22. package/vendor/cli/dist/chrome-extension/console-capture.js +627 -0
  23. package/vendor/cli/dist/chrome-extension/control-activity.js +70 -0
  24. package/vendor/cli/dist/chrome-extension/debugger-lease.js +439 -0
  25. package/vendor/cli/dist/chrome-extension/feed-listener.js +488 -0
  26. package/vendor/cli/dist/chrome-extension/feed-transaction.js +48 -0
  27. package/vendor/cli/dist/chrome-extension/feeds.js +632 -0
  28. package/vendor/cli/dist/chrome-extension/focus-tab.js +25 -0
  29. package/vendor/cli/dist/chrome-extension/fonts/dm-mono-latin-500-normal.woff2 +0 -0
  30. package/vendor/cli/dist/chrome-extension/fonts/dm-sans-latin-400-normal.woff2 +0 -0
  31. package/vendor/cli/dist/chrome-extension/fonts/dm-sans-latin-600-normal.woff2 +0 -0
  32. package/vendor/cli/dist/chrome-extension/heartbeat.js +140 -0
  33. package/vendor/cli/dist/chrome-extension/icons/icon-128-rec.png +0 -0
  34. package/vendor/cli/dist/chrome-extension/icons/icon-128.png +0 -0
  35. package/vendor/cli/dist/chrome-extension/icons/icon-16-rec.png +0 -0
  36. package/vendor/cli/dist/chrome-extension/icons/icon-16.png +0 -0
  37. package/vendor/cli/dist/chrome-extension/icons/icon-32-rec.png +0 -0
  38. package/vendor/cli/dist/chrome-extension/icons/icon-32.png +0 -0
  39. package/vendor/cli/dist/chrome-extension/icons/icon-48-rec.png +0 -0
  40. package/vendor/cli/dist/chrome-extension/icons/icon-48.png +0 -0
  41. package/vendor/cli/dist/chrome-extension/lens-page.js +135 -0
  42. package/vendor/cli/dist/chrome-extension/lens-target.js +20 -0
  43. package/vendor/cli/dist/chrome-extension/manifest.json +76 -0
  44. package/vendor/cli/dist/chrome-extension/network-intercept.js +657 -0
  45. package/vendor/cli/dist/chrome-extension/page-activation.js +120 -0
  46. package/vendor/cli/dist/chrome-extension/page-dialogs.js +125 -0
  47. package/vendor/cli/dist/chrome-extension/page-url.js +11 -0
  48. package/vendor/cli/dist/chrome-extension/panel-session.js +184 -0
  49. package/vendor/cli/dist/chrome-extension/poll-auth.js +85 -0
  50. package/vendor/cli/dist/chrome-extension/poll-backoff.js +22 -0
  51. package/vendor/cli/dist/chrome-extension/run-fence.js +117 -0
  52. package/vendor/cli/dist/chrome-extension/setup-status.js +71 -0
  53. package/vendor/cli/dist/chrome-extension/side-panel-action-click.js +65 -0
  54. package/vendor/cli/dist/chrome-extension/sidepanel-context.js +50 -0
  55. package/vendor/cli/dist/chrome-extension/sidepanel.html +680 -0
  56. package/vendor/cli/dist/chrome-extension/sidepanel.js +1643 -0
  57. package/vendor/cli/dist/chrome-extension/tab-labels.js +233 -0
  58. package/vendor/cli/dist/chrome-extension/tools.js +3354 -0
  59. package/vendor/cli/dist/chrome-extension/watch-observer.js +354 -0
  60. package/vendor/cli/dist/chrome-extension/watch-redact.js +96 -0
  61. package/vendor/cli/dist/chrome-extension/watch.js +348 -0
  62. package/vendor/cli/dist/commands/_lib/apply/desired-state.d.ts +6 -4
  63. package/vendor/cli/dist/commands/_lib/apply/desired-state.js +5 -3
  64. package/vendor/cli/dist/commands/_lib/apply/diff.js +4 -3
  65. package/vendor/cli/dist/commands/_lib/apply/render.js +4 -14
  66. package/vendor/cli/dist/commands/_lib/chrome-for-testing.d.ts +13 -0
  67. package/vendor/cli/dist/commands/_lib/chrome-for-testing.js +226 -0
  68. package/vendor/cli/dist/commands/_lib/device-credential.d.ts +34 -0
  69. package/vendor/cli/dist/commands/_lib/device-credential.js +157 -0
  70. package/vendor/cli/dist/commands/_lib/device-wizard.d.ts +17 -0
  71. package/vendor/cli/dist/commands/_lib/device-wizard.js +11 -2
  72. package/vendor/cli/dist/commands/_lib/native-messaging.d.ts +7 -0
  73. package/vendor/cli/dist/commands/_lib/native-messaging.js +40 -0
  74. package/vendor/cli/dist/commands/browser.d.ts +23 -0
  75. package/vendor/cli/dist/commands/browser.js +492 -0
  76. package/vendor/cli/dist/commands/call.d.ts +12 -0
  77. package/vendor/cli/dist/commands/call.js +48 -26
  78. package/vendor/cli/dist/commands/context.d.ts +3 -1
  79. package/vendor/cli/dist/commands/context.js +13 -2
  80. package/vendor/cli/dist/commands/daemon.js +2 -152
  81. package/vendor/cli/dist/commands/memory/_lib/errors.d.ts +4 -1
  82. package/vendor/cli/dist/commands/memory/_lib/errors.js +9 -1
  83. package/vendor/cli/dist/commands/memory/_lib/mcp.d.ts +0 -9
  84. package/vendor/cli/dist/commands/memory/_lib/mcp.js +1 -23
  85. package/vendor/cli/dist/commands/memory/_lib/memory-auth.d.ts +20 -4
  86. package/vendor/cli/dist/commands/memory/_lib/memory-auth.js +21 -17
  87. package/vendor/cli/dist/commands/memory/_lib/seed-cmd.js +6 -17
  88. package/vendor/cli/dist/commands/memory/run.js +4 -25
  89. package/vendor/cli/dist/connectors/google_gmail.ts +70 -41
  90. package/vendor/cli/dist/connectors/google_gmail_references.ts +406 -0
  91. package/vendor/cli/dist/connectors/linkedin-inbox-adapter.js +107 -36
  92. package/vendor/cli/dist/connectors/linkedin-inbox.ts +13 -0
  93. package/vendor/cli/dist/connectors/linkedin.ts +1 -1
  94. package/vendor/cli/dist/connectors/postgres.ts +5 -3
  95. package/vendor/cli/dist/connectors/reddit.ts +171 -5
  96. package/vendor/cli/dist/connectors/whatsapp-web-adapter.js +147 -61
  97. package/vendor/cli/dist/connectors/whatsapp-web-helpers.ts +6 -2
  98. package/vendor/cli/dist/connectors/whatsapp_web.ts +48 -17
  99. package/vendor/cli/dist/connectors/x-dm-adapter.js +252 -35
  100. package/vendor/cli/dist/connectors/x.ts +189 -13
  101. package/vendor/cli/dist/index.js +46 -6
  102. package/vendor/cli/dist/internal/device-state.d.ts +2 -0
  103. package/vendor/cli/dist/internal/device-state.js +4 -0
  104. package/vendor/cli/dist/runtime-components.json +4 -4
  105. package/vendor/cli/dist/templates/AGENTS.md.tmpl +3 -1
  106. package/vendor/cli/dist/templates/TESTING.md.tmpl +8 -8
  107. package/vendor/cli/package.json +1 -1
  108. package/vendor/connector-sdk/dist/browser-requirement.js +1 -1
  109. package/vendor/connector-sdk/dist/connector-types.d.ts +5 -1
  110. package/vendor/connector-sdk/package.json +1 -1
  111. package/vendor/connector-worker/dist/agent-turn/gateway-tools.d.ts +9 -0
  112. package/vendor/connector-worker/dist/agent-turn/gateway-tools.js +23 -2
  113. package/vendor/connector-worker/dist/agent-turn/guest-entry.js +14 -6
  114. package/vendor/connector-worker/dist/agent-turn/guest.bundle.js +62 -25
  115. package/vendor/connector-worker/dist/agent-turn/media-tools.d.ts +1 -0
  116. package/vendor/connector-worker/dist/agent-turn/media-tools.js +5 -2
  117. package/vendor/connector-worker/dist/bin.js +2 -0
  118. package/vendor/connector-worker/dist/daemon/agent-turn.js +52 -17
  119. package/vendor/connector-worker/dist/daemon/automation.js +2 -12
  120. package/vendor/connector-worker/dist/daemon/client.d.ts +8 -2
  121. package/vendor/connector-worker/dist/daemon/client.js +8 -1
  122. package/vendor/connector-worker/dist/daemon/interactive-session.js +29 -6
  123. package/vendor/connector-worker/dist/daemon/poll-loop.js +23 -1
  124. package/vendor/connector-worker/dist/daemon/terminal-delivery.d.ts +5 -10
  125. package/vendor/connector-worker/dist/daemon/terminal-delivery.js +55 -23
  126. package/vendor/connector-worker/dist/daemon/terminal-failure.js +2 -2
  127. package/vendor/connector-worker/dist/executor/isolate.js +3 -0
  128. package/vendor/connector-worker/package.json +1 -1
  129. package/vendor/core/dist/agent-tooling.d.ts +8 -0
  130. package/vendor/core/dist/agent-tooling.js +9 -1
  131. package/vendor/core/dist/capabilities.d.ts +1 -1
  132. package/vendor/core/dist/capabilities.js +5 -0
  133. package/vendor/core/dist/contracts/entity-reference.d.ts +3 -0
  134. package/vendor/core/dist/contracts/entity-reference.js +31 -0
  135. package/vendor/core/dist/contracts/tools/manage-automations.d.ts +3 -0
  136. package/vendor/core/dist/contracts/tools/manage-automations.js +3 -0
  137. package/vendor/core/dist/contracts/tools/manage-connections.js +1 -1
  138. package/vendor/core/dist/contracts/tools/manage-entity-schema.js +1 -1
  139. package/vendor/core/dist/contracts/tools/manage-entity.d.ts +113 -34
  140. package/vendor/core/dist/contracts/tools/manage-entity.js +41 -14
  141. package/vendor/core/dist/contracts/tools/manage-operations.d.ts +13 -4
  142. package/vendor/core/dist/contracts/tools/manage-operations.js +19 -7
  143. package/vendor/core/dist/contracts/tools/read-knowledge.d.ts +6 -1
  144. package/vendor/core/dist/contracts/tools/read-knowledge.js +20 -1
  145. package/vendor/core/dist/contracts/tools/view-attach.d.ts +1 -1
  146. package/vendor/core/dist/contracts/tools/view-runtime.d.ts +2 -0
  147. package/vendor/core/dist/contracts/tools/view-runtime.js +3 -1
  148. package/vendor/core/dist/contracts/worker/device-automation.d.ts +4 -9
  149. package/vendor/core/dist/contracts/worker/device-automation.js +10 -15
  150. package/vendor/core/dist/contracts/worker/protocol.d.ts +20 -0
  151. package/vendor/core/dist/contracts/worker/protocol.js +20 -0
  152. package/vendor/core/dist/reserved.d.ts +6 -3
  153. package/vendor/core/dist/reserved.js +6 -3
  154. package/vendor/core/dist/worker/auth.d.ts +3 -2
  155. package/vendor/core/package.json +6 -1
  156. package/vendor/postgres/cf/src/query.js +3 -1
  157. package/vendor/postgres/cjs/src/query.js +3 -1
  158. package/vendor/postgres/src/query.js +3 -1
  159. /package/vendor/postgres/{.bun-tag-2f292c6554a8475e → .bun-tag-22d644c2873790db} +0 -0
@@ -1,21 +1,9 @@
1
1
  import { resolveDaemonLaunchContext, resolveDaemonWorkerId, startDaemonCommand, } from "@lobu/connector-worker/daemon";
2
2
  import { hostname } from "node:os";
3
3
  import { addContext, apiUrlToGatewayOrigin, findContextByOrigin, getActiveOrg, loadContextConfig, resolveContext, } from "../internal/context.js";
4
- import { getContextToken } from "../internal/credentials.js";
5
- import { loadDeviceState, saveDeviceState, updateDeviceState, } from "../internal/device-state.js";
6
- import { extractApiError, fetchWithRetry, parseJsonResponse, } from "../internal/http.js";
4
+ import { loadDeviceState } from "../internal/device-state.js";
5
+ import { canPrompt, DeviceMintError, mintDeviceCredentialWithReauth, persistDeviceCredential, requireInstallationLogin, } from "./_lib/device-credential.js";
7
6
  import { deviceWizard } from "./_lib/device-wizard.js";
8
- import { loginCommand } from "./login.js";
9
- class DeviceMintError extends Error {
10
- status;
11
- code;
12
- constructor(message, status, code) {
13
- super(message);
14
- this.status = status;
15
- this.code = code;
16
- this.name = "DeviceMintError";
17
- }
18
- }
19
7
  /**
20
8
  * How much of a child PAT's life must remain before a start or idle running
21
9
  * daemon re-mints it. A third of the server's 90-day expiry keeps rotations
@@ -27,7 +15,6 @@ const CHILD_TOKEN_RETRY_MS = 60 * 1000;
27
15
  const SETUP_MESSAGE = "Could not determine a gateway to poll. Configure one of:\n" +
28
16
  " - run `lobu login` to configure a context, or\n" +
29
17
  " - pass --api-url <origin>.";
30
- const LOGIN_SETUP_MESSAGE = (contextName) => `This Lobu installation is not logged in. Run \`lobu login --force --context ${contextName}\` in an interactive terminal, then retry.`;
31
18
  /**
32
19
  * Run a headless device worker against one Lobu installation.
33
20
  *
@@ -239,77 +226,6 @@ async function ensureInstallationContext(gatewayOrigin) {
239
226
  console.log(`\n Saved Lobu installation context "${name}" (${gatewayOrigin}).`);
240
227
  return name;
241
228
  }
242
- async function requireInstallationLogin(contextName) {
243
- const existing = await getContextToken(contextName);
244
- if (existing)
245
- return existing;
246
- return refreshInstallationLogin(contextName);
247
- }
248
- async function refreshInstallationLogin(contextName) {
249
- if (!canPrompt())
250
- throw new Error(LOGIN_SETUP_MESSAGE(contextName));
251
- // The stored credential is absent, expired, revoked, or predates the daemon's
252
- // device_worker:run scope. Without --force `lobu login` can short-circuit on
253
- // that same credential with "Already logged in" and authorize nothing.
254
- await loginCommand({ context: contextName, force: true });
255
- const authenticated = await getContextToken(contextName);
256
- if (!authenticated)
257
- throw new Error(LOGIN_SETUP_MESSAGE(contextName));
258
- return authenticated;
259
- }
260
- async function mintDeviceCredentialWithReauth({ contextName, initialBearerIsChild, initialChildExpiresAt, interactiveReauth, options, }) {
261
- try {
262
- return await mintDeviceCredential(options);
263
- }
264
- catch (error) {
265
- if (!isDeviceMintAuthError(error))
266
- throw error;
267
- // Do not let OAuth silently undo revocation of a still-live child.
268
- if (initialBearerIsChild) {
269
- if (!interactiveReauth)
270
- throw error;
271
- if (typeof initialChildExpiresAt !== "number" ||
272
- initialChildExpiresAt > Date.now()) {
273
- throw new DeviceMintError("The stored device credential was rejected before its local expiry; refusing to replace a possibly revoked device automatically. Re-pair this device explicitly.", error.status, error.code);
274
- }
275
- const installationBearer = await requireInstallationLogin(contextName);
276
- try {
277
- return await mintDeviceCredential({
278
- ...options,
279
- bearer: installationBearer,
280
- });
281
- }
282
- catch (loginError) {
283
- if (!isDeviceMintAuthError(loginError))
284
- throw loginError;
285
- }
286
- }
287
- // A stored login can be valid for ordinary MCP work but lack the newer
288
- // device_worker:run scope. Interactive starts repair it through the same
289
- // device-code flow; non-interactive starts receive the exact login command.
290
- if (!interactiveReauth)
291
- throw error;
292
- return mintDeviceCredential({
293
- ...options,
294
- bearer: await refreshInstallationLogin(contextName),
295
- });
296
- }
297
- }
298
- /**
299
- * True only for a refusal that re-authenticating can actually clear: an expired
300
- * or revoked bearer (401), or a bearer the endpoint refuses to mint from
301
- * (`insufficient_scope` — a missing `device_worker:run`, an MCP resource-bound
302
- * token, or a child reaching past its own worker id). Every other 403 is a
303
- * standing account condition (`personal_org_missing`); retrying it would
304
- * force-revoke a working login through `lobu login --force` and still fail.
305
- */
306
- function isDeviceMintAuthError(error) {
307
- if (!(error instanceof DeviceMintError))
308
- return false;
309
- if (error.status === 401)
310
- return true;
311
- return error.status === 403 && error.code === "insufficient_scope";
312
- }
313
229
  function hasUsableCachedWorkerToken(state) {
314
230
  return Boolean(state.workerApiToken?.startsWith("owl_pat_") &&
315
231
  typeof state.expiresAt === "number" &&
@@ -389,66 +305,6 @@ function createWorkerCredentialMaintenance(options) {
389
305
  function warnCredentialMaintenance(message, error) {
390
306
  process.stderr.write(`[daemon] ${message}; retrying: ${error instanceof Error ? error.message : String(error)}\n`);
391
307
  }
392
- async function mintDeviceCredential(options) {
393
- const url = `${options.gatewayOrigin}/api/me/devices/mint-child-token`;
394
- const res = await fetchWithRetry(url, {
395
- method: "POST",
396
- headers: {
397
- Accept: "application/json",
398
- Authorization: `Bearer ${options.bearer}`,
399
- "Content-Type": "application/json",
400
- "X-Lobu-Client": "cli",
401
- },
402
- body: JSON.stringify({
403
- platform: options.platform,
404
- worker_id: options.workerId,
405
- label: options.label,
406
- }),
407
- });
408
- const parsed = (await parseJsonResponse(res, url, (message) => {
409
- throw new DeviceMintError(message, res.status);
410
- }));
411
- if (!res.ok) {
412
- const { message, code } = extractApiError(parsed, res.status, res.statusText);
413
- throw new DeviceMintError(`Could not authorize this device: ${message}`, res.status, code);
414
- }
415
- const workerId = typeof parsed?.worker_id === "string" ? parsed.worker_id : "";
416
- const workerApiToken = typeof parsed?.access_token === "string" ? parsed.access_token : "";
417
- const expiresAt = typeof parsed?.expires_at === "string"
418
- ? Date.parse(parsed.expires_at)
419
- : Number.NaN;
420
- if (!workerId ||
421
- !workerApiToken.startsWith("owl_pat_") ||
422
- !Number.isFinite(expiresAt)) {
423
- throw new DeviceMintError("The gateway returned an invalid device credential.", res.status);
424
- }
425
- return {
426
- workerId,
427
- workerApiToken,
428
- expiresAt,
429
- };
430
- }
431
- async function persistDeviceCredential(contextName, statePlatform, credential) {
432
- const state = {
433
- workerId: credential.workerId,
434
- workerApiToken: credential.workerApiToken,
435
- expiresAt: credential.expiresAt,
436
- };
437
- const existing = await loadDeviceState(contextName, statePlatform);
438
- if (existing) {
439
- await updateDeviceState(contextName, statePlatform, state);
440
- return;
441
- }
442
- try {
443
- await saveDeviceState(contextName, statePlatform, state);
444
- }
445
- catch (error) {
446
- const winner = await loadDeviceState(contextName, statePlatform);
447
- if (winner?.workerId !== state.workerId)
448
- throw error;
449
- await updateDeviceState(contextName, statePlatform, state);
450
- }
451
- }
452
308
  /**
453
309
  * Resolve a normal host identity for a device that has no cached one yet: the
454
310
  * TTY first-run wizard, else the deterministic `<platform>:<hostname>`. Callers
@@ -472,10 +328,4 @@ async function resolveHostWorkerId(platform, contextName, gatewayOrigin, authori
472
328
  });
473
329
  return result.workerId;
474
330
  }
475
- function canPrompt() {
476
- const ci = process.env.CI?.trim().toLowerCase();
477
- return (process.stdin.isTTY === true &&
478
- process.stdout.isTTY === true &&
479
- (!ci || ci === "0" || ci === "false"));
480
- }
481
331
  //# sourceMappingURL=daemon.js.map
@@ -14,7 +14,10 @@ export declare class ApiError extends CliError {
14
14
  * True when an already-printed tool result payload reports failure, so the
15
15
  * command can exit non-zero without changing its stdout contract (the JSON
16
16
  * still parses — `gh`/`kubectl -o json` semantics, not curl's). Three shapes:
17
- * - MCP `tools/call` failures, marked `isError` at the protocol boundary;
17
+ * - MCP `tools/call` failures, marked `isError` at the protocol boundary, or
18
+ * reported inside the result's `structuredContent` (a failed `run_sdk`
19
+ * script is a successful tool call whose structured result has
20
+ * `success: false`);
18
21
  * - `run_sdk` script failures, reported as data (`success` is a required
19
22
  * field of the script result) — the tool ran fine, the script did not;
20
23
  * - REST-proxy soft failures, a top-level `error` string. This mirrors the
@@ -26,7 +26,10 @@ export class ApiError extends CliError {
26
26
  * True when an already-printed tool result payload reports failure, so the
27
27
  * command can exit non-zero without changing its stdout contract (the JSON
28
28
  * still parses — `gh`/`kubectl -o json` semantics, not curl's). Three shapes:
29
- * - MCP `tools/call` failures, marked `isError` at the protocol boundary;
29
+ * - MCP `tools/call` failures, marked `isError` at the protocol boundary, or
30
+ * reported inside the result's `structuredContent` (a failed `run_sdk`
31
+ * script is a successful tool call whose structured result has
32
+ * `success: false`);
30
33
  * - `run_sdk` script failures, reported as data (`success` is a required
31
34
  * field of the script result) — the tool ran fine, the script did not;
32
35
  * - REST-proxy soft failures, a top-level `error` string. This mirrors the
@@ -39,6 +42,11 @@ export function isFailedToolPayload(tool, result) {
39
42
  const payload = result;
40
43
  if (payload.isError === true)
41
44
  return true;
45
+ if (typeof payload.structuredContent === "object" &&
46
+ payload.structuredContent !== null &&
47
+ isFailedToolPayload(tool, payload.structuredContent)) {
48
+ return true;
49
+ }
42
50
  if (tool === "run_sdk" && payload.success === false)
43
51
  return true;
44
52
  return typeof payload.error === "string" && payload.error.length > 0;
@@ -1,12 +1,3 @@
1
- /**
2
- * Resolve the MCP endpoint URL.
3
- * Priority: explicit config > LOBU_MEMORY_URL env > saved memory server > default cloud server.
4
- */
5
- export declare function resolveMcpEndpoint(config?: {
6
- mcpUrl?: unknown;
7
- url?: unknown;
8
- apiUrl?: unknown;
9
- }): Promise<string | null>;
10
1
  export declare function mcpRpc(mcpUrl: string, method: string, params?: Record<string, unknown>, contextName?: string): Promise<unknown>;
11
2
  /**
12
3
  * Call a Lobu memory tool over the REST proxy at `POST /api/{orgSlug}/{toolName}`.
@@ -2,7 +2,7 @@ import { MCP_PROTOCOL_VERSION } from "@lobu/core";
2
2
  import { toolApiOriginForMcpUrl } from "../../../internal/context.js";
3
3
  import { extractApiError } from "../../../internal/http.js";
4
4
  import { ApiError } from "./errors.js";
5
- import { getUsableToken, orgFromMcpUrl, resolveServerUrl, } from "./memory-auth.js";
5
+ import { getUsableToken, orgFromMcpUrl } from "./memory-auth.js";
6
6
  const JSON_MCP_ACCEPT = "application/json";
7
7
  function uniqueStrings(values) {
8
8
  const seen = new Set();
@@ -53,28 +53,6 @@ async function fetchMcpWithFallback(mcpUrl, init) {
53
53
  }
54
54
  throw new Error(formatNetworkErrorMessage(lastError, candidates));
55
55
  }
56
- /**
57
- * Resolve the MCP endpoint URL.
58
- * Priority: explicit config > LOBU_MEMORY_URL env > saved memory server > default cloud server.
59
- */
60
- export async function resolveMcpEndpoint(config) {
61
- // Explicit config should win over ambient auth/session state so callers can
62
- // deterministically target a specific server.
63
- if (config) {
64
- if (typeof config.mcpUrl === "string" && config.mcpUrl.trim().length > 0) {
65
- return config.mcpUrl;
66
- }
67
- if (typeof config.url === "string" && config.url.trim().length > 0) {
68
- const url = config.url;
69
- return url.includes("/mcp") ? url : `${url.replace(/\/+$/, "")}/mcp`;
70
- }
71
- if (typeof config.apiUrl === "string" && config.apiUrl.trim().length > 0) {
72
- return `${config.apiUrl.replace(/\/+$/, "")}/mcp`;
73
- }
74
- }
75
- // Fall back to auth store / env when no explicit target was provided.
76
- return resolveServerUrl();
77
- }
78
56
  async function mcpFetch(mcpUrl, body, sessionId, protocolVersion, contextName) {
79
57
  const headers = {
80
58
  "Content-Type": "application/json",
@@ -17,20 +17,36 @@ export declare function getActiveSession(context?: string): Promise<{
17
17
  session: MemorySession | null;
18
18
  key: string | null;
19
19
  }>;
20
- export declare function getSessionForOrg(orgSlug: string, context?: string, urlFlag?: string): Promise<{
21
- session: MemorySession;
22
- key: string;
23
- } | null>;
24
20
  /**
25
21
  * Resolve which server URL to use.
26
22
  * Priority: explicit url arg > LOBU_MEMORY_URL > context preference > cloud default.
27
23
  */
28
24
  export declare function resolveServerUrl(urlFlag?: string, context?: string): Promise<string>;
25
+ /**
26
+ * True when the process was handed a self-contained runtime credential: an
27
+ * explicit bearer plus the MCP URL it is valid for (a device Automation run's
28
+ * worker access). That URL already names the org, and a worker token is only
29
+ * accepted on MCP routes, so callers must dispatch to it as-is.
30
+ */
31
+ export declare function hasRuntimeMcpAccess(): boolean;
29
32
  /**
30
33
  * Resolve which org to use.
31
34
  * Priority: explicit org arg > LOBU_MEMORY_ORG > session > context preference.
32
35
  */
33
36
  export declare function resolveOrg(orgFlag?: string, session?: MemorySession | null, context?: string): Promise<string | undefined>;
37
+ /**
38
+ * The MCP URL a tool call goes to: the server URL scoped to the resolved org,
39
+ * or the server URL as given when no org resolves (a runtime credential's URL
40
+ * already names its org; see `resolveOrg`).
41
+ */
42
+ export declare function resolveToolMcpUrl(options: {
43
+ url?: string;
44
+ org?: string;
45
+ context?: string;
46
+ }): Promise<{
47
+ url: string;
48
+ org: string | undefined;
49
+ }>;
34
50
  /**
35
51
  * Resolve a usable bearer token from top-level `lobu login` credentials.
36
52
  */
@@ -44,9 +44,7 @@ export async function setActiveMcpUrl(mcpUrl, context) {
44
44
  await setContextMemoryUrl(mcpUrl, context);
45
45
  }
46
46
  export async function getActiveSession(context) {
47
- const base = await resolveServerUrl(undefined, context);
48
- const org = await resolveOrg(undefined, undefined, context);
49
- const key = org ? mcpUrlForOrg(base, org) : base;
47
+ const { url: key, org } = await resolveToolMcpUrl({ context });
50
48
  return {
51
49
  session: {
52
50
  mcpUrl: key,
@@ -57,19 +55,6 @@ export async function getActiveSession(context) {
57
55
  key,
58
56
  };
59
57
  }
60
- export async function getSessionForOrg(orgSlug, context, urlFlag) {
61
- const base = await resolveServerUrl(urlFlag, context);
62
- const key = mcpUrlForOrg(base, orgSlug);
63
- return {
64
- session: {
65
- mcpUrl: key,
66
- org: orgSlug,
67
- tokenType: "Bearer",
68
- updatedAt: new Date().toISOString(),
69
- },
70
- key,
71
- };
72
- }
73
58
  /**
74
59
  * Resolve which server URL to use.
75
60
  * Priority: explicit url arg > LOBU_MEMORY_URL > context preference > cloud default.
@@ -79,6 +64,15 @@ export async function resolveServerUrl(urlFlag, context) {
79
64
  return normalizeMcpUrl(urlFlag);
80
65
  return normalizeMcpUrl(await getMemoryUrl(context));
81
66
  }
67
+ /**
68
+ * True when the process was handed a self-contained runtime credential: an
69
+ * explicit bearer plus the MCP URL it is valid for (a device Automation run's
70
+ * worker access). That URL already names the org, and a worker token is only
71
+ * accepted on MCP routes, so callers must dispatch to it as-is.
72
+ */
73
+ export function hasRuntimeMcpAccess() {
74
+ return Boolean(process.env.LOBU_API_TOKEN?.trim() && process.env.LOBU_MEMORY_URL?.trim());
75
+ }
82
76
  /**
83
77
  * Resolve which org to use.
84
78
  * Priority: explicit org arg > LOBU_MEMORY_ORG > session > context preference.
@@ -89,12 +83,22 @@ export async function resolveOrg(orgFlag, session, context) {
89
83
  if (process.env.LOBU_MEMORY_ORG)
90
84
  return process.env.LOBU_MEMORY_ORG;
91
85
  // Explicit runtime bearer + MCP URL is self-contained; do not rewrite a mounted endpoint with ambient org state.
92
- if (process.env.LOBU_API_TOKEN?.trim() && process.env.LOBU_MEMORY_URL?.trim())
86
+ if (hasRuntimeMcpAccess())
93
87
  return undefined;
94
88
  if (session?.org)
95
89
  return session.org;
96
90
  return getActiveOrg(context);
97
91
  }
92
+ /**
93
+ * The MCP URL a tool call goes to: the server URL scoped to the resolved org,
94
+ * or the server URL as given when no org resolves (a runtime credential's URL
95
+ * already names its org; see `resolveOrg`).
96
+ */
97
+ export async function resolveToolMcpUrl(options) {
98
+ const org = await resolveOrg(options.org, undefined, options.context);
99
+ const base = await resolveServerUrl(options.url, options.context);
100
+ return { url: org ? mcpUrlForOrg(base, org) : base, org };
101
+ }
98
102
  /**
99
103
  * Resolve a usable bearer token from top-level `lobu login` credentials.
100
104
  */
@@ -4,7 +4,7 @@ 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
6
  import { ApiError, ValidationError } from "./errors.js";
7
- import { getSessionForOrg, getUsableToken, mcpUrlForOrg, orgFromMcpUrl, resolveOrg, resolveServerUrl, } from "./memory-auth.js";
7
+ import { getUsableToken, mcpUrlForOrg, orgFromMcpUrl, resolveOrg, resolveServerUrl, } from "./memory-auth.js";
8
8
  import { toolApiOriginForMcpUrl } from "../../../internal/context.js";
9
9
  import { printError, printText } from "../../../internal/output.js";
10
10
  import { validateDataRecord, } from "./schema.js";
@@ -326,22 +326,11 @@ async function seedDataRelationship(relationship, entityMap, ctx) {
326
326
  async function resolveAuth(urlFlag, orgFlag, context) {
327
327
  const org = await resolveOrg(orgFlag, undefined, context);
328
328
  if (org) {
329
- const orgSession = await getSessionForOrg(org, context, urlFlag);
330
- if (orgSession) {
331
- const result = await getUsableToken(orgSession.key, context);
332
- if (result) {
333
- return { token: result.token, mcpUrl: orgSession.key, orgSlug: org };
334
- }
335
- }
336
- const serverUrl = await resolveServerUrl(urlFlag, context);
337
- if (serverUrl) {
338
- const orgUrl = mcpUrlForOrg(serverUrl, org);
339
- const result = await getUsableToken(orgUrl, context);
340
- if (result) {
341
- return { token: result.token, mcpUrl: orgUrl, orgSlug: org };
342
- }
343
- }
344
- throw new ValidationError("Not logged in. Run: lobu login");
329
+ const mcpUrl = mcpUrlForOrg(await resolveServerUrl(urlFlag, context), org);
330
+ const result = await getUsableToken(mcpUrl, context);
331
+ if (!result)
332
+ throw new ValidationError("Not logged in. Run: lobu login");
333
+ return { token: result.token, mcpUrl, orgSlug: org };
345
334
  }
346
335
  const serverUrl = await resolveServerUrl(urlFlag, context);
347
336
  const result = await getUsableToken(serverUrl || undefined, context);
@@ -1,30 +1,9 @@
1
- import { ValidationError, isFailedToolPayload } from "./_lib/errors.js";
2
- import { mcpRpc, resolveMcpEndpoint } from "./_lib/mcp.js";
3
- import { getSessionForOrg, mcpUrlForOrg, resolveOrg, resolveServerUrl, } from "./_lib/memory-auth.js";
1
+ import { isFailedToolPayload } from "./_lib/errors.js";
2
+ import { mcpRpc } from "./_lib/mcp.js";
3
+ import { resolveToolMcpUrl } from "./_lib/memory-auth.js";
4
4
  import { printText } from "../../internal/output.js";
5
5
  export async function memoryRunCommand(tool, params, options = {}) {
6
- const org = await resolveOrg(options.org, undefined, options.context);
7
- let mcpUrl;
8
- if (org) {
9
- const orgSession = await getSessionForOrg(org, options.context, options.url);
10
- if (orgSession) {
11
- mcpUrl = orgSession.key;
12
- }
13
- else {
14
- const serverUrl = await resolveServerUrl(options.url, options.context);
15
- const base = serverUrl || (await resolveMcpEndpoint());
16
- if (!base)
17
- throw new ValidationError("Server URL required. Pass --url or set LOBU_MEMORY_URL.");
18
- mcpUrl = mcpUrlForOrg(base, org);
19
- }
20
- }
21
- else {
22
- const serverUrl = await resolveServerUrl(options.url, options.context);
23
- const resolved = serverUrl || (await resolveMcpEndpoint());
24
- if (!resolved)
25
- throw new ValidationError("Server URL required. Pass --url or set LOBU_MEMORY_URL.");
26
- mcpUrl = resolved;
27
- }
6
+ const { url: mcpUrl } = await resolveToolMcpUrl(options);
28
7
  if (!tool) {
29
8
  const result = await mcpRpc(mcpUrl, "tools/list", undefined, options.context);
30
9
  const resultObj = result;
@@ -28,6 +28,7 @@ import type { DiscoveryDocument } from './_google/discovery';
28
28
  import gmailDiscovery from './_google/discovery/gmail_v1.json';
29
29
  import { GOOGLE_API_POLICIES } from './_google/policies';
30
30
  import TurndownService from 'turndown';
31
+ import { syncGmailReferences, type GmailReferenceState } from './google_gmail_references';
31
32
 
32
33
  /**
33
34
  * Supported Gmail API methods as actions, compiled from the pinned Discovery
@@ -108,6 +109,7 @@ interface GmailThreadGetResponse {
108
109
  // ---------------------------------------------------------------------------
109
110
 
110
111
  interface GmailCheckpoint {
112
+ references?: GmailReferenceState;
111
113
  /** Bumped when the shape below changes; a mismatch re-runs the lookback. */
112
114
  schema_version?: number;
113
115
  /** Serialized search + person filter the two fields below were produced under. */
@@ -173,7 +175,7 @@ export default class GmailConnector extends ConnectorRuntime<GmailCheckpoint, Gm
173
175
  name: 'Gmail',
174
176
  description:
175
177
  'Syncs Gmail threads, live-reads matching messages, and supports sending, drafts, and replies.',
176
- version: '1.0.7',
178
+ version: '1.1.0',
177
179
  faviconDomain: 'mail.google.com',
178
180
  authSchema: {
179
181
  methods: [
@@ -193,6 +195,59 @@ export default class GmailConnector extends ConnectorRuntime<GmailCheckpoint, Gm
193
195
  ],
194
196
  },
195
197
  feeds: {
198
+ message_references: {
199
+ key: 'message_references',
200
+ name: 'Message references',
201
+ userManaged: true,
202
+ requiredScopes: ['https://www.googleapis.com/auth/gmail.readonly'],
203
+ description:
204
+ 'ID-only references to available messages and subsequent additions, including spam, trash, imports and drafts. No subjects, senders, snippets, bodies or provider occurrence dates. Use created_at for arrival previews; source_occurred_at is unknown. History expiry is a visible gap; recovery lists currently available messages. Sync-only, explicitly triggered or scheduled. Not a current-state mirror, edit/deletion archive or observer subscription.',
205
+ sync: (ctx) =>
206
+ syncGmailReferences(ctx, (token) => this.createClient(token)),
207
+ configSchema: {
208
+ type: 'object',
209
+ properties: {
210
+ max_results: {
211
+ type: 'integer',
212
+ minimum: 1,
213
+ maximum: 500,
214
+ default: 500,
215
+ description:
216
+ 'Maximum message references per pass, without individual message downloads. Unfinished inventory/history resumes immediately from its committed checkpoint, even without a schedule.',
217
+ },
218
+ },
219
+ },
220
+ eventKinds: {
221
+ message_reference: {
222
+ description:
223
+ 'An available Gmail message reference, without email content',
224
+ metadataSchema: {
225
+ type: 'object',
226
+ properties: {
227
+ source_id: { type: 'string' },
228
+ thread_id: { type: 'string' },
229
+ source_occurred_at: { type: 'null' },
230
+ timestamp_basis: { type: 'string', enum: ['unknown'] },
231
+ },
232
+ },
233
+ },
234
+ source_gap: {
235
+ description:
236
+ 'A retained Gmail history discontinuity; available inventory cannot restore deleted or expired history',
237
+ metadataSchema: {
238
+ type: 'object',
239
+ properties: {
240
+ reason: { type: 'string' },
241
+ from_history_id: { type: 'string' },
242
+ to_history_id: { type: 'string' },
243
+ recovery: { type: 'string' },
244
+ source_occurred_at: { type: 'null' },
245
+ timestamp_basis: { type: 'string', enum: ['unknown'] },
246
+ },
247
+ },
248
+ },
249
+ },
250
+ },
196
251
  threads: {
197
252
  key: 'threads',
198
253
  name: 'Threads',
@@ -270,15 +325,12 @@ export default class GmailConnector extends ConnectorRuntime<GmailCheckpoint, Gm
270
325
  attributions: [
271
326
  {
272
327
  role: 'authored_by',
273
- // Promote on interaction, never on receipt alone. Every from-address
274
- // is a sender — overwhelmingly brands, newsletters, and no-reply
275
- // system addresses, all of which carry a from_name — so receipt
276
- // alone must not mint a contact. The gate is `person_relevant`,
277
- // computed by the connector: it is `replied` by default; the
278
- // human_senders_only mode additionally admits human-looking
279
- // unreplied counterparties and rejects role/list/broadcast noise.
280
- // Only person-relevant senders materialize a `person`; everything
281
- // else still links to an existing contact on identity match.
328
+ // Default mode requires interaction with a non-role counterparty;
329
+ // human_senders_only also admits unreplied heuristic matches.
330
+ // Both reject list/bulk threads for person creation.
331
+ // Missing verdicts from older runs fail closed for creation;
332
+ // a replied-only fallback would override explicit rejections.
333
+ // Rejected or unclassified senders still link to existing contacts.
282
334
  autoCreate: true,
283
335
  target: {
284
336
  entityType: 'person',
@@ -297,32 +349,6 @@ export default class GmailConnector extends ConnectorRuntime<GmailCheckpoint, Gm
297
349
  },
298
350
  },
299
351
  },
300
- {
301
- role: 'authored_by',
302
- // Legacy gate for v1.0.3 run payloads, which carry `replied` but
303
- // not `person_relevant`. Keep it until old in-flight runs/caches
304
- // drain: the server loads the current definition by connector key,
305
- // so a rolling deploy would otherwise silently skip person creation
306
- // for a pre-refresh event. Both rules share the email identity, so
307
- // the pipeline's first-writer-wins dedupes them for new payloads.
308
- autoCreate: true,
309
- target: {
310
- entityType: 'person',
311
- createWhen: { path: 'metadata.replied', equals: true },
312
- titlePath: 'metadata.from_name',
313
- identities: [{ namespace: 'email', eventPath: 'metadata.from_email' }],
314
- },
315
- traits: {
316
- from_name: {
317
- eventPath: 'metadata.from_name',
318
- mergeStrategy: 'prefer_non_empty',
319
- },
320
- last_email_at: {
321
- eventPath: 'occurred_at',
322
- mergeStrategy: 'overwrite',
323
- },
324
- },
325
- },
326
352
  ],
327
353
  },
328
354
  },
@@ -1156,7 +1182,10 @@ export default class GmailConnector extends ConnectorRuntime<GmailCheckpoint, Gm
1156
1182
  !this.isListThread(messages) &&
1157
1183
  (replied ||
1158
1184
  this.externalRecipientCount(selectedSentMessage, isSelf) <= BROADCAST_RECIPIENT_CAP)
1159
- : replied;
1185
+ : replied &&
1186
+ !!selected &&
1187
+ isPersonRelevantSender(selected.email, selected.name, true) &&
1188
+ !this.isListThread(messages);
1160
1189
 
1161
1190
  return {
1162
1191
  replied,
@@ -1497,10 +1526,10 @@ const CONSUMER_MAIL_DOMAINS = new Set([
1497
1526
  const HUMAN_NAME_RE = /^[A-ZÀ-Ý][a-zà-ÿ]+(?:[ '\u2019-][A-ZÀ-Ý][a-zà-ÿ]+)+$/;
1498
1527
 
1499
1528
  /**
1500
- * Whether a thread's counterparty is eligible for person minting under
1501
- * `human_senders_only`. Role/system mailboxes never qualify. A replied
1502
- * non-role address qualifies directly; an unreplied address additionally needs
1503
- * a consumer-mail domain or a human-looking display name.
1529
+ * Address eligibility for person minting in both feed modes. Role/system
1530
+ * mailboxes never qualify. A replied non-role address qualifies directly;
1531
+ * human_senders_only also admits unreplied addresses with a consumer-mail
1532
+ * domain or a human-looking display name. Thread-level gates apply separately.
1504
1533
  */
1505
1534
  export function isPersonRelevantSender(
1506
1535
  email: string | null | undefined,