@treeseed/sdk 0.10.11 → 0.10.12

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/dist/db/schema.js CHANGED
@@ -1,240 +1,49 @@
1
- import { index, integer, primaryKey, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
2
- const betterAuthUser = sqliteTable("better_auth_user", {
3
- id: text("id").primaryKey(),
4
- name: text("name").notNull(),
5
- email: text("email").notNull().unique(),
6
- username: text("username").unique(),
7
- firstName: text("firstName"),
8
- lastName: text("lastName"),
9
- emailVerified: integer("emailVerified", { mode: "boolean" }).notNull().default(false),
10
- image: text("image"),
11
- createdAt: integer("createdAt", { mode: "timestamp_ms" }).notNull(),
12
- updatedAt: integer("updatedAt", { mode: "timestamp_ms" }).notNull()
13
- });
14
- const betterAuthSession = sqliteTable("better_auth_session", {
15
- id: text("id").primaryKey(),
16
- expiresAt: integer("expiresAt", { mode: "timestamp_ms" }).notNull(),
17
- token: text("token").notNull().unique(),
18
- createdAt: integer("createdAt", { mode: "timestamp_ms" }).notNull(),
19
- updatedAt: integer("updatedAt", { mode: "timestamp_ms" }).notNull(),
20
- ipAddress: text("ipAddress"),
21
- userAgent: text("userAgent"),
22
- userId: text("userId").notNull().references(() => betterAuthUser.id, { onDelete: "cascade" })
23
- });
24
- const betterAuthAccount = sqliteTable("better_auth_account", {
25
- id: text("id").primaryKey(),
26
- accountId: text("accountId").notNull(),
27
- providerId: text("providerId").notNull(),
28
- userId: text("userId").notNull().references(() => betterAuthUser.id, { onDelete: "cascade" }),
29
- accessToken: text("accessToken"),
30
- refreshToken: text("refreshToken"),
31
- idToken: text("idToken"),
32
- accessTokenExpiresAt: integer("accessTokenExpiresAt", { mode: "timestamp_ms" }),
33
- refreshTokenExpiresAt: integer("refreshTokenExpiresAt", { mode: "timestamp_ms" }),
34
- scope: text("scope"),
35
- password: text("password"),
36
- createdAt: integer("createdAt", { mode: "timestamp_ms" }).notNull(),
37
- updatedAt: integer("updatedAt", { mode: "timestamp_ms" }).notNull()
38
- }, (table) => [
39
- uniqueIndex("idx_better_auth_account_provider_account").on(table.providerId, table.accountId)
40
- ]);
41
- const betterAuthVerification = sqliteTable("better_auth_verification", {
42
- id: text("id").primaryKey(),
43
- identifier: text("identifier").notNull(),
44
- value: text("value").notNull(),
45
- expiresAt: integer("expiresAt", { mode: "timestamp_ms" }).notNull(),
46
- createdAt: integer("createdAt", { mode: "timestamp_ms" }).notNull(),
47
- updatedAt: integer("updatedAt", { mode: "timestamp_ms" }).notNull()
48
- });
49
- const userPreferences = sqliteTable("user_preferences", {
50
- userId: text("user_id").primaryKey().references(() => betterAuthUser.id, { onDelete: "cascade" }),
51
- colorScheme: text("color_scheme").notNull().default("fern"),
52
- themeMode: text("theme_mode").notNull().default("system"),
53
- createdAt: text("created_at").notNull(),
54
- updatedAt: text("updated_at").notNull()
55
- });
56
- const users = sqliteTable("users", {
57
- id: text("id").primaryKey(),
58
- email: text("email"),
59
- username: text("username").unique(),
60
- displayName: text("display_name"),
61
- status: text("status").notNull().default("active"),
62
- metadataJson: text("metadata_json"),
63
- createdAt: text("created_at").notNull(),
64
- updatedAt: text("updated_at").notNull()
65
- });
66
- const userIdentities = sqliteTable("user_identities", {
67
- id: text("id").primaryKey(),
68
- userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
69
- provider: text("provider").notNull(),
70
- providerSubject: text("provider_subject").notNull(),
71
- email: text("email"),
72
- emailVerified: integer("email_verified", { mode: "boolean" }).notNull().default(false),
73
- profileJson: text("profile_json"),
74
- createdAt: text("created_at").notNull(),
75
- updatedAt: text("updated_at").notNull()
76
- }, (table) => [
77
- uniqueIndex("idx_user_identities_provider_subject").on(table.provider, table.providerSubject)
78
- ]);
79
- const roles = sqliteTable("roles", {
80
- id: text("id").primaryKey(),
81
- key: text("key").notNull().unique(),
82
- description: text("description"),
83
- createdAt: text("created_at").notNull()
84
- });
85
- const permissions = sqliteTable("permissions", {
86
- id: text("id").primaryKey(),
87
- key: text("key").notNull().unique(),
88
- resource: text("resource").notNull(),
89
- action: text("action").notNull(),
90
- scope: text("scope").notNull(),
91
- description: text("description"),
1
+ import { index, integer, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
2
+ const subscribers = sqliteTable("subscribers", {
3
+ email: text("email").primaryKey(),
92
4
  createdAt: text("created_at").notNull()
93
5
  });
94
- const rolePermissions = sqliteTable("role_permissions", {
95
- roleId: text("role_id").notNull().references(() => roles.id, { onDelete: "cascade" }),
96
- permissionId: text("permission_id").notNull().references(() => permissions.id, { onDelete: "cascade" }),
97
- createdAt: text("created_at").notNull()
98
- }, (table) => [
99
- primaryKey({ columns: [table.roleId, table.permissionId] })
100
- ]);
101
- const userRoleBindings = sqliteTable("user_role_bindings", {
102
- id: text("id").primaryKey(),
103
- userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
104
- roleId: text("role_id").notNull().references(() => roles.id, { onDelete: "cascade" }),
105
- createdAt: text("created_at").notNull()
106
- }, (table) => [
107
- uniqueIndex("idx_user_role_bindings_user_role").on(table.userId, table.roleId)
108
- ]);
109
- const teams = sqliteTable("teams", {
110
- id: text("id").primaryKey(),
111
- slug: text("slug").notNull().unique(),
112
- name: text("name").notNull().unique(),
113
- displayName: text("display_name"),
114
- logoUrl: text("logo_url"),
115
- profileSummary: text("profile_summary"),
116
- metadataJson: text("metadata_json"),
117
- createdAt: text("created_at").notNull(),
118
- updatedAt: text("updated_at").notNull()
119
- });
120
- const teamInvites = sqliteTable("team_invites", {
121
- id: text("id").primaryKey(),
122
- teamId: text("team_id").notNull().references(() => teams.id, { onDelete: "cascade" }),
6
+ const contactSubmissions = sqliteTable("contact_submissions", {
7
+ id: integer("id").primaryKey({ autoIncrement: true }),
8
+ name: text("name"),
123
9
  email: text("email").notNull(),
124
- roleKey: text("role_key").notNull(),
125
- tokenPrefix: text("token_prefix").notNull(),
126
- tokenHash: text("token_hash").notNull(),
127
- status: text("status").notNull().default("pending"),
128
- invitedByUserId: text("invited_by_user_id").references(() => users.id, { onDelete: "set null" }),
129
- acceptedByUserId: text("accepted_by_user_id").references(() => users.id, { onDelete: "set null" }),
130
- acceptedAt: text("accepted_at"),
131
- expiresAt: text("expires_at").notNull(),
132
- createdAt: text("created_at").notNull(),
133
- updatedAt: text("updated_at").notNull()
134
- }, (table) => [
135
- index("idx_team_invites_team_status").on(table.teamId, table.status, table.createdAt),
136
- index("idx_team_invites_token_prefix").on(table.tokenPrefix)
137
- ]);
138
- const teamMemberships = sqliteTable("team_memberships", {
139
- id: text("id").primaryKey(),
140
- teamId: text("team_id").notNull().references(() => teams.id, { onDelete: "cascade" }),
141
- userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
142
- status: text("status").notNull().default("active"),
143
- createdAt: text("created_at").notNull(),
144
- updatedAt: text("updated_at").notNull()
145
- }, (table) => [
146
- uniqueIndex("idx_team_memberships_team_user").on(table.teamId, table.userId)
147
- ]);
148
- const webSessions = sqliteTable("web_sessions", {
149
- id: text("id").primaryKey(),
150
- userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
151
- identityId: text("identity_id"),
152
- betterAuthSessionId: text("better_auth_session_id"),
153
- provider: text("provider").notNull(),
154
- providerSubject: text("provider_subject").notNull(),
155
- email: text("email"),
156
- displayName: text("display_name"),
157
- principalJson: text("principal_json").notNull(),
158
- ipAddress: text("ip_address"),
10
+ organization: text("organization"),
11
+ contactType: text("contact_type"),
12
+ subject: text("subject"),
13
+ message: text("message").notNull(),
159
14
  userAgent: text("user_agent"),
160
- authenticatedAt: text("authenticated_at").notNull(),
161
- lastSeenAt: text("last_seen_at").notNull(),
162
- expiresAt: text("expires_at").notNull(),
163
- revokedAt: text("revoked_at"),
164
- createdAt: text("created_at").notNull(),
165
- updatedAt: text("updated_at").notNull()
166
- });
167
- const projects = sqliteTable("projects", {
168
- id: text("id").primaryKey(),
169
- teamId: text("team_id").notNull().references(() => teams.id, { onDelete: "cascade" }),
170
- slug: text("slug").notNull(),
171
- name: text("name").notNull(),
172
- description: text("description"),
173
- metadataJson: text("metadata_json"),
174
15
  createdAt: text("created_at").notNull(),
175
- updatedAt: text("updated_at").notNull()
16
+ ipHash: text("ip_hash")
176
17
  }, (table) => [
177
- uniqueIndex("idx_projects_team_slug").on(table.teamId, table.slug)
18
+ index("idx_contact_submissions_created_at").on(table.createdAt),
19
+ index("idx_contact_submissions_email").on(table.email)
178
20
  ]);
179
- const remoteJobs = sqliteTable("remote_jobs", {
180
- id: text("id").primaryKey(),
181
- projectId: text("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
182
- namespace: text("namespace").notNull(),
183
- operation: text("operation").notNull(),
21
+ const runtimeRecords = sqliteTable("runtime_records", {
22
+ id: integer("id").primaryKey({ autoIncrement: true }),
23
+ recordType: text("record_type").notNull(),
24
+ recordKey: text("record_key").notNull(),
25
+ lookupKey: text("lookup_key"),
26
+ secondaryKey: text("secondary_key"),
184
27
  status: text("status").notNull(),
185
- preferredMode: text("preferred_mode"),
186
- selectedTarget: text("selected_target"),
187
- requestedByType: text("requested_by_type").notNull(),
188
- requestedById: text("requested_by_id"),
189
- inputJson: text("input_json"),
190
- outputJson: text("output_json"),
191
- errorJson: text("error_json"),
192
- idempotencyKey: text("idempotency_key"),
28
+ schemaVersion: integer("schema_version").notNull().default(1),
193
29
  createdAt: text("created_at").notNull(),
194
30
  updatedAt: text("updated_at").notNull(),
195
- startedAt: text("started_at"),
196
- finishedAt: text("finished_at")
197
- });
31
+ expiresAt: text("expires_at"),
32
+ payloadJson: text("payload_json").notNull(),
33
+ metaJson: text("meta_json").notNull()
34
+ }, (table) => [
35
+ index("idx_runtime_records_type_lookup_updated").on(table.recordType, table.lookupKey, table.updatedAt),
36
+ index("idx_runtime_records_type_status_updated").on(table.recordType, table.status, table.updatedAt),
37
+ uniqueIndex("idx_runtime_records_type_record_key").on(table.recordType, table.recordKey)
38
+ ]);
198
39
  const treeseedSchema = {
199
- better_auth_user: betterAuthUser,
200
- better_auth_session: betterAuthSession,
201
- better_auth_account: betterAuthAccount,
202
- better_auth_verification: betterAuthVerification,
203
- userPreferences,
204
- user: betterAuthUser,
205
- session: betterAuthSession,
206
- account: betterAuthAccount,
207
- verification: betterAuthVerification,
208
- users,
209
- userIdentities,
210
- roles,
211
- permissions,
212
- rolePermissions,
213
- userRoleBindings,
214
- teams,
215
- teamInvites,
216
- teamMemberships,
217
- webSessions,
218
- projects,
219
- remoteJobs
40
+ subscribers,
41
+ contactSubmissions,
42
+ runtimeRecords
220
43
  };
221
44
  export {
222
- betterAuthAccount,
223
- betterAuthSession,
224
- betterAuthUser,
225
- betterAuthVerification,
226
- permissions,
227
- projects,
228
- remoteJobs,
229
- rolePermissions,
230
- roles,
231
- teamInvites,
232
- teamMemberships,
233
- teams,
234
- treeseedSchema,
235
- userIdentities,
236
- userPreferences,
237
- userRoleBindings,
238
- users,
239
- webSessions
45
+ contactSubmissions,
46
+ runtimeRecords,
47
+ subscribers,
48
+ treeseedSchema
240
49
  };
package/dist/index.d.ts CHANGED
@@ -7,7 +7,7 @@ export * from './seeds/index.ts';
7
7
  export { CAPACITY_PROVIDER_ENDPOINTS, CAPACITY_PROVIDER_DEPLOYMENT_SERVICE_ROLES, CAPACITY_PROVIDER_ENV_KEYS, CAPACITY_PROVIDER_SCOPES, CapacityProviderApiError, MarketProviderClient, assertCapacityProviderOkEnvelope, assertCapacityProviderPortfolioManifest, assertCapacityProviderRegistrationResponse, buildCapacityProviderAuthHeaders, deployCapacityProviderToManagedMarketHost, deployCapacityProviderToRailway, isCapacityProviderSecretEnvKey, redactCapacityProviderEnv, redactCapacityProviderSecret, renderCapacityProviderSelfHostInstructions, persistCapacityProviderConnectionToTreeseedConfig, resolveCapacityProviderEnvironment, resolveCapacityProviderLaunchEnvironment, } from './capacity-provider.ts';
8
8
  export { PLATFORM_OPERATION_ENDPOINTS, PLATFORM_OPERATION_NAMESPACES, PLATFORM_OPERATION_SCOPES, PLATFORM_OPERATION_STATUSES, PLATFORM_OPERATION_TARGETS, PlatformOperationApiError, PlatformRunnerClient, assertPlatformOperation, assertPlatformOperationEvent, assertPlatformOperationOkEnvelope, buildPlatformRunnerAuthHeaders, createPlatformOperationExecutorRegistry, derivePlatformOperationNavigation, isPlatformOperationSuccessful, isPlatformOperationTerminal, pollPlatformOperation, runPlatformOperationOnce, type PlatformOperation, type PlatformOperationEvent, type PlatformOperationNavigationResult, type PlatformOperationPollOptions, type PlatformOperationPollResult, } from './platform-operations.ts';
9
9
  export { PLATFORM_CONTENT_COLLECTIONS, PLATFORM_WORK_CONTENT_COLLECTIONS, createPlatformRepositoryClaim, derivePlatformRepositoryKey, executePlatformRepositoryOperation, normalizePlatformContentInput, normalizePlatformRelationArray, platformContentRelationPolicy, resolvePlatformRepositoryWorkspacePath, slugifyPlatformContent, type PlatformContentCollection, type PlatformRepositoryClaim, type PlatformRepositoryClaimInput, type PlatformRepositoryDescriptor, type PlatformRepositoryOperationInput, type PlatformRepositoryOperationOptions, type PlatformRepositoryOperationResult, type PlatformRepositoryPathPolicy, type PlatformRepositoryVerificationCommand, type PlatformRepositoryVerificationResult, type NormalizedPlatformContentInput, } from './operations/repository-operations.ts';
10
- export { DEFAULT_EXECUTION_PROFILE_ID, DEFAULT_EXECUTION_PROFILES, DEFAULT_TASK_ADMISSION_POLICY, buildTaskEstimateProfileFromActuals, computeWorkdayBudgetEnvelope, decideTaskAdmission, estimateAttentionForTask, estimateConfidenceFromProfile, estimateLearningPercentile, estimateLearningVariance, estimateForClassification, estimateProfileConfidenceScore, estimateUtilityForTask, isInterruptedUsageActual, normalizeHybridExecutionPlan, mutationRequiresRepositoryClaim, normalizePlanningPolicy, normalizePredictiveReservePolicy, normalizeTaskPlanProposal, normalizeExecutionProfile, normalizeAttentionPolicy, normalizeTaskAdmissionPolicy, normalizeUtilityPolicy, predictReserveForCapacityPlan, progressivelyAdmitPlanProposal, rankPlannedTaskNodes, reservationHasCapacity, reserveCreditsForEstimate, routeAndReserveCapacity, scoreCapacityLane, selectBestCapacityLane, selectTaskEstimateProfile, settleCapacityActuals, shouldInterruptForCapacity, synthesizePlanEstimate, createReservationReleaseEntry, summarizeCapacityPlan, summarizeProjectCapacityPlan, summarizeTeamCapacityPlan, validateTaskPlanProposal, } from './capacity.ts';
10
+ export { DEFAULT_EXECUTION_PROFILE_ID, DEFAULT_EXECUTION_PROFILES, DEFAULT_TASK_ADMISSION_POLICY, buildTaskEstimateProfileFromActuals, computeWorkdayBudgetEnvelope, decideTaskAdmission, estimateAttentionForTask, estimateConfidenceFromProfile, estimateLearningPercentile, estimateLearningVariance, estimateForClassification, estimateProfileConfidenceScore, estimateUtilityForTask, isInterruptedUsageActual, normalizeHybridExecutionPlan, mutationRequiresRepositoryClaim, normalizePlanningPolicy, normalizePredictiveReservePolicy, normalizeTaskPlanProposal, normalizeExecutionProfile, normalizeAttentionPolicy, normalizeTaskAdmissionPolicy, normalizeUtilityPolicy, predictReserveForCapacityPlan, progressivelyAdmitPlanProposal, rankPlannedTaskNodes, reservationHasCapacity, reserveCreditsForEstimate, routeAndReserveCapacity, scoreCapacityLane, selectBestCapacityLane, selectTaskEstimateProfile, ACTUAL_CREDIT_FORMULA_VERSION, buildCreditConversionProfileFromActuals, calculateActualCredits, deriveAvailableCredits, nativeUsageAmount, nativeUsageUnit, selectCreditConversionProfile, settleCapacityActuals, shouldInterruptForCapacity, synthesizePlanEstimate, createReservationReleaseEntry, summarizeCapacityPlan, summarizeProjectCapacityPlan, summarizeTeamCapacityPlan, validateTaskPlanProposal, } from './capacity.ts';
11
11
  export { executeKnowledgeHubProviderLaunch, validateKnowledgeHubProviderLaunchPrerequisites, } from './operations/services/hub-provider-launch.ts';
12
12
  export { createKnowledgeHubRepositories, defaultHubContentResolutionPolicy, executeKnowledgeHubLaunch, normalizeKnowledgeHubLaunchIntent, planKnowledgeHubLaunch, planKnowledgeHubRepositories, validateRepositoryHost, type HubContentResolutionPolicy, type KnowledgeHubLaunchIntent, type KnowledgeHubLaunchPhase, type KnowledgeHubLaunchPlan, type KnowledgeHubLaunchResult, type KnowledgeHubRepositoryPlan, type RepositoryHost, } from './operations/services/hub-launch.ts';
13
13
  export { ensureRailwayEnvironment, ensureRailwayProject, ensureRailwayService, getRailwayAuthProfile, listRailwayEnvironments, listRailwayProjects, listRailwayServices, listRailwayVariables, railwayGraphqlRequest, resolveRailwayApiToken, resolveRailwayApiUrl, resolveRailwayWorkspace, resolveRailwayWorkspaceContext, upsertRailwayVariables, } from './operations/services/railway-api.ts';
@@ -38,12 +38,12 @@ export { TreeseedWorkflowSdk } from './workflow.ts';
38
38
  export * from './db/index.ts';
39
39
  export { collectTreeseedReconcileStatus, createTreeseedReconcileRegistry, deriveTreeseedDesiredUnits, destroyTreeseedTargetUnits, observeTreeseedUnits, planTreeseedReconciliation, reconcileTreeseedTarget, } from './reconcile/index.ts';
40
40
  export { getTreeseedVerifyDriverStatus, runTreeseedVerifyDriver } from './verification.ts';
41
- export type { KnowledgeHubProviderLaunchPreflightReport, KnowledgeHubProviderLaunchFailurePhase, KnowledgeHubProviderLaunchInput, KnowledgeHubProviderLaunchResult, AgentMessageKind, AgentMessageRecord, AgentStatusRecord, DirectBoardItemSummary, InboxItem, ProjectJobStatus, LaunchProjectRequest, LaunchProjectResult, LinkedProjectRecordRef, ProjectConnectionStatus, ProjectOverviewSummary, ReleaseDetail, ReleaseState, ReleaseSummary, SharePackageState, SharePackageStatus, TeamCapability, TeamHomeSummary, TeamMemberSummary, WorkstreamDetail, WorkstreamEvent, WorkstreamState, WorkstreamSummary, SdkContentEntry, SdkDispatchCapability, SdkDispatchConfig, SdkDispatchCredentialSource, SdkDispatchExecutionClass, SdkDispatchNamespace, SdkDispatchPolicy, SdkDispatchRequest, SdkDispatchResult, SdkDispatchTarget, SdkCursorEntity, SdkFilterCondition, SdkFollowRequest, SdkGraphEdge, SdkGraphEdgeType, SdkGraphDslRelation, SdkGraphDslParseResult, SdkGraphModelConfig, SdkGraphNode, SdkGraphNodeType, SdkGraphPathExplanation, SdkGraphQueryStage, SdkGraphQueryView, SdkGraphQueryOptions, SdkGraphQueryRequest, SdkGraphQueryResult, SdkGraphRankingBuildInput, SdkGraphRankingDiagnostics, SdkGraphRankingIndex, SdkGraphRankingNodeResult, SdkGraphRankingProvider, SdkGraphRankingQueryRequest, SdkGraphRankingQueryResult, SdkGraphRankingSearchRequest, SdkGraphRefreshPayload, SdkGraphRefreshRequest, SdkGraphSearchOptions, SdkGraphSearchResult, SdkGraphSeed, SdkGraphSeedResolution, SdkGraphTraversalResult, SdkGraphWhereFilter, SdkContextPack, SdkContextPackRequest, SdkGetRequest, SdkJsonEnvelope, SdkLeaseEntity, SdkManagerContextPayload, SdkMessageEntity, SdkModelFieldBinding, SdkModelDefinition, SdkModelRegistry, SdkModelName, SdkMutationRequest, SdkOperation, SdkPickRequest, SdkPickResult, SdkQueueMessageEnvelope, SdkRunEntity, SdkSearchRequest, SdkTaskEntity, SdkTaskEventEntity, SdkTaskOutputEntity, SdkWorkDayEntity, SdkGraphRunEntity, SdkReportEntity, SdkSubscriptionEntity, SdkTemplateCatalogEntry, SdkTemplateCatalogPublisher, SdkTemplateCatalogResponse, SdkTemplateCatalogSource, SdkUpdateRequest, ProjectCapabilityGrant, ProjectConnection, ProjectConnectionMode, ProjectDeployment, ProjectDeploymentKind, ProjectDeploymentStatus, ProjectEnvironment, ProjectExecutionOwner, ProjectHosting, ProjectInfrastructureResource, ProjectInfrastructureResourceKind, ProjectInfrastructureResourceProvider, ProjectRunnerRegistrationState, RemoteJob, RemoteJobEvent, RemoteJobStatus, AgentPool, AgentPoolAutoscalePolicy, AgentPoolRegistration, AgentPoolScaleDecision, AgentPoolStatus, CatalogArtifactVersion, CatalogItem, CatalogItemFilters, CatalogItemOfferMode, ProjectEnvironmentName, ProjectWorkdaySummary, TreeseedHostingKind, TreeseedHostingRegistration, PriorityOverride, WorkdayWindow, WorkdaySchedule, WorkdayRequest, WorkdayManagerLease, WorkerRunner, WorkerRunnerState, RepositoryClaim, TaskCreditWeight, TaskCreditBudget, WorkdayPolicy, PrioritySnapshotItem, PrioritySnapshot, TaskCreditLedgerEntry, ApprovalRequest, DecideApprovalRequestRequest, ListApprovalRequestsRequest, CapacityBusinessModel, CapacityGrant, CapacityGrantScope, CapacityLedgerEntry, CapacityLaneUnit, CapacityPlan, CapacityProvider, CapacityProviderHost, CapacityProviderKind, CapacityProviderLane, CapacityReservation, CapacityRoutingDecision, CapacityTaskExecutionEnvelope, CanonicalTaskState, CreateApprovalRequestRequest, CreateCapacityReservationRequest, CreateCapacityRoutingDecisionRequest, CreateTaskEstimateRequest, CreateTaskUsageActualRequest, UpsertTeamInboxItemRequest, ExecutionProfile, HybridExecutionPhase, HybridExecutionPlan, PlannedTaskNode, PlanningAdmissionResult, PlanningPolicy, PredictiveReservePolicy, RecordCapacityUsageRequest, RepositoryWorkState, ReservePrediction, TaskAdmissionDecision, TaskAdmissionOutcome, TaskAdmissionPolicy, TaskClassification, TaskEstimate, TaskEstimateProfile, TaskCheckpointArtifact, TaskConcurrencyClass, TaskPlanProposal, TaskMutationScope, TaskRiskClass, TaskUsageActual, UtilityEstimate, UtilityPolicy, UpsertCapacityGrantRequest, UpsertCapacityProviderHostRequest, UpsertCapacityProviderLaneRequest, UpsertCapacityProviderRequest, ScaleDecision, RunnerScaleDecision, TeamStorageLocator, TeamWebHost, TeamWebHostOwnership, TeamWebHostProvider, EncryptedWebHostPayload, UpsertAgentPoolRequest, UpsertCatalogArtifactVersionRequest, UpsertCatalogItemRequest, UpsertProjectEnvironmentRequest, UpsertProjectHostingRequest, UpsertProjectInfrastructureResourceRequest, UpsertTeamStorageLocatorRequest, UpsertTeamWebHostRequest, CreateProjectDeploymentRequest, RecordAgentPoolRegistrationRequest, SdkAppendTaskEventRequest, SdkClaimTaskRequest, SdkCreateWorkdayRequest, SdkCloseWorkDayRequest, SdkCompleteTaskRequest, SdkCreateTaskRequest, SdkFailTaskRequest, SdkManagerContextPayload, SdkClaimWorkdayManagerLeaseRequest, SdkReleaseWorkdayManagerLeaseRequest, SdkRecordWorkerRunnerRequest, SdkRecordRepositoryClaimRequest, SdkRecordRunnerScaleDecisionRequest, SdkStartWorkDayRequest, SdkTaskEntity, SdkTaskEventEntity, SdkTaskOutputEntity, SdkTaskProgressRequest, SdkTaskSearchRequest, SdkUpdateWorkDayGraphRequest, SdkWorkDayEntity, WorkerPoolScaleResult, WorkerPoolScaler, } from './sdk-types.ts';
41
+ export type { KnowledgeHubProviderLaunchPreflightReport, KnowledgeHubProviderLaunchFailurePhase, KnowledgeHubProviderLaunchInput, KnowledgeHubProviderLaunchResult, AgentMessageKind, AgentMessageRecord, AgentStatusRecord, DirectBoardItemSummary, InboxItem, ProjectJobStatus, LaunchProjectRequest, LaunchProjectResult, LinkedProjectRecordRef, ProjectConnectionStatus, ProjectOverviewSummary, ReleaseDetail, ReleaseState, ReleaseSummary, SharePackageState, SharePackageStatus, TeamCapability, TeamHomeSummary, TeamMemberSummary, WorkstreamDetail, WorkstreamEvent, WorkstreamState, WorkstreamSummary, SdkContentEntry, SdkDispatchCapability, SdkDispatchConfig, SdkDispatchCredentialSource, SdkDispatchExecutionClass, SdkDispatchNamespace, SdkDispatchPolicy, SdkDispatchRequest, SdkDispatchResult, SdkDispatchTarget, SdkCursorEntity, SdkFilterCondition, SdkFollowRequest, SdkGraphEdge, SdkGraphEdgeType, SdkGraphDslRelation, SdkGraphDslParseResult, SdkGraphModelConfig, SdkGraphNode, SdkGraphNodeType, SdkGraphPathExplanation, SdkGraphQueryStage, SdkGraphQueryView, SdkGraphQueryOptions, SdkGraphQueryRequest, SdkGraphQueryResult, SdkGraphRankingBuildInput, SdkGraphRankingDiagnostics, SdkGraphRankingIndex, SdkGraphRankingNodeResult, SdkGraphRankingProvider, SdkGraphRankingQueryRequest, SdkGraphRankingQueryResult, SdkGraphRankingSearchRequest, SdkGraphRefreshPayload, SdkGraphRefreshRequest, SdkGraphSearchOptions, SdkGraphSearchResult, SdkGraphSeed, SdkGraphSeedResolution, SdkGraphTraversalResult, SdkGraphWhereFilter, SdkContextPack, SdkContextPackRequest, SdkGetRequest, SdkJsonEnvelope, SdkLeaseEntity, SdkManagerContextPayload, SdkMessageEntity, SdkModelFieldBinding, SdkModelDefinition, SdkModelRegistry, SdkModelName, SdkMutationRequest, SdkOperation, SdkPickRequest, SdkPickResult, SdkQueueMessageEnvelope, SdkRunEntity, SdkSearchRequest, SdkTaskEntity, SdkTaskEventEntity, SdkTaskOutputEntity, SdkWorkDayEntity, SdkGraphRunEntity, SdkReportEntity, SdkSubscriptionEntity, SdkTemplateCatalogEntry, SdkTemplateCatalogPublisher, SdkTemplateCatalogResponse, SdkTemplateCatalogSource, SdkUpdateRequest, ProjectCapabilityGrant, ProjectConnection, ProjectConnectionMode, ProjectDeployment, ProjectDeploymentKind, ProjectDeploymentStatus, ProjectEnvironment, ProjectExecutionOwner, ProjectHosting, ProjectInfrastructureResource, ProjectInfrastructureResourceKind, ProjectInfrastructureResourceProvider, ProjectRunnerRegistrationState, RemoteJob, RemoteJobEvent, RemoteJobStatus, AgentPool, AgentPoolAutoscalePolicy, AgentPoolRegistration, AgentPoolScaleDecision, AgentPoolStatus, CatalogArtifactVersion, CatalogItem, CatalogItemFilters, CatalogItemOfferMode, ProjectEnvironmentName, ProjectWorkdaySummary, TreeseedHostingKind, TreeseedHostingRegistration, PriorityOverride, WorkdayWindow, WorkdaySchedule, WorkdayRequest, WorkdayManagerLease, WorkerRunner, WorkerRunnerState, RepositoryClaim, TaskCreditWeight, TaskCreditBudget, WorkdayPolicy, PrioritySnapshotItem, PrioritySnapshot, TaskCreditLedgerEntry, ApprovalRequest, DecideApprovalRequestRequest, ListApprovalRequestsRequest, CapacityBusinessModel, CapacityGrant, CapacityGrantScope, CapacityLedgerEntry, CapacityLaneUnit, CapacityPlan, CapacityProvider, CapacityProviderHost, CapacityProviderKind, CapacityProviderLane, CapacityReservation, CapacityRoutingDecision, CapacityTaskExecutionEnvelope, CanonicalTaskState, CreateApprovalRequestRequest, CreateCapacityReservationRequest, CreateCapacityRoutingDecisionRequest, CreateTaskEstimateRequest, CreateTaskUsageActualRequest, CreditConversionProfile, DerivedCapacityAvailability, DerivedCapacityInput, DerivedCapacitySummary, NativeUsageObservation, UpsertTeamInboxItemRequest, ExecutionProfile, HybridExecutionPhase, HybridExecutionPlan, PlannedTaskNode, PlanningAdmissionResult, PlanningPolicy, PredictiveReservePolicy, RecordCapacityUsageRequest, RepositoryWorkState, ReservePrediction, TaskAdmissionDecision, TaskAdmissionOutcome, TaskAdmissionPolicy, TaskClassification, TaskEstimate, TaskEstimateProfile, TaskCheckpointArtifact, TaskConcurrencyClass, TaskPlanProposal, TaskMutationScope, TaskRiskClass, TaskUsageActual, UtilityEstimate, UtilityPolicy, UpsertCapacityGrantRequest, UpsertCapacityProviderHostRequest, UpsertCapacityProviderLaneRequest, UpsertCapacityProviderRequest, ScaleDecision, RunnerScaleDecision, TeamStorageLocator, TeamWebHost, TeamWebHostOwnership, TeamWebHostProvider, EncryptedWebHostPayload, UpsertAgentPoolRequest, UpsertCatalogArtifactVersionRequest, UpsertCatalogItemRequest, UpsertProjectEnvironmentRequest, UpsertProjectHostingRequest, UpsertProjectInfrastructureResourceRequest, UpsertTeamStorageLocatorRequest, UpsertTeamWebHostRequest, CreateProjectDeploymentRequest, RecordAgentPoolRegistrationRequest, SdkAppendTaskEventRequest, SdkClaimTaskRequest, SdkCreateWorkdayRequest, SdkCloseWorkDayRequest, SdkCompleteTaskRequest, SdkCreateTaskRequest, SdkFailTaskRequest, SdkManagerContextPayload, SdkClaimWorkdayManagerLeaseRequest, SdkReleaseWorkdayManagerLeaseRequest, SdkRecordWorkerRunnerRequest, SdkRecordRepositoryClaimRequest, SdkRecordRunnerScaleDecisionRequest, SdkStartWorkDayRequest, SdkTaskEntity, SdkTaskEventEntity, SdkTaskOutputEntity, SdkTaskProgressRequest, SdkTaskSearchRequest, SdkUpdateWorkDayGraphRequest, SdkWorkDayEntity, WorkerPoolScaleResult, WorkerPoolScaler, } from './sdk-types.ts';
42
42
  export type * from './project-workflow.ts';
43
43
  export type { ControlPlaneAgentPoolHeartbeat, ControlPlaneDeploymentReport, ControlPlaneEnvironmentReport, ControlPlaneReporter, ControlPlaneReporterKind, ControlPlaneResourceReport, ControlPlaneScaleDecisionReport, ControlPlaneWorkdaySummaryReport, } from './control-plane.ts';
44
44
  export type { ControlPlaneClientOptions } from './control-plane-client.ts';
45
- export type { CapacityProviderBudgetCapacity, CapacityProviderCapability, CapacityProviderConnectionState, CapacityProviderDeploymentIntent, CapacityProviderDeploymentResult, CapacityProviderDeploymentStatus, CapacityProviderEnvironmentInput, CapacityProviderEnvironmentName, CapacityProviderHealthState, CapacityProviderHeartbeatRequest, CapacityProviderHeartbeatResponse, CapacityProviderLaunchMode, CapacityProviderLaunchEnvironment, CapacityProviderLaunchEnvironmentInput, CapacityProviderConnectionConfigInput, CapacityProviderConnectionConfigResult, CapacityProviderPortfolioManifest, CapacityProviderPortfolioProject, CapacityProviderRegistrationRequest, CapacityProviderRegistrationResponse, CapacityProviderRuntimeInfo, CapacityProviderScope, CapacityProviderSelfHostInstructions, CapacityProviderStatus, MarketProviderClientOptions, ProviderReportRequest, ProviderReportResponse, ProviderTaskClaimRequest, ProviderTaskClaimResponse, ProviderTaskCompleteRequest, ProviderTaskCompleteResponse, ProviderTaskEventRequest, ProviderTaskEventResponse, ProviderTaskFailRequest, ProviderTaskFailResponse, ProviderUsageReport, ProviderUsageReportResponse, ProviderWorkdayRequest, ProviderWorkdayResponse, } from './capacity-provider.ts';
46
- export type { AdmissionEstimateInput, CapacityInterruptionInput, CapacityEstimateInput, CapacityLaneCandidate, CapacityLaneScore, CapacityTaskEstimate, AttentionEstimate, AttentionPolicy, CapacityRoutePressure, RouteAndReserveCandidate, RouteAndReserveResult, TaskAdmissionInput, WorkdayBudgetEnvelopeInput, } from './capacity.ts';
45
+ export type { CapacityProviderBudgetCapacity, CapacityProviderCapability, CapacityProviderConnectionState, CapacityProviderDeploymentIntent, CapacityProviderDeploymentResult, CapacityProviderDeploymentStatus, CapacityProviderEnvironmentInput, CapacityProviderEnvironmentName, CapacityProviderHealthState, CapacityProviderHeartbeatRequest, CapacityProviderHeartbeatResponse, CapacityProviderLaunchMode, CapacityProviderLaunchEnvironment, CapacityProviderLaunchEnvironmentInput, CapacityProviderConnectionConfigInput, CapacityProviderConnectionConfigResult, CapacityProviderPortfolioManifest, CapacityProviderPortfolioProject, CapacityProviderRegistrationRequest, CapacityProviderRegistrationResponse, CapacityProviderRuntimeInfo, CapacityProviderScope, CapacityProviderSelfHostInstructions, CapacityProviderStatus, CapacityProviderNativeCapacity, ExecutionProviderNativeCapacity, ExecutionProviderNativeLimitCapacity, ExecutionProviderObservationCapacity, MarketProviderClientOptions, NativeCapacityConfidence, NativeCapacityLimitScope, NativeCapacityLimitSource, NativeCapacityUnit, ProviderQuotaVisibility, ProviderReportRequest, ProviderReportResponse, ProviderTaskClaimRequest, ProviderTaskClaimResponse, ProviderTaskCompleteRequest, ProviderTaskCompleteResponse, ProviderTaskEventRequest, ProviderTaskEventResponse, ProviderTaskFailRequest, ProviderTaskFailResponse, ProviderUsageReport, ProviderUsageReportResponse, ProviderWorkdayRequest, ProviderWorkdayResponse, } from './capacity-provider.ts';
46
+ export type { AdmissionEstimateInput, CapacityInterruptionInput, CapacityEstimateInput, CapacityLaneCandidate, CapacityLaneScore, CapacityTaskEstimate, AttentionEstimate, AttentionPolicy, CapacityRouteNativePressure, CapacityRoutePressure, ActualCreditCalculation, ActualCreditCalculationInput, RouteAndReserveCandidate, RouteAndReserveResult, TaskAdmissionInput, WorkdayBudgetEnvelopeInput, } from './capacity.ts';
47
47
  export type { TreeseedFieldAliasBinding, TreeseedFieldAliasRegistry, } from './field-aliases.ts';
48
48
  export type * from './operations-types.ts';
49
49
  export type * from './workflow.ts';
package/dist/index.js CHANGED
@@ -89,6 +89,13 @@ import {
89
89
  scoreCapacityLane,
90
90
  selectBestCapacityLane,
91
91
  selectTaskEstimateProfile,
92
+ ACTUAL_CREDIT_FORMULA_VERSION,
93
+ buildCreditConversionProfileFromActuals,
94
+ calculateActualCredits,
95
+ deriveAvailableCredits,
96
+ nativeUsageAmount,
97
+ nativeUsageUnit,
98
+ selectCreditConversionProfile,
92
99
  settleCapacityActuals,
93
100
  shouldInterruptForCapacity,
94
101
  synthesizePlanEstimate,
@@ -296,6 +303,7 @@ import {
296
303
  import { getTreeseedVerifyDriverStatus, runTreeseedVerifyDriver } from "./verification.js";
297
304
  import { CloudflareHttpD1Database } from "./d1-http.js";
298
305
  export {
306
+ ACTUAL_CREDIT_FORMULA_VERSION,
299
307
  AGENT_MESSAGE_KINDS,
300
308
  AGENT_OPERATION_MODES,
301
309
  AGENT_OPERATION_NAMES,
@@ -365,12 +373,14 @@ export {
365
373
  buildBuiltinModelRegistry,
366
374
  buildCapacityProviderAuthHeaders,
367
375
  buildCopilotAllowToolArgs,
376
+ buildCreditConversionProfileFromActuals,
368
377
  buildKnowledgePackMarketPackage,
369
378
  buildModelRegistry,
370
379
  buildPlatformRunnerAuthHeaders,
371
380
  buildScopedModelRegistry,
372
381
  buildTaskEstimateProfileFromActuals,
373
382
  buildTemplateMarketPackage,
383
+ calculateActualCredits,
374
384
  canonicalizeFrontmatter,
375
385
  clearMarketSession,
376
386
  collectTreeseedDependencyStatus,
@@ -399,6 +409,7 @@ export {
399
409
  deniedAgentOperationResult,
400
410
  deployCapacityProviderToManagedMarketHost,
401
411
  deployCapacityProviderToRailway,
412
+ deriveAvailableCredits,
402
413
  derivePlatformOperationNavigation,
403
414
  derivePlatformRepositoryKey,
404
415
  deriveTreeseedDesiredUnits,
@@ -446,6 +457,8 @@ export {
446
457
  loadTreeseedTenantManifest,
447
458
  mergeModelRegistries,
448
459
  mutationRequiresRepositoryClaim,
460
+ nativeUsageAmount,
461
+ nativeUsageUnit,
449
462
  normalizeAgentCliOptions,
450
463
  normalizeAliasedRecord,
451
464
  normalizeAttentionPolicy,
@@ -525,6 +538,7 @@ export {
525
538
  runTreeseedVerifyDriver,
526
539
  scoreCapacityLane,
527
540
  selectBestCapacityLane,
541
+ selectCreditConversionProfile,
528
542
  selectTaskEstimateProfile,
529
543
  setActiveMarketProfile,
530
544
  setMarketSession,
@@ -290,6 +290,10 @@ export declare class MarketClient {
290
290
  ok: true;
291
291
  payload: Record<string, unknown>;
292
292
  }>;
293
+ teamCapacityProviders(teamId: string): Promise<{
294
+ ok: true;
295
+ payload: unknown[];
296
+ }>;
293
297
  launchManagedCapacityProvider(teamId: string, body?: Record<string, unknown>): Promise<{
294
298
  ok: true;
295
299
  payload: Record<string, unknown>;
@@ -306,10 +310,34 @@ export declare class MarketClient {
306
310
  ok: true;
307
311
  payload: unknown[];
308
312
  }>;
313
+ updateCapacityProvider(teamId: string, providerId: string, body: Record<string, unknown>): Promise<{
314
+ ok: true;
315
+ provider: Record<string, unknown>;
316
+ }>;
309
317
  createCapacityGrant(teamId: string, body: Record<string, unknown>): Promise<{
310
318
  ok: true;
311
319
  payload: Record<string, unknown>;
312
320
  }>;
321
+ executionProviders(teamId: string, providerId: string): Promise<{
322
+ ok: true;
323
+ payload: unknown[];
324
+ }>;
325
+ createExecutionProvider(teamId: string, providerId: string, body: Record<string, unknown>): Promise<{
326
+ ok: true;
327
+ payload: Record<string, unknown>;
328
+ }>;
329
+ updateExecutionProvider(teamId: string, providerId: string, executionProviderId: string, body: Record<string, unknown>): Promise<{
330
+ ok: true;
331
+ payload: Record<string, unknown>;
332
+ }>;
333
+ createExecutionProviderNativeLimit(teamId: string, providerId: string, executionProviderId: string, body: Record<string, unknown>): Promise<{
334
+ ok: true;
335
+ payload: Record<string, unknown>;
336
+ }>;
337
+ projectCapacityPlan(projectId: string, environment?: string | null): Promise<{
338
+ ok: true;
339
+ payload: Record<string, unknown>;
340
+ }>;
313
341
  planSeed(seedName: string, body: Record<string, unknown>): Promise<Record<string, unknown>>;
314
342
  applySeed(seedName: string, body: Record<string, unknown>): Promise<Record<string, unknown>>;
315
343
  listSeedRuns(limit?: number): Promise<{
@@ -432,6 +432,12 @@ class MarketClient {
432
432
  { requireAuth: true }
433
433
  );
434
434
  }
435
+ teamCapacityProviders(teamId) {
436
+ return this.request(
437
+ `/v1/teams/${encodeURIComponent(teamId)}/capacity-providers`,
438
+ { requireAuth: true }
439
+ );
440
+ }
435
441
  launchManagedCapacityProvider(teamId, body = {}) {
436
442
  return this.request(
437
443
  `/v1/teams/${encodeURIComponent(teamId)}/capacity/providers/managed`,
@@ -456,12 +462,49 @@ class MarketClient {
456
462
  { requireAuth: true }
457
463
  );
458
464
  }
465
+ updateCapacityProvider(teamId, providerId, body) {
466
+ return this.request(
467
+ `/v1/teams/${encodeURIComponent(teamId)}/capacity-providers/${encodeURIComponent(providerId)}`,
468
+ { method: "PATCH", body, requireAuth: true }
469
+ );
470
+ }
459
471
  createCapacityGrant(teamId, body) {
460
472
  return this.request(
461
473
  `/v1/teams/${encodeURIComponent(teamId)}/capacity-grants`,
462
474
  { method: "POST", body, requireAuth: true }
463
475
  );
464
476
  }
477
+ executionProviders(teamId, providerId) {
478
+ return this.request(
479
+ `/v1/teams/${encodeURIComponent(teamId)}/capacity-providers/${encodeURIComponent(providerId)}/execution-providers`,
480
+ { requireAuth: true }
481
+ );
482
+ }
483
+ createExecutionProvider(teamId, providerId, body) {
484
+ return this.request(
485
+ `/v1/teams/${encodeURIComponent(teamId)}/capacity-providers/${encodeURIComponent(providerId)}/execution-providers`,
486
+ { method: "POST", body, requireAuth: true }
487
+ );
488
+ }
489
+ updateExecutionProvider(teamId, providerId, executionProviderId, body) {
490
+ return this.request(
491
+ `/v1/teams/${encodeURIComponent(teamId)}/capacity-providers/${encodeURIComponent(providerId)}/execution-providers/${encodeURIComponent(executionProviderId)}`,
492
+ { method: "PATCH", body, requireAuth: true }
493
+ );
494
+ }
495
+ createExecutionProviderNativeLimit(teamId, providerId, executionProviderId, body) {
496
+ return this.request(
497
+ `/v1/teams/${encodeURIComponent(teamId)}/capacity-providers/${encodeURIComponent(providerId)}/execution-providers/${encodeURIComponent(executionProviderId)}/native-limits`,
498
+ { method: "POST", body, requireAuth: true }
499
+ );
500
+ }
501
+ projectCapacityPlan(projectId, environment) {
502
+ const query = environment ? `?environment=${encodeURIComponent(environment)}` : "";
503
+ return this.request(
504
+ `/v1/projects/${encodeURIComponent(projectId)}/capacity-plan${query}`,
505
+ { requireAuth: true }
506
+ );
507
+ }
465
508
  planSeed(seedName, body) {
466
509
  return this.request(
467
510
  `/v1/seeds/${encodeURIComponent(seedName)}/plan`,
@@ -62,7 +62,7 @@ function changedPaths(changedFiles) {
62
62
  function changedFileGroups(paths) {
63
63
  const counts = /* @__PURE__ */ new Map();
64
64
  for (const path of paths) {
65
- const group = path.startsWith(".github/") || path.includes("/workflows/") ? "ci" : /(^|\/)(test|tests|__tests__)\/|\.test\.|\.spec\./u.test(path) ? "tests" : path.startsWith("docs/") || /\.(md|mdx|txt)$/u.test(path) ? "docs" : path.includes("workflow") || path.includes("repository-save-orchestrator") ? "workflow" : path.includes("package-reference") || path.includes("release") || path.includes("publish") ? "release" : /(^|\/)(package|package-lock)\.json$/u.test(path) || path.includes("build") || path.includes("scripts/") ? "build" : path.includes("config") || path.endsWith(".yaml") || path.endsWith(".yml") ? "config" : path.startsWith("migrations/") || path.includes("/db/") ? "database" : path.startsWith("src/pages/") || path.startsWith("src/layouts/") || path.includes("/ui/") ? "ui" : path.startsWith("src/api/") || path.includes("/api/") ? "api" : "source";
65
+ const group = path.startsWith(".github/") || path.includes("/workflows/") ? "ci" : /(^|\/)(test|tests|__tests__)\/|\.test\.|\.spec\./u.test(path) ? "tests" : path.startsWith("docs/") || /\.(md|mdx|txt)$/u.test(path) ? "docs" : path.includes("workflow") || path.includes("repository-save-orchestrator") ? "workflow" : path.includes("package-reference") || path.includes("release") || path.includes("publish") ? "release" : /(^|\/)(package|package-lock)\.json$/u.test(path) || path.includes("build") || path.includes("scripts/") ? "build" : path.includes("config") || path.endsWith(".yaml") || path.endsWith(".yml") ? "config" : path.startsWith("packages/sdk/drizzle/") || path.includes("/db/") ? "database" : path.startsWith("src/pages/") || path.startsWith("src/layouts/") || path.includes("/ui/") ? "ui" : path.startsWith("src/api/") || path.includes("/api/") ? "api" : "source";
66
66
  counts.set(group, (counts.get(group) ?? 0) + 1);
67
67
  }
68
68
  return [...counts.entries()].sort((left, right) => right[1] - left[1] || left[0].localeCompare(right[0]));
@@ -1,8 +1,6 @@
1
1
  import { existsSync, readdirSync } from "node:fs";
2
- import { readFileSync } from "node:fs";
3
2
  import { resolve } from "node:path";
4
3
  import { spawnSync } from "node:child_process";
5
- import { NodeSqliteD1Database } from "../../db/node-sqlite.js";
6
4
  import { resolveWranglerBin } from "./runtime-tools.js";
7
5
  const DATABASE_BINDING = "SITE_DATA_DB";
8
6
  const WRANGLER_D1_TIMEOUT_MS = 12e4;
@@ -100,58 +98,6 @@ function markMigrationApplied({ cwd, wranglerConfig, persistTo, migration }) {
100
98
  command: `INSERT OR REPLACE INTO treeseed_schema_migrations (name, applied_at) VALUES ('${migration.replace(/'/g, "''")}', datetime('now'));`
101
99
  });
102
100
  }
103
- function tableColumns({ cwd, wranglerConfig, persistTo, tableName }) {
104
- const result = executeSqlCommand({
105
- cwd,
106
- wranglerConfig,
107
- persistTo,
108
- capture: true,
109
- command: `PRAGMA table_info(${tableName.replace(/[^A-Za-z0-9_]/g, "")});`
110
- });
111
- const parsed = parseWranglerJsonOutput(result.stdout);
112
- const rows = (Array.isArray(parsed) ? parsed : [parsed]).flatMap((entry) => entry.results ?? []);
113
- return new Set(rows.map((row) => row.name).filter(Boolean));
114
- }
115
- function migrationAlreadySatisfied({ cwd, wranglerConfig, persistTo, filePath }) {
116
- const sql = readFileSync(filePath, "utf8");
117
- if (!sql.includes("execution_profile_id") || !sql.includes("task_estimate_profiles")) {
118
- return false;
119
- }
120
- const estimateColumns = tableColumns({ cwd, wranglerConfig, persistTo, tableName: "task_estimates" });
121
- const actualColumns = tableColumns({ cwd, wranglerConfig, persistTo, tableName: "task_usage_actuals" });
122
- const profileColumns = tableColumns({ cwd, wranglerConfig, persistTo, tableName: "task_estimate_profiles" });
123
- return estimateColumns.has("execution_profile_id") && actualColumns.has("execution_profile_id") && profileColumns.has("execution_profile_id") && profileColumns.has("completed_sample_count") && profileColumns.has("interrupted_sample_count") && profileColumns.has("confidence_score");
124
- }
125
- function ensureLocalSdkRuntimeState({ migrationsRoot, persistTo }) {
126
- if (!persistTo) {
127
- return;
128
- }
129
- const migrationPath = resolve(migrationsRoot, "0025_agent_runtime_state.sql");
130
- if (!existsSync(migrationPath)) {
131
- return;
132
- }
133
- const sql = readFileSync(migrationPath, "utf8");
134
- const targets = /* @__PURE__ */ new Set();
135
- const sdkDb = new NodeSqliteD1Database(persistTo);
136
- targets.add(sdkDb.path);
137
- sdkDb.close();
138
- const miniflareRoot = resolve(persistTo, "miniflare-D1DatabaseObject");
139
- if (existsSync(miniflareRoot)) {
140
- for (const entry of readdirSync(miniflareRoot)) {
141
- if (entry.endsWith(".sqlite") && entry !== "metadata.sqlite") {
142
- targets.add(resolve(miniflareRoot, entry));
143
- }
144
- }
145
- }
146
- for (const target of targets) {
147
- const db = new NodeSqliteD1Database(target);
148
- try {
149
- db.client.exec(sql);
150
- } finally {
151
- db.close();
152
- }
153
- }
154
- }
155
101
  function runLocalD1Migrations({ cwd, wranglerConfig, migrationsRoot, persistTo }) {
156
102
  ensureSchemaMigrationsTable({ cwd, wranglerConfig, persistTo });
157
103
  const appliedMigrations = loadAppliedMigrations({ cwd, wranglerConfig, persistTo });
@@ -165,14 +111,9 @@ function runLocalD1Migrations({ cwd, wranglerConfig, migrationsRoot, persistTo }
165
111
  console.error(`Unable to find migration file at ${filePath}.`);
166
112
  process.exit(1);
167
113
  }
168
- if (migrationAlreadySatisfied({ cwd, wranglerConfig, persistTo, filePath })) {
169
- markMigrationApplied({ cwd, wranglerConfig, persistTo, migration });
170
- continue;
171
- }
172
114
  executeSqlFile({ cwd, wranglerConfig, filePath, persistTo });
173
115
  markMigrationApplied({ cwd, wranglerConfig, persistTo, migration });
174
116
  }
175
- ensureLocalSdkRuntimeState({ migrationsRoot, persistTo });
176
117
  }
177
118
  export {
178
119
  runLocalD1Migrations
@@ -6,6 +6,7 @@ import { createInterface } from "node:readline/promises";
6
6
  import { resolveTreeseedWebCachePolicy } from "../../platform/deploy-config.js";
7
7
  import { normalizeRailwayEnvironmentName } from "./railway-api.js";
8
8
  import { loadCliDeployConfig, resolveWranglerBin } from "./runtime-tools.js";
9
+ import { sdkD1MigrationsRoot } from "./runtime-paths.js";
9
10
  const DEFAULT_COMPATIBILITY_DATE = "2026-04-05";
10
11
  const DEFAULT_COMPATIBILITY_FLAGS = ["nodejs_compat"];
11
12
  const DEFAULT_TREESEED_MARKET_BASE_URL = "https://api.treeseed.ai";
@@ -737,7 +738,7 @@ function buildWranglerConfigContents(tenantRoot, deployConfig, state, options =
737
738
  const workerName = state.workerName ?? targetWorkerName(deployConfig, target);
738
739
  const mainPath = relativeFromGeneratedRoot(resolve(tenantRoot, "dist/_worker.js/index.js"), generatedRoot);
739
740
  const assetsDirectory = relativeFromGeneratedRoot(resolve(tenantRoot, "dist"), generatedRoot);
740
- const migrationsDir = relativeFromGeneratedRoot(resolve(tenantRoot, "migrations"), generatedRoot);
741
+ const migrationsDir = relativeFromGeneratedRoot(sdkD1MigrationsRoot, generatedRoot);
741
742
  const vars = {
742
743
  ...buildPublicVars(deployConfig),
743
744
  ...buildLocalRuntimeVars(deployConfig, state, target, options.env)
@@ -2,10 +2,10 @@ import { spawn, spawnSync } from "node:child_process";
2
2
  import { resolve } from "node:path";
3
3
  import { runLocalD1Migrations as applyLocalD1Migrations } from "./d1-migration.js";
4
4
  import {
5
- fixtureMigrationsRoot,
6
5
  fixtureRoot,
7
6
  fixtureWranglerConfig,
8
- corePackageRoot
7
+ corePackageRoot,
8
+ sdkD1MigrationsRoot
9
9
  } from "./runtime-paths.js";
10
10
  import { resolveTreeseedToolCommand } from "../../managed-dependencies.js";
11
11
  function mergeEnv(extraEnv = {}) {
@@ -41,7 +41,7 @@ function runLocalD1Migration(persistTo) {
41
41
  applyLocalD1Migrations({
42
42
  cwd: fixtureRoot,
43
43
  wranglerConfig: fixtureWranglerConfig,
44
- migrationsRoot: fixtureMigrationsRoot,
44
+ migrationsRoot: sdkD1MigrationsRoot,
45
45
  persistTo
46
46
  });
47
47
  }