Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

31 changes: 31 additions & 0 deletions packages/server/src/gateway/connections/chat-instance-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ import {
resolveSecretValue,
} from "../secrets/index.js";
import { resolveAgentOptions } from "../services/platform-helpers.js";
import { orgContext, tryGetOrgId } from "../../lobu/stores/org-context.js";
import { getAgentOrganizationId } from "../../lobu/stores/postgres-stores.js";
import {
ConversationStateStore,
type HistoryEntry,
Expand Down Expand Up @@ -123,6 +125,10 @@ export class ChatInstanceManager {

try {
if (connection.status === "active") {
// Boot runs without an HTTP request, so AsyncLocalStorage has
// no orgId. startInstance() now self-binds the connection's
// agent org so PostgresSecretStore.get() resolves per-org
// refs correctly; see comment on startInstance().
await this.startInstance(connection);
}
} catch (error) {
Expand Down Expand Up @@ -500,6 +506,31 @@ export class ChatInstanceManager {
// --- Private ---

private async startInstance(connection: PlatformConnection): Promise<void> {
// Multi-tenant secret resolution: PostgresSecretStore.get/put route
// by AsyncLocalStorage org context (see #516). Some callers reach
// here with org context already bound (HTTP routes via agent-routes
// middleware); others don't (boot-time initialize(), the public
// /slack/events webhook, anywhere ensureConnectionRunning() is
// triggered without an HTTP request). Self-binding the connection's
// owning org keeps per-org secret refs resolvable from every entry
// point — no caller has to remember.
const callerOrgId = tryGetOrgId();
if (!callerOrgId && connection.templateAgentId) {
const organizationId = await getAgentOrganizationId(
connection.templateAgentId
);
if (organizationId) {
return orgContext.run({ organizationId }, () =>
this.startInstanceUnscoped(connection)
);
}
}
return this.startInstanceUnscoped(connection);
}

private async startInstanceUnscoped(
connection: PlatformConnection
): Promise<void> {
try {
// Resolve any `secret://` refs in the connection config to plaintext
// values for the Chat SDK adapter. This is idempotent — addConnection
Expand Down
Loading