@inkeep/agents-core 0.59.4 → 0.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/dist/auth/auth-schema.d.ts +86 -86
  2. package/dist/auth/auth-validation-schemas.d.ts +154 -154
  3. package/dist/auth/auth.d.ts +6 -6
  4. package/dist/auth/permissions.d.ts +13 -13
  5. package/dist/client-exports.d.ts +2 -2
  6. package/dist/client-exports.js +2 -2
  7. package/dist/constants/context-breakdown.js +5 -0
  8. package/dist/constants/otel-attributes.d.ts +25 -1
  9. package/dist/constants/otel-attributes.js +25 -1
  10. package/dist/data-access/manage/agentFull.js +5 -5
  11. package/dist/data-access/manage/agents.d.ts +31 -31
  12. package/dist/data-access/manage/artifactComponents.d.ts +14 -14
  13. package/dist/data-access/manage/contextConfigs.d.ts +8 -8
  14. package/dist/data-access/manage/dataComponents.d.ts +6 -6
  15. package/dist/data-access/manage/functionTools.d.ts +14 -14
  16. package/dist/data-access/manage/functionTools.js +2 -2
  17. package/dist/data-access/manage/skills.d.ts +13 -13
  18. package/dist/data-access/manage/skills.js +2 -3
  19. package/dist/data-access/manage/subAgentExternalAgentRelations.d.ts +18 -18
  20. package/dist/data-access/manage/subAgentExternalAgentRelations.js +2 -2
  21. package/dist/data-access/manage/subAgentRelations.d.ts +20 -20
  22. package/dist/data-access/manage/subAgentRelations.js +2 -2
  23. package/dist/data-access/manage/subAgentTeamAgentRelations.d.ts +18 -18
  24. package/dist/data-access/manage/subAgentTeamAgentRelations.js +2 -2
  25. package/dist/data-access/manage/subAgents.d.ts +21 -21
  26. package/dist/data-access/manage/tools.d.ts +18 -18
  27. package/dist/data-access/manage/tools.js +2 -2
  28. package/dist/data-access/manage/triggers.d.ts +2 -2
  29. package/dist/data-access/runtime/apiKeys.d.ts +16 -16
  30. package/dist/data-access/runtime/apps.d.ts +13 -10
  31. package/dist/data-access/runtime/conversations.d.ts +18 -18
  32. package/dist/data-access/runtime/conversations.js +17 -1
  33. package/dist/data-access/runtime/messages.d.ts +27 -27
  34. package/dist/data-access/runtime/scheduledTriggerInvocations.d.ts +3 -3
  35. package/dist/data-access/runtime/tasks.d.ts +4 -4
  36. package/dist/db/manage/manage-schema.d.ts +453 -453
  37. package/dist/db/runtime/runtime-schema.d.ts +353 -334
  38. package/dist/db/runtime/runtime-schema.js +4 -1
  39. package/dist/dolt/fk-map.d.ts +5 -0
  40. package/dist/dolt/fk-map.js +34 -0
  41. package/dist/dolt/index.d.ts +3 -2
  42. package/dist/dolt/index.js +3 -2
  43. package/dist/dolt/resolve-conflicts.d.ts +11 -1
  44. package/dist/dolt/resolve-conflicts.js +105 -47
  45. package/dist/index.d.ts +8 -5
  46. package/dist/index.js +7 -4
  47. package/dist/types/utility.d.ts +2 -0
  48. package/dist/utils/apiKeys.js +1 -1
  49. package/dist/utils/conversations.d.ts +7 -1
  50. package/dist/utils/conversations.js +10 -1
  51. package/dist/utils/error.d.ts +51 -51
  52. package/dist/utils/index.d.ts +6 -2
  53. package/dist/utils/index.js +4 -2
  54. package/dist/utils/model-factory.js +35 -10
  55. package/dist/utils/token-estimator.d.ts +19 -0
  56. package/dist/utils/token-estimator.js +17 -0
  57. package/dist/utils/usage-cost-middleware.d.ts +13 -0
  58. package/dist/utils/usage-cost-middleware.js +60 -0
  59. package/dist/utils/usage-tracker.d.ts +2 -0
  60. package/dist/utils/usage-tracker.js +1 -0
  61. package/dist/validation/drizzle-schema-helpers.d.ts +3 -3
  62. package/dist/validation/schemas.d.ts +2162 -2086
  63. package/drizzle/runtime/0025_faulty_kylun.sql +1 -0
  64. package/drizzle/runtime/meta/0025_snapshot.json +4276 -0
  65. package/drizzle/runtime/meta/_journal.json +7 -0
  66. package/package.json +1 -1
@@ -1,10 +1,12 @@
1
1
  import { __exportAll } from "../../_virtual/rolldown_runtime.js";
2
2
  import { account, deviceCode, invitation, member, organization, session, ssoProvider, user, verification } from "../../auth/auth-schema.js";
3
+ import { USAGE_GENERATION_TYPES } from "../../constants/otel-attributes.js";
3
4
  import { relations } from "drizzle-orm";
4
5
  import { boolean, foreignKey, index, integer, jsonb, pgTable, primaryKey, text, timestamp, unique, uniqueIndex, varchar } from "drizzle-orm/pg-core";
5
6
 
6
7
  //#region src/db/runtime/runtime-schema.ts
7
8
  var runtime_schema_exports = /* @__PURE__ */ __exportAll({
9
+ USAGE_GENERATION_TYPES: () => USAGE_GENERATION_TYPES,
8
10
  account: () => account,
9
11
  apiKeys: () => apiKeys,
10
12
  apps: () => apps,
@@ -150,6 +152,7 @@ const apps = pgTable("apps", {
150
152
  type: varchar("type", { length: 64 }).$type().notNull(),
151
153
  defaultProjectId: varchar("default_project_id", { length: 256 }),
152
154
  defaultAgentId: varchar("default_agent_id", { length: 256 }),
155
+ prompt: text("prompt"),
153
156
  enabled: boolean("enabled").notNull().default(true),
154
157
  config: jsonb("config").$type().notNull(),
155
158
  lastUsedAt: timestamp("last_used_at", { mode: "string" }),
@@ -822,4 +825,4 @@ const workAppSlackMcpToolAccessConfig = pgTable("work_app_slack_mcp_tool_access_
822
825
  ]);
823
826
 
824
827
  //#endregion
825
- export { account, apiKeys, apps, contextCache, conversations, conversationsRelations, datasetRun, datasetRunConversationRelations, deviceCode, evaluationResult, evaluationRun, invitation, ledgerArtifacts, ledgerArtifactsRelations, member, messages, messagesRelations, organization, projectMetadata, runtime_schema_exports, scheduledTriggerInvocations, session, ssoProvider, taskRelations, taskRelationsRelations, tasks, tasksRelations, triggerInvocations, user, userProfile, userProfileRelations, verification, workAppGitHubInstallations, workAppGitHubInstallationsRelations, workAppGitHubMcpToolAccessMode, workAppGitHubMcpToolRepositoryAccess, workAppGitHubMcpToolRepositoryAccessRelations, workAppGitHubProjectAccessMode, workAppGitHubProjectRepositoryAccess, workAppGitHubProjectRepositoryAccessRelations, workAppGitHubRepositories, workAppGitHubRepositoriesRelations, workAppSlackChannelAgentConfigs, workAppSlackMcpToolAccessConfig, workAppSlackUserMappings, workAppSlackWorkspaces };
828
+ export { USAGE_GENERATION_TYPES, account, apiKeys, apps, contextCache, conversations, conversationsRelations, datasetRun, datasetRunConversationRelations, deviceCode, evaluationResult, evaluationRun, invitation, ledgerArtifacts, ledgerArtifactsRelations, member, messages, messagesRelations, organization, projectMetadata, runtime_schema_exports, scheduledTriggerInvocations, session, ssoProvider, taskRelations, taskRelationsRelations, tasks, tasksRelations, triggerInvocations, user, userProfile, userProfileRelations, verification, workAppGitHubInstallations, workAppGitHubInstallationsRelations, workAppGitHubMcpToolAccessMode, workAppGitHubMcpToolRepositoryAccess, workAppGitHubMcpToolRepositoryAccessRelations, workAppGitHubProjectAccessMode, workAppGitHubProjectRepositoryAccess, workAppGitHubProjectRepositoryAccessRelations, workAppGitHubRepositories, workAppGitHubRepositoriesRelations, workAppSlackChannelAgentConfigs, workAppSlackMcpToolAccessConfig, workAppSlackUserMappings, workAppSlackWorkspaces };
@@ -0,0 +1,5 @@
1
+ //#region src/dolt/fk-map.d.ts
2
+ type FkDeps = Record<string, string[]>;
3
+ declare const manageFkDeps: FkDeps;
4
+ //#endregion
5
+ export { FkDeps, manageFkDeps };
@@ -0,0 +1,34 @@
1
+ import { manage_schema_exports } from "../db/manage/manage-schema.js";
2
+ import { getTableConfig } from "drizzle-orm/pg-core";
3
+
4
+ //#region src/dolt/fk-map.ts
5
+ function buildFkDepsFromSchema() {
6
+ const deps = {};
7
+ for (const value of Object.values(manage_schema_exports)) {
8
+ if (value == null || typeof value !== "object") continue;
9
+ let config;
10
+ try {
11
+ config = getTableConfig(value);
12
+ } catch {
13
+ continue;
14
+ }
15
+ if (!config?.name) continue;
16
+ const tableDeps = /* @__PURE__ */ new Set();
17
+ for (const fk of config.foreignKeys ?? []) {
18
+ const ref = fk.reference();
19
+ let refName;
20
+ try {
21
+ refName = getTableConfig(ref.foreignTable).name;
22
+ } catch {
23
+ continue;
24
+ }
25
+ if (refName && refName !== config.name) tableDeps.add(refName);
26
+ }
27
+ if (tableDeps.size > 0) deps[config.name] = [...tableDeps];
28
+ }
29
+ return deps;
30
+ }
31
+ const manageFkDeps = buildFkDepsFromSchema();
32
+
33
+ //#endregion
34
+ export { manageFkDeps };
@@ -3,11 +3,12 @@ import { branchScopes, doltActiveBranch, doltBranch, doltBranchExists, doltCheck
3
3
  import { CheckoutBranchParams, CheckoutBranchResult, CreateBranchParams, DeleteBranchParams, GetBranchParams, MAIN_BRANCH_SUFFIX, checkoutBranch, createBranch, deleteBranch, getBranch, getTempBranchSuffix, getTenantMainBranch, invalidBranchParamsError, isProtectedBranchName, isTempBranchName, listBranches, listBranchesForAgent, syncSchemaOnBranch } from "./branches-api.js";
4
4
  import { doltAdd, doltAddAndCommit, doltCommit, doltDeleteTag, doltHashOf, doltListTags, doltLog, doltReset, doltStatus, doltTag } from "./commit.js";
5
5
  import { doltDiff, doltDiffSummary } from "./diff.js";
6
+ import { FkDeps, manageFkDeps } from "./fk-map.js";
6
7
  import { MergeConflictError, doltAbortMerge, doltConflicts, doltMerge, doltMergeStatus, doltPreviewMergeConflicts, doltPreviewMergeConflictsSummary, doltResolveConflicts, doltSchemaConflicts, doltTableConflicts } from "./merge.js";
7
8
  import { PkMap, isValidManageTable, managePkMap } from "./pk-map.js";
8
9
  import { RefType, checkoutRef, getCurrentBranchOrCommit, getProjectMainResolvedRef, getProjectScopedRef, getTenantScopedRef, isRefWritable, isValidCommitHash, resolveProjectMainRefs, resolveRef } from "./ref-helpers.js";
9
10
  import { RefContext, RefMiddlewareOptions, createRefMiddleware, createWriteProtectionMiddleware, isMergeRoute, refMiddlewareFactory, writeProtectionMiddlewareFactory } from "./ref-middleware.js";
10
11
  import { NestedRefScopeError, WithRefOptions, getCurrentRefScope, getRefScopedDb, isInRefScope, withRef } from "./ref-scope.js";
11
- import { ResolutionValidationError, applyResolutions } from "./resolve-conflicts.js";
12
+ import { ResolutionValidationError, applyResolutions, computeTableInsertOrder, sortByFkDependencyOrder } from "./resolve-conflicts.js";
12
13
  import { EnsureSchemaSyncOptions, SCHEMA_SOURCE_BRANCH, SchemaDiff, SchemaSyncOptions, SchemaSyncResult, areBranchesSchemaCompatible, ensureSchemaSync, formatSchemaDiffSummary, getActiveBranch, getSchemaDiff, hasSchemaDifferences, hasUncommittedChanges, isLocalhostUrl, syncSchemaFromMain } from "./schema-sync.js";
13
- export { CheckoutBranchParams, CheckoutBranchResult, CreateBranchParams, DeleteBranchParams, EnsureSchemaSyncOptions, GetBranchParams, MAIN_BRANCH_SUFFIX, MergeConflictError, NestedRefScopeError, PkMap, RefContext, RefMiddlewareOptions, RefType, ResolutionValidationError, SCHEMA_SOURCE_BRANCH, SchemaDiff, SchemaSyncOptions, SchemaSyncResult, WithRefOptions, applyResolutions, areBranchesSchemaCompatible, branchScopes, checkoutBranch, checkoutRef, createBranch, createRefMiddleware, createWriteProtectionMiddleware, deleteBranch, doltAbortMerge, doltActiveBranch, doltAdd, doltAddAndCommit, doltBranch, doltBranchExists, doltCheckout, doltCommit, doltConflicts, doltDeleteBranch, doltDeleteTag, doltDiff, doltDiffSummary, doltGetBranchNamespace, doltHashOf, doltListBranches, doltListTags, doltLog, doltMerge, doltMergeStatus, doltPreviewMergeConflicts, doltPreviewMergeConflictsSummary, doltRenameBranch, doltReset, doltResolveConflicts, doltSchemaConflicts, doltStatus, doltTableConflicts, doltTag, ensureBranchExists, ensureSchemaSync, formatSchemaDiffSummary, getActiveBranch, getBranch, getCurrentBranchOrCommit, getCurrentRefScope, getProjectMainResolvedRef, getProjectScopedRef, getRefScopedDb, getSchemaDiff, getTempBranchSuffix, getTenantMainBranch, getTenantScopedRef, hasSchemaDifferences, hasUncommittedChanges, invalidBranchParamsError, isInRefScope, isLocalhostUrl, isMergeRoute, isProtectedBranchName, isRefWritable, isTempBranchName, isValidCommitHash, isValidManageTable, listBranches, listBranchesForAgent, managePkMap, refMiddlewareFactory, releaseAdvisoryLock, resolveProjectMainRefs, resolveRef, syncSchemaFromMain, syncSchemaOnBranch, tryAdvisoryLock, withRef, writeProtectionMiddlewareFactory };
14
+ export { CheckoutBranchParams, CheckoutBranchResult, CreateBranchParams, DeleteBranchParams, EnsureSchemaSyncOptions, FkDeps, GetBranchParams, MAIN_BRANCH_SUFFIX, MergeConflictError, NestedRefScopeError, PkMap, RefContext, RefMiddlewareOptions, RefType, ResolutionValidationError, SCHEMA_SOURCE_BRANCH, SchemaDiff, SchemaSyncOptions, SchemaSyncResult, WithRefOptions, applyResolutions, areBranchesSchemaCompatible, branchScopes, checkoutBranch, checkoutRef, computeTableInsertOrder, createBranch, createRefMiddleware, createWriteProtectionMiddleware, deleteBranch, doltAbortMerge, doltActiveBranch, doltAdd, doltAddAndCommit, doltBranch, doltBranchExists, doltCheckout, doltCommit, doltConflicts, doltDeleteBranch, doltDeleteTag, doltDiff, doltDiffSummary, doltGetBranchNamespace, doltHashOf, doltListBranches, doltListTags, doltLog, doltMerge, doltMergeStatus, doltPreviewMergeConflicts, doltPreviewMergeConflictsSummary, doltRenameBranch, doltReset, doltResolveConflicts, doltSchemaConflicts, doltStatus, doltTableConflicts, doltTag, ensureBranchExists, ensureSchemaSync, formatSchemaDiffSummary, getActiveBranch, getBranch, getCurrentBranchOrCommit, getCurrentRefScope, getProjectMainResolvedRef, getProjectScopedRef, getRefScopedDb, getSchemaDiff, getTempBranchSuffix, getTenantMainBranch, getTenantScopedRef, hasSchemaDifferences, hasUncommittedChanges, invalidBranchParamsError, isInRefScope, isLocalhostUrl, isMergeRoute, isProtectedBranchName, isRefWritable, isTempBranchName, isValidCommitHash, isValidManageTable, listBranches, listBranchesForAgent, manageFkDeps, managePkMap, refMiddlewareFactory, releaseAdvisoryLock, resolveProjectMainRefs, resolveRef, sortByFkDependencyOrder, syncSchemaFromMain, syncSchemaOnBranch, tryAdvisoryLock, withRef, writeProtectionMiddlewareFactory };
@@ -1,6 +1,7 @@
1
1
  import { doltAdd, doltAddAndCommit, doltCommit, doltDeleteTag, doltHashOf, doltListTags, doltLog, doltReset, doltStatus, doltTag } from "./commit.js";
2
2
  import { isValidManageTable, managePkMap } from "./pk-map.js";
3
- import { ResolutionValidationError, applyResolutions } from "./resolve-conflicts.js";
3
+ import { manageFkDeps } from "./fk-map.js";
4
+ import { ResolutionValidationError, applyResolutions, computeTableInsertOrder, sortByFkDependencyOrder } from "./resolve-conflicts.js";
4
5
  import { MergeConflictError, doltAbortMerge, doltConflicts, doltMerge, doltMergeStatus, doltPreviewMergeConflicts, doltPreviewMergeConflictsSummary, doltResolveConflicts, doltSchemaConflicts, doltTableConflicts } from "./merge.js";
5
6
  import { SCHEMA_SOURCE_BRANCH, areBranchesSchemaCompatible, ensureSchemaSync, formatSchemaDiffSummary, getActiveBranch, getSchemaDiff, hasSchemaDifferences, hasUncommittedChanges, isLocalhostUrl, syncSchemaFromMain } from "./schema-sync.js";
6
7
  import { MAIN_BRANCH_SUFFIX, checkoutBranch, createBranch, deleteBranch, getBranch, getTempBranchSuffix, getTenantMainBranch, invalidBranchParamsError, isProtectedBranchName, isTempBranchName, listBranches, listBranchesForAgent, syncSchemaOnBranch } from "./branches-api.js";
@@ -11,4 +12,4 @@ import { doltDiff, doltDiffSummary } from "./diff.js";
11
12
  import { createRefMiddleware, createWriteProtectionMiddleware, isMergeRoute, refMiddlewareFactory, writeProtectionMiddlewareFactory } from "./ref-middleware.js";
12
13
  import { NestedRefScopeError, getCurrentRefScope, getRefScopedDb, isInRefScope, withRef } from "./ref-scope.js";
13
14
 
14
- export { MAIN_BRANCH_SUFFIX, MergeConflictError, NestedRefScopeError, ResolutionValidationError, SCHEMA_SOURCE_BRANCH, applyResolutions, areBranchesSchemaCompatible, checkoutBranch, checkoutRef, createBranch, createRefMiddleware, createWriteProtectionMiddleware, deleteBranch, doltAbortMerge, doltActiveBranch, doltAdd, doltAddAndCommit, doltBranch, doltBranchExists, doltCheckout, doltCommit, doltConflicts, doltDeleteBranch, doltDeleteTag, doltDiff, doltDiffSummary, doltGetBranchNamespace, doltHashOf, doltListBranches, doltListTags, doltLog, doltMerge, doltMergeStatus, doltPreviewMergeConflicts, doltPreviewMergeConflictsSummary, doltRenameBranch, doltReset, doltResolveConflicts, doltSchemaConflicts, doltStatus, doltTableConflicts, doltTag, ensureBranchExists, ensureSchemaSync, formatSchemaDiffSummary, getActiveBranch, getBranch, getCurrentBranchOrCommit, getCurrentRefScope, getProjectMainResolvedRef, getProjectScopedRef, getRefScopedDb, getSchemaDiff, getTempBranchSuffix, getTenantMainBranch, getTenantScopedRef, hasSchemaDifferences, hasUncommittedChanges, invalidBranchParamsError, isInRefScope, isLocalhostUrl, isMergeRoute, isProtectedBranchName, isRefWritable, isTempBranchName, isValidCommitHash, isValidManageTable, listBranches, listBranchesForAgent, managePkMap, refMiddlewareFactory, releaseAdvisoryLock, resolveProjectMainRefs, resolveRef, syncSchemaFromMain, syncSchemaOnBranch, tryAdvisoryLock, withRef, writeProtectionMiddlewareFactory };
15
+ export { MAIN_BRANCH_SUFFIX, MergeConflictError, NestedRefScopeError, ResolutionValidationError, SCHEMA_SOURCE_BRANCH, applyResolutions, areBranchesSchemaCompatible, checkoutBranch, checkoutRef, computeTableInsertOrder, createBranch, createRefMiddleware, createWriteProtectionMiddleware, deleteBranch, doltAbortMerge, doltActiveBranch, doltAdd, doltAddAndCommit, doltBranch, doltBranchExists, doltCheckout, doltCommit, doltConflicts, doltDeleteBranch, doltDeleteTag, doltDiff, doltDiffSummary, doltGetBranchNamespace, doltHashOf, doltListBranches, doltListTags, doltLog, doltMerge, doltMergeStatus, doltPreviewMergeConflicts, doltPreviewMergeConflictsSummary, doltRenameBranch, doltReset, doltResolveConflicts, doltSchemaConflicts, doltStatus, doltTableConflicts, doltTag, ensureBranchExists, ensureSchemaSync, formatSchemaDiffSummary, getActiveBranch, getBranch, getCurrentBranchOrCommit, getCurrentRefScope, getProjectMainResolvedRef, getProjectScopedRef, getRefScopedDb, getSchemaDiff, getTempBranchSuffix, getTenantMainBranch, getTenantScopedRef, hasSchemaDifferences, hasUncommittedChanges, invalidBranchParamsError, isInRefScope, isLocalhostUrl, isMergeRoute, isProtectedBranchName, isRefWritable, isTempBranchName, isValidCommitHash, isValidManageTable, listBranches, listBranchesForAgent, manageFkDeps, managePkMap, refMiddlewareFactory, releaseAdvisoryLock, resolveProjectMainRefs, resolveRef, sortByFkDependencyOrder, syncSchemaFromMain, syncSchemaOnBranch, tryAdvisoryLock, withRef, writeProtectionMiddlewareFactory };
@@ -1,10 +1,20 @@
1
1
  import { ConflictResolution } from "../validation/dolt-schemas.js";
2
2
  import { AgentsManageDatabaseClient } from "../db/manage/manage-client.js";
3
+ import { FkDeps } from "./fk-map.js";
3
4
 
4
5
  //#region src/dolt/resolve-conflicts.d.ts
5
6
  declare class ResolutionValidationError extends Error {
6
7
  constructor(message: string);
7
8
  }
9
+ type OperationType = 'skip' | 'delete' | 'update' | 'insert';
10
+ interface ClassifiedResolution {
11
+ resolution: ConflictResolution;
12
+ conflictRow: Record<string, unknown>;
13
+ pkColumns: string[];
14
+ operation: OperationType;
15
+ }
16
+ declare function computeTableInsertOrder(fkDeps: FkDeps): Map<string, number>;
17
+ declare function sortByFkDependencyOrder(classified: ClassifiedResolution[]): ClassifiedResolution[];
8
18
  declare const applyResolutions: (db: AgentsManageDatabaseClient) => (resolutions: ConflictResolution[]) => Promise<void>;
9
19
  //#endregion
10
- export { ResolutionValidationError, applyResolutions };
20
+ export { ResolutionValidationError, applyResolutions, computeTableInsertOrder, sortByFkDependencyOrder };
@@ -1,4 +1,5 @@
1
1
  import { isValidManageTable, managePkMap } from "./pk-map.js";
2
+ import { manageFkDeps } from "./fk-map.js";
2
3
  import { sql } from "drizzle-orm";
3
4
 
4
5
  //#region src/dolt/resolve-conflicts.ts
@@ -13,21 +14,114 @@ function toSqlLiteral(val) {
13
14
  if (typeof val === "object") return `'${JSON.stringify(val).replace(/'/g, "''")}'`;
14
15
  return `'${String(val).replace(/'/g, "''")}'`;
15
16
  }
17
+ function classifyOperation(conflictRow, rowDefaultPick, hasColumnOverrides) {
18
+ const ourDiffType = conflictRow.our_diff_type;
19
+ const theirDiffType = conflictRow.their_diff_type;
20
+ if (rowDefaultPick === "theirs" && !hasColumnOverrides) {
21
+ if (theirDiffType === "removed") return "delete";
22
+ if (ourDiffType === "removed") return "insert";
23
+ return "update";
24
+ }
25
+ if (theirDiffType === "removed" || ourDiffType === "removed") {
26
+ if (rowDefaultPick === "ours") return "skip";
27
+ if (theirDiffType === "removed") return "delete";
28
+ if (ourDiffType === "removed") return "insert";
29
+ }
30
+ return "update";
31
+ }
32
+ function computeTableInsertOrder(fkDeps) {
33
+ const order = /* @__PURE__ */ new Map();
34
+ const visited = /* @__PURE__ */ new Set();
35
+ let counter = 0;
36
+ function visit(table) {
37
+ if (visited.has(table)) return;
38
+ visited.add(table);
39
+ for (const dep of fkDeps[table] ?? []) visit(dep);
40
+ order.set(table, counter++);
41
+ }
42
+ for (const table of Object.keys(fkDeps)) visit(table);
43
+ return order;
44
+ }
45
+ const PHASE_ORDER = {
46
+ delete: 0,
47
+ update: 1,
48
+ insert: 2,
49
+ skip: 3
50
+ };
51
+ const tableOrder = computeTableInsertOrder(manageFkDeps);
52
+ function sortByFkDependencyOrder(classified) {
53
+ return [...classified].sort((a, b) => {
54
+ const phaseA = PHASE_ORDER[a.operation];
55
+ const phaseB = PHASE_ORDER[b.operation];
56
+ if (phaseA !== phaseB) return phaseA - phaseB;
57
+ const orderA = tableOrder.get(a.resolution.table) ?? 0;
58
+ const orderB = tableOrder.get(b.resolution.table) ?? 0;
59
+ if (a.operation === "delete") return orderB - orderA;
60
+ if (a.operation === "insert") return orderA - orderB;
61
+ return 0;
62
+ });
63
+ }
16
64
  const applyResolutions = (db) => async (resolutions) => {
17
65
  const affectedTables = /* @__PURE__ */ new Set();
66
+ const classified = [];
18
67
  for (const resolution of resolutions) {
19
68
  if (!isValidManageTable(resolution.table)) throw new ResolutionValidationError(`Invalid table name: ${resolution.table}`);
20
69
  affectedTables.add(resolution.table);
21
70
  const pkColumns = managePkMap[resolution.table];
22
71
  if (!pkColumns) throw new ResolutionValidationError(`No PK columns found for table: ${resolution.table}`);
23
72
  const hasColumnOverrides = resolution.columns && Object.keys(resolution.columns).length > 0;
24
- if (resolution.rowDefaultPick === "ours" && !hasColumnOverrides) continue;
73
+ if (resolution.rowDefaultPick === "ours" && !hasColumnOverrides) {
74
+ classified.push({
75
+ resolution,
76
+ conflictRow: {},
77
+ pkColumns,
78
+ operation: "skip"
79
+ });
80
+ continue;
81
+ }
25
82
  const conflictRow = await readConflictRow(db, resolution.table, resolution.primaryKey, pkColumns);
26
83
  if (!conflictRow) throw new ResolutionValidationError(`No conflict found for table ${resolution.table} with PK ${JSON.stringify(resolution.primaryKey)}`);
27
- const ourDiffType = conflictRow.our_diff_type;
28
- const theirDiffType = conflictRow.their_diff_type;
29
- if (resolution.rowDefaultPick === "theirs" && !hasColumnOverrides) await applyTheirsResolution(db, resolution.table, resolution.primaryKey, pkColumns, conflictRow, ourDiffType, theirDiffType);
30
- else await applyMixedResolution(db, resolution.table, resolution.primaryKey, pkColumns, conflictRow, resolution.rowDefaultPick, resolution.columns ?? {});
84
+ if (hasColumnOverrides) {
85
+ const ourDiffType = conflictRow.our_diff_type;
86
+ const theirDiffType = conflictRow.their_diff_type;
87
+ if (Object.values(resolution.columns ?? {}).some((pick) => pick !== resolution.rowDefaultPick) && (ourDiffType === "removed" || theirDiffType === "removed")) {
88
+ const removedSide = ourDiffType === "removed" ? "ours" : "theirs";
89
+ throw new ResolutionValidationError(`Cannot apply column overrides for table ${resolution.table} (PK ${JSON.stringify(resolution.primaryKey)}): ${removedSide} side deleted the row`);
90
+ }
91
+ }
92
+ const operation = classifyOperation(conflictRow, resolution.rowDefaultPick, hasColumnOverrides ?? false);
93
+ classified.push({
94
+ resolution,
95
+ conflictRow,
96
+ pkColumns,
97
+ operation
98
+ });
99
+ }
100
+ const sorted = sortByFkDependencyOrder(classified);
101
+ for (const { resolution, conflictRow, pkColumns, operation } of sorted) {
102
+ if (operation === "skip") continue;
103
+ const pkWhere = buildPkWhere(pkColumns, resolution.primaryKey);
104
+ switch (operation) {
105
+ case "delete":
106
+ await db.execute(sql.raw(`DELETE FROM "${resolution.table}" WHERE ${pkWhere}`));
107
+ break;
108
+ case "insert": {
109
+ const columns = getColumnNames(conflictRow, pkColumns);
110
+ const allCols = [...pkColumns, ...columns];
111
+ const values = allCols.map((col) => {
112
+ return toSqlLiteral(pkColumns.includes(col) ? resolution.primaryKey[col] : conflictRow[`their_${col}`]);
113
+ });
114
+ await db.execute(sql.raw(`INSERT INTO "${resolution.table}" (${allCols.map((c) => `"${c}"`).join(", ")}) VALUES (${values.join(", ")})`));
115
+ break;
116
+ }
117
+ case "update": {
118
+ const setClauses = getColumnNames(conflictRow, pkColumns).map((col) => {
119
+ return `"${col}" = ${toSqlLiteral(conflictRow[`${(resolution.columns?.[col] ?? resolution.rowDefaultPick) === "theirs" ? "their_" : "our_"}${col}`])}`;
120
+ });
121
+ await db.execute(sql.raw(`UPDATE "${resolution.table}" SET ${setClauses.join(", ")} WHERE ${pkWhere}`));
122
+ break;
123
+ }
124
+ }
31
125
  }
32
126
  for (const table of affectedTables) await db.execute(sql.raw(`SELECT DOLT_CONFLICTS_RESOLVE('--ours', '${table}')`));
33
127
  };
@@ -40,6 +134,11 @@ async function readConflictRow(db, table, primaryKey, pkColumns) {
40
134
  }).join(" AND ");
41
135
  return (await db.execute(sql.raw(`SELECT * FROM dolt_conflicts_${table} WHERE ${whereClause} LIMIT 1`))).rows[0] ?? null;
42
136
  }
137
+ function buildPkWhere(pkColumns, primaryKey) {
138
+ return pkColumns.map((col) => {
139
+ return `"${col}" = '${primaryKey[col]?.replace(/'/g, "''")}'`;
140
+ }).join(" AND ");
141
+ }
43
142
  function getColumnNames(conflictRow, pkColumns) {
44
143
  const theirPrefix = "their_";
45
144
  const skipColumns = new Set([
@@ -54,47 +153,6 @@ function getColumnNames(conflictRow, pkColumns) {
54
153
  for (const key of Object.keys(conflictRow)) if (key.startsWith(theirPrefix) && !skipColumns.has(key)) columns.push(key.slice(6));
55
154
  return columns;
56
155
  }
57
- async function applyTheirsResolution(db, table, primaryKey, pkColumns, conflictRow, ourDiffType, theirDiffType) {
58
- const pkWhere = pkColumns.map((col) => {
59
- return `"${col}" = '${primaryKey[col]?.replace(/'/g, "''")}'`;
60
- }).join(" AND ");
61
- if (theirDiffType === "removed") {
62
- await db.execute(sql.raw(`DELETE FROM "${table}" WHERE ${pkWhere}`));
63
- return;
64
- }
65
- const columns = getColumnNames(conflictRow, pkColumns);
66
- if (ourDiffType === "removed") {
67
- const allCols = [...pkColumns, ...columns];
68
- const values = allCols.map((col) => {
69
- return toSqlLiteral(pkColumns.includes(col) ? primaryKey[col] : conflictRow[`their_${col}`]);
70
- });
71
- await db.execute(sql.raw(`INSERT INTO "${table}" (${allCols.map((c) => `"${c}"`).join(", ")}) VALUES (${values.join(", ")})`));
72
- return;
73
- }
74
- const setClauses = columns.map((col) => {
75
- const val = conflictRow[`their_${col}`];
76
- return `"${col}" = ${toSqlLiteral(val)}`;
77
- });
78
- await db.execute(sql.raw(`UPDATE "${table}" SET ${setClauses.join(", ")} WHERE ${pkWhere}`));
79
- }
80
- async function applyMixedResolution(db, table, primaryKey, pkColumns, conflictRow, rowDefaultPick, columnOverrides) {
81
- const ourDiffType = conflictRow.our_diff_type;
82
- const theirDiffType = conflictRow.their_diff_type;
83
- if (theirDiffType === "removed" || ourDiffType === "removed") {
84
- if (rowDefaultPick === "ours") return;
85
- await applyTheirsResolution(db, table, primaryKey, pkColumns, conflictRow, ourDiffType, theirDiffType);
86
- return;
87
- }
88
- const columns = getColumnNames(conflictRow, pkColumns);
89
- const pkWhere = pkColumns.map((col) => {
90
- return `"${col}" = '${primaryKey[col]?.replace(/'/g, "''")}'`;
91
- }).join(" AND ");
92
- const setClauses = columns.map((col) => {
93
- const val = conflictRow[`${(columnOverrides[col] ?? rowDefaultPick) === "theirs" ? "their_" : "our_"}${col}`];
94
- return `"${col}" = ${toSqlLiteral(val)}`;
95
- });
96
- await db.execute(sql.raw(`UPDATE "${table}" SET ${setClauses.join(", ")} WHERE ${pkWhere}`));
97
- }
98
156
 
99
157
  //#endregion
100
- export { ResolutionValidationError, applyResolutions };
158
+ export { ResolutionValidationError, applyResolutions, computeTableInsertOrder, sortByFkDependencyOrder };