@agent-native/core 0.77.8 → 0.77.11
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.
- package/corpus/README.md +1 -1
- package/corpus/core/CHANGELOG.md +35 -0
- package/corpus/core/package.json +3 -3
- package/corpus/core/src/a2a/task-store.ts +25 -3
- package/corpus/core/src/agent/harness/store.ts +89 -55
- package/corpus/core/src/agent/observational-memory/store.ts +40 -14
- package/corpus/core/src/agent/run-store.ts +116 -59
- package/corpus/core/src/application-state/store.ts +36 -2
- package/corpus/core/src/audit/store.ts +37 -6
- package/corpus/core/src/browser-sessions/store.ts +31 -12
- package/corpus/core/src/chat-threads/store.ts +67 -3
- package/corpus/core/src/checkpoints/store.ts +14 -3
- package/corpus/core/src/cli/create.ts +9 -0
- package/corpus/core/src/collab/awareness.ts +12 -9
- package/corpus/core/src/collab/client.ts +4 -2
- package/corpus/core/src/collab/storage.ts +20 -2
- package/corpus/core/src/db/ddl-guard.ts +112 -0
- package/corpus/core/src/extensions/store.ts +76 -3
- package/corpus/core/src/integrations/a2a-continuations-store.ts +69 -26
- package/corpus/core/src/integrations/config-store.ts +19 -18
- package/corpus/core/src/integrations/pending-tasks-store.ts +40 -16
- package/corpus/core/src/integrations/remote-commands-store.ts +37 -23
- package/corpus/core/src/integrations/remote-devices-store.ts +64 -20
- package/corpus/core/src/integrations/remote-push-store.ts +75 -35
- package/corpus/core/src/integrations/remote-run-events-store.ts +38 -12
- package/corpus/core/src/integrations/thread-mapping-store.ts +11 -2
- package/corpus/core/src/mcp/connect-store.ts +53 -16
- package/corpus/core/src/mcp/oauth-store.ts +32 -7
- package/corpus/core/src/notifications/store.ts +20 -4
- package/corpus/core/src/oauth-tokens/store.ts +45 -2
- package/corpus/core/src/observability/store.ts +154 -47
- package/corpus/core/src/progress/store.ts +36 -21
- package/corpus/core/src/provider-api/corpus-jobs-store.ts +25 -5
- package/corpus/core/src/provider-api/custom-registry.ts +15 -4
- package/corpus/core/src/provider-api/quota-governor.ts +15 -3
- package/corpus/core/src/provider-api/staged-datasets-store.ts +22 -5
- package/corpus/core/src/resources/store.ts +66 -31
- package/corpus/core/src/secrets/storage.ts +18 -22
- package/corpus/core/src/server/agent-teams-run-queue.ts +22 -10
- package/corpus/core/src/server/auth.ts +22 -4
- package/corpus/core/src/server/better-auth-instance.ts +49 -15
- package/corpus/core/src/server/embed-session.ts +19 -4
- package/corpus/core/src/server/identity-sso-store.ts +40 -11
- package/corpus/core/src/server/recap-image-store.ts +28 -9
- package/corpus/core/src/settings/store.ts +14 -19
- package/corpus/core/src/usage/store.ts +51 -16
- package/corpus/core/src/workspace-connections/store.ts +200 -22
- package/corpus/templates/calendar/changelog/2026-06-25-booking-link-previews-now-show-the-content-directly-on-the-g.md +6 -0
- package/corpus/templates/calendar/server/lib/booking-og-image.ts +0 -2
- package/corpus/templates/clips/chrome-extension/package.json +1 -1
- package/corpus/templates/content/actions/list-trashed-content-databases.ts +36 -2
- package/corpus/templates/content/actions/move-document.ts +79 -33
- package/corpus/templates/content/actions/restore-content-database.ts +40 -3
- package/corpus/templates/content/app/components/editor/BubbleToolbar.tsx +84 -2
- package/corpus/templates/content/app/components/editor/CommentsSidebar.tsx +177 -49
- package/corpus/templates/content/app/components/editor/DocumentEditor.tsx +393 -219
- package/corpus/templates/content/app/components/editor/DocumentToolbar.tsx +632 -467
- package/corpus/templates/content/app/components/editor/SlashCommandMenu.tsx +114 -14
- package/corpus/templates/content/app/components/editor/VisualEditor.tsx +56 -15
- package/corpus/templates/content/app/components/editor/extensions/NotionExtensions.tsx +6 -5
- package/corpus/templates/content/app/components/sidebar/DocumentTreeItem.tsx +12 -4
- package/corpus/templates/content/app/global.css +9 -0
- package/corpus/templates/content/app/hooks/use-create-page.ts +36 -7
- package/corpus/templates/content/app/i18n-data.ts +140 -10
- package/corpus/templates/content/changelog/2026-06-25-comment-cards-now-track-their-highlighted-text-while-scrolli.md +6 -0
- package/corpus/templates/content/changelog/2026-06-25-comments-now-scroll-with-the-document-and-stay-below-the-pag.md +6 -0
- package/corpus/templates/content/changelog/2026-06-25-creating-a-database-from-the-slash-menu-no-longer-leaves-sta.md +6 -0
- package/corpus/templates/content/changelog/2026-06-25-sidebar-hover-controls-no-longer-leave-a-lingering-fade-when.md +6 -0
- package/corpus/templates/content/changelog/2026-06-25-sidebar-page-actions-are-now-easier-to-see-when-hovering-ina.md +6 -0
- package/corpus/templates/content/changelog/2026-06-25-text-selections-in-the-editor-no-longer-show-white-gaps-when.md +6 -0
- package/corpus/templates/content/changelog/2026-06-25-the-editor-toolbar-now-has-a-one-click-page-link-copy-button.md +6 -0
- package/corpus/templates/content/changelog/2026-06-25-the-editor-toolbar-now-shows-page-breadcrumbs-and-the-latest.md +6 -0
- package/corpus/templates/content/changelog/2026-06-25-the-page-command-now-leaves-a-notion-style-page-reference-an.md +6 -0
- package/corpus/templates/content/shared/nfm.ts +16 -0
- package/corpus/templates/forms/changelog/2026-06-25-form-previews-now-show-the-content-directly-on-the-grid-back.md +6 -0
- package/corpus/templates/forms/server/lib/form-og-image.ts +0 -2
- package/corpus/templates/plan/app/global.css +6 -11
- package/corpus/templates/plan/app/pages/PlansPage.tsx +12 -10
- package/corpus/templates/plan/changelog/2026-06-25-plan-access-request-pages-stay-visible-during-background-ref.md +6 -0
- package/corpus/templates/plan/changelog/2026-06-25-plan-documents-keep-their-full-reading-width-below-1200px-an.md +6 -0
- package/dist/a2a/task-store.d.ts.map +1 -1
- package/dist/a2a/task-store.js +19 -3
- package/dist/a2a/task-store.js.map +1 -1
- package/dist/agent/harness/store.d.ts.map +1 -1
- package/dist/agent/harness/store.js +63 -34
- package/dist/agent/harness/store.js.map +1 -1
- package/dist/agent/observational-memory/store.d.ts.map +1 -1
- package/dist/agent/observational-memory/store.js +30 -8
- package/dist/agent/observational-memory/store.js.map +1 -1
- package/dist/agent/run-store.d.ts.map +1 -1
- package/dist/agent/run-store.js +103 -46
- package/dist/agent/run-store.js.map +1 -1
- package/dist/application-state/store.d.ts.map +1 -1
- package/dist/application-state/store.js +28 -2
- package/dist/application-state/store.js.map +1 -1
- package/dist/audit/store.d.ts.map +1 -1
- package/dist/audit/store.js +18 -3
- package/dist/audit/store.js.map +1 -1
- package/dist/browser-sessions/store.d.ts.map +1 -1
- package/dist/browser-sessions/store.js +22 -7
- package/dist/browser-sessions/store.js.map +1 -1
- package/dist/chat-threads/store.d.ts.map +1 -1
- package/dist/chat-threads/store.js +51 -3
- package/dist/chat-threads/store.js.map +1 -1
- package/dist/checkpoints/store.d.ts.map +1 -1
- package/dist/checkpoints/store.js +12 -3
- package/dist/checkpoints/store.js.map +1 -1
- package/dist/cli/create.d.ts.map +1 -1
- package/dist/cli/create.js +9 -0
- package/dist/cli/create.js.map +1 -1
- package/dist/collab/awareness.d.ts +1 -1
- package/dist/collab/awareness.d.ts.map +1 -1
- package/dist/collab/awareness.js +12 -8
- package/dist/collab/awareness.js.map +1 -1
- package/dist/collab/client.d.ts.map +1 -1
- package/dist/collab/client.js +4 -3
- package/dist/collab/client.js.map +1 -1
- package/dist/collab/routes.d.ts +1 -1
- package/dist/collab/storage.d.ts.map +1 -1
- package/dist/collab/storage.js +14 -2
- package/dist/collab/storage.js.map +1 -1
- package/dist/db/ddl-guard.d.ts +63 -0
- package/dist/db/ddl-guard.d.ts.map +1 -1
- package/dist/db/ddl-guard.js +85 -0
- package/dist/db/ddl-guard.js.map +1 -1
- package/dist/extensions/store.d.ts.map +1 -1
- package/dist/extensions/store.js +32 -3
- package/dist/extensions/store.js.map +1 -1
- package/dist/integrations/a2a-continuations-store.d.ts.map +1 -1
- package/dist/integrations/a2a-continuations-store.js +44 -24
- package/dist/integrations/a2a-continuations-store.js.map +1 -1
- package/dist/integrations/config-store.d.ts.map +1 -1
- package/dist/integrations/config-store.js +17 -11
- package/dist/integrations/config-store.js.map +1 -1
- package/dist/integrations/pending-tasks-store.d.ts.map +1 -1
- package/dist/integrations/pending-tasks-store.js +24 -16
- package/dist/integrations/pending-tasks-store.js.map +1 -1
- package/dist/integrations/remote-commands-store.d.ts.map +1 -1
- package/dist/integrations/remote-commands-store.js +29 -21
- package/dist/integrations/remote-commands-store.js.map +1 -1
- package/dist/integrations/remote-devices-store.d.ts.map +1 -1
- package/dist/integrations/remote-devices-store.js +33 -18
- package/dist/integrations/remote-devices-store.js.map +1 -1
- package/dist/integrations/remote-push-store.d.ts.map +1 -1
- package/dist/integrations/remote-push-store.js +53 -31
- package/dist/integrations/remote-push-store.js.map +1 -1
- package/dist/integrations/remote-run-events-store.d.ts.map +1 -1
- package/dist/integrations/remote-run-events-store.js +26 -10
- package/dist/integrations/remote-run-events-store.js.map +1 -1
- package/dist/integrations/thread-mapping-store.d.ts.map +1 -1
- package/dist/integrations/thread-mapping-store.js +10 -2
- package/dist/integrations/thread-mapping-store.js.map +1 -1
- package/dist/mcp/connect-store.d.ts.map +1 -1
- package/dist/mcp/connect-store.js +34 -16
- package/dist/mcp/connect-store.js.map +1 -1
- package/dist/mcp/oauth-store.d.ts.map +1 -1
- package/dist/mcp/oauth-store.js +22 -7
- package/dist/mcp/oauth-store.js.map +1 -1
- package/dist/notifications/store.d.ts.map +1 -1
- package/dist/notifications/store.js +15 -3
- package/dist/notifications/store.js.map +1 -1
- package/dist/oauth-tokens/store.d.ts.map +1 -1
- package/dist/oauth-tokens/store.js +33 -2
- package/dist/oauth-tokens/store.js.map +1 -1
- package/dist/observability/store.d.ts.map +1 -1
- package/dist/observability/store.js +72 -29
- package/dist/observability/store.js.map +1 -1
- package/dist/progress/store.d.ts.map +1 -1
- package/dist/progress/store.js +31 -16
- package/dist/progress/store.js.map +1 -1
- package/dist/provider-api/corpus-jobs-store.d.ts.map +1 -1
- package/dist/provider-api/corpus-jobs-store.js +16 -5
- package/dist/provider-api/corpus-jobs-store.js.map +1 -1
- package/dist/provider-api/custom-registry.d.ts.map +1 -1
- package/dist/provider-api/custom-registry.js +14 -4
- package/dist/provider-api/custom-registry.js.map +1 -1
- package/dist/provider-api/quota-governor.d.ts.map +1 -1
- package/dist/provider-api/quota-governor.js +12 -3
- package/dist/provider-api/quota-governor.js.map +1 -1
- package/dist/provider-api/staged-datasets-store.d.ts.map +1 -1
- package/dist/provider-api/staged-datasets-store.js +16 -5
- package/dist/provider-api/staged-datasets-store.js.map +1 -1
- package/dist/resources/store.d.ts.map +1 -1
- package/dist/resources/store.js +56 -25
- package/dist/resources/store.js.map +1 -1
- package/dist/secrets/storage.d.ts.map +1 -1
- package/dist/secrets/storage.js +10 -14
- package/dist/secrets/storage.js.map +1 -1
- package/dist/server/agent-teams-run-queue.d.ts.map +1 -1
- package/dist/server/agent-teams-run-queue.js +15 -4
- package/dist/server/agent-teams-run-queue.js.map +1 -1
- package/dist/server/auth.d.ts.map +1 -1
- package/dist/server/auth.js +16 -2
- package/dist/server/auth.js.map +1 -1
- package/dist/server/better-auth-instance.d.ts.map +1 -1
- package/dist/server/better-auth-instance.js +55 -21
- package/dist/server/better-auth-instance.js.map +1 -1
- package/dist/server/embed-session.d.ts.map +1 -1
- package/dist/server/embed-session.js +15 -4
- package/dist/server/embed-session.js.map +1 -1
- package/dist/server/identity-sso-store.d.ts.map +1 -1
- package/dist/server/identity-sso-store.js +30 -11
- package/dist/server/identity-sso-store.js.map +1 -1
- package/dist/server/recap-image-store.d.ts.map +1 -1
- package/dist/server/recap-image-store.js +21 -7
- package/dist/server/recap-image-store.js.map +1 -1
- package/dist/settings/store.d.ts.map +1 -1
- package/dist/settings/store.js +11 -13
- package/dist/settings/store.js.map +1 -1
- package/dist/usage/store.d.ts.map +1 -1
- package/dist/usage/store.js +36 -11
- package/dist/usage/store.js.map +1 -1
- package/dist/workspace-connections/store.d.ts.map +1 -1
- package/dist/workspace-connections/store.js +57 -7
- package/dist/workspace-connections/store.js.map +1 -1
- package/package.json +3 -3
|
@@ -1,19 +1,25 @@
|
|
|
1
|
-
import { getDbExec, isPostgres, intType
|
|
1
|
+
import { getDbExec, isPostgres, intType } from "../db/client.js";
|
|
2
|
+
import { ensureTableExists } from "../db/ddl-guard.js";
|
|
2
3
|
let _initPromise;
|
|
3
4
|
async function ensureTable() {
|
|
4
5
|
if (!_initPromise) {
|
|
5
6
|
_initPromise = (async () => {
|
|
6
7
|
const client = getDbExec();
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
8
|
+
const createSql = `CREATE TABLE IF NOT EXISTS integration_configs (
|
|
9
|
+
platform TEXT NOT NULL,
|
|
10
|
+
config_key TEXT NOT NULL,
|
|
11
|
+
config_data TEXT NOT NULL,
|
|
12
|
+
owner TEXT,
|
|
13
|
+
updated_at ${intType()} NOT NULL,
|
|
14
|
+
PRIMARY KEY (platform, config_key)
|
|
15
|
+
)`;
|
|
16
|
+
if (isPostgres()) {
|
|
17
|
+
// PG guard: probe via information_schema, only issue DDL if missing, bounded lock_timeout
|
|
18
|
+
await ensureTableExists("integration_configs", createSql);
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
// SQLite (local dev): keep existing behavior
|
|
22
|
+
await client.execute(createSql);
|
|
17
23
|
})().catch((err) => {
|
|
18
24
|
// Don't cache the rejection — let the next caller retry a fresh init.
|
|
19
25
|
_initPromise = undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config-store.js","sourceRoot":"","sources":["../../src/integrations/config-store.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"config-store.js","sourceRoot":"","sources":["../../src/integrations/config-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAEvD,IAAI,YAAuC,CAAC;AAE5C,KAAK,UAAU,WAAW;IACxB,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,YAAY,GAAG,CAAC,KAAK,I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QAAQ,EAAE,GAAG,CAAC,QAAkB;QAChC,SAAS,EAAE,GAAG,CAAC,UAAoB;QACnC,UAAU,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,WAAqB,CAAC;QACjD,KAAK,EAAG,GAAG,CAAC,KAAgB,IAAI,IAAI;QACpC,SAAS,EAAE,GAAG,CAAC,UAAoB;KACpC,CAAC,CAAC,CAAC;AACN,CAAC","sourcesContent":["import { getDbExec, isPostgres, intType } from \"../db/client.js\";\nimport { ensureTableExists } from \"../db/ddl-guard.js\";\n\nlet _initPromise: Promise<void> | undefined;\n\nasync function ensureTable(): Promise<void> {\n if (!_initPromise) {\n _initPromise = (async () => {\n const client = getDbExec();\n const createSql = `CREATE TABLE IF NOT EXISTS integration_configs (\n platform TEXT NOT NULL,\n config_key TEXT NOT NULL,\n config_data TEXT NOT NULL,\n owner TEXT,\n updated_at ${intType()} NOT NULL,\n PRIMARY KEY (platform, config_key)\n)`;\n\n if (isPostgres()) {\n // PG guard: probe via information_schema, only issue DDL if missing, bounded lock_timeout\n await ensureTableExists(\"integration_configs\", createSql);\n return;\n }\n\n // SQLite (local dev): keep existing behavior\n await client.execute(createSql);\n })().catch((err) => {\n // Don't cache the rejection — let the next caller retry a fresh init.\n _initPromise = undefined;\n throw err;\n });\n }\n return _initPromise;\n}\n\nexport interface IntegrationConfig {\n platform: string;\n configKey: string;\n configData: Record<string, unknown>;\n owner: string | null;\n updatedAt: number;\n}\n\n/**\n * Get the config for a platform integration.\n */\nexport async function getIntegrationConfig(\n platform: string,\n configKey = \"default\",\n): Promise<IntegrationConfig | null> {\n await ensureTable();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT platform, config_key, config_data, owner, updated_at FROM integration_configs WHERE platform = ? AND config_key = ?`,\n args: [platform, configKey],\n });\n if (rows.length === 0) return null;\n const row = rows[0];\n return {\n platform: row.platform as string,\n configKey: row.config_key as string,\n configData: JSON.parse(row.config_data as string),\n owner: (row.owner as string) ?? null,\n updatedAt: row.updated_at as number,\n };\n}\n\n/**\n * Save or update a platform integration config.\n */\nexport async function saveIntegrationConfig(\n platform: string,\n configData: Record<string, unknown>,\n configKey = \"default\",\n owner?: string,\n): Promise<void> {\n await ensureTable();\n const client = getDbExec();\n await client.execute({\n sql: isPostgres()\n ? `INSERT INTO integration_configs (platform, config_key, config_data, owner, updated_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT (platform, config_key) DO UPDATE SET config_data=EXCLUDED.config_data, owner=EXCLUDED.owner, updated_at=EXCLUDED.updated_at`\n : `INSERT OR REPLACE INTO integration_configs (platform, config_key, config_data, owner, updated_at) VALUES (?, ?, ?, ?, ?)`,\n args: [\n platform,\n configKey,\n JSON.stringify(configData),\n owner ?? null,\n Date.now(),\n ],\n });\n}\n\n/**\n * Delete a platform integration config.\n */\nexport async function deleteIntegrationConfig(\n platform: string,\n configKey = \"default\",\n): Promise<void> {\n await ensureTable();\n const client = getDbExec();\n await client.execute({\n sql: `DELETE FROM integration_configs WHERE platform = ? AND config_key = ?`,\n args: [platform, configKey],\n });\n}\n\n/**\n * List all configs for a platform.\n */\nexport async function listIntegrationConfigs(\n platform?: string,\n): Promise<IntegrationConfig[]> {\n await ensureTable();\n const client = getDbExec();\n const { rows } = platform\n ? await client.execute({\n sql: `SELECT platform, config_key, config_data, owner, updated_at FROM integration_configs WHERE platform = ?`,\n args: [platform],\n })\n : await client.execute(\n `SELECT platform, config_key, config_data, owner, updated_at FROM integration_configs`,\n );\n return rows.map((row) => ({\n platform: row.platform as string,\n configKey: row.config_key as string,\n configData: JSON.parse(row.config_data as string),\n owner: (row.owner as string) ?? null,\n updatedAt: row.updated_at as number,\n }));\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pending-tasks-store.d.ts","sourceRoot":"","sources":["../../src/integrations/pending-tasks-store.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"pending-tasks-store.d.ts","sourceRoot":"","sources":["../../src/integrations/pending-tasks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wBAAsB,iBAAiB,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAUjE;AAED,wDAAwD;AACxD,wBAAsB,cAAc,CAClC,EAAE,EAAE,MAAM,EACV,YAAY,EAAE,MAAM,GACnB,OAAO,CAAC,IAAI,CAAC,CAUf"}
|
|
@@ -11,27 +11,35 @@
|
|
|
11
11
|
* invocation gets its own fresh function timeout budget.
|
|
12
12
|
*/
|
|
13
13
|
import { getDbExec, isPostgres, intType } from "../db/client.js";
|
|
14
|
+
import { ensureTableExists, ensureColumnExists, ensureIndexExists, } from "../db/ddl-guard.js";
|
|
14
15
|
let _initPromise;
|
|
15
16
|
async function ensureTable() {
|
|
16
17
|
if (!_initPromise) {
|
|
17
18
|
_initPromise = (async () => {
|
|
18
19
|
const client = getDbExec();
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
20
|
+
const createSql = `CREATE TABLE IF NOT EXISTS integration_pending_tasks (
|
|
21
|
+
id TEXT PRIMARY KEY,
|
|
22
|
+
platform TEXT NOT NULL,
|
|
23
|
+
external_thread_id TEXT NOT NULL,
|
|
24
|
+
payload TEXT NOT NULL,
|
|
25
|
+
owner_email TEXT NOT NULL,
|
|
26
|
+
org_id TEXT,
|
|
27
|
+
status TEXT NOT NULL,
|
|
28
|
+
attempts ${intType()} NOT NULL DEFAULT 0,
|
|
29
|
+
error_message TEXT,
|
|
30
|
+
created_at ${intType()} NOT NULL,
|
|
31
|
+
updated_at ${intType()} NOT NULL,
|
|
32
|
+
completed_at ${intType()}
|
|
33
|
+
)`;
|
|
34
|
+
if (isPostgres()) {
|
|
35
|
+
// PG guard: probe via information_schema, only issue DDL if missing, bounded lock_timeout
|
|
36
|
+
await ensureTableExists("integration_pending_tasks", createSql);
|
|
37
|
+
await ensureColumnExists("integration_pending_tasks", "external_event_key", `ALTER TABLE integration_pending_tasks ADD COLUMN IF NOT EXISTS external_event_key TEXT`);
|
|
38
|
+
await ensureIndexExists("idx_pending_tasks_status_created", `CREATE INDEX IF NOT EXISTS idx_pending_tasks_status_created ON integration_pending_tasks(status, created_at)`);
|
|
39
|
+
await ensureIndexExists("idx_pending_tasks_event_key", `CREATE UNIQUE INDEX IF NOT EXISTS idx_pending_tasks_event_key ON integration_pending_tasks(platform, external_event_key)`);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
await client.execute(createSql);
|
|
35
43
|
await client.execute(`CREATE INDEX IF NOT EXISTS idx_pending_tasks_status_created ON integration_pending_tasks(status, created_at)`);
|
|
36
44
|
// Additive migration: add a stable per-event dedup key so duplicate
|
|
37
45
|
// webhook deliveries from the same platform get rejected at the SQL
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pending-tasks-store.js","sourceRoot":"","sources":["../../src/integrations/pending-tasks-store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAEjE,IAAI,YAAuC,CAAC;AAE5C,KAAK,UAAU,WAAW;IACxB,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,YAAY,GAAG,CAAC,KAAK,IAAI,EAAE;YACzB,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;YAC3B,MAAM,MAAM,CAAC,OAAO,CAAC;;;;;;;;;qBASN,OAAO,EAAE;;uBAEP,OAAO,EAAE;uBACT,OAAO,EAAE;yBACP,OAAO,EAAE;;OAE3B,CAAC,CAAC;YACH,MAAM,MAAM,CAAC,OAAO,CAClB,8GAA8G,CAC/G,CAAC;YACF,oEAAoE;YACpE,oEAAoE;YACpE,+DAA+D;YAC/D,kEAAkE;YAClE,iEAAiE;YACjE,+BAA+B;YAC/B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GACX,MAAuD,CAAC,YAAY;QACpE,MAAuD,CAAC,QAAQ,CAAC;IACpE,IAAI,QAAQ,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IAChC,MAAM,OAAO,GAAG,MAAM,cAAc,CAAC,EAAE,CAAC,CAAC;IACzC,IAAI,CAAC,OAAO,IAAI,OAAO,CAAC,MAAM,KAAK,YAAY;QAAE,OAAO,IAAI,CAAC;IAC7D,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,gCAAgC;AAChC,MAAM,CAAC,KAAK,UAAU,iBAAiB,CAAC,EAAU;IAChD,MAAM,WAAW,EAAE,CAAC;IACpB,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAC3B,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IACvB,MAAM,MAAM,CAAC,OAAO,CAAC;QACnB,GAAG,EAAE;;uBAEc;QACnB,IAAI,EAAE,CAAC,WAAW,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,CAAC;KAClC,CAAC,CAAC;AACL,CAAC;AAED,wDAAwD;AACxD,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,EAAU,EACV,YAAoB;IAEpB,MAAM,WAAW,EAAE,CAAC;IACpB,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAC3B,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IACvB,MAAM,MAAM,CAAC,OAAO,CAAC;QACnB,GAAG,EAAE;;uBAEc;QACnB,IAAI,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE,YAAY,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;KACvD,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * SQL-backed pending task queue for integration webhooks.\n *\n * Why this exists: serverless platforms (Netlify Lambda, Vercel, Cloudflare\n * Workers) freeze the function execution as soon as the HTTP response is\n * returned. Fire-and-forget background `Promise`s get killed mid-flight,\n * meaning agent loops triggered from a Slack/Telegram webhook never finish.\n *\n * Solution: persist the inbound message to SQL inside the webhook handler,\n * then dispatch a fresh HTTP POST to a separate processor endpoint. Each\n * invocation gets its own fresh function timeout budget.\n */\nimport { getDbExec, isPostgres, intType } from \"../db/client.js\";\n\nlet _initPromise: Promise<void> | undefined;\n\nasync function ensureTable(): Promise<void> {\n if (!_initPromise) {\n _initPromise = (async () => {\n const client = getDbExec();\n await client.execute(`\n CREATE TABLE IF NOT EXISTS integration_pending_tasks (\n id TEXT PRIMARY KEY,\n platform TEXT NOT NULL,\n external_thread_id TEXT NOT NULL,\n payload TEXT NOT NULL,\n owner_email TEXT NOT NULL,\n org_id TEXT,\n status TEXT NOT NULL,\n attempts ${intType()} NOT NULL DEFAULT 0,\n error_message TEXT,\n created_at ${intType()} NOT NULL,\n updated_at ${intType()} NOT NULL,\n completed_at ${intType()}\n )\n `);\n await client.execute(\n `CREATE INDEX IF NOT EXISTS idx_pending_tasks_status_created ON integration_pending_tasks(status, created_at)`,\n );\n // Additive migration: add a stable per-event dedup key so duplicate\n // webhook deliveries from the same platform get rejected at the SQL\n // layer instead of via an in-memory Map (which doesn't survive\n // serverless cold starts — H3 in the webhook security audit). The\n // unique index ensures a duplicate INSERT raises an error we can\n // catch as \"already-enqueued\".\n await ensureExternalEventKey(client);\n await client.execute(\n `CREATE UNIQUE INDEX IF NOT EXISTS idx_pending_tasks_event_key ON integration_pending_tasks(platform, external_event_key)`,\n );\n })().catch((err) => {\n // Retry init on the next call after a failed startup.\n _initPromise = undefined;\n throw err;\n });\n }\n return _initPromise;\n}\n\nasync function ensureExternalEventKey(\n client: ReturnType<typeof getDbExec>,\n): Promise<void> {\n if (isPostgres()) {\n await client.execute(\n `ALTER TABLE integration_pending_tasks ADD COLUMN IF NOT EXISTS external_event_key TEXT`,\n );\n return;\n }\n // SQLite doesn't support `ADD COLUMN IF NOT EXISTS` until 3.35; swallow\n // the duplicate-column error so reruns are idempotent.\n try {\n await client.execute(\n `ALTER TABLE integration_pending_tasks ADD COLUMN external_event_key TEXT`,\n );\n } catch (err: any) {\n if (\n !String(err?.message ?? err)\n .toLowerCase()\n .includes(\"duplicate\")\n ) {\n throw err;\n }\n }\n}\n\n/** Status values for an integration pending task. */\nexport type PendingTaskStatus =\n | \"pending\"\n | \"processing\"\n | \"completed\"\n | \"failed\";\n\nexport interface PendingTask {\n id: string;\n platform: string;\n externalThreadId: string;\n payload: string;\n ownerEmail: string;\n orgId: string | null;\n status: PendingTaskStatus;\n attempts: number;\n errorMessage: string | null;\n createdAt: number;\n updatedAt: number;\n completedAt: number | null;\n}\n\nfunction rowToTask(row: Record<string, unknown>): PendingTask {\n return {\n id: row.id as string,\n platform: row.platform as string,\n externalThreadId: row.external_thread_id as string,\n payload: row.payload as string,\n ownerEmail: row.owner_email as string,\n orgId: (row.org_id as string | null) ?? null,\n status: row.status as PendingTaskStatus,\n attempts: Number(row.attempts ?? 0),\n errorMessage: (row.error_message as string | null) ?? null,\n createdAt: Number(row.created_at ?? 0),\n updatedAt: Number(row.updated_at ?? 0),\n completedAt:\n row.completed_at == null ? null : Number(row.completed_at as number),\n };\n}\n\n/**\n * Insert a new pending task. Returns the generated task id.\n *\n * If `externalEventKey` is supplied, the unique index on\n * `(platform, external_event_key)` will reject duplicates — callers should\n * catch the resulting constraint-violation error and treat it as\n * \"already enqueued\" instead of a hard failure (H3 in the webhook security\n * audit). This is the SQL-backed replacement for the in-memory dedup map.\n */\nexport async function insertPendingTask(input: {\n id: string;\n platform: string;\n externalThreadId: string;\n payload: string;\n ownerEmail: string;\n orgId?: string | null;\n externalEventKey?: string | null;\n}): Promise<void> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n await client.execute({\n sql: `INSERT INTO integration_pending_tasks\n (id, platform, external_thread_id, payload, owner_email, org_id, status, attempts, created_at, updated_at, external_event_key)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n args: [\n input.id,\n input.platform,\n input.externalThreadId,\n input.payload,\n input.ownerEmail,\n input.orgId ?? null,\n \"pending\",\n 0,\n now,\n now,\n input.externalEventKey ?? null,\n ],\n });\n}\n\n/**\n * Returns whether a duplicate-event error from `insertPendingTask` looks\n * like a unique-constraint violation on `(platform, external_event_key)`.\n *\n * Postgres surfaces these as `error.code === \"23505\"`, while SQLite uses\n * a substring match on the error text. Used by the webhook handler to\n * distinguish \"already enqueued\" (silently OK) from genuine insert failures.\n */\nexport function isDuplicateEventError(err: unknown): boolean {\n const e = err as { code?: string; message?: string } | null;\n if (!e) return false;\n if (e.code === \"23505\") return true; // Postgres unique-violation\n const msg = String(e.message ?? \"\").toLowerCase();\n return (\n msg.includes(\"unique\") ||\n msg.includes(\"duplicate entry\") ||\n msg.includes(\"duplicate key\")\n );\n}\n\n/** Fetch a pending task by id. */\nexport async function getPendingTask(id: string): Promise<PendingTask | null> {\n await ensureTable();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT id, platform, external_thread_id, payload, owner_email, org_id, status, attempts, error_message, created_at, updated_at, completed_at\n FROM integration_pending_tasks WHERE id = ? LIMIT 1`,\n args: [id],\n });\n if (rows.length === 0) return null;\n return rowToTask(rows[0] as Record<string, unknown>);\n}\n\n/**\n * Atomically claim a task: transition pending → processing and increment\n * attempts. Returns the updated task if the transition succeeded, otherwise\n * null (e.g. the task was already claimed by a concurrent worker).\n */\nexport async function claimPendingTask(\n id: string,\n): Promise<PendingTask | null> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n\n // Conditional update: only flip if currently pending. Failed tasks are\n // terminal unless an explicit retry path resets them to pending first.\n const result = await client.execute({\n sql: isPostgres()\n ? `UPDATE integration_pending_tasks\n SET status = ?, attempts = attempts + 1, updated_at = ?\n WHERE id = ? AND status = 'pending'\n RETURNING id, platform, external_thread_id, payload, owner_email, org_id, status, attempts, error_message, created_at, updated_at, completed_at`\n : `UPDATE integration_pending_tasks\n SET status = ?, attempts = attempts + 1, updated_at = ?\n WHERE id = ? AND status = 'pending'`,\n args: [\"processing\", now, id],\n });\n const rows = result.rows ?? [];\n\n if (isPostgres()) {\n if (rows.length === 0) return null;\n return rowToTask(rows[0] as Record<string, unknown>);\n }\n\n // SQLite: no RETURNING, so re-read after the update. Confirm we actually\n // moved it into 'processing' (vs. lost the race).\n const affected =\n (result as { rowsAffected?: number; rowCount?: number }).rowsAffected ??\n (result as { rowsAffected?: number; rowCount?: number }).rowCount;\n if (affected === 0) return null;\n const fetched = await getPendingTask(id);\n if (!fetched || fetched.status !== \"processing\") return null;\n return fetched;\n}\n\n/** Mark a task as completed. */\nexport async function markTaskCompleted(id: string): Promise<void> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n await client.execute({\n sql: `UPDATE integration_pending_tasks\n SET status = ?, updated_at = ?, completed_at = ?\n WHERE id = ?`,\n args: [\"completed\", now, now, id],\n });\n}\n\n/** Mark a task as failed and stash an error message. */\nexport async function markTaskFailed(\n id: string,\n errorMessage: string,\n): Promise<void> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n await client.execute({\n sql: `UPDATE integration_pending_tasks\n SET status = ?, updated_at = ?, error_message = ?\n WHERE id = ?`,\n args: [\"failed\", now, errorMessage.slice(0, 2000), id],\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"pending-tasks-store.js","sourceRoot":"","sources":["../../src/integrations/pending-tasks-store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AACjE,OAAO,EACL,iBAAiB,EACjB,kBAAkB,EAClB,iBAAiB,GAClB,MAAM,oBAAoB,CAAC;AAE5B,IAAI,YAAuC,CAAC;AAE5C,KAAK,UAAU,WAAW;IACxB,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,YAAY,GAAG,CAAC,KAAK,IAAI,EAAE;YACzB,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;YAC3B,MAAM,SAAS,GAAG;;;;;;;;aAQX,OAAO,E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C;KAClC,CAAC,CAAC;AACL,CAAC;AAED,wDAAwD;AACxD,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,EAAU,EACV,YAAoB;IAEpB,MAAM,WAAW,EAAE,CAAC;IACpB,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAC3B,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IACvB,MAAM,MAAM,CAAC,OAAO,CAAC;QACnB,GAAG,EAAE;;uBAEc;QACnB,IAAI,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE,YAAY,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;KACvD,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * SQL-backed pending task queue for integration webhooks.\n *\n * Why this exists: serverless platforms (Netlify Lambda, Vercel, Cloudflare\n * Workers) freeze the function execution as soon as the HTTP response is\n * returned. Fire-and-forget background `Promise`s get killed mid-flight,\n * meaning agent loops triggered from a Slack/Telegram webhook never finish.\n *\n * Solution: persist the inbound message to SQL inside the webhook handler,\n * then dispatch a fresh HTTP POST to a separate processor endpoint. Each\n * invocation gets its own fresh function timeout budget.\n */\nimport { getDbExec, isPostgres, intType } from \"../db/client.js\";\nimport {\n ensureTableExists,\n ensureColumnExists,\n ensureIndexExists,\n} from \"../db/ddl-guard.js\";\n\nlet _initPromise: Promise<void> | undefined;\n\nasync function ensureTable(): Promise<void> {\n if (!_initPromise) {\n _initPromise = (async () => {\n const client = getDbExec();\n const createSql = `CREATE TABLE IF NOT EXISTS integration_pending_tasks (\n id TEXT PRIMARY KEY,\n platform TEXT NOT NULL,\n external_thread_id TEXT NOT NULL,\n payload TEXT NOT NULL,\n owner_email TEXT NOT NULL,\n org_id TEXT,\n status TEXT NOT NULL,\n attempts ${intType()} NOT NULL DEFAULT 0,\n error_message TEXT,\n created_at ${intType()} NOT NULL,\n updated_at ${intType()} NOT NULL,\n completed_at ${intType()}\n)`;\n\n if (isPostgres()) {\n // PG guard: probe via information_schema, only issue DDL if missing, bounded lock_timeout\n await ensureTableExists(\"integration_pending_tasks\", createSql);\n await ensureColumnExists(\n \"integration_pending_tasks\",\n \"external_event_key\",\n `ALTER TABLE integration_pending_tasks ADD COLUMN IF NOT EXISTS external_event_key TEXT`,\n );\n await ensureIndexExists(\n \"idx_pending_tasks_status_created\",\n `CREATE INDEX IF NOT EXISTS idx_pending_tasks_status_created ON integration_pending_tasks(status, created_at)`,\n );\n await ensureIndexExists(\n \"idx_pending_tasks_event_key\",\n `CREATE UNIQUE INDEX IF NOT EXISTS idx_pending_tasks_event_key ON integration_pending_tasks(platform, external_event_key)`,\n );\n return;\n }\n\n await client.execute(createSql);\n await client.execute(\n `CREATE INDEX IF NOT EXISTS idx_pending_tasks_status_created ON integration_pending_tasks(status, created_at)`,\n );\n // Additive migration: add a stable per-event dedup key so duplicate\n // webhook deliveries from the same platform get rejected at the SQL\n // layer instead of via an in-memory Map (which doesn't survive\n // serverless cold starts — H3 in the webhook security audit). The\n // unique index ensures a duplicate INSERT raises an error we can\n // catch as \"already-enqueued\".\n await ensureExternalEventKey(client);\n await client.execute(\n `CREATE UNIQUE INDEX IF NOT EXISTS idx_pending_tasks_event_key ON integration_pending_tasks(platform, external_event_key)`,\n );\n })().catch((err) => {\n // Retry init on the next call after a failed startup.\n _initPromise = undefined;\n throw err;\n });\n }\n return _initPromise;\n}\n\nasync function ensureExternalEventKey(\n client: ReturnType<typeof getDbExec>,\n): Promise<void> {\n if (isPostgres()) {\n await client.execute(\n `ALTER TABLE integration_pending_tasks ADD COLUMN IF NOT EXISTS external_event_key TEXT`,\n );\n return;\n }\n // SQLite doesn't support `ADD COLUMN IF NOT EXISTS` until 3.35; swallow\n // the duplicate-column error so reruns are idempotent.\n try {\n await client.execute(\n `ALTER TABLE integration_pending_tasks ADD COLUMN external_event_key TEXT`,\n );\n } catch (err: any) {\n if (\n !String(err?.message ?? err)\n .toLowerCase()\n .includes(\"duplicate\")\n ) {\n throw err;\n }\n }\n}\n\n/** Status values for an integration pending task. */\nexport type PendingTaskStatus =\n | \"pending\"\n | \"processing\"\n | \"completed\"\n | \"failed\";\n\nexport interface PendingTask {\n id: string;\n platform: string;\n externalThreadId: string;\n payload: string;\n ownerEmail: string;\n orgId: string | null;\n status: PendingTaskStatus;\n attempts: number;\n errorMessage: string | null;\n createdAt: number;\n updatedAt: number;\n completedAt: number | null;\n}\n\nfunction rowToTask(row: Record<string, unknown>): PendingTask {\n return {\n id: row.id as string,\n platform: row.platform as string,\n externalThreadId: row.external_thread_id as string,\n payload: row.payload as string,\n ownerEmail: row.owner_email as string,\n orgId: (row.org_id as string | null) ?? null,\n status: row.status as PendingTaskStatus,\n attempts: Number(row.attempts ?? 0),\n errorMessage: (row.error_message as string | null) ?? null,\n createdAt: Number(row.created_at ?? 0),\n updatedAt: Number(row.updated_at ?? 0),\n completedAt:\n row.completed_at == null ? null : Number(row.completed_at as number),\n };\n}\n\n/**\n * Insert a new pending task. Returns the generated task id.\n *\n * If `externalEventKey` is supplied, the unique index on\n * `(platform, external_event_key)` will reject duplicates — callers should\n * catch the resulting constraint-violation error and treat it as\n * \"already enqueued\" instead of a hard failure (H3 in the webhook security\n * audit). This is the SQL-backed replacement for the in-memory dedup map.\n */\nexport async function insertPendingTask(input: {\n id: string;\n platform: string;\n externalThreadId: string;\n payload: string;\n ownerEmail: string;\n orgId?: string | null;\n externalEventKey?: string | null;\n}): Promise<void> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n await client.execute({\n sql: `INSERT INTO integration_pending_tasks\n (id, platform, external_thread_id, payload, owner_email, org_id, status, attempts, created_at, updated_at, external_event_key)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n args: [\n input.id,\n input.platform,\n input.externalThreadId,\n input.payload,\n input.ownerEmail,\n input.orgId ?? null,\n \"pending\",\n 0,\n now,\n now,\n input.externalEventKey ?? null,\n ],\n });\n}\n\n/**\n * Returns whether a duplicate-event error from `insertPendingTask` looks\n * like a unique-constraint violation on `(platform, external_event_key)`.\n *\n * Postgres surfaces these as `error.code === \"23505\"`, while SQLite uses\n * a substring match on the error text. Used by the webhook handler to\n * distinguish \"already enqueued\" (silently OK) from genuine insert failures.\n */\nexport function isDuplicateEventError(err: unknown): boolean {\n const e = err as { code?: string; message?: string } | null;\n if (!e) return false;\n if (e.code === \"23505\") return true; // Postgres unique-violation\n const msg = String(e.message ?? \"\").toLowerCase();\n return (\n msg.includes(\"unique\") ||\n msg.includes(\"duplicate entry\") ||\n msg.includes(\"duplicate key\")\n );\n}\n\n/** Fetch a pending task by id. */\nexport async function getPendingTask(id: string): Promise<PendingTask | null> {\n await ensureTable();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT id, platform, external_thread_id, payload, owner_email, org_id, status, attempts, error_message, created_at, updated_at, completed_at\n FROM integration_pending_tasks WHERE id = ? LIMIT 1`,\n args: [id],\n });\n if (rows.length === 0) return null;\n return rowToTask(rows[0] as Record<string, unknown>);\n}\n\n/**\n * Atomically claim a task: transition pending → processing and increment\n * attempts. Returns the updated task if the transition succeeded, otherwise\n * null (e.g. the task was already claimed by a concurrent worker).\n */\nexport async function claimPendingTask(\n id: string,\n): Promise<PendingTask | null> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n\n // Conditional update: only flip if currently pending. Failed tasks are\n // terminal unless an explicit retry path resets them to pending first.\n const result = await client.execute({\n sql: isPostgres()\n ? `UPDATE integration_pending_tasks\n SET status = ?, attempts = attempts + 1, updated_at = ?\n WHERE id = ? AND status = 'pending'\n RETURNING id, platform, external_thread_id, payload, owner_email, org_id, status, attempts, error_message, created_at, updated_at, completed_at`\n : `UPDATE integration_pending_tasks\n SET status = ?, attempts = attempts + 1, updated_at = ?\n WHERE id = ? AND status = 'pending'`,\n args: [\"processing\", now, id],\n });\n const rows = result.rows ?? [];\n\n if (isPostgres()) {\n if (rows.length === 0) return null;\n return rowToTask(rows[0] as Record<string, unknown>);\n }\n\n // SQLite: no RETURNING, so re-read after the update. Confirm we actually\n // moved it into 'processing' (vs. lost the race).\n const affected =\n (result as { rowsAffected?: number; rowCount?: number }).rowsAffected ??\n (result as { rowsAffected?: number; rowCount?: number }).rowCount;\n if (affected === 0) return null;\n const fetched = await getPendingTask(id);\n if (!fetched || fetched.status !== \"processing\") return null;\n return fetched;\n}\n\n/** Mark a task as completed. */\nexport async function markTaskCompleted(id: string): Promise<void> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n await client.execute({\n sql: `UPDATE integration_pending_tasks\n SET status = ?, updated_at = ?, completed_at = ?\n WHERE id = ?`,\n args: [\"completed\", now, now, id],\n });\n}\n\n/** Mark a task as failed and stash an error message. */\nexport async function markTaskFailed(\n id: string,\n errorMessage: string,\n): Promise<void> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n await client.execute({\n sql: `UPDATE integration_pending_tasks\n SET status = ?, updated_at = ?, error_message = ?\n WHERE id = ?`,\n args: [\"failed\", now, errorMessage.slice(0, 2000), id],\n });\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remote-commands-store.d.ts","sourceRoot":"","sources":["../../src/integrations/remote-commands-store.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"remote-commands-store.d.ts","sourceRoot":"","sources":["../../src/integrations/remote-commands-store.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EACV,aAAa,EACb,iBAAiB,EAElB,MAAM,mBAAmB,CAAC;AAmG3B,wBAAgB,mBAAmB,CACjC,KAAK,EAAE,OAAO,GACb,KAAK,IAAI,iBAAiB,CAK5B;AAED,wBAAsB,oBAAoB,CAAC,KAAK,EAAE;IAChD,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,IAAI,EAAE,iBAAiB,CAAC;IACxB,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,QAAQ,CAAC,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} from "../db/client.js";
|
|
2
|
+
import { ensureTableExists, ensureIndexExists } from "../db/ddl-guard.js";
|
|
2
3
|
let _initPromise;
|
|
3
4
|
const REMOTE_COMMAND_KINDS = [
|
|
4
5
|
"create-run",
|
|
@@ -15,27 +16,34 @@ async function ensureTable() {
|
|
|
15
16
|
if (!_initPromise) {
|
|
16
17
|
_initPromise = (async () => {
|
|
17
18
|
const client = getDbExec();
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
19
|
+
const createSql = `CREATE TABLE IF NOT EXISTS integration_remote_commands (
|
|
20
|
+
id TEXT PRIMARY KEY,
|
|
21
|
+
device_id TEXT NOT NULL,
|
|
22
|
+
owner_email TEXT NOT NULL,
|
|
23
|
+
org_id TEXT,
|
|
24
|
+
kind TEXT NOT NULL,
|
|
25
|
+
params_json TEXT NOT NULL,
|
|
26
|
+
status TEXT NOT NULL,
|
|
27
|
+
result_json TEXT,
|
|
28
|
+
platform TEXT,
|
|
29
|
+
external_thread_id TEXT,
|
|
30
|
+
attempts ${intType()} NOT NULL DEFAULT 0,
|
|
31
|
+
next_check_at ${intType()} NOT NULL,
|
|
32
|
+
claimed_at ${intType()},
|
|
33
|
+
completed_at ${intType()},
|
|
34
|
+
error_message TEXT,
|
|
35
|
+
created_at ${intType()} NOT NULL,
|
|
36
|
+
updated_at ${intType()} NOT NULL
|
|
37
|
+
)`;
|
|
38
|
+
if (isPostgres()) {
|
|
39
|
+
// PG guard: probe via information_schema, only issue DDL if missing, bounded lock_timeout
|
|
40
|
+
await ensureTableExists("integration_remote_commands", createSql);
|
|
41
|
+
await ensureIndexExists("idx_remote_commands_device_status_next", `CREATE INDEX IF NOT EXISTS idx_remote_commands_device_status_next ON integration_remote_commands(device_id, status, next_check_at)`);
|
|
42
|
+
await ensureIndexExists("idx_remote_commands_owner", `CREATE INDEX IF NOT EXISTS idx_remote_commands_owner ON integration_remote_commands(owner_email, org_id)`);
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
// SQLite: keep existing behavior
|
|
46
|
+
await retryOnDdlRace(() => client.execute(createSql));
|
|
39
47
|
await retryOnDdlRace(() => client.execute(`CREATE INDEX IF NOT EXISTS idx_remote_commands_device_status_next ON integration_remote_commands(device_id, status, next_check_at)`));
|
|
40
48
|
await retryOnDdlRace(() => client.execute(`CREATE INDEX IF NOT EXISTS idx_remote_commands_owner ON integration_remote_commands(owner_email, org_id)`));
|
|
41
49
|
})().catch((err) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remote-commands-store.js","sourceRoot":"","sources":["../../src/integrations/remote-commands-store.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,OAAO,EACP,UAAU,EACV,cAAc,GACf,MAAM,iBAAiB,CAAC;AAOzB,IAAI,YAAuC,CAAC;AAE5C,MAAM,oBAAoB,GAAwB;IAChD,YAAY;IACZ,WAAW;IACX,SAAS;IACT,iBAAiB;IACjB,SAAS;IACT,MAAM;IACN,MAAM;IACN,QAAQ;CACT,CAAC;AAEF,MAAM,iBAAiB,GAAG,IAAI,GAAG,CAAsB,CAAC,WAAW,EAAE,QAAQ,CAAC,CAAC,CAAC;AAEhF,KAAK,UAAU,WAAW;IACxB,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,YAAY,GAAG,CAAC,KAAK,IAAI,EAAE;YACzB,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;YAC3B,MAAM,cAAc,CAAC,GAAG,EAAE,CACxB,MAAM,CAAC,OAAO,CAAC;;;;;;;;;;;;uBAYA,OAAO,EAAE;4BACJ,OAAO,EAAE;yBACZ,OAAO,EAAE;2BACP,OAAO,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oteCommand,\n RemoteCommandKind,\n RemoteCommandStatus,\n} from \"./remote-types.js\";\n\nlet _initPromise: Promise<void> | undefined;\n\nconst REMOTE_COMMAND_KINDS: RemoteCommandKind[] = [\n \"create-run\",\n \"list-runs\",\n \"get-run\",\n \"append-followup\",\n \"approve\",\n \"deny\",\n \"stop\",\n \"status\",\n];\n\nconst TERMINAL_STATUSES = new Set<RemoteCommandStatus>([\"completed\", \"failed\"]);\n\nasync function ensureTable(): Promise<void> {\n if (!_initPromise) {\n _initPromise = (async () => {\n const client = getDbExec();\n await retryOnDdlRace(() =>\n client.execute(`\n CREATE TABLE IF NOT EXISTS integration_remote_commands (\n id TEXT PRIMARY KEY,\n device_id TEXT NOT NULL,\n owner_email TEXT NOT NULL,\n org_id TEXT,\n kind TEXT NOT NULL,\n params_json TEXT NOT NULL,\n status TEXT NOT NULL,\n result_json TEXT,\n platform TEXT,\n external_thread_id TEXT,\n attempts ${intType()} NOT NULL DEFAULT 0,\n next_check_at ${intType()} NOT NULL,\n claimed_at ${intType()},\n completed_at ${intType()},\n error_message TEXT,\n created_at ${intType()} NOT NULL,\n updated_at ${intType()} NOT NULL\n )\n `),\n );\n await retryOnDdlRace(() =>\n client.execute(\n `CREATE INDEX IF NOT EXISTS idx_remote_commands_device_status_next ON integration_remote_commands(device_id, status, next_check_at)`,\n ),\n );\n await retryOnDdlRace(() =>\n client.execute(\n `CREATE INDEX IF NOT EXISTS idx_remote_commands_owner ON integration_remote_commands(owner_email, org_id)`,\n ),\n );\n })().catch((err) => {\n // Retry init on the next call after a failed startup.\n _initPromise = undefined;\n throw err;\n });\n }\n return _initPromise;\n}\n\nfunction rowToCommand(row: Record<string, unknown>): RemoteCommand {\n return {\n id: row.id as string,\n deviceId: row.device_id as string,\n ownerEmail: row.owner_email as string,\n orgId: (row.org_id as string | null) ?? null,\n kind: row.kind as RemoteCommandKind,\n params: parseJson(row.params_json, {}),\n status: row.status as RemoteCommandStatus,\n result: parseJson(row.result_json, null),\n platform: (row.platform as string | null) ?? null,\n externalThreadId: (row.external_thread_id as string | null) ?? null,\n attempts: Number(row.attempts ?? 0),\n nextCheckAt: Number(row.next_check_at ?? 0),\n claimedAt: row.claimed_at == null ? null : Number(row.claimed_at as number),\n completedAt:\n row.completed_at == null ? null : Number(row.completed_at as number),\n errorMessage: (row.error_message as string | null) ?? null,\n createdAt: Number(row.created_at ?? 0),\n updatedAt: Number(row.updated_at ?? 0),\n };\n}\n\nexport function isRemoteCommandKind(\n value: unknown,\n): value is RemoteCommandKind {\n return (\n typeof value === \"string\" &&\n REMOTE_COMMAND_KINDS.includes(value as RemoteCommandKind)\n );\n}\n\nexport async function enqueueRemoteCommand(input: {\n deviceId: string;\n ownerEmail: string;\n orgId?: string | null;\n kind: RemoteCommandKind;\n params?: unknown;\n platform?: string | null;\n externalThreadId?: string | null;\n nextCheckAt?: number;\n}): Promise<RemoteCommand> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const id = `remote-command-${now}-${randomHex(8)}`;\n\n await client.execute({\n sql: `INSERT INTO integration_remote_commands\n (id, device_id, owner_email, org_id, kind, params_json, status, result_json,\n platform, external_thread_id, attempts, next_check_at, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n args: [\n id,\n input.deviceId,\n input.ownerEmail,\n input.orgId ?? null,\n input.kind,\n JSON.stringify(input.params ?? {}),\n \"pending\",\n null,\n input.platform ?? null,\n input.externalThreadId ?? null,\n 0,\n input.nextCheckAt ?? now,\n now,\n now,\n ],\n });\n\n const command = await getRemoteCommand(id);\n if (!command) throw new Error(\"remote command insert failed\");\n return command;\n}\n\nexport async function getRemoteCommand(\n id: string,\n): Promise<RemoteCommand | null> {\n await ensureTable();\n const { rows } = await getDbExec().execute({\n sql: `SELECT * FROM integration_remote_commands WHERE id = ? LIMIT 1`,\n args: [id],\n });\n return rows[0] ? rowToCommand(rows[0] as Record<string, unknown>) : null;\n}\n\nexport async function listRemoteCommandsForOwner(input: {\n ownerEmail: string;\n orgId?: string | null;\n limit?: number;\n}): Promise<RemoteCommand[]> {\n await ensureTable();\n const limit = Math.max(1, Math.min(input.limit ?? 100, 250));\n if (!Object.prototype.hasOwnProperty.call(input, \"orgId\")) {\n const { rows } = await getDbExec().execute({\n sql: `SELECT * FROM integration_remote_commands\n WHERE owner_email = ?\n ORDER BY updated_at DESC\n LIMIT ?`,\n args: [input.ownerEmail, limit],\n });\n return rows.map((row) => rowToCommand(row as Record<string, unknown>));\n }\n const { rows } = await getDbExec().execute({\n sql: `SELECT * FROM integration_remote_commands\n WHERE owner_email = ?\n AND ((org_id IS NULL AND ? IS NULL) OR org_id = ?)\n ORDER BY updated_at DESC\n LIMIT ?`,\n args: [input.ownerEmail, input.orgId ?? null, input.orgId ?? null, limit],\n });\n return rows.map((row) => rowToCommand(row as Record<string, unknown>));\n}\n\nexport async function claimNextRemoteCommand(\n deviceId: string,\n): Promise<RemoteCommand | null> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const { rows } = await client.execute({\n sql: `SELECT id FROM integration_remote_commands\n WHERE device_id = ?\n AND status = 'pending'\n AND next_check_at <= ?\n ORDER BY created_at ASC\n LIMIT 1`,\n args: [deviceId, now],\n });\n const id = rows[0]?.id as string | undefined;\n if (!id) return null;\n\n const result = await client.execute({\n sql: isPostgres()\n ? `UPDATE integration_remote_commands\n SET status = ?, attempts = attempts + 1, claimed_at = ?, updated_at = ?\n WHERE id = ? AND device_id = ? AND status = 'pending'\n RETURNING *`\n : `UPDATE integration_remote_commands\n SET status = ?, attempts = attempts + 1, claimed_at = ?, updated_at = ?\n WHERE id = ? AND device_id = ? AND status = 'pending'`,\n args: [\"claimed\", now, now, id, deviceId],\n });\n if (isPostgres()) {\n const row = result.rows?.[0];\n return row ? rowToCommand(row as Record<string, unknown>) : null;\n }\n const affected = result.rowsAffected ?? (result as any).rowCount;\n if (affected === 0) return null;\n\n const command = await getRemoteCommand(id);\n if (!command || command.status !== \"claimed\") return null;\n return command;\n}\n\nexport async function updateRemoteCommandResult(input: {\n deviceId: string;\n commandId: string;\n status: \"running\" | \"completed\" | \"failed\";\n result?: unknown;\n errorMessage?: string | null;\n}): Promise<RemoteCommand | null> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const completedAt = TERMINAL_STATUSES.has(input.status) ? now : null;\n const resultJson =\n input.result === undefined ? undefined : JSON.stringify(input.result);\n\n await client.execute({\n sql: `UPDATE integration_remote_commands\n SET status = ?,\n result_json = COALESCE(?, result_json),\n error_message = ?,\n completed_at = COALESCE(?, completed_at),\n updated_at = ?\n WHERE id = ? AND device_id = ?`,\n args: [\n input.status,\n resultJson ?? null,\n input.errorMessage ? input.errorMessage.slice(0, 2000) : null,\n completedAt,\n now,\n input.commandId,\n input.deviceId,\n ],\n });\n\n const command = await getRemoteCommand(input.commandId);\n if (!command || command.deviceId !== input.deviceId) return null;\n return command;\n}\n\nexport async function retryStaleRemoteCommands(options?: {\n claimedStaleAfterMs?: number;\n runningStaleAfterMs?: number;\n maxAttempts?: number;\n limit?: number;\n}): Promise<{ retried: number; failed: number }> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const claimedCutoff = now - (options?.claimedStaleAfterMs ?? 75_000);\n const runningCutoff = now - (options?.runningStaleAfterMs ?? 5 * 60_000);\n const maxAttempts = options?.maxAttempts ?? 3;\n const limit = options?.limit ?? 50;\n\n const { rows } = await client.execute({\n sql: `SELECT id, status, attempts FROM integration_remote_commands\n WHERE (status = 'claimed' AND updated_at <= ?)\n OR (status = 'running' AND updated_at <= ?)\n ORDER BY updated_at ASC\n LIMIT ?`,\n args: [claimedCutoff, runningCutoff, limit],\n });\n\n let retried = 0;\n let failed = 0;\n for (const row of rows) {\n const id = row.id as string;\n const status = row.status as RemoteCommandStatus;\n const attempts = Number(row.attempts ?? 0);\n if (attempts >= maxAttempts) {\n const result = await client.execute({\n sql: `UPDATE integration_remote_commands\n SET status = 'failed',\n error_message = COALESCE(error_message, ?),\n completed_at = ?,\n updated_at = ?\n WHERE id = ? AND status = ?`,\n args: [\n `Retry job: exceeded ${maxAttempts} attempts`,\n now,\n now,\n id,\n status,\n ],\n });\n if ((result.rowsAffected ?? (result as any).rowCount) > 0) failed++;\n continue;\n }\n\n const result = await client.execute({\n sql: `UPDATE integration_remote_commands\n SET status = 'pending',\n next_check_at = ?,\n updated_at = ?\n WHERE id = ? AND status = ?`,\n args: [now, now, id, status],\n });\n if ((result.rowsAffected ?? (result as any).rowCount) > 0) retried++;\n }\n\n return { retried, failed };\n}\n\nfunction parseJson(value: unknown, fallback: unknown): unknown {\n if (value == null) return fallback;\n try {\n return JSON.parse(String(value));\n } catch {\n return fallback;\n }\n}\n\nfunction randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n globalThis.crypto.getRandomValues(bytes);\n return Array.from(bytes)\n .map((byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n"]}
|
|
1
|
+
{"version":3,"file":"remote-commands-store.js","sourceRoot":"","sources":["../../src/integrations/remote-commands-store.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,OAAO,EACP,UAAU,EACV,cAAc,GACf,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAO1E,IAAI,YAAuC,CAAC;AAE5C,MAAM,oBAAoB,GAAwB;IAChD,YAAY;IACZ,WAAW;IACX,SAAS;IACT,iBAAiB;IACjB,SAAS;IACT,MAAM;IACN,MAAM;IACN,QAAQ;CACT,CAAC;AAEF,MAAM,iBAAiB,GAAG,IAAI,GAAG,CAAsB,CAAC,WAAW,EAAE,QAAQ,CAAC,CAAC,CAAC;AAEhF,KAAK,UAAU,WAAW;IACxB,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,YAAY,GAAG,CAAC,KAAK,IAAI,EAAE;YACzB,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;YAC3B,MAAM,SAAS,GAAG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;IACnC,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,UAAU,CAAC,CAAC;IACzC,UAAU,CAAC,MAAM,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC;IACzC,OAAO,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC;SACrB,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;SACjD,IAAI,CAAC,EAAE,CAAC,CAAC;AACd,CAAC","sourcesContent":["import {\n getDbExec,\n intType,\n isPostgres,\n retryOnDdlRace,\n} from \"../db/client.js\";\nimport { ensureTableExists, ensureIndexExists } from \"../db/ddl-guard.js\";\nimport type {\n RemoteCommand,\n RemoteCommandKind,\n RemoteCommandStatus,\n} from \"./remote-types.js\";\n\nlet _initPromise: Promise<void> | undefined;\n\nconst REMOTE_COMMAND_KINDS: RemoteCommandKind[] = [\n \"create-run\",\n \"list-runs\",\n \"get-run\",\n \"append-followup\",\n \"approve\",\n \"deny\",\n \"stop\",\n \"status\",\n];\n\nconst TERMINAL_STATUSES = new Set<RemoteCommandStatus>([\"completed\", \"failed\"]);\n\nasync function ensureTable(): Promise<void> {\n if (!_initPromise) {\n _initPromise = (async () => {\n const client = getDbExec();\n const createSql = `CREATE TABLE IF NOT EXISTS integration_remote_commands (\n id TEXT PRIMARY KEY,\n device_id TEXT NOT NULL,\n owner_email TEXT NOT NULL,\n org_id TEXT,\n kind TEXT NOT NULL,\n params_json TEXT NOT NULL,\n status TEXT NOT NULL,\n result_json TEXT,\n platform TEXT,\n external_thread_id TEXT,\n attempts ${intType()} NOT NULL DEFAULT 0,\n next_check_at ${intType()} NOT NULL,\n claimed_at ${intType()},\n completed_at ${intType()},\n error_message TEXT,\n created_at ${intType()} NOT NULL,\n updated_at ${intType()} NOT NULL\n)`;\n\n if (isPostgres()) {\n // PG guard: probe via information_schema, only issue DDL if missing, bounded lock_timeout\n await ensureTableExists(\"integration_remote_commands\", createSql);\n await ensureIndexExists(\n \"idx_remote_commands_device_status_next\",\n `CREATE INDEX IF NOT EXISTS idx_remote_commands_device_status_next ON integration_remote_commands(device_id, status, next_check_at)`,\n );\n await ensureIndexExists(\n \"idx_remote_commands_owner\",\n `CREATE INDEX IF NOT EXISTS idx_remote_commands_owner ON integration_remote_commands(owner_email, org_id)`,\n );\n return;\n }\n\n // SQLite: keep existing behavior\n await retryOnDdlRace(() => client.execute(createSql));\n await retryOnDdlRace(() =>\n client.execute(\n `CREATE INDEX IF NOT EXISTS idx_remote_commands_device_status_next ON integration_remote_commands(device_id, status, next_check_at)`,\n ),\n );\n await retryOnDdlRace(() =>\n client.execute(\n `CREATE INDEX IF NOT EXISTS idx_remote_commands_owner ON integration_remote_commands(owner_email, org_id)`,\n ),\n );\n })().catch((err) => {\n // Retry init on the next call after a failed startup.\n _initPromise = undefined;\n throw err;\n });\n }\n return _initPromise;\n}\n\nfunction rowToCommand(row: Record<string, unknown>): RemoteCommand {\n return {\n id: row.id as string,\n deviceId: row.device_id as string,\n ownerEmail: row.owner_email as string,\n orgId: (row.org_id as string | null) ?? null,\n kind: row.kind as RemoteCommandKind,\n params: parseJson(row.params_json, {}),\n status: row.status as RemoteCommandStatus,\n result: parseJson(row.result_json, null),\n platform: (row.platform as string | null) ?? null,\n externalThreadId: (row.external_thread_id as string | null) ?? null,\n attempts: Number(row.attempts ?? 0),\n nextCheckAt: Number(row.next_check_at ?? 0),\n claimedAt: row.claimed_at == null ? null : Number(row.claimed_at as number),\n completedAt:\n row.completed_at == null ? null : Number(row.completed_at as number),\n errorMessage: (row.error_message as string | null) ?? null,\n createdAt: Number(row.created_at ?? 0),\n updatedAt: Number(row.updated_at ?? 0),\n };\n}\n\nexport function isRemoteCommandKind(\n value: unknown,\n): value is RemoteCommandKind {\n return (\n typeof value === \"string\" &&\n REMOTE_COMMAND_KINDS.includes(value as RemoteCommandKind)\n );\n}\n\nexport async function enqueueRemoteCommand(input: {\n deviceId: string;\n ownerEmail: string;\n orgId?: string | null;\n kind: RemoteCommandKind;\n params?: unknown;\n platform?: string | null;\n externalThreadId?: string | null;\n nextCheckAt?: number;\n}): Promise<RemoteCommand> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const id = `remote-command-${now}-${randomHex(8)}`;\n\n await client.execute({\n sql: `INSERT INTO integration_remote_commands\n (id, device_id, owner_email, org_id, kind, params_json, status, result_json,\n platform, external_thread_id, attempts, next_check_at, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n args: [\n id,\n input.deviceId,\n input.ownerEmail,\n input.orgId ?? null,\n input.kind,\n JSON.stringify(input.params ?? {}),\n \"pending\",\n null,\n input.platform ?? null,\n input.externalThreadId ?? null,\n 0,\n input.nextCheckAt ?? now,\n now,\n now,\n ],\n });\n\n const command = await getRemoteCommand(id);\n if (!command) throw new Error(\"remote command insert failed\");\n return command;\n}\n\nexport async function getRemoteCommand(\n id: string,\n): Promise<RemoteCommand | null> {\n await ensureTable();\n const { rows } = await getDbExec().execute({\n sql: `SELECT * FROM integration_remote_commands WHERE id = ? LIMIT 1`,\n args: [id],\n });\n return rows[0] ? rowToCommand(rows[0] as Record<string, unknown>) : null;\n}\n\nexport async function listRemoteCommandsForOwner(input: {\n ownerEmail: string;\n orgId?: string | null;\n limit?: number;\n}): Promise<RemoteCommand[]> {\n await ensureTable();\n const limit = Math.max(1, Math.min(input.limit ?? 100, 250));\n if (!Object.prototype.hasOwnProperty.call(input, \"orgId\")) {\n const { rows } = await getDbExec().execute({\n sql: `SELECT * FROM integration_remote_commands\n WHERE owner_email = ?\n ORDER BY updated_at DESC\n LIMIT ?`,\n args: [input.ownerEmail, limit],\n });\n return rows.map((row) => rowToCommand(row as Record<string, unknown>));\n }\n const { rows } = await getDbExec().execute({\n sql: `SELECT * FROM integration_remote_commands\n WHERE owner_email = ?\n AND ((org_id IS NULL AND ? IS NULL) OR org_id = ?)\n ORDER BY updated_at DESC\n LIMIT ?`,\n args: [input.ownerEmail, input.orgId ?? null, input.orgId ?? null, limit],\n });\n return rows.map((row) => rowToCommand(row as Record<string, unknown>));\n}\n\nexport async function claimNextRemoteCommand(\n deviceId: string,\n): Promise<RemoteCommand | null> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const { rows } = await client.execute({\n sql: `SELECT id FROM integration_remote_commands\n WHERE device_id = ?\n AND status = 'pending'\n AND next_check_at <= ?\n ORDER BY created_at ASC\n LIMIT 1`,\n args: [deviceId, now],\n });\n const id = rows[0]?.id as string | undefined;\n if (!id) return null;\n\n const result = await client.execute({\n sql: isPostgres()\n ? `UPDATE integration_remote_commands\n SET status = ?, attempts = attempts + 1, claimed_at = ?, updated_at = ?\n WHERE id = ? AND device_id = ? AND status = 'pending'\n RETURNING *`\n : `UPDATE integration_remote_commands\n SET status = ?, attempts = attempts + 1, claimed_at = ?, updated_at = ?\n WHERE id = ? AND device_id = ? AND status = 'pending'`,\n args: [\"claimed\", now, now, id, deviceId],\n });\n if (isPostgres()) {\n const row = result.rows?.[0];\n return row ? rowToCommand(row as Record<string, unknown>) : null;\n }\n const affected = result.rowsAffected ?? (result as any).rowCount;\n if (affected === 0) return null;\n\n const command = await getRemoteCommand(id);\n if (!command || command.status !== \"claimed\") return null;\n return command;\n}\n\nexport async function updateRemoteCommandResult(input: {\n deviceId: string;\n commandId: string;\n status: \"running\" | \"completed\" | \"failed\";\n result?: unknown;\n errorMessage?: string | null;\n}): Promise<RemoteCommand | null> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const completedAt = TERMINAL_STATUSES.has(input.status) ? now : null;\n const resultJson =\n input.result === undefined ? undefined : JSON.stringify(input.result);\n\n await client.execute({\n sql: `UPDATE integration_remote_commands\n SET status = ?,\n result_json = COALESCE(?, result_json),\n error_message = ?,\n completed_at = COALESCE(?, completed_at),\n updated_at = ?\n WHERE id = ? AND device_id = ?`,\n args: [\n input.status,\n resultJson ?? null,\n input.errorMessage ? input.errorMessage.slice(0, 2000) : null,\n completedAt,\n now,\n input.commandId,\n input.deviceId,\n ],\n });\n\n const command = await getRemoteCommand(input.commandId);\n if (!command || command.deviceId !== input.deviceId) return null;\n return command;\n}\n\nexport async function retryStaleRemoteCommands(options?: {\n claimedStaleAfterMs?: number;\n runningStaleAfterMs?: number;\n maxAttempts?: number;\n limit?: number;\n}): Promise<{ retried: number; failed: number }> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const claimedCutoff = now - (options?.claimedStaleAfterMs ?? 75_000);\n const runningCutoff = now - (options?.runningStaleAfterMs ?? 5 * 60_000);\n const maxAttempts = options?.maxAttempts ?? 3;\n const limit = options?.limit ?? 50;\n\n const { rows } = await client.execute({\n sql: `SELECT id, status, attempts FROM integration_remote_commands\n WHERE (status = 'claimed' AND updated_at <= ?)\n OR (status = 'running' AND updated_at <= ?)\n ORDER BY updated_at ASC\n LIMIT ?`,\n args: [claimedCutoff, runningCutoff, limit],\n });\n\n let retried = 0;\n let failed = 0;\n for (const row of rows) {\n const id = row.id as string;\n const status = row.status as RemoteCommandStatus;\n const attempts = Number(row.attempts ?? 0);\n if (attempts >= maxAttempts) {\n const result = await client.execute({\n sql: `UPDATE integration_remote_commands\n SET status = 'failed',\n error_message = COALESCE(error_message, ?),\n completed_at = ?,\n updated_at = ?\n WHERE id = ? AND status = ?`,\n args: [\n `Retry job: exceeded ${maxAttempts} attempts`,\n now,\n now,\n id,\n status,\n ],\n });\n if ((result.rowsAffected ?? (result as any).rowCount) > 0) failed++;\n continue;\n }\n\n const result = await client.execute({\n sql: `UPDATE integration_remote_commands\n SET status = 'pending',\n next_check_at = ?,\n updated_at = ?\n WHERE id = ? AND status = ?`,\n args: [now, now, id, status],\n });\n if ((result.rowsAffected ?? (result as any).rowCount) > 0) retried++;\n }\n\n return { retried, failed };\n}\n\nfunction parseJson(value: unknown, fallback: unknown): unknown {\n if (value == null) return fallback;\n try {\n return JSON.parse(String(value));\n } catch {\n return fallback;\n }\n}\n\nfunction randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n globalThis.crypto.getRandomValues(bytes);\n return Array.from(bytes)\n .map((byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remote-devices-store.d.ts","sourceRoot":"","sources":["../../src/integrations/remote-devices-store.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"remote-devices-store.d.ts","sourceRoot":"","sources":["../../src/integrations/remote-devices-store.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AA6I1E,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,YAAY,GAAG,kBAAkB,CAgB7E;AAED,wBAAsB,kBAAkB,CAAC,KAAK,EAAE;IAC9C,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;CAC3C,GAAG,OAAO,CAAC;IAAE,MAAM,EAAE,YAAY,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC,CAkCnD;AAED,wBAAsB,eAAe,CACnC,EAAE,EAAE,MAAM,GACT,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAO9B;AAED,wBAAsB,uBAAuB,CAAC,KAAK,EAAE;IACnD,EAAE,EAAE,MAAM,CAAC;IACX,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;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@@
|
|
|
1
1
|
import { getDbExec, intType, isPostgres, retryOnDdlRace, } from "../db/client.js";
|
|
2
|
+
import { ensureColumnExists, ensureIndexExists, ensureTableExists, } from "../db/ddl-guard.js";
|
|
2
3
|
let _initPromise;
|
|
3
4
|
async function ensureTable() {
|
|
4
5
|
if (!_initPromise) {
|
|
5
6
|
_initPromise = (async () => {
|
|
6
7
|
const client = getDbExec();
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
8
|
+
const createSql = `
|
|
9
|
+
CREATE TABLE IF NOT EXISTS integration_remote_devices (
|
|
10
|
+
id TEXT PRIMARY KEY,
|
|
11
|
+
owner_email TEXT NOT NULL,
|
|
12
|
+
org_id TEXT,
|
|
13
|
+
label TEXT NOT NULL,
|
|
14
|
+
platform TEXT,
|
|
15
|
+
app_version TEXT,
|
|
16
|
+
host_name TEXT,
|
|
17
|
+
metadata_json TEXT,
|
|
18
|
+
device_token_hash TEXT NOT NULL,
|
|
19
|
+
last_seen_at ${intType()},
|
|
20
|
+
status TEXT NOT NULL,
|
|
21
|
+
revoked_at ${intType()},
|
|
22
|
+
created_at ${intType()} NOT NULL,
|
|
23
|
+
updated_at ${intType()} NOT NULL
|
|
24
|
+
)
|
|
25
|
+
`;
|
|
26
|
+
if (isPostgres()) {
|
|
27
|
+
// PG guard: probe via information_schema, only issue DDL if missing, bounded lock_timeout
|
|
28
|
+
await ensureTableExists("integration_remote_devices", createSql);
|
|
29
|
+
await ensureColumnExists("integration_remote_devices", "platform", `ALTER TABLE integration_remote_devices ADD COLUMN IF NOT EXISTS platform TEXT`);
|
|
30
|
+
await ensureColumnExists("integration_remote_devices", "app_version", `ALTER TABLE integration_remote_devices ADD COLUMN IF NOT EXISTS app_version TEXT`);
|
|
31
|
+
await ensureColumnExists("integration_remote_devices", "host_name", `ALTER TABLE integration_remote_devices ADD COLUMN IF NOT EXISTS host_name TEXT`);
|
|
32
|
+
await ensureColumnExists("integration_remote_devices", "metadata_json", `ALTER TABLE integration_remote_devices ADD COLUMN IF NOT EXISTS metadata_json TEXT`);
|
|
33
|
+
await ensureColumnExists("integration_remote_devices", "revoked_at", `ALTER TABLE integration_remote_devices ADD COLUMN IF NOT EXISTS revoked_at ${intType()}`);
|
|
34
|
+
await ensureIndexExists("idx_remote_devices_token_hash", `CREATE UNIQUE INDEX IF NOT EXISTS idx_remote_devices_token_hash ON integration_remote_devices(device_token_hash)`);
|
|
35
|
+
await ensureIndexExists("idx_remote_devices_owner", `CREATE INDEX IF NOT EXISTS idx_remote_devices_owner ON integration_remote_devices(owner_email, org_id)`);
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
// SQLite (local dev): keep existing behavior verbatim
|
|
39
|
+
await retryOnDdlRace(() => client.execute(createSql));
|
|
25
40
|
await addColumnIfMissing("platform", "TEXT");
|
|
26
41
|
await addColumnIfMissing("app_version", "TEXT");
|
|
27
42
|
await addColumnIfMissing("host_name", "TEXT");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remote-devices-store.js","sourceRoot":"","sources":["../../src/integrations/remote-devices-store.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,OAAO,EACP,UAAU,EACV,cAAc,GACf,MAAM,iBAAiB,CAAC;AAGzB,IAAI,YAAuC,CAAC;AAE5C,KAAK,UAAU,WAAW;IACxB,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,YAAY,GAAG,CAAC,KAAK,IAAI,EAAE;YACzB,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;YAC3B,MAAM,cAAc,CAAC,GAAG,EAAE,CACxB,MAAM,CAAC,OAAO,CAAC;;;;;;;;;;;2BAWI,OAAO,EAAE;;yBAEX,OAAO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,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;SACjD,IAAI,CAAC,EAAE,CAAC,CAAC;AACd,CAAC","sourcesContent":["import {\n getDbExec,\n intType,\n isPostgres,\n retryOnDdlRace,\n} from \"../db/client.js\";\nimport type { PublicRemoteDevice, RemoteDevice } from \"./remote-types.js\";\n\nlet _initPromise: Promise<void> | undefined;\n\nasync function ensureTable(): Promise<void> {\n if (!_initPromise) {\n _initPromise = (async () => {\n const client = getDbExec();\n await retryOnDdlRace(() =>\n client.execute(`\n CREATE TABLE IF NOT EXISTS integration_remote_devices (\n id TEXT PRIMARY KEY,\n owner_email TEXT NOT NULL,\n org_id TEXT,\n label TEXT NOT NULL,\n platform TEXT,\n app_version TEXT,\n host_name TEXT,\n metadata_json TEXT,\n device_token_hash TEXT NOT NULL,\n last_seen_at ${intType()},\n status TEXT NOT NULL,\n revoked_at ${intType()},\n created_at ${intType()} NOT NULL,\n updated_at ${intType()} NOT NULL\n )\n `),\n );\n await addColumnIfMissing(\"platform\", \"TEXT\");\n await addColumnIfMissing(\"app_version\", \"TEXT\");\n await addColumnIfMissing(\"host_name\", \"TEXT\");\n await addColumnIfMissing(\"metadata_json\", \"TEXT\");\n await addColumnIfMissing(\"revoked_at\", intType());\n await retryOnDdlRace(() =>\n client.execute(\n `CREATE UNIQUE INDEX IF NOT EXISTS idx_remote_devices_token_hash ON integration_remote_devices(device_token_hash)`,\n ),\n );\n await retryOnDdlRace(() =>\n client.execute(\n `CREATE INDEX IF NOT EXISTS idx_remote_devices_owner ON integration_remote_devices(owner_email, org_id)`,\n ),\n );\n })().catch((err) => {\n // Retry init on the next call after a failed startup.\n _initPromise = undefined;\n throw err;\n });\n }\n return _initPromise;\n}\n\nasync function addColumnIfMissing(\n name: string,\n definition: string,\n): Promise<void> {\n const sql = isPostgres()\n ? `ALTER TABLE integration_remote_devices ADD COLUMN IF NOT EXISTS ${name} ${definition}`\n : `ALTER TABLE integration_remote_devices ADD COLUMN ${name} ${definition}`;\n try {\n await retryOnDdlRace(() => getDbExec().execute(sql));\n } catch (err) {\n if (isDuplicateColumnError(err)) return;\n throw err;\n }\n}\n\nfunction isDuplicateColumnError(err: unknown): boolean {\n const code = String((err as { code?: unknown })?.code ?? \"\");\n const message = String((err as { message?: unknown })?.message ?? err)\n .toLowerCase()\n .trim();\n return (\n code === \"42701\" ||\n message.includes(\"duplicate column\") ||\n message.includes(\"already exists\")\n );\n}\n\nfunction rowToDevice(row: Record<string, unknown>): RemoteDevice {\n return {\n id: row.id as string,\n ownerEmail: row.owner_email as string,\n orgId: (row.org_id as string | null) ?? null,\n label: row.label as string,\n platform: (row.platform as string | null) ?? null,\n appVersion: (row.app_version as string | null) ?? null,\n hostName: (row.host_name as string | null) ?? null,\n metadata: parseJson(row.metadata_json, null) as Record<\n string,\n unknown\n > | null,\n deviceTokenHash: row.device_token_hash as string,\n lastSeenAt:\n row.last_seen_at == null ? null : Number(row.last_seen_at as number),\n status: row.status as RemoteDevice[\"status\"],\n revokedAt: row.revoked_at == null ? null : Number(row.revoked_at as number),\n createdAt: Number(row.created_at ?? 0),\n updatedAt: Number(row.updated_at ?? 0),\n };\n}\n\nexport function toPublicRemoteDevice(device: RemoteDevice): PublicRemoteDevice {\n return {\n id: device.id,\n ownerEmail: device.ownerEmail,\n orgId: device.orgId,\n label: device.label,\n platform: device.platform,\n appVersion: device.appVersion,\n hostName: device.hostName,\n metadata: device.metadata,\n lastSeenAt: device.lastSeenAt,\n status: device.status,\n revokedAt: device.revokedAt,\n createdAt: device.createdAt,\n updatedAt: device.updatedAt,\n };\n}\n\nexport async function createRemoteDevice(input: {\n ownerEmail: string;\n orgId?: string | null;\n label: string;\n platform?: string | null;\n appVersion?: string | null;\n hostName?: string | null;\n metadata?: Record<string, unknown> | null;\n}): Promise<{ device: RemoteDevice; token: string }> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const id = `remote-device-${now}-${randomHex(8)}`;\n const token = `anr_${randomHex(32)}`;\n const tokenHash = await hashRemoteDeviceToken(token);\n\n await client.execute({\n sql: `INSERT INTO integration_remote_devices\n (id, owner_email, org_id, label, platform, app_version, host_name, metadata_json,\n device_token_hash, last_seen_at, status, revoked_at, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n args: [\n id,\n input.ownerEmail,\n input.orgId ?? null,\n input.label.trim() || \"Remote device\",\n sanitizeOptionalString(input.platform, 80),\n sanitizeOptionalString(input.appVersion, 120),\n sanitizeOptionalString(input.hostName, 200),\n input.metadata ? JSON.stringify(input.metadata) : null,\n tokenHash,\n now,\n \"active\",\n null,\n now,\n now,\n ],\n });\n\n const device = await getRemoteDevice(id);\n if (!device) throw new Error(\"remote device insert failed\");\n return { device, token };\n}\n\nexport async function getRemoteDevice(\n id: string,\n): Promise<RemoteDevice | null> {\n await ensureTable();\n const { rows } = await getDbExec().execute({\n sql: `SELECT * FROM integration_remote_devices WHERE id = ? LIMIT 1`,\n args: [id],\n });\n return rows[0] ? rowToDevice(rows[0] as Record<string, unknown>) : null;\n}\n\nexport async function getRemoteDeviceForOwner(input: {\n id: string;\n ownerEmail: string;\n orgId?: string | null;\n}): Promise<RemoteDevice | null> {\n await ensureTable();\n const { rows } = await getDbExec().execute({\n sql: `SELECT * FROM integration_remote_devices\n WHERE id = ?\n AND owner_email = ?\n AND ((org_id IS NULL AND ? IS NULL) OR org_id = ?)\n LIMIT 1`,\n args: [\n input.id,\n input.ownerEmail,\n input.orgId ?? null,\n input.orgId ?? null,\n ],\n });\n return rows[0] ? rowToDevice(rows[0] as Record<string, unknown>) : null;\n}\n\nexport async function listRemoteDevicesForOwner(input: {\n ownerEmail: string;\n orgId?: string | null;\n status?: RemoteDevice[\"status\"];\n limit?: number;\n}): Promise<RemoteDevice[]> {\n await ensureTable();\n const limit = Math.max(1, Math.min(input.limit ?? 50, 100));\n const statusClause = input.status ? \" AND status = ?\" : \"\";\n if (!Object.prototype.hasOwnProperty.call(input, \"orgId\")) {\n const args: Array<string | number> = [input.ownerEmail];\n if (input.status) args.push(input.status);\n args.push(limit);\n const { rows } = await getDbExec().execute({\n sql: `SELECT * FROM integration_remote_devices\n WHERE owner_email = ?${statusClause}\n ORDER BY COALESCE(last_seen_at, updated_at) DESC\n LIMIT ?`,\n args,\n });\n return rows.map((row) => rowToDevice(row as Record<string, unknown>));\n }\n const args: Array<string | number | null> = [\n input.ownerEmail,\n input.orgId ?? null,\n input.orgId ?? null,\n ];\n if (input.status) args.push(input.status);\n args.push(limit);\n const { rows } = await getDbExec().execute({\n sql: `SELECT * FROM integration_remote_devices\n WHERE owner_email = ?\n AND ((org_id IS NULL AND ? IS NULL) OR org_id = ?)${statusClause}\n ORDER BY COALESCE(last_seen_at, updated_at) DESC\n LIMIT ?`,\n args,\n });\n return rows.map((row) => rowToDevice(row as Record<string, unknown>));\n}\n\nexport async function authenticateRemoteDeviceToken(\n rawToken: string | null | undefined,\n): Promise<RemoteDevice | null> {\n if (!rawToken) return null;\n await ensureTable();\n const tokenHash = await hashRemoteDeviceToken(rawToken);\n const now = Date.now();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT * FROM integration_remote_devices\n WHERE device_token_hash = ? AND status = 'active'\n LIMIT 1`,\n args: [tokenHash],\n });\n if (!rows[0]) return null;\n const device = rowToDevice(rows[0] as Record<string, unknown>);\n await client.execute({\n sql: `UPDATE integration_remote_devices\n SET last_seen_at = ?, updated_at = ?\n WHERE id = ?`,\n args: [now, now, device.id],\n });\n return { ...device, lastSeenAt: now, updatedAt: now };\n}\n\nexport async function updateRemoteDeviceDetails(input: {\n id: string;\n label?: string | null;\n platform?: string | null;\n appVersion?: string | null;\n hostName?: string | null;\n metadata?: Record<string, unknown> | null;\n}): Promise<RemoteDevice | null> {\n await ensureTable();\n const now = Date.now();\n const updates: string[] = [];\n const args: Array<string | number | null> = [];\n if (input.label !== undefined) {\n updates.push(\"label = ?\");\n args.push(sanitizeOptionalString(input.label, 200) ?? \"Remote device\");\n }\n if (input.platform !== undefined) {\n updates.push(\"platform = ?\");\n args.push(sanitizeOptionalString(input.platform, 80));\n }\n if (input.appVersion !== undefined) {\n updates.push(\"app_version = ?\");\n args.push(sanitizeOptionalString(input.appVersion, 120));\n }\n if (input.hostName !== undefined) {\n updates.push(\"host_name = ?\");\n args.push(sanitizeOptionalString(input.hostName, 200));\n }\n if (input.metadata !== undefined) {\n updates.push(\"metadata_json = ?\");\n args.push(input.metadata ? JSON.stringify(input.metadata) : null);\n }\n if (updates.length === 0) return getRemoteDevice(input.id);\n\n updates.push(\"updated_at = ?\");\n args.push(now, input.id);\n await getDbExec().execute({\n sql: `UPDATE integration_remote_devices\n SET ${updates.join(\", \")}\n WHERE id = ? AND status = 'active'`,\n args,\n });\n return getRemoteDevice(input.id);\n}\n\nexport async function revokeRemoteDeviceForOwner(input: {\n id: string;\n ownerEmail: string;\n orgId?: string | null;\n}): Promise<RemoteDevice | null> {\n await ensureTable();\n const now = Date.now();\n await getDbExec().execute({\n sql: `UPDATE integration_remote_devices\n SET status = 'inactive',\n revoked_at = COALESCE(revoked_at, ?),\n updated_at = ?\n WHERE id = ?\n AND owner_email = ?\n AND ((org_id IS NULL AND ? IS NULL) OR org_id = ?)`,\n args: [\n now,\n now,\n input.id,\n input.ownerEmail,\n input.orgId ?? null,\n input.orgId ?? null,\n ],\n });\n return getRemoteDeviceForOwner(input);\n}\n\nexport async function unregisterRemoteDevice(id: string): Promise<boolean> {\n await ensureTable();\n const now = Date.now();\n const result = await getDbExec().execute({\n sql: `UPDATE integration_remote_devices\n SET status = 'inactive',\n revoked_at = COALESCE(revoked_at, ?),\n updated_at = ?\n WHERE id = ? AND status = 'active'`,\n args: [now, now, id],\n });\n return (result.rowsAffected ?? (result as any).rowCount ?? 0) > 0;\n}\n\nexport async function hashRemoteDeviceToken(token: string): Promise<string> {\n const bytes = new TextEncoder().encode(token);\n const digest = await globalThis.crypto.subtle.digest(\"SHA-256\", bytes);\n return bytesToHex(new Uint8Array(digest));\n}\n\nfunction sanitizeOptionalString(\n value: string | null | undefined,\n max: number,\n): string | null {\n if (typeof value !== \"string\") return null;\n const trimmed = value.trim();\n return trimmed ? trimmed.slice(0, max) : null;\n}\n\nfunction parseJson(value: unknown, fallback: unknown): unknown {\n if (value == null) return fallback;\n try {\n return JSON.parse(String(value));\n } catch {\n return fallback;\n }\n}\n\nfunction randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n globalThis.crypto.getRandomValues(bytes);\n return bytesToHex(bytes);\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes)\n .map((byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n"]}
|
|
1
|
+
{"version":3,"file":"remote-devices-store.js","sourceRoot":"","sources":["../../src/integrations/remote-devices-store.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,OAAO,EACP,UAAU,EACV,cAAc,GACf,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,oBAAoB,CAAC;AAG5B,IAAI,YAAuC,CAAC;AAE5C,KAAK,UAAU,WAAW;IACxB,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,YAAY,GAAG,CAAC,KAAK,IAAI,EAAE;YACzB,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;YAC3B,MAAM,SAAS,GAAG;;;;;;;;;;;yBAWC,OAAO,EAAE;;uBAEX,OAAO,EAAE;uBACT,OAAO,EAAE;uBACT,OAAO,EAAE;;OAEzB,CAAC;YAEF,IAAI,UAAU,EAAE,EAAE,CAAC;gBACjB,0FAA0F;gBAC1F,MAAM,iBAAiB,CAAC,4BAA4B,EAAE,SAAS,CAAC,CAAC;gBACjE,MAAM,kBAAkB,CACtB,4BAA4B,EAC5B,UAAU,EACV,+EAA+E,CAChF,CAAC;gBACF,MAA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O,QAAQ,CAAC;IACnC,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IACnC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,QAAQ,CAAC;IAClB,CAAC;AACH,CAAC;AAED,SAAS,SAAS,CAAC,UAAkB;IACnC,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,UAAU,CAAC,CAAC;IACzC,UAAU,CAAC,MAAM,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC;IACzC,OAAO,UAAU,CAAC,KAAK,CAAC,CAAC;AAC3B,CAAC;AAED,SAAS,UAAU,CAAC,KAAiB;IACnC,OAAO,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC;SACrB,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;SACjD,IAAI,CAAC,EAAE,CAAC,CAAC;AACd,CAAC","sourcesContent":["import {\n getDbExec,\n intType,\n isPostgres,\n retryOnDdlRace,\n} from \"../db/client.js\";\nimport {\n ensureColumnExists,\n ensureIndexExists,\n ensureTableExists,\n} from \"../db/ddl-guard.js\";\nimport type { PublicRemoteDevice, RemoteDevice } from \"./remote-types.js\";\n\nlet _initPromise: Promise<void> | undefined;\n\nasync function ensureTable(): Promise<void> {\n if (!_initPromise) {\n _initPromise = (async () => {\n const client = getDbExec();\n const createSql = `\n CREATE TABLE IF NOT EXISTS integration_remote_devices (\n id TEXT PRIMARY KEY,\n owner_email TEXT NOT NULL,\n org_id TEXT,\n label TEXT NOT NULL,\n platform TEXT,\n app_version TEXT,\n host_name TEXT,\n metadata_json TEXT,\n device_token_hash TEXT NOT NULL,\n last_seen_at ${intType()},\n status TEXT NOT NULL,\n revoked_at ${intType()},\n created_at ${intType()} NOT NULL,\n updated_at ${intType()} NOT NULL\n )\n `;\n\n if (isPostgres()) {\n // PG guard: probe via information_schema, only issue DDL if missing, bounded lock_timeout\n await ensureTableExists(\"integration_remote_devices\", createSql);\n await ensureColumnExists(\n \"integration_remote_devices\",\n \"platform\",\n `ALTER TABLE integration_remote_devices ADD COLUMN IF NOT EXISTS platform TEXT`,\n );\n await ensureColumnExists(\n \"integration_remote_devices\",\n \"app_version\",\n `ALTER TABLE integration_remote_devices ADD COLUMN IF NOT EXISTS app_version TEXT`,\n );\n await ensureColumnExists(\n \"integration_remote_devices\",\n \"host_name\",\n `ALTER TABLE integration_remote_devices ADD COLUMN IF NOT EXISTS host_name TEXT`,\n );\n await ensureColumnExists(\n \"integration_remote_devices\",\n \"metadata_json\",\n `ALTER TABLE integration_remote_devices ADD COLUMN IF NOT EXISTS metadata_json TEXT`,\n );\n await ensureColumnExists(\n \"integration_remote_devices\",\n \"revoked_at\",\n `ALTER TABLE integration_remote_devices ADD COLUMN IF NOT EXISTS revoked_at ${intType()}`,\n );\n await ensureIndexExists(\n \"idx_remote_devices_token_hash\",\n `CREATE UNIQUE INDEX IF NOT EXISTS idx_remote_devices_token_hash ON integration_remote_devices(device_token_hash)`,\n );\n await ensureIndexExists(\n \"idx_remote_devices_owner\",\n `CREATE INDEX IF NOT EXISTS idx_remote_devices_owner ON integration_remote_devices(owner_email, org_id)`,\n );\n return;\n }\n // SQLite (local dev): keep existing behavior verbatim\n await retryOnDdlRace(() => client.execute(createSql));\n await addColumnIfMissing(\"platform\", \"TEXT\");\n await addColumnIfMissing(\"app_version\", \"TEXT\");\n await addColumnIfMissing(\"host_name\", \"TEXT\");\n await addColumnIfMissing(\"metadata_json\", \"TEXT\");\n await addColumnIfMissing(\"revoked_at\", intType());\n await retryOnDdlRace(() =>\n client.execute(\n `CREATE UNIQUE INDEX IF NOT EXISTS idx_remote_devices_token_hash ON integration_remote_devices(device_token_hash)`,\n ),\n );\n await retryOnDdlRace(() =>\n client.execute(\n `CREATE INDEX IF NOT EXISTS idx_remote_devices_owner ON integration_remote_devices(owner_email, org_id)`,\n ),\n );\n })().catch((err) => {\n // Retry init on the next call after a failed startup.\n _initPromise = undefined;\n throw err;\n });\n }\n return _initPromise;\n}\n\nasync function addColumnIfMissing(\n name: string,\n definition: string,\n): Promise<void> {\n const sql = isPostgres()\n ? `ALTER TABLE integration_remote_devices ADD COLUMN IF NOT EXISTS ${name} ${definition}`\n : `ALTER TABLE integration_remote_devices ADD COLUMN ${name} ${definition}`;\n try {\n await retryOnDdlRace(() => getDbExec().execute(sql));\n } catch (err) {\n if (isDuplicateColumnError(err)) return;\n throw err;\n }\n}\n\nfunction isDuplicateColumnError(err: unknown): boolean {\n const code = String((err as { code?: unknown })?.code ?? \"\");\n const message = String((err as { message?: unknown })?.message ?? err)\n .toLowerCase()\n .trim();\n return (\n code === \"42701\" ||\n message.includes(\"duplicate column\") ||\n message.includes(\"already exists\")\n );\n}\n\nfunction rowToDevice(row: Record<string, unknown>): RemoteDevice {\n return {\n id: row.id as string,\n ownerEmail: row.owner_email as string,\n orgId: (row.org_id as string | null) ?? null,\n label: row.label as string,\n platform: (row.platform as string | null) ?? null,\n appVersion: (row.app_version as string | null) ?? null,\n hostName: (row.host_name as string | null) ?? null,\n metadata: parseJson(row.metadata_json, null) as Record<\n string,\n unknown\n > | null,\n deviceTokenHash: row.device_token_hash as string,\n lastSeenAt:\n row.last_seen_at == null ? null : Number(row.last_seen_at as number),\n status: row.status as RemoteDevice[\"status\"],\n revokedAt: row.revoked_at == null ? null : Number(row.revoked_at as number),\n createdAt: Number(row.created_at ?? 0),\n updatedAt: Number(row.updated_at ?? 0),\n };\n}\n\nexport function toPublicRemoteDevice(device: RemoteDevice): PublicRemoteDevice {\n return {\n id: device.id,\n ownerEmail: device.ownerEmail,\n orgId: device.orgId,\n label: device.label,\n platform: device.platform,\n appVersion: device.appVersion,\n hostName: device.hostName,\n metadata: device.metadata,\n lastSeenAt: device.lastSeenAt,\n status: device.status,\n revokedAt: device.revokedAt,\n createdAt: device.createdAt,\n updatedAt: device.updatedAt,\n };\n}\n\nexport async function createRemoteDevice(input: {\n ownerEmail: string;\n orgId?: string | null;\n label: string;\n platform?: string | null;\n appVersion?: string | null;\n hostName?: string | null;\n metadata?: Record<string, unknown> | null;\n}): Promise<{ device: RemoteDevice; token: string }> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const id = `remote-device-${now}-${randomHex(8)}`;\n const token = `anr_${randomHex(32)}`;\n const tokenHash = await hashRemoteDeviceToken(token);\n\n await client.execute({\n sql: `INSERT INTO integration_remote_devices\n (id, owner_email, org_id, label, platform, app_version, host_name, metadata_json,\n device_token_hash, last_seen_at, status, revoked_at, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n args: [\n id,\n input.ownerEmail,\n input.orgId ?? null,\n input.label.trim() || \"Remote device\",\n sanitizeOptionalString(input.platform, 80),\n sanitizeOptionalString(input.appVersion, 120),\n sanitizeOptionalString(input.hostName, 200),\n input.metadata ? JSON.stringify(input.metadata) : null,\n tokenHash,\n now,\n \"active\",\n null,\n now,\n now,\n ],\n });\n\n const device = await getRemoteDevice(id);\n if (!device) throw new Error(\"remote device insert failed\");\n return { device, token };\n}\n\nexport async function getRemoteDevice(\n id: string,\n): Promise<RemoteDevice | null> {\n await ensureTable();\n const { rows } = await getDbExec().execute({\n sql: `SELECT * FROM integration_remote_devices WHERE id = ? LIMIT 1`,\n args: [id],\n });\n return rows[0] ? rowToDevice(rows[0] as Record<string, unknown>) : null;\n}\n\nexport async function getRemoteDeviceForOwner(input: {\n id: string;\n ownerEmail: string;\n orgId?: string | null;\n}): Promise<RemoteDevice | null> {\n await ensureTable();\n const { rows } = await getDbExec().execute({\n sql: `SELECT * FROM integration_remote_devices\n WHERE id = ?\n AND owner_email = ?\n AND ((org_id IS NULL AND ? IS NULL) OR org_id = ?)\n LIMIT 1`,\n args: [\n input.id,\n input.ownerEmail,\n input.orgId ?? null,\n input.orgId ?? null,\n ],\n });\n return rows[0] ? rowToDevice(rows[0] as Record<string, unknown>) : null;\n}\n\nexport async function listRemoteDevicesForOwner(input: {\n ownerEmail: string;\n orgId?: string | null;\n status?: RemoteDevice[\"status\"];\n limit?: number;\n}): Promise<RemoteDevice[]> {\n await ensureTable();\n const limit = Math.max(1, Math.min(input.limit ?? 50, 100));\n const statusClause = input.status ? \" AND status = ?\" : \"\";\n if (!Object.prototype.hasOwnProperty.call(input, \"orgId\")) {\n const args: Array<string | number> = [input.ownerEmail];\n if (input.status) args.push(input.status);\n args.push(limit);\n const { rows } = await getDbExec().execute({\n sql: `SELECT * FROM integration_remote_devices\n WHERE owner_email = ?${statusClause}\n ORDER BY COALESCE(last_seen_at, updated_at) DESC\n LIMIT ?`,\n args,\n });\n return rows.map((row) => rowToDevice(row as Record<string, unknown>));\n }\n const args: Array<string | number | null> = [\n input.ownerEmail,\n input.orgId ?? null,\n input.orgId ?? null,\n ];\n if (input.status) args.push(input.status);\n args.push(limit);\n const { rows } = await getDbExec().execute({\n sql: `SELECT * FROM integration_remote_devices\n WHERE owner_email = ?\n AND ((org_id IS NULL AND ? IS NULL) OR org_id = ?)${statusClause}\n ORDER BY COALESCE(last_seen_at, updated_at) DESC\n LIMIT ?`,\n args,\n });\n return rows.map((row) => rowToDevice(row as Record<string, unknown>));\n}\n\nexport async function authenticateRemoteDeviceToken(\n rawToken: string | null | undefined,\n): Promise<RemoteDevice | null> {\n if (!rawToken) return null;\n await ensureTable();\n const tokenHash = await hashRemoteDeviceToken(rawToken);\n const now = Date.now();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT * FROM integration_remote_devices\n WHERE device_token_hash = ? AND status = 'active'\n LIMIT 1`,\n args: [tokenHash],\n });\n if (!rows[0]) return null;\n const device = rowToDevice(rows[0] as Record<string, unknown>);\n await client.execute({\n sql: `UPDATE integration_remote_devices\n SET last_seen_at = ?, updated_at = ?\n WHERE id = ?`,\n args: [now, now, device.id],\n });\n return { ...device, lastSeenAt: now, updatedAt: now };\n}\n\nexport async function updateRemoteDeviceDetails(input: {\n id: string;\n label?: string | null;\n platform?: string | null;\n appVersion?: string | null;\n hostName?: string | null;\n metadata?: Record<string, unknown> | null;\n}): Promise<RemoteDevice | null> {\n await ensureTable();\n const now = Date.now();\n const updates: string[] = [];\n const args: Array<string | number | null> = [];\n if (input.label !== undefined) {\n updates.push(\"label = ?\");\n args.push(sanitizeOptionalString(input.label, 200) ?? \"Remote device\");\n }\n if (input.platform !== undefined) {\n updates.push(\"platform = ?\");\n args.push(sanitizeOptionalString(input.platform, 80));\n }\n if (input.appVersion !== undefined) {\n updates.push(\"app_version = ?\");\n args.push(sanitizeOptionalString(input.appVersion, 120));\n }\n if (input.hostName !== undefined) {\n updates.push(\"host_name = ?\");\n args.push(sanitizeOptionalString(input.hostName, 200));\n }\n if (input.metadata !== undefined) {\n updates.push(\"metadata_json = ?\");\n args.push(input.metadata ? JSON.stringify(input.metadata) : null);\n }\n if (updates.length === 0) return getRemoteDevice(input.id);\n\n updates.push(\"updated_at = ?\");\n args.push(now, input.id);\n await getDbExec().execute({\n sql: `UPDATE integration_remote_devices\n SET ${updates.join(\", \")}\n WHERE id = ? AND status = 'active'`,\n args,\n });\n return getRemoteDevice(input.id);\n}\n\nexport async function revokeRemoteDeviceForOwner(input: {\n id: string;\n ownerEmail: string;\n orgId?: string | null;\n}): Promise<RemoteDevice | null> {\n await ensureTable();\n const now = Date.now();\n await getDbExec().execute({\n sql: `UPDATE integration_remote_devices\n SET status = 'inactive',\n revoked_at = COALESCE(revoked_at, ?),\n updated_at = ?\n WHERE id = ?\n AND owner_email = ?\n AND ((org_id IS NULL AND ? IS NULL) OR org_id = ?)`,\n args: [\n now,\n now,\n input.id,\n input.ownerEmail,\n input.orgId ?? null,\n input.orgId ?? null,\n ],\n });\n return getRemoteDeviceForOwner(input);\n}\n\nexport async function unregisterRemoteDevice(id: string): Promise<boolean> {\n await ensureTable();\n const now = Date.now();\n const result = await getDbExec().execute({\n sql: `UPDATE integration_remote_devices\n SET status = 'inactive',\n revoked_at = COALESCE(revoked_at, ?),\n updated_at = ?\n WHERE id = ? AND status = 'active'`,\n args: [now, now, id],\n });\n return (result.rowsAffected ?? (result as any).rowCount ?? 0) > 0;\n}\n\nexport async function hashRemoteDeviceToken(token: string): Promise<string> {\n const bytes = new TextEncoder().encode(token);\n const digest = await globalThis.crypto.subtle.digest(\"SHA-256\", bytes);\n return bytesToHex(new Uint8Array(digest));\n}\n\nfunction sanitizeOptionalString(\n value: string | null | undefined,\n max: number,\n): string | null {\n if (typeof value !== \"string\") return null;\n const trimmed = value.trim();\n return trimmed ? trimmed.slice(0, max) : null;\n}\n\nfunction parseJson(value: unknown, fallback: unknown): unknown {\n if (value == null) return fallback;\n try {\n return JSON.parse(String(value));\n } catch {\n return fallback;\n }\n}\n\nfunction randomHex(byteLength: number): string {\n const bytes = new Uint8Array(byteLength);\n globalThis.crypto.getRandomValues(bytes);\n return bytesToHex(bytes);\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes)\n .map((byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remote-push-store.d.ts","sourceRoot":"","sources":["../../src/integrations/remote-push-store.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"remote-push-store.d.ts","sourceRoot":"","sources":["../../src/integrations/remote-push-store.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EACV,4BAA4B,EAC5B,sBAAsB,EACtB,sBAAsB,EACvB,MAAM,mBAAmB,CAAC;AA0I3B,wBAAgB,8BAA8B,CAC5C,YAAY,EAAE,sBAAsB,GACnC,4BAA4B,CAc9B;AAED,wBAAsB,4BAA4B,CAAC,KAAK,EAAE;IACxD,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,C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