@lota-sdk/core 0.4.10 → 0.4.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.
Files changed (108) hide show
  1. package/package.json +2 -2
  2. package/src/ai-gateway/ai-gateway.ts +149 -95
  3. package/src/ai-gateway/index.ts +16 -1
  4. package/src/config/agent-defaults.ts +4 -120
  5. package/src/config/logger.ts +18 -34
  6. package/src/config/thread-defaults.ts +1 -18
  7. package/src/create-runtime.ts +90 -28
  8. package/src/db/base.service.ts +30 -38
  9. package/src/db/service.ts +489 -545
  10. package/src/effect/index.ts +0 -2
  11. package/src/effect/layers.ts +6 -13
  12. package/src/embeddings/provider.ts +2 -7
  13. package/src/index.ts +4 -5
  14. package/src/queues/autonomous-job.queue.ts +159 -113
  15. package/src/queues/context-compaction.queue.ts +39 -25
  16. package/src/queues/delayed-node-promotion.queue.ts +56 -29
  17. package/src/queues/document-processor.queue.ts +5 -3
  18. package/src/queues/index.ts +1 -0
  19. package/src/queues/memory-consolidation.queue.ts +79 -53
  20. package/src/queues/organization-learning.queue.ts +63 -39
  21. package/src/queues/plan-agent-heartbeat.queue.ts +104 -79
  22. package/src/queues/plan-scheduler.queue.ts +100 -84
  23. package/src/queues/post-chat-memory.queue.ts +55 -33
  24. package/src/queues/queue-factory.ts +40 -41
  25. package/src/queues/queues.service.ts +61 -0
  26. package/src/queues/title-generation.queue.ts +42 -31
  27. package/src/redis/org-memory-lock.ts +24 -9
  28. package/src/redis/redis-lease-lock.ts +8 -1
  29. package/src/runtime/agent-identity-overrides.ts +7 -3
  30. package/src/runtime/agent-runtime-policy.ts +9 -4
  31. package/src/runtime/agent-stream-helpers.ts +9 -4
  32. package/src/runtime/context-compaction/context-compaction-runtime.ts +28 -32
  33. package/src/runtime/context-compaction/context-compaction.ts +9 -7
  34. package/src/runtime/domain-layer.ts +15 -4
  35. package/src/runtime/execution-plan-visibility.ts +5 -2
  36. package/src/runtime/graph-designer.ts +0 -22
  37. package/src/runtime/index.ts +1 -0
  38. package/src/runtime/indexed-repositories-policy.ts +2 -6
  39. package/src/runtime/plugin-resolution.ts +29 -12
  40. package/src/runtime/post-turn-side-effects.ts +139 -141
  41. package/src/runtime/runtime-config.ts +0 -6
  42. package/src/runtime/runtime-extensions.ts +0 -54
  43. package/src/runtime/runtime-lifecycle.ts +4 -4
  44. package/src/runtime/runtime-services.ts +122 -53
  45. package/src/runtime/runtime-worker-registry.ts +113 -30
  46. package/src/runtime/social-chat/social-chat-agent-runner.ts +6 -3
  47. package/src/runtime/social-chat/social-chat-history.ts +3 -1
  48. package/src/runtime/social-chat/social-chat.ts +35 -20
  49. package/src/runtime/team-consultation/team-consultation-orchestrator.ts +6 -5
  50. package/src/runtime/team-consultation/team-consultation-prompts.ts +11 -6
  51. package/src/runtime/thread-chat-helpers.ts +18 -9
  52. package/src/runtime/thread-turn-context.ts +7 -47
  53. package/src/runtime/turn-lifecycle.ts +6 -14
  54. package/src/services/agent-activity.service.ts +168 -175
  55. package/src/services/agent-executor.service.ts +35 -16
  56. package/src/services/attachment.service.ts +4 -70
  57. package/src/services/autonomous-job.service.ts +53 -61
  58. package/src/services/context-compaction.service.ts +7 -9
  59. package/src/services/execution-plan/execution-plan-graph.ts +106 -115
  60. package/src/services/execution-plan/execution-plan-schedule.ts +1 -15
  61. package/src/services/execution-plan/execution-plan.service.ts +67 -50
  62. package/src/services/global-orchestrator.service.ts +18 -7
  63. package/src/services/graph-full-routing.ts +7 -6
  64. package/src/services/memory/memory-conversation.ts +10 -5
  65. package/src/services/memory/memory.service.ts +11 -8
  66. package/src/services/ownership-dispatcher.service.ts +16 -5
  67. package/src/services/plan/plan-agent-heartbeat.service.ts +29 -15
  68. package/src/services/plan/plan-agent-query.service.ts +12 -8
  69. package/src/services/plan/plan-completion-side-effects.ts +93 -101
  70. package/src/services/plan/plan-cycle.service.ts +7 -45
  71. package/src/services/plan/plan-deadline.service.ts +28 -17
  72. package/src/services/plan/plan-event-delivery.service.ts +47 -40
  73. package/src/services/plan/plan-executor-context.ts +2 -0
  74. package/src/services/plan/plan-executor-graph.ts +366 -391
  75. package/src/services/plan/plan-executor.service.ts +13 -91
  76. package/src/services/plan/plan-scheduler.service.ts +62 -49
  77. package/src/services/plan/plan-transaction-events.ts +1 -1
  78. package/src/services/recent-activity-title.service.ts +6 -2
  79. package/src/services/thread/thread-bootstrap.ts +11 -9
  80. package/src/services/thread/thread-message.service.ts +6 -5
  81. package/src/services/thread/thread-turn-execution.ts +86 -82
  82. package/src/services/thread/thread-turn-preparation.service.ts +47 -24
  83. package/src/services/thread/thread-turn-streaming.ts +20 -25
  84. package/src/services/thread/thread-turn.ts +25 -44
  85. package/src/services/thread/thread.service.ts +21 -6
  86. package/src/system-agents/recent-activity-title-refiner.agent.ts +8 -5
  87. package/src/system-agents/thread-router.agent.ts +23 -20
  88. package/src/tools/execution-plan.tool.ts +8 -3
  89. package/src/tools/fetch-webpage.tool.ts +10 -9
  90. package/src/tools/firecrawl-client.ts +0 -15
  91. package/src/tools/remember-memory.tool.ts +3 -6
  92. package/src/tools/research-topic.tool.ts +12 -3
  93. package/src/tools/search-web.tool.ts +10 -9
  94. package/src/tools/search.tool.ts +4 -5
  95. package/src/tools/team-think.tool.ts +139 -121
  96. package/src/workers/bootstrap.ts +9 -10
  97. package/src/workers/memory-consolidation.worker.ts +4 -1
  98. package/src/workers/organization-learning.worker.ts +15 -2
  99. package/src/workers/regular-chat-memory-digest.helpers.ts +3 -4
  100. package/src/workers/regular-chat-memory-digest.runner.ts +21 -14
  101. package/src/workers/skill-extraction.runner.ts +13 -15
  102. package/src/workers/worker-utils.ts +6 -18
  103. package/src/effect/awaitable-effect.ts +0 -96
  104. package/src/effect/runtime-ref.ts +0 -25
  105. package/src/effect/runtime.ts +0 -46
  106. package/src/redis/runtime-connection.ts +0 -20
  107. package/src/runtime/runtime-accessors.ts +0 -92
  108. package/src/runtime/runtime-token.ts +0 -47
@@ -3,12 +3,8 @@ import { Schema, Effect } from 'effect'
3
3
 
4
4
  import type { ResolvedAgentConfig } from '../config/agent-defaults'
5
5
  import type { RecordIdRef } from '../db/record-id'
6
- import { runPromise } from '../effect/runtime'
7
6
  import { AgentConfigServiceTag, RuntimeAdaptersServiceTag } from '../effect/services'
8
- import { enqueueMemoryConsolidation } from '../queues/memory-consolidation.queue'
9
- import { enqueueRegularChatMemoryDigest, enqueueSkillExtraction } from '../queues/organization-learning.queue'
10
- import { enqueuePostChatMemory } from '../queues/post-chat-memory.queue'
11
- import { enqueueRecentActivityTitleRefinement } from '../queues/title-generation.queue'
7
+ import { LotaQueuesServiceTag } from '../queues/queues.service'
12
8
  import { RecentActivityServiceTag } from '../services/recent-activity.service'
13
9
  import { ThreadServiceTag } from '../services/thread/thread.service'
14
10
  import type { NormalizedThread, ThreadRecord } from '../services/thread/thread.types'
@@ -114,157 +110,159 @@ interface PostTurnSideEffectsParams {
114
110
  agentDisplayNamesById?: Partial<Record<string, string>>
115
111
  }
116
112
 
117
- const runPostTurnSideEffectsEffect = (params: PostTurnSideEffectsParams) =>
118
- Effect.gen(function* () {
119
- const recentActivityService = yield* RecentActivityServiceTag
120
- const threadService = yield* ThreadServiceTag
121
- const agentConfig: ResolvedAgentConfig = yield* AgentConfigServiceTag
122
- const runtimeAdapters = yield* RuntimeAdaptersServiceTag
123
- const recentHistory = yield* tryPostTurnSideEffect('Failed to load recent thread history.', () =>
124
- params.loadRecentHistory(),
113
+ export const runPostTurnSideEffects = Effect.fn('PostTurnSideEffects.run')(function* (
114
+ params: PostTurnSideEffectsParams,
115
+ ) {
116
+ const recentActivityService = yield* RecentActivityServiceTag
117
+ const threadService = yield* ThreadServiceTag
118
+ const agentConfig: ResolvedAgentConfig = yield* AgentConfigServiceTag
119
+ const runtimeAdapters = yield* RuntimeAdaptersServiceTag
120
+ const queues = yield* LotaQueuesServiceTag
121
+ const recentHistory = yield* tryPostTurnSideEffect('Failed to load recent thread history.', () =>
122
+ params.loadRecentHistory(),
123
+ )
124
+ const turnCount = yield* threadService.incrementTurnCount(params.threadRef)
125
+ const agentMessages = buildAgentHistoryMessages(agentConfig, params.allAssistantMessages)
126
+ const historyMessagesForMemory = appendPersistedThreadContextToHistoryMessages(
127
+ toHistoryMessages(agentConfig, recentHistory),
128
+ { compactionSummary: params.latestThreadRecord.compactionSummary },
129
+ )
130
+
131
+ const userMessageText = params.referenceUserMessage ? extractMessageText(params.referenceUserMessage).trim() : ''
132
+ const readableUploads = params.listReadableUploads()
133
+ const attachmentMetadataContext = buildReadableUploadMetadataContext(readableUploads)
134
+ const hasAttachmentContext = Boolean(attachmentMetadataContext)
135
+ const shouldExtractMemory = params.onboardingActive
136
+ ? shouldEnqueueOnboardingPostChatMemory({
137
+ onboardingActive: params.onboardingActive,
138
+ userMessageText,
139
+ hasAttachmentContext,
140
+ agentMessageCount: agentMessages.length,
141
+ })
142
+ : shouldEnqueueMemoryExtraction({ onboardingActive: params.onboardingActive, turnCount }) &&
143
+ userMessageText.length > 0
144
+
145
+ if (shouldExtractMemory) {
146
+ const memoryUserMessage = userMessageText || 'User uploaded attachment(s).'
147
+ yield* tryPostTurnSideEffect('Failed to enqueue post-chat memory extraction.', () =>
148
+ safeEnqueue(
149
+ () =>
150
+ queues.postChatMemory.enqueuePostChatMemory({
151
+ orgId: params.orgIdString,
152
+ threadId: params.threadIdString,
153
+ sourceId: params.referenceUserMessageId,
154
+ onboardStatus: readOptionalString((params.workspace as { onboardStatus?: unknown }).onboardStatus),
155
+ userMessage: memoryUserMessage,
156
+ historyMessages: historyMessagesForMemory,
157
+ agentMessages,
158
+ memoryBlock: params.memoryBlock.trim() ? params.memoryBlock : undefined,
159
+ attachmentContext: attachmentMetadataContext,
160
+ }),
161
+ { operationName: 'post-chat memory extraction enqueue' },
162
+ ),
125
163
  )
126
- const turnCount = yield* threadService.incrementTurnCount(params.threadRef)
127
- const agentMessages = buildAgentHistoryMessages(params.allAssistantMessages)
128
- const historyMessagesForMemory = appendPersistedThreadContextToHistoryMessages(toHistoryMessages(recentHistory), {
129
- compactionSummary: params.latestThreadRecord.compactionSummary,
130
- })
164
+ }
131
165
 
132
- const userMessageText = params.referenceUserMessage ? extractMessageText(params.referenceUserMessage).trim() : ''
133
- const readableUploads = params.listReadableUploads()
134
- const attachmentMetadataContext = buildReadableUploadMetadataContext(readableUploads)
135
- const hasAttachmentContext = Boolean(attachmentMetadataContext)
136
- const shouldExtractMemory = params.onboardingActive
137
- ? shouldEnqueueOnboardingPostChatMemory({
138
- onboardingActive: params.onboardingActive,
139
- userMessageText,
140
- hasAttachmentContext,
141
- agentMessageCount: agentMessages.length,
142
- })
143
- : shouldEnqueueMemoryExtraction({ onboardingActive: params.onboardingActive, turnCount }) &&
144
- userMessageText.length > 0
166
+ const referenceUserMessage = params.referenceUserMessage
167
+ if (params.isUserTurn && referenceUserMessage) {
168
+ const conversationSummary = buildConversationSummary({
169
+ agentConfig,
170
+ userMessageText,
171
+ assistantMessages: params.allAssistantMessages,
172
+ })
173
+ if (conversationSummary) {
174
+ const effectiveAgentId = params.visibleThreadAgentId ?? params.defaultLeadAgentId
175
+ const recentActivityResult = yield* recentActivityService.recordEvent({
176
+ orgId: params.orgRef,
177
+ userId: params.userRef,
178
+ source: 'system',
179
+ event: {
180
+ sourceEventId: `chat-turn:${params.referenceUserMessageId}`,
181
+ kind: 'chat.turn.completed',
182
+ targetKind: 'thread',
183
+ targetId: params.threadIdString,
184
+ mergeKey: `thread:${params.threadIdString}`,
185
+ title: buildRecentActivityChatSystemTitle({
186
+ agentConfig,
187
+ thread: params.thread,
188
+ visibleAgentId: effectiveAgentId,
189
+ agentDisplayNamesById: params.agentDisplayNamesById,
190
+ }),
191
+ sourceLabel: resolveDisplayName(agentConfig, effectiveAgentId, params.agentDisplayNamesById),
192
+ deepLink: buildRecentActivityChatDeepLink({
193
+ thread: params.thread,
194
+ threadId: params.threadIdString,
195
+ visibleAgentId: effectiveAgentId,
196
+ }),
197
+ metadata: {
198
+ agentId: effectiveAgentId,
199
+ agentName: resolveDisplayName(agentConfig, effectiveAgentId, params.agentDisplayNamesById),
200
+ threadId: params.threadIdString,
201
+ threadTitle: params.latestThreadRecord.title ?? params.thread.title,
202
+ threadType: params.thread.type,
203
+ ...(params.thread.threadType ? { coreType: params.thread.threadType } : {}),
204
+ userMessageText,
205
+ assistantSummary: conversationSummary,
206
+ messageId: params.referenceUserMessageId,
207
+ },
208
+ occurredAt: toIsoDateTimeString(referenceUserMessage.metadata?.createdAt ?? nowEpochMillis()),
209
+ },
210
+ })
145
211
 
146
- if (shouldExtractMemory) {
147
- const memoryUserMessage = userMessageText || 'User uploaded attachment(s).'
148
- yield* tryPostTurnSideEffect('Failed to enqueue post-chat memory extraction.', () =>
212
+ yield* tryPostTurnSideEffect('Failed to enqueue post-chat org action.', () =>
149
213
  safeEnqueue(
150
- () =>
151
- enqueuePostChatMemory({
214
+ () => {
215
+ const enqueuePostChatOrgAction = runtimeAdapters.enqueuePostChatOrgAction
216
+ if (!enqueuePostChatOrgAction) {
217
+ return
218
+ }
219
+
220
+ const sourceCreatedAt = referenceUserMessage.metadata?.createdAt ?? nowEpochMillis()
221
+ return enqueuePostChatOrgAction({
152
222
  orgId: params.orgIdString,
153
223
  threadId: params.threadIdString,
154
224
  sourceId: params.referenceUserMessageId,
155
- onboardStatus: readOptionalString((params.workspace as { onboardStatus?: unknown }).onboardStatus),
156
- userMessage: memoryUserMessage,
157
- historyMessages: historyMessagesForMemory,
158
- agentMessages,
159
- memoryBlock: params.memoryBlock.trim() ? params.memoryBlock : undefined,
160
- attachmentContext: attachmentMetadataContext,
161
- }),
162
- { operationName: 'post-chat memory extraction enqueue' },
225
+ sourceCreatedAt,
226
+ conversationSummary,
227
+ })
228
+ },
229
+ { operationName: 'post-chat org action enqueue' },
163
230
  ),
164
231
  )
165
- }
166
-
167
- const referenceUserMessage = params.referenceUserMessage
168
- if (params.isUserTurn && referenceUserMessage) {
169
- const conversationSummary = buildConversationSummary({
170
- userMessageText,
171
- assistantMessages: params.allAssistantMessages,
172
- })
173
- if (conversationSummary) {
174
- const effectiveAgentId = params.visibleThreadAgentId ?? params.defaultLeadAgentId
175
- const recentActivityResult = yield* recentActivityService.recordEvent({
176
- orgId: params.orgRef,
177
- userId: params.userRef,
178
- source: 'system',
179
- event: {
180
- sourceEventId: `chat-turn:${params.referenceUserMessageId}`,
181
- kind: 'chat.turn.completed',
182
- targetKind: 'thread',
183
- targetId: params.threadIdString,
184
- mergeKey: `thread:${params.threadIdString}`,
185
- title: buildRecentActivityChatSystemTitle({
186
- agentConfig,
187
- thread: params.thread,
188
- visibleAgentId: effectiveAgentId,
189
- agentDisplayNamesById: params.agentDisplayNamesById,
190
- }),
191
- sourceLabel: resolveDisplayName(agentConfig, effectiveAgentId, params.agentDisplayNamesById),
192
- deepLink: buildRecentActivityChatDeepLink({
193
- thread: params.thread,
194
- threadId: params.threadIdString,
195
- visibleAgentId: effectiveAgentId,
196
- }),
197
- metadata: {
198
- agentId: effectiveAgentId,
199
- agentName: resolveDisplayName(agentConfig, effectiveAgentId, params.agentDisplayNamesById),
200
- threadId: params.threadIdString,
201
- threadTitle: params.latestThreadRecord.title ?? params.thread.title,
202
- threadType: params.thread.type,
203
- ...(params.thread.threadType ? { coreType: params.thread.threadType } : {}),
204
- userMessageText,
205
- assistantSummary: conversationSummary,
206
- messageId: params.referenceUserMessageId,
207
- },
208
- occurredAt: toIsoDateTimeString(referenceUserMessage.metadata?.createdAt ?? nowEpochMillis()),
209
- },
210
- })
211
232
 
212
- yield* tryPostTurnSideEffect('Failed to enqueue post-chat org action.', () =>
233
+ if (recentActivityService.isMeaningfulRefinementCandidate(recentActivityResult.item)) {
234
+ yield* tryPostTurnSideEffect('Failed to enqueue recent activity title refinement.', () =>
213
235
  safeEnqueue(
214
- () => {
215
- const enqueuePostChatOrgAction = runtimeAdapters.enqueuePostChatOrgAction
216
- if (!enqueuePostChatOrgAction) {
217
- return
218
- }
219
-
220
- const sourceCreatedAt = referenceUserMessage.metadata?.createdAt ?? nowEpochMillis()
221
- return enqueuePostChatOrgAction({
222
- orgId: params.orgIdString,
223
- threadId: params.threadIdString,
224
- sourceId: params.referenceUserMessageId,
225
- sourceCreatedAt,
226
- conversationSummary,
227
- })
228
- },
229
- { operationName: 'post-chat org action enqueue' },
236
+ () =>
237
+ queues.titleGeneration.enqueueRecentActivityTitleRefinement({ activityId: recentActivityResult.item.id }),
238
+ { operationName: 'recent activity title refinement enqueue' },
230
239
  ),
231
240
  )
232
-
233
- if (recentActivityService.isMeaningfulRefinementCandidate(recentActivityResult.item)) {
234
- yield* tryPostTurnSideEffect('Failed to enqueue recent activity title refinement.', () =>
235
- safeEnqueue(() => enqueueRecentActivityTitleRefinement({ activityId: recentActivityResult.item.id }), {
236
- operationName: 'recent activity title refinement enqueue',
237
- }),
238
- )
239
- }
240
241
  }
241
242
  }
243
+ }
242
244
 
243
- if (shouldEnqueueRegularDigestForThread({ onboardingActive: params.onboardingActive, turnCount })) {
244
- yield* tryPostTurnSideEffect('Failed to enqueue regular chat memory digest.', () =>
245
- safeEnqueue(() => enqueueRegularChatMemoryDigest({ orgId: params.orgIdString }), {
246
- operationName: 'regular chat memory digest enqueue',
247
- }),
248
- )
249
- }
250
-
251
- if (shouldEnqueueSkillExtraction({ onboardingActive: params.onboardingActive, turnCount })) {
252
- yield* tryPostTurnSideEffect('Failed to enqueue skill extraction.', () =>
253
- safeEnqueue(() => enqueueSkillExtraction({ orgId: params.orgIdString }), {
254
- operationName: 'skill extraction enqueue',
255
- }),
256
- )
257
- }
245
+ if (shouldEnqueueRegularDigestForThread({ onboardingActive: params.onboardingActive, turnCount })) {
246
+ yield* tryPostTurnSideEffect('Failed to enqueue regular chat memory digest.', () =>
247
+ safeEnqueue(() => queues.organizationLearning.enqueueRegularChatMemoryDigest({ orgId: params.orgIdString }), {
248
+ operationName: 'regular chat memory digest enqueue',
249
+ }),
250
+ )
251
+ }
258
252
 
259
- if (shouldEnqueueMemoryConsolidation({ onboardingActive: params.onboardingActive, turnCount })) {
260
- yield* tryPostTurnSideEffect('Failed to enqueue memory consolidation.', () =>
261
- safeEnqueue(() => enqueueMemoryConsolidation({ scopeId: params.orgIdString }), {
262
- operationName: 'memory consolidation enqueue',
263
- }),
264
- )
265
- }
266
- })
253
+ if (shouldEnqueueSkillExtraction({ onboardingActive: params.onboardingActive, turnCount })) {
254
+ yield* tryPostTurnSideEffect('Failed to enqueue skill extraction.', () =>
255
+ safeEnqueue(() => queues.organizationLearning.enqueueSkillExtraction({ orgId: params.orgIdString }), {
256
+ operationName: 'skill extraction enqueue',
257
+ }),
258
+ )
259
+ }
267
260
 
268
- export function runPostTurnSideEffects(params: PostTurnSideEffectsParams): Promise<void> {
269
- return runPromise(runPostTurnSideEffectsEffect(params))
270
- }
261
+ if (shouldEnqueueMemoryConsolidation({ onboardingActive: params.onboardingActive, turnCount })) {
262
+ yield* tryPostTurnSideEffect('Failed to enqueue memory consolidation.', () =>
263
+ safeEnqueue(() => queues.memoryConsolidation.enqueueMemoryConsolidation({ scopeId: params.orgIdString }), {
264
+ operationName: 'memory consolidation enqueue',
265
+ }),
266
+ )
267
+ }
268
+ })
@@ -8,8 +8,6 @@ import { DEFAULT_AI_GATEWAY_URL } from '../config/constants'
8
8
  import { OPENROUTER_FAST_RERANK_MODEL_ID } from '../config/model-constants'
9
9
  import type { LotaThreadConfig, ThreadBootstrapWelcomeConfig } from '../config/thread-defaults'
10
10
  import type { RecordIdRef } from '../db/record-id'
11
- import { getCurrentRuntime } from '../effect/runtime-ref'
12
- import { RuntimeConfigServiceTag } from '../effect/services'
13
11
  import type { NotificationService } from '../services/notification.service'
14
12
  import { isRecord } from '../utils/string'
15
13
  import type { GraphDesigner } from './graph-designer'
@@ -422,8 +420,4 @@ export function loadLotaRuntimeConfigFromEnv(
422
420
  )
423
421
  }
424
422
 
425
- export function getRuntimeConfig(): ResolvedLotaRuntimeConfig {
426
- return getCurrentRuntime().runSync(Effect.service(RuntimeConfigServiceTag))
427
- }
428
-
429
423
  export type { LotaThreadConfig }
@@ -8,15 +8,7 @@ import type {
8
8
  import type { ToolSet } from 'ai'
9
9
 
10
10
  import type { RecordIdRef } from '../db/record-id'
11
- import { resolveLotaService } from '../effect/runtime'
12
- import {
13
- RuntimeAdaptersServiceTag,
14
- RuntimeWorkerExtensionsServiceTag,
15
- ToolProvidersServiceTag,
16
- TurnHooksServiceTag,
17
- } from '../effect/services'
18
11
  import type { ReadableUploadMetadata } from '../storage/attachment-types'
19
- import type { LotaRuntimeWorkerExtensions } from './runtime-worker-registry'
20
12
 
21
13
  export interface LotaRuntimeBackgroundCursor {
22
14
  createdAt: Date
@@ -199,49 +191,3 @@ export interface LotaRuntimeAdapters {
199
191
  connectPluginDatabases?: () => Promise<void>
200
192
  withWorkspaceMemoryLock?: <T>(workspaceId: string, fn: () => Promise<T>) => Promise<T>
201
193
  }
202
-
203
- interface RuntimeExtensionsAccessors {
204
- adapters: LotaRuntimeAdapters
205
- turnHooks: LotaRuntimeTurnHooks
206
- toolProviders: ToolSet
207
- extraWorkers: LotaRuntimeWorkerExtensions
208
- }
209
-
210
- let runtimeExtensionsAccessors: RuntimeExtensionsAccessors | null = null
211
-
212
- export function configureRuntimeExtensionsAccessors(accessors: RuntimeExtensionsAccessors): void {
213
- runtimeExtensionsAccessors = accessors
214
- }
215
-
216
- export function clearRuntimeExtensionsAccessors(): void {
217
- runtimeExtensionsAccessors = null
218
- }
219
-
220
- export function getRuntimeAdapters(): LotaRuntimeAdapters {
221
- return runtimeExtensionsAccessors?.adapters ?? resolveLotaService(RuntimeAdaptersServiceTag)
222
- }
223
-
224
- export function getTurnHooks(): LotaRuntimeTurnHooks {
225
- return runtimeExtensionsAccessors?.turnHooks ?? resolveLotaService(TurnHooksServiceTag)
226
- }
227
-
228
- export function getToolProviders(): ToolSet {
229
- return runtimeExtensionsAccessors?.toolProviders ?? resolveLotaService(ToolProvidersServiceTag)
230
- }
231
-
232
- export function getConfiguredPluginDatabaseConnector(): (() => Promise<void>) | undefined {
233
- return getRuntimeAdapters().connectPluginDatabases
234
- }
235
-
236
- export function getExtraWorkers(): LotaRuntimeWorkerExtensions {
237
- return runtimeExtensionsAccessors?.extraWorkers ?? resolveLotaService(RuntimeWorkerExtensionsServiceTag)
238
- }
239
-
240
- export function withConfiguredWorkspaceMemoryLock<T>(workspaceId: string, fn: () => Promise<T>): Promise<T> {
241
- const adapter = getRuntimeAdapters().withWorkspaceMemoryLock
242
- if (!adapter) {
243
- return fn()
244
- }
245
-
246
- return adapter(workspaceId, fn)
247
- }
@@ -13,6 +13,7 @@
13
13
  import type { ManagedRuntime } from 'effect'
14
14
  import { Effect } from 'effect'
15
15
 
16
+ import { clearAiGatewayRuntime } from '../ai-gateway/ai-gateway'
16
17
  import { effectTryPromise } from '../effect/helpers'
17
18
  import type { LotaPlugin } from './plugin-types'
18
19
 
@@ -93,7 +94,6 @@ interface CreateDisconnectInput {
93
94
  runPromiseWithCurrentContext: <A, E>(effect: Effect.Effect<A, E, never>) => Promise<A>
94
95
  socialChatShutdown: () => Promise<void>
95
96
  disconnectPluginDatabases: () => Promise<void>
96
- onFinalize: () => void
97
97
  }
98
98
 
99
99
  /**
@@ -102,8 +102,7 @@ interface CreateDisconnectInput {
102
102
  * return the same in-flight promise.
103
103
  */
104
104
  export function createRuntimeDisconnect(input: CreateDisconnectInput): () => Promise<void> {
105
- const { managedRuntime, runPromiseWithCurrentContext, socialChatShutdown, disconnectPluginDatabases, onFinalize } =
106
- input
105
+ const { managedRuntime, runPromiseWithCurrentContext, socialChatShutdown, disconnectPluginDatabases } = input
107
106
 
108
107
  let disconnectPromise: Promise<void> | null = null
109
108
 
@@ -117,7 +116,8 @@ export function createRuntimeDisconnect(input: CreateDisconnectInput): () => Pro
117
116
  yield* Effect.ignore(effectTryPromise(() => socialChatShutdown()))
118
117
  yield* Effect.ignore(effectTryPromise(() => disconnectPluginDatabases()))
119
118
  yield* effectTryPromise(() => managedRuntime.dispose())
120
- }).pipe(Effect.ensuring(Effect.sync(onFinalize))),
119
+ yield* Effect.sync(() => clearAiGatewayRuntime())
120
+ }),
121
121
  )
122
122
  return disconnectPromise
123
123
  }