@geminixiang/mikan 1.0.0-beta.56 → 1.0.0-beta.57
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/CHANGELOG.md +10 -0
- package/dist/env-manifest.d.ts.map +1 -1
- package/dist/env-manifest.js +0 -5
- package/dist/env-manifest.js.map +1 -1
- package/dist/harness/presenter.d.ts.map +1 -1
- package/dist/harness/presenter.js +5 -9
- package/dist/harness/presenter.js.map +1 -1
- package/dist/harness/runner.d.ts.map +1 -1
- package/dist/harness/runner.js +3 -3
- package/dist/harness/runner.js.map +1 -1
- package/dist/observability/index.d.ts +0 -1
- package/dist/observability/index.d.ts.map +1 -1
- package/dist/observability/index.js +8 -12
- package/dist/observability/index.js.map +1 -1
- package/dist/observability/sentry.d.ts.map +1 -1
- package/dist/observability/sentry.js +7 -10
- package/dist/observability/sentry.js.map +1 -1
- package/package.json +1 -1
- package/dist/observability/privacy.d.ts +0 -3
- package/dist/observability/privacy.d.ts.map +0 -1
- package/dist/observability/privacy.js +0 -12
- package/dist/observability/privacy.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runner.js","sourceRoot":"","sources":["../../src/harness/runner.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACvE,OAAO,EAAE,WAAW,EAAE,6BAA6B,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAC7F,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AACxE,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,EAAE,KAAK,EAAE,MAAM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QACE,KAAK;QACL,SAAS,EAAE,GAAG,EAAE,CAAC,aAAa,CAAC,oBAAoB,CAAC,KAAK,CAAC,QAAQ,CAAC;QACnE,sEAAsE;QACtE,sEAAsE;QACtE,sCAAsC;QACtC,SAAS,EAAE,eAAe;KAC3B,CACF,CAAC;IAEF,MAAM,YAAY,GAAG,MAAM,wBAAwB,CAAC;QAClD,MAAM;QACN,WAAW;QACX,UAAU;QACV,aAAa;KACd,CAAC,CAAC;IACH,OAAO,CAAC,MAAM,EAAE,cAAc,EAAE,CAAC;IACjC,MAAM,EAAE,WAAW,EAAE,iBAAiB,EAAE,GAAG,YAAY,CAAC;IACxD,MAAM,cAAc,GAAG,MAAM,wBAAwB,CAAC;QACpD,WAAW;QACX,oBAAoB,EAAE,WAAW,CAAC,oBAAoB;QACtD,UAAU;QACV,iBAAiB;KAClB,CAAC,CAAC;IACH,OAAO,oBAAoB,CAAC;QAC1B,OAAO;QACP,cAAc;QACd,eAAe;QACf,YAAY;QACZ,QAAQ;QACR,aAAa;QACb,KAAK;QACL,aAAa;QACb,WAAW;QACX,YAAY;QACZ,cAAc;QACd,YAAY;QACZ,WAAW;KACZ,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { Office, Workspace } from \"../office/index.js\";\nimport type { ExecutionToolContext, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, Model } from \"@earendil-works/pi-ai\";\nimport { MikanModels } from \"./models.js\";\nimport type { SessionStore } from \"../sessions/session-store.js\";\nimport { MikanAgentSession, DEFAULT_EVENT_BUDGET } from \"./session.js\";\nimport { runSubagent, DEFAULT_GLOBAL_SUBAGENT_SLOTS, SubagentSlotPool } from \"./subagent.js\";\nimport { loadSubagentProfiles } from \"./subagent-profiles.js\";\nimport { createMikanTools, createSubagentTool } from \"./tools/index.js\";\nimport { adaptAgentTool } from \"./tools/pi-tools.js\";\nimport { createSandboxExecutionEnv } from \"./execution-env.js\";\nimport { mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type {\n ConversationMessage,\n ConversationKind,\n ConversationResponder,\n MessagingInfo,\n PlatformName,\n} from \"../adapter.js\";\nimport { ActorExecutionResolver } from \"./execution-resolver.js\";\nimport type { DockerContainerManager } from \"../sandbox/provisioner.js\";\nimport {\n assertSandboxSupportsWorkspacePolicy,\n createExecutor,\n type Executor,\n type RuntimePathContext,\n type SandboxConfig,\n getUnresolvedSandboxPathContext,\n} from \"../sandbox/index.js\";\nimport type { VaultManager } from \"../vault/index.js\";\nimport { resolveWorkspaceProjection } from \"../office/projection.js\";\nimport type {\n RunnerExecutionContext,\n PreparedRunContext,\n RunPresentation,\n RunnerSessionState,\n} from \"./types.js\";\nimport type { CreateRunnerOptions, OfficeAddress, PiAgentWrapper } from \"../types.js\";\nimport { createHash } from \"node:crypto\";\nimport { resolveConversationSettings } from \"../config.js\";\nimport { provisionOfficeOpenConnectorToken } from \"./open-connector.js\";\nimport {\n addLifecycleEvent,\n telemetryIdentifier,\n updateActiveSpanAttribution,\n} from \"../observability/index.js\";\nimport { ChatHistorySync } from \"../sessions/chat-history-sync.js\";\nimport { conversationIdOf, isThreadSessionKey } from \"../sessions/session-key.js\";\nimport {\n extractSessionUuid,\n openManagedSession,\n type ThreadRootMessage,\n} from \"../sessions/store.js\";\nimport type { PlatformToolRunContext } from \"./tools/types.js\";\nimport { loadMikanSkills } from \"./skills.js\";\nimport {\n normalizeAttachRuntimePath,\n withStagedRuntimeFile,\n buildPromptPayload,\n buildSystemPrompt,\n buildTurnInstructions,\n getMemory,\n resolveTriggerAttribution,\n} from \"./prompt.js\";\nimport {\n attachSessionEventHandlers,\n activateRunPresentation,\n createRunState,\n finalizeRunResponse,\n isEventTriggerAttribution,\n reportUsageSummary,\n} from \"./presenter.js\";\n\nimport * as log from \"../log.js\";\n\n// One process-wide fan-out account: per-conversation queues serialize runs,\n// but each run can fan out up to the per-run cap — without this shared\n// ceiling, N busy conversations hold N × cap live subagent sessions.\nconst globalSubagentSlots = new SubagentSlotPool(DEFAULT_GLOBAL_SUBAGENT_SLOTS);\n\nasync function createConfiguredAgentSession(params: {\n workspaceDir: string;\n systemPrompt: string;\n model: Model<Api>;\n thinkingLevel: ThinkingLevel;\n tools: Awaited<ReturnType<typeof createMikanTools>>[\"tools\"];\n toolContext: ExecutionToolContext;\n sessionStore: SessionStore;\n models: MikanModels;\n}): Promise<MikanAgentSession> {\n const {\n workspaceDir,\n systemPrompt,\n model,\n thinkingLevel,\n tools,\n toolContext,\n sessionStore,\n models,\n } = params;\n const loadedProfiles = loadSubagentProfiles(workspaceDir);\n for (const diagnostic of loadedProfiles.diagnostics) {\n log.logWarning(`Subagent profile ignored: ${diagnostic.path}`, diagnostic.message);\n }\n\n const availableToolNames = new Set(tools.map((tool) => tool.name));\n const runnableProfiles = new Map(\n [...loadedProfiles.profiles].filter(([, profile]) =>\n profile.tools.every((tool) => availableToolNames.has(tool)),\n ),\n );\n let session: MikanAgentSession | undefined;\n const subagentTool = createSubagentTool(\n (request, hooks) =>\n runSubagent({\n request,\n ...(hooks?.onActivity ? { onActivity: hooks.onActivity } : {}),\n defaultModel: model,\n thinkingLevel,\n models,\n workspaceDir,\n availableTools: tools,\n profiles: runnableProfiles,\n slots: globalSubagentSlots,\n toolContext,\n parentMessages: [...session!.messages],\n onUsage: session!.captureExternalUsageSink(),\n }),\n runnableProfiles,\n );\n\n session = new MikanAgentSession({\n systemPrompt,\n model,\n thinkingLevel,\n tools: [...tools, adaptAgentTool(subagentTool)],\n toolContext,\n models,\n sessionStore,\n });\n const reloaded = await session.reloadFromSession();\n if (reloaded > 0) log.logInfo(`Reloaded ${reloaded} messages from session context`);\n return session;\n}\n\nfunction createRunnerExecutionContext(\n sandboxConfig: SandboxConfig,\n vaultManager: VaultManager | undefined,\n provisioner: DockerContainerManager | undefined,\n workspace: Workspace,\n): RunnerExecutionContext {\n const executionResolver =\n vaultManager && sandboxConfig.type !== \"host\"\n ? new ActorExecutionResolver(sandboxConfig, vaultManager, provisioner, workspace)\n : undefined;\n\n // activeExecutor is replaced at the start of each run() call when executionResolver\n // is present, so the stable `executor` wrapper always delegates to the latest resolved value.\n let activeExecutor: Executor =\n executionResolver !== undefined\n ? createExecutor({ type: \"host\" })\n : createExecutor(sandboxConfig);\n const executor: Executor = {\n exec(command, options) {\n return activeExecutor.exec(command, options);\n },\n readFile(path, options) {\n return activeExecutor.readFile(path, options);\n },\n readFileBase64(path, options) {\n return activeExecutor.readFileBase64(path, options);\n },\n writeFile(path, content, options) {\n return activeExecutor.writeFile(path, content, options);\n },\n getWorkspacePath(hostPath) {\n return activeExecutor.getWorkspacePath(hostPath);\n },\n getSandboxConfig() {\n return activeExecutor.getSandboxConfig();\n },\n getPathContext(hostWorkspaceRoot) {\n return activeExecutor.getPathContext(hostWorkspaceRoot);\n },\n };\n\n return {\n executor,\n async resolveForRun(context) {\n if (executionResolver) {\n const decision = await executionResolver.resolve(context);\n activeExecutor = decision.executor;\n return {\n pathContext: decision.pathContext,\n projection: decision.projection,\n };\n }\n\n const office = workspace.office(context.address);\n const projection = resolveWorkspaceProjection(office);\n assertSandboxSupportsWorkspacePolicy(\n sandboxConfig,\n projection.doorPolicy,\n projection.promptSources.globalMemoryReadOnly === true,\n );\n return {\n pathContext: executor.getPathContext(workspace.root),\n projection,\n };\n },\n };\n}\n\nfunction buildThreadSessionName(message: ThreadRootMessage | null): string | undefined {\n const text = message?.text?.trim();\n if (!text) return undefined;\n const userLabel = message?.userName || message?.user || \"unknown\";\n return `[${userLabel}]: ${text}`;\n}\n\nasync function resolveRunnerMcpServers(options: {\n office: Office;\n trustModel: CreateRunnerOptions[\"trustModel\"];\n platformWorkspaceId?: string;\n servers: ReturnType<typeof resolveConversationSettings>[\"mcpServers\"];\n openConnector?: CreateRunnerOptions[\"openConnector\"];\n signal?: AbortSignal;\n}): Promise<Awaited<ReturnType<typeof provisionOfficeOpenConnectorToken>>> {\n if (options.trustModel === \"open-trigger\") return {};\n return provisionOfficeOpenConnectorToken(\n options.office,\n options.platformWorkspaceId,\n options.servers,\n options.openConnector,\n options.signal,\n );\n}\n\ntype PrepareRunParams = {\n message: ConversationMessage;\n responder: ConversationResponder;\n platform: MessagingInfo;\n office: Office;\n executor: Executor;\n resolveForRun: RunnerExecutionContext[\"resolveForRun\"];\n session: MikanAgentSession;\n setEventContext: (context: {\n platform: string;\n conversationId: string;\n conversationKind: ConversationKind;\n userId: string;\n }) => void;\n setSandboxContext: (context: { address: OfficeAddress; userId: string }) => void;\n setUploadFunction: (fn: (filePath: string, title?: string) => Promise<void>) => void;\n setImageUploadFunction: (fn: (hostPath: string, title?: string) => Promise<void>) => void;\n setReactFunction: (fn: ((emoji: string) => Promise<void>) | null) => void;\n bindPlatformToolPacks: (ctx: PlatformToolRunContext) => void;\n};\n\ntype RunPromptContext = {\n pathContext: RuntimePathContext;\n memory: string;\n systemPrompt: string;\n triggerAttribution: string | undefined;\n};\n\nasync function preparePromptContext(params: PrepareRunParams): Promise<RunPromptContext> {\n const { message, platform, office, executor, resolveForRun, session } = params;\n const conversationId = office.address.conversationId;\n const decision = await resolveForRun({\n address: message.address,\n userId: message.userId,\n trustModel: platform.trustModel,\n });\n const { pathContext, projection } = decision;\n const reloaded = await session.reloadFromSession();\n if (reloaded > 0) {\n log.logInfo(`[${conversationId}] Reloaded ${reloaded} messages from context`);\n }\n\n const memory = await getMemory(projection);\n const conversationSkillLoad = loadMikanSkills(\n office,\n pathContext.runtimeWorkspaceRoot,\n projection,\n );\n const triggerAttribution = resolveTriggerAttribution(message);\n const systemPrompt = buildSystemPrompt({\n workspacePath: pathContext.runtimeWorkspaceRoot,\n office,\n memory,\n sandboxConfig: executor.getSandboxConfig(),\n platform,\n skills: conversationSkillLoad.skills,\n projection,\n skippedSkillLinks: conversationSkillLoad.skippedSkillLinks,\n });\n session.setSystemPrompt(systemPrompt);\n // A stable hash across turns verifies that turn-specific data did not leak\n // into the provider-cacheable system prompt.\n const promptHash = createHash(\"sha256\").update(systemPrompt).digest(\"hex\").slice(0, 8);\n log.logInfo(\n `[${conversationId}] System prompt (base): ${systemPrompt.length} chars, sha ${promptHash}`,\n );\n return { pathContext, memory, systemPrompt, triggerAttribution };\n}\n\nfunction bindRunCapabilities(params: PrepareRunParams, pathContext: RuntimePathContext): void {\n const {\n message,\n responder,\n platform,\n office,\n executor,\n setEventContext,\n setSandboxContext,\n setUploadFunction,\n setImageUploadFunction,\n setReactFunction,\n bindPlatformToolPacks,\n } = params;\n setEventContext({\n platform: platform.name,\n conversationId: office.address.conversationId,\n conversationKind: message.conversationKind,\n userId: message.userId,\n });\n setSandboxContext({ address: message.address, userId: message.userId });\n setUploadFunction(async (filePath: string, title?: string) => {\n const runtimePath = normalizeAttachRuntimePath(filePath, pathContext.runtimeWorkspaceRoot);\n await withStagedRuntimeFile(executor, runtimePath, (stagedPath) =>\n responder.uploadFile(stagedPath, title),\n );\n });\n // Generated images already live host-side and must not be staged through a sandbox.\n setImageUploadFunction(async (hostPath: string, title?: string) => {\n await responder.uploadFile(hostPath, title);\n });\n // Unset reaction support when the active responder cannot react.\n setReactFunction(responder.react ? async (emoji: string) => responder.react!(emoji) : null);\n bindPlatformToolPacks({\n conversationId: office.address.conversationId,\n platformName: platform.name,\n threadTs: message.threadTs,\n });\n}\n\nasync function prepareRunContext(params: PrepareRunParams): Promise<PreparedRunContext> {\n const { message, platform, office, executor } = params;\n const sessionConversation = conversationIdOf(message.sessionKey);\n await mkdir(join(office.dir, \"scratch\"), { recursive: true });\n const { pathContext, memory, systemPrompt, triggerAttribution } =\n await preparePromptContext(params);\n bindRunCapabilities(params, pathContext);\n\n log.logInfo(\n `Context sizes - system: ${systemPrompt.length} chars, memory: ${memory.length} chars`,\n );\n log.logInfo(`Channels: ${platform.channels.length}, Users: ${platform.users.length}`);\n\n const { userMessage, imageAttachments } = await buildPromptPayload(\n message,\n pathContext.runtimeWorkspaceRoot,\n pathContext,\n (runtimePath) => executor.readFileBase64(runtimePath),\n );\n const turnInstructions = buildTurnInstructions(\n message.id.startsWith(\"event:\"),\n triggerAttribution,\n platform.name,\n );\n const finalUserMessage = turnInstructions ? `${turnInstructions}\\n\\n${userMessage}` : userMessage;\n return {\n sessionConversation,\n userMessage: finalUserMessage,\n imageAttachments,\n triggerAttribution,\n };\n}\n\nasync function buildInitialSystemPrompt(params: {\n office: Office;\n pathContext: RuntimePathContext;\n projection: ReturnType<typeof resolveWorkspaceProjection>;\n sandboxConfig: CreateRunnerOptions[\"sandboxConfig\"];\n}): Promise<string> {\n const { office, pathContext, projection, sandboxConfig } = params;\n const memory = await getMemory(projection);\n const { skills, skippedSkillLinks } = loadMikanSkills(\n office,\n pathContext.runtimeWorkspaceRoot,\n projection,\n );\n return buildSystemPrompt({\n workspacePath: pathContext.runtimeWorkspaceRoot,\n office,\n memory,\n sandboxConfig,\n platform: {\n name: \"chat\",\n formattingGuide: \"\",\n channels: [],\n users: [],\n trustModel: \"membership\",\n },\n skills,\n projection,\n skippedSkillLinks,\n });\n}\n\nasync function rollbackRunnerResource(label: string, cleanup: () => Promise<void>): Promise<void> {\n try {\n await cleanup();\n } catch (error) {\n log.logWarning(`Runner rollback failed to ${label}`, String(error));\n }\n}\n\nasync function openRunnerSessionManager(params: {\n contextFile: string;\n runtimeWorkspaceRoot: string;\n sessionKey: string;\n threadRootMessage: ThreadRootMessage | null;\n}) {\n const { contextFile, runtimeWorkspaceRoot, sessionKey, threadRootMessage } = params;\n const sessionManager = await openManagedSession(contextFile, runtimeWorkspaceRoot);\n try {\n const threadSessionName = buildThreadSessionName(threadRootMessage);\n if (\n isThreadSessionKey(sessionKey) &&\n threadSessionName &&\n (await sessionManager.getSessionName()) !== threadSessionName\n ) {\n await sessionManager.setSessionName(threadSessionName);\n }\n return sessionManager;\n } catch (error) {\n await rollbackRunnerResource(\"close the session writer\", () => sessionManager.close());\n throw error;\n }\n}\n\nasync function createRunnerAgentSession(params: {\n workspaceDir: string;\n systemPrompt: string;\n model: Model<Api>;\n agentConfig: ReturnType<typeof resolveConversationSettings>;\n tools: ReturnType<typeof createMikanTools>[\"tools\"];\n toolContext: ExecutionToolContext;\n sessionManager: Awaited<ReturnType<typeof openManagedSession>>;\n modelRegistry: MikanModels;\n conversationId: string;\n signal?: AbortSignal;\n}) {\n const {\n workspaceDir,\n systemPrompt,\n model,\n agentConfig,\n tools,\n toolContext,\n sessionManager,\n modelRegistry,\n signal,\n } = params;\n const mcpTools = await sessionManager.connectMcp(agentConfig.mcpServers ?? {}, signal);\n return createConfiguredAgentSession({\n workspaceDir,\n systemPrompt,\n model,\n thinkingLevel: agentConfig.thinkingLevel,\n tools: [...tools, ...mcpTools.map(adaptAgentTool)],\n toolContext,\n sessionStore: sessionManager,\n models: modelRegistry,\n });\n}\n\ntype PreparedTurnParams = {\n prepared: PreparedRunContext;\n presentation: RunPresentation;\n message: ConversationMessage;\n responder: ConversationResponder;\n platform: MessagingInfo;\n runState: RunnerSessionState;\n session: MikanAgentSession;\n model: Model<Api>;\n agentConfig: ReturnType<typeof resolveConversationSettings>;\n sessionUuid: string;\n conversationId: string;\n contextFile: string;\n sessionView: CreateRunnerOptions[\"sessionView\"];\n};\n\nasync function runPreparedTurn(params: PreparedTurnParams): Promise<{\n stopReason: string;\n errorMessage?: string;\n}> {\n const {\n prepared,\n presentation,\n message,\n responder,\n platform,\n runState,\n session,\n model,\n agentConfig,\n sessionUuid,\n conversationId,\n contextFile,\n sessionView,\n } = params;\n if (runState.logCtx) {\n log.logAgentRunStart(runState.logCtx, model.provider, model.id, model.name);\n }\n\n updateActiveSpanAttribution({\n provider: model.provider,\n model: model.id,\n channel_id: telemetryIdentifier(\"conv\", prepared.sessionConversation),\n session_id: telemetryIdentifier(\"session_file\", sessionUuid),\n \"mikan.input.message_count\": 1,\n \"mikan.input.characters\": prepared.userMessage.length,\n \"mikan.input.attachment_count\": message.attachments?.length ?? 0,\n \"mikan.input.image_count\": prepared.imageAttachments.length,\n \"mikan.input.has_text\": prepared.userMessage.length > 0,\n });\n addLifecycleEvent(\"agent.prompt.sent\", {\n provider: model.provider,\n model: agentConfig.model,\n channel_id: prepared.sessionConversation,\n session_id: sessionUuid,\n attachment_count: message.attachments?.length ?? 0,\n image_attachment_count: prepared.imageAttachments.length,\n });\n\n const isEventRun = message.id.startsWith(\"event:\");\n await session.prompt(prepared.userMessage, {\n ...(prepared.imageAttachments.length > 0 ? { images: prepared.imageAttachments } : {}),\n ...(isEventRun ? { budget: DEFAULT_EVENT_BUDGET } : {}),\n });\n await presentation.wait();\n\n const sessionViewTokenStore = sessionView?.tokenStore;\n const sessionViewPortalBaseUrl = sessionView?.portalBaseUrl;\n let sessionViewLink: string | undefined;\n const createSessionViewLink =\n sessionViewTokenStore && sessionViewPortalBaseUrl\n ? () => {\n if (!sessionViewLink) {\n const token = sessionViewTokenStore.create({\n platform: platform.name as PlatformName,\n platformUserId: message.userId,\n conversationId,\n sessionKey: message.sessionKey,\n sessionFile: contextFile,\n platformUserName: message.userName,\n });\n sessionViewLink = `${sessionViewPortalBaseUrl}/session?token=${token.token}`;\n }\n return sessionViewLink;\n }\n : undefined;\n\n await finalizeRunResponse(responder, session, runState, {\n triggerSessionLink: isEventTriggerAttribution(prepared.triggerAttribution)\n ? createSessionViewLink?.()\n : undefined,\n createOverflowLink: createSessionViewLink,\n platform: platform.name,\n model,\n sessionConversation: prepared.sessionConversation,\n sessionUuid,\n });\n await reportUsageSummary({\n session,\n runState,\n responder,\n platform,\n model,\n agentConfig,\n sessionConversation: prepared.sessionConversation,\n sessionUuid,\n waitForQueue: presentation.wait,\n });\n return { stopReason: runState.stopReason, errorMessage: runState.errorMessage };\n}\n\ntype MikanToolBindings = ReturnType<typeof createMikanTools>;\n\ntype RunnerInterfaceParams = {\n conversationId: string;\n conversationDir: string;\n sessionKey: string;\n office: Office;\n sessionUuid: string;\n contextFile: string;\n sessionView: CreateRunnerOptions[\"sessionView\"];\n runState: RunnerSessionState;\n executor: Executor;\n resolveForRun: RunnerExecutionContext[\"resolveForRun\"];\n session: MikanAgentSession;\n model: Model<Api>;\n agentConfig: ReturnType<typeof resolveConversationSettings>;\n sessionManager: Awaited<ReturnType<typeof openManagedSession>>;\n chatSessionManager: ChatHistorySync;\n toolBindings: MikanToolBindings;\n};\n\nfunction createRunnerInterface(params: RunnerInterfaceParams): PiAgentWrapper {\n const {\n conversationId,\n conversationDir,\n sessionKey,\n office,\n sessionUuid,\n contextFile,\n sessionView,\n runState,\n executor,\n resolveForRun,\n session,\n model,\n agentConfig,\n sessionManager,\n chatSessionManager,\n toolBindings,\n } = params;\n return {\n async syncChatHistory(currentMessageId?: string): Promise<void> {\n await chatSessionManager.syncSessionManager({\n conversationDir,\n sessionKey,\n sessionManager,\n currentMessageId,\n });\n },\n\n async run(message, responder, platform) {\n const prepared = await prepareRunContext({\n message,\n responder,\n platform,\n office,\n executor,\n resolveForRun,\n session,\n setEventContext: toolBindings.setEventContext,\n setSandboxContext: toolBindings.setSandboxContext,\n setUploadFunction: toolBindings.setUploadFunction,\n setImageUploadFunction: toolBindings.setImageUploadFunction,\n setReactFunction: toolBindings.setReactFunction,\n bindPlatformToolPacks: toolBindings.bindPlatformToolPacks,\n });\n const presentation = activateRunPresentation(runState, {\n responder,\n sessionConversation: prepared.sessionConversation,\n userName: message.userName,\n sessionUuid,\n triggerAttribution: prepared.triggerAttribution,\n });\n try {\n return await runPreparedTurn({\n prepared,\n presentation,\n message,\n responder,\n platform,\n runState,\n session,\n model,\n agentConfig,\n sessionUuid,\n conversationId,\n contextFile,\n sessionView,\n });\n } finally {\n presentation.dispose();\n }\n },\n\n abort(): void {\n session.abort();\n },\n\n async dispose(): Promise<void> {\n await sessionManager.close();\n },\n\n getCurrentStep(): { toolName?: string; label?: string } | undefined {\n const first = runState.pendingTools.values().next().value;\n if (!first) return undefined;\n return {\n toolName: first.toolName,\n label: (first.args as { label?: string })?.label,\n };\n },\n };\n}\n\nasync function finishRunnerCreation(params: {\n options: CreateRunnerOptions;\n conversationId: string;\n conversationDir: string;\n workspaceDir: string;\n executor: Executor;\n resolveForRun: RunnerExecutionContext[\"resolveForRun\"];\n model: Model<Api>;\n modelRegistry: MikanModels;\n agentConfig: ReturnType<typeof resolveConversationSettings>;\n systemPrompt: string;\n sessionManager: Awaited<ReturnType<typeof openManagedSession>>;\n toolBindings: MikanToolBindings;\n toolContext: ExecutionToolContext;\n}): Promise<PiAgentWrapper> {\n const {\n options,\n conversationId,\n conversationDir,\n workspaceDir,\n executor,\n resolveForRun,\n model,\n modelRegistry,\n agentConfig,\n systemPrompt,\n sessionManager,\n toolBindings,\n toolContext,\n } = params;\n const { sessionKey, office, sessionScope, sessionView } = options;\n const { contextFile } = sessionScope;\n try {\n const sessionUuid = extractSessionUuid(contextFile);\n const chatSessionManager = new ChatHistorySync();\n const session = await createRunnerAgentSession({\n workspaceDir,\n systemPrompt,\n model,\n agentConfig,\n tools: toolBindings.tools,\n toolContext,\n sessionManager,\n modelRegistry,\n conversationId,\n signal: options.signal,\n });\n options.signal?.throwIfAborted();\n\n const runState = createRunState();\n attachSessionEventHandlers({ session, runState, model, agentConfig });\n\n return createRunnerInterface({\n conversationId,\n conversationDir,\n sessionKey,\n office,\n sessionUuid,\n contextFile,\n sessionView,\n runState,\n executor,\n resolveForRun,\n session,\n model,\n agentConfig,\n sessionManager,\n chatSessionManager,\n toolBindings,\n });\n } catch (error) {\n await rollbackRunnerResource(\"close the session writer\", () => sessionManager.close());\n throw error;\n }\n}\n\nexport async function createRunner(options: CreateRunnerOptions): Promise<PiAgentWrapper> {\n options.signal?.throwIfAborted();\n const {\n sandboxConfig,\n sessionKey,\n office,\n trustModel,\n sessionScope,\n vaultManager,\n provisioner,\n resourceController,\n platformToolPackFactories,\n } = options;\n const conversationId = office.address.conversationId;\n const conversationDir = office.dir;\n const workspaceDir = office.workspace.root;\n const resolvedAgentConfig = resolveConversationSettings(office);\n const mcpServers = await resolveRunnerMcpServers({\n office,\n trustModel,\n platformWorkspaceId: options.platformWorkspaceId,\n servers: resolvedAgentConfig.mcpServers,\n openConnector: options.openConnector,\n signal: options.signal,\n });\n options.signal?.throwIfAborted();\n const agentConfig = { ...resolvedAgentConfig, mcpServers };\n\n const projection = resolveWorkspaceProjection(office);\n // Bootstrap validation fails runner creation early. resolveForRun repeats\n // the check against the actor-specific decision before any provider call.\n assertSandboxSupportsWorkspacePolicy(\n sandboxConfig,\n projection.doorPolicy,\n projection.promptSources.globalMemoryReadOnly === true,\n );\n const { executor, resolveForRun } = createRunnerExecutionContext(\n sandboxConfig,\n vaultManager,\n provisioner,\n office.workspace,\n );\n const pathContext = getUnresolvedSandboxPathContext(sandboxConfig, workspaceDir);\n // The env wraps the stable executor wrapper, which delegates to the\n // actor-resolved executor per call, so one env serves every run.\n const toolContext: ExecutionToolContext = {\n env: createSandboxExecutionEnv(executor, sandboxConfig.type, pathContext.runtimeWorkspaceRoot),\n };\n\n const modelRegistry = options.models ?? MikanModels.create();\n if (modelRegistry.getError()) {\n log.logWarning(\"models.json load error\", modelRegistry.getError()!);\n }\n const model = modelRegistry.resolve(agentConfig.provider, agentConfig.model);\n\n // Create tools (per-runner, with per-runner upload function setter)\n const toolBindings = createMikanTools(\n executor,\n workspaceDir,\n { sandbox: sandboxConfig, resourceController: resourceController ?? provisioner },\n platformToolPackFactories ?? [],\n {\n model,\n getApiKey: () => modelRegistry.getApiKeyForProvider(model.provider),\n // The conversation's own office dir: mounted into the sandbox, unlike\n // the workspace base — generated images must land somewhere the agent\n // (and a future run) can still reach.\n outputDir: conversationDir,\n },\n );\n\n const systemPrompt = await buildInitialSystemPrompt({\n office,\n pathContext,\n projection,\n sandboxConfig,\n });\n options.signal?.throwIfAborted();\n const { contextFile, threadRootMessage } = sessionScope;\n const sessionManager = await openRunnerSessionManager({\n contextFile,\n runtimeWorkspaceRoot: pathContext.runtimeWorkspaceRoot,\n sessionKey,\n threadRootMessage,\n });\n return finishRunnerCreation({\n options,\n conversationId,\n conversationDir,\n workspaceDir,\n executor,\n resolveForRun,\n model,\n modelRegistry,\n agentConfig,\n systemPrompt,\n sessionManager,\n toolBindings,\n toolContext,\n });\n}\n"]}
|
|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ecutionToolContext, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, Model } from \"@earendil-works/pi-ai\";\nimport { MikanModels } from \"./models.js\";\nimport type { SessionStore } from \"../sessions/session-store.js\";\nimport { MikanAgentSession, DEFAULT_EVENT_BUDGET } from \"./session.js\";\nimport { runSubagent, DEFAULT_GLOBAL_SUBAGENT_SLOTS, SubagentSlotPool } from \"./subagent.js\";\nimport { loadSubagentProfiles } from \"./subagent-profiles.js\";\nimport { createMikanTools, createSubagentTool } from \"./tools/index.js\";\nimport { adaptAgentTool } from \"./tools/pi-tools.js\";\nimport { createSandboxExecutionEnv } from \"./execution-env.js\";\nimport { mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type {\n ConversationMessage,\n ConversationKind,\n ConversationResponder,\n MessagingInfo,\n PlatformName,\n} from \"../adapter.js\";\nimport { ActorExecutionResolver } from \"./execution-resolver.js\";\nimport type { DockerContainerManager } from \"../sandbox/provisioner.js\";\nimport {\n assertSandboxSupportsWorkspacePolicy,\n createExecutor,\n type Executor,\n type RuntimePathContext,\n type SandboxConfig,\n getUnresolvedSandboxPathContext,\n} from \"../sandbox/index.js\";\nimport type { VaultManager } from \"../vault/index.js\";\nimport { resolveWorkspaceProjection } from \"../office/projection.js\";\nimport type {\n RunnerExecutionContext,\n PreparedRunContext,\n RunPresentation,\n RunnerSessionState,\n} from \"./types.js\";\nimport type { CreateRunnerOptions, OfficeAddress, PiAgentWrapper } from \"../types.js\";\nimport { createHash } from \"node:crypto\";\nimport { resolveConversationSettings } from \"../config.js\";\nimport { provisionOfficeOpenConnectorToken } from \"./open-connector.js\";\nimport { addLifecycleEvent, updateActiveSpanAttribution } from \"../observability/index.js\";\nimport { ChatHistorySync } from \"../sessions/chat-history-sync.js\";\nimport { conversationIdOf, isThreadSessionKey } from \"../sessions/session-key.js\";\nimport {\n extractSessionUuid,\n openManagedSession,\n type ThreadRootMessage,\n} from \"../sessions/store.js\";\nimport type { PlatformToolRunContext } from \"./tools/types.js\";\nimport { loadMikanSkills } from \"./skills.js\";\nimport {\n normalizeAttachRuntimePath,\n withStagedRuntimeFile,\n buildPromptPayload,\n buildSystemPrompt,\n buildTurnInstructions,\n getMemory,\n resolveTriggerAttribution,\n} from \"./prompt.js\";\nimport {\n attachSessionEventHandlers,\n activateRunPresentation,\n createRunState,\n finalizeRunResponse,\n isEventTriggerAttribution,\n reportUsageSummary,\n} from \"./presenter.js\";\n\nimport * as log from \"../log.js\";\n\n// One process-wide fan-out account: per-conversation queues serialize runs,\n// but each run can fan out up to the per-run cap — without this shared\n// ceiling, N busy conversations hold N × cap live subagent sessions.\nconst globalSubagentSlots = new SubagentSlotPool(DEFAULT_GLOBAL_SUBAGENT_SLOTS);\n\nasync function createConfiguredAgentSession(params: {\n workspaceDir: string;\n systemPrompt: string;\n model: Model<Api>;\n thinkingLevel: ThinkingLevel;\n tools: Awaited<ReturnType<typeof createMikanTools>>[\"tools\"];\n toolContext: ExecutionToolContext;\n sessionStore: SessionStore;\n models: MikanModels;\n}): Promise<MikanAgentSession> {\n const {\n workspaceDir,\n systemPrompt,\n model,\n thinkingLevel,\n tools,\n toolContext,\n sessionStore,\n models,\n } = params;\n const loadedProfiles = loadSubagentProfiles(workspaceDir);\n for (const diagnostic of loadedProfiles.diagnostics) {\n log.logWarning(`Subagent profile ignored: ${diagnostic.path}`, diagnostic.message);\n }\n\n const availableToolNames = new Set(tools.map((tool) => tool.name));\n const runnableProfiles = new Map(\n [...loadedProfiles.profiles].filter(([, profile]) =>\n profile.tools.every((tool) => availableToolNames.has(tool)),\n ),\n );\n let session: MikanAgentSession | undefined;\n const subagentTool = createSubagentTool(\n (request, hooks) =>\n runSubagent({\n request,\n ...(hooks?.onActivity ? { onActivity: hooks.onActivity } : {}),\n defaultModel: model,\n thinkingLevel,\n models,\n workspaceDir,\n availableTools: tools,\n profiles: runnableProfiles,\n slots: globalSubagentSlots,\n toolContext,\n parentMessages: [...session!.messages],\n onUsage: session!.captureExternalUsageSink(),\n }),\n runnableProfiles,\n );\n\n session = new MikanAgentSession({\n systemPrompt,\n model,\n thinkingLevel,\n tools: [...tools, adaptAgentTool(subagentTool)],\n toolContext,\n models,\n sessionStore,\n });\n const reloaded = await session.reloadFromSession();\n if (reloaded > 0) log.logInfo(`Reloaded ${reloaded} messages from session context`);\n return session;\n}\n\nfunction createRunnerExecutionContext(\n sandboxConfig: SandboxConfig,\n vaultManager: VaultManager | undefined,\n provisioner: DockerContainerManager | undefined,\n workspace: Workspace,\n): RunnerExecutionContext {\n const executionResolver =\n vaultManager && sandboxConfig.type !== \"host\"\n ? new ActorExecutionResolver(sandboxConfig, vaultManager, provisioner, workspace)\n : undefined;\n\n // activeExecutor is replaced at the start of each run() call when executionResolver\n // is present, so the stable `executor` wrapper always delegates to the latest resolved value.\n let activeExecutor: Executor =\n executionResolver !== undefined\n ? createExecutor({ type: \"host\" })\n : createExecutor(sandboxConfig);\n const executor: Executor = {\n exec(command, options) {\n return activeExecutor.exec(command, options);\n },\n readFile(path, options) {\n return activeExecutor.readFile(path, options);\n },\n readFileBase64(path, options) {\n return activeExecutor.readFileBase64(path, options);\n },\n writeFile(path, content, options) {\n return activeExecutor.writeFile(path, content, options);\n },\n getWorkspacePath(hostPath) {\n return activeExecutor.getWorkspacePath(hostPath);\n },\n getSandboxConfig() {\n return activeExecutor.getSandboxConfig();\n },\n getPathContext(hostWorkspaceRoot) {\n return activeExecutor.getPathContext(hostWorkspaceRoot);\n },\n };\n\n return {\n executor,\n async resolveForRun(context) {\n if (executionResolver) {\n const decision = await executionResolver.resolve(context);\n activeExecutor = decision.executor;\n return {\n pathContext: decision.pathContext,\n projection: decision.projection,\n };\n }\n\n const office = workspace.office(context.address);\n const projection = resolveWorkspaceProjection(office);\n assertSandboxSupportsWorkspacePolicy(\n sandboxConfig,\n projection.doorPolicy,\n projection.promptSources.globalMemoryReadOnly === true,\n );\n return {\n pathContext: executor.getPathContext(workspace.root),\n projection,\n };\n },\n };\n}\n\nfunction buildThreadSessionName(message: ThreadRootMessage | null): string | undefined {\n const text = message?.text?.trim();\n if (!text) return undefined;\n const userLabel = message?.userName || message?.user || \"unknown\";\n return `[${userLabel}]: ${text}`;\n}\n\nasync function resolveRunnerMcpServers(options: {\n office: Office;\n trustModel: CreateRunnerOptions[\"trustModel\"];\n platformWorkspaceId?: string;\n servers: ReturnType<typeof resolveConversationSettings>[\"mcpServers\"];\n openConnector?: CreateRunnerOptions[\"openConnector\"];\n signal?: AbortSignal;\n}): Promise<Awaited<ReturnType<typeof provisionOfficeOpenConnectorToken>>> {\n if (options.trustModel === \"open-trigger\") return {};\n return provisionOfficeOpenConnectorToken(\n options.office,\n options.platformWorkspaceId,\n options.servers,\n options.openConnector,\n options.signal,\n );\n}\n\ntype PrepareRunParams = {\n message: ConversationMessage;\n responder: ConversationResponder;\n platform: MessagingInfo;\n office: Office;\n executor: Executor;\n resolveForRun: RunnerExecutionContext[\"resolveForRun\"];\n session: MikanAgentSession;\n setEventContext: (context: {\n platform: string;\n conversationId: string;\n conversationKind: ConversationKind;\n userId: string;\n }) => void;\n setSandboxContext: (context: { address: OfficeAddress; userId: string }) => void;\n setUploadFunction: (fn: (filePath: string, title?: string) => Promise<void>) => void;\n setImageUploadFunction: (fn: (hostPath: string, title?: string) => Promise<void>) => void;\n setReactFunction: (fn: ((emoji: string) => Promise<void>) | null) => void;\n bindPlatformToolPacks: (ctx: PlatformToolRunContext) => void;\n};\n\ntype RunPromptContext = {\n pathContext: RuntimePathContext;\n memory: string;\n systemPrompt: string;\n triggerAttribution: string | undefined;\n};\n\nasync function preparePromptContext(params: PrepareRunParams): Promise<RunPromptContext> {\n const { message, platform, office, executor, resolveForRun, session } = params;\n const conversationId = office.address.conversationId;\n const decision = await resolveForRun({\n address: message.address,\n userId: message.userId,\n trustModel: platform.trustModel,\n });\n const { pathContext, projection } = decision;\n const reloaded = await session.reloadFromSession();\n if (reloaded > 0) {\n log.logInfo(`[${conversationId}] Reloaded ${reloaded} messages from context`);\n }\n\n const memory = await getMemory(projection);\n const conversationSkillLoad = loadMikanSkills(\n office,\n pathContext.runtimeWorkspaceRoot,\n projection,\n );\n const triggerAttribution = resolveTriggerAttribution(message);\n const systemPrompt = buildSystemPrompt({\n workspacePath: pathContext.runtimeWorkspaceRoot,\n office,\n memory,\n sandboxConfig: executor.getSandboxConfig(),\n platform,\n skills: conversationSkillLoad.skills,\n projection,\n skippedSkillLinks: conversationSkillLoad.skippedSkillLinks,\n });\n session.setSystemPrompt(systemPrompt);\n // A stable hash across turns verifies that turn-specific data did not leak\n // into the provider-cacheable system prompt.\n const promptHash = createHash(\"sha256\").update(systemPrompt).digest(\"hex\").slice(0, 8);\n log.logInfo(\n `[${conversationId}] System prompt (base): ${systemPrompt.length} chars, sha ${promptHash}`,\n );\n return { pathContext, memory, systemPrompt, triggerAttribution };\n}\n\nfunction bindRunCapabilities(params: PrepareRunParams, pathContext: RuntimePathContext): void {\n const {\n message,\n responder,\n platform,\n office,\n executor,\n setEventContext,\n setSandboxContext,\n setUploadFunction,\n setImageUploadFunction,\n setReactFunction,\n bindPlatformToolPacks,\n } = params;\n setEventContext({\n platform: platform.name,\n conversationId: office.address.conversationId,\n conversationKind: message.conversationKind,\n userId: message.userId,\n });\n setSandboxContext({ address: message.address, userId: message.userId });\n setUploadFunction(async (filePath: string, title?: string) => {\n const runtimePath = normalizeAttachRuntimePath(filePath, pathContext.runtimeWorkspaceRoot);\n await withStagedRuntimeFile(executor, runtimePath, (stagedPath) =>\n responder.uploadFile(stagedPath, title),\n );\n });\n // Generated images already live host-side and must not be staged through a sandbox.\n setImageUploadFunction(async (hostPath: string, title?: string) => {\n await responder.uploadFile(hostPath, title);\n });\n // Unset reaction support when the active responder cannot react.\n setReactFunction(responder.react ? async (emoji: string) => responder.react!(emoji) : null);\n bindPlatformToolPacks({\n conversationId: office.address.conversationId,\n platformName: platform.name,\n threadTs: message.threadTs,\n });\n}\n\nasync function prepareRunContext(params: PrepareRunParams): Promise<PreparedRunContext> {\n const { message, platform, office, executor } = params;\n const sessionConversation = conversationIdOf(message.sessionKey);\n await mkdir(join(office.dir, \"scratch\"), { recursive: true });\n const { pathContext, memory, systemPrompt, triggerAttribution } =\n await preparePromptContext(params);\n bindRunCapabilities(params, pathContext);\n\n log.logInfo(\n `Context sizes - system: ${systemPrompt.length} chars, memory: ${memory.length} chars`,\n );\n log.logInfo(`Channels: ${platform.channels.length}, Users: ${platform.users.length}`);\n\n const { userMessage, imageAttachments } = await buildPromptPayload(\n message,\n pathContext.runtimeWorkspaceRoot,\n pathContext,\n (runtimePath) => executor.readFileBase64(runtimePath),\n );\n const turnInstructions = buildTurnInstructions(\n message.id.startsWith(\"event:\"),\n triggerAttribution,\n platform.name,\n );\n const finalUserMessage = turnInstructions ? `${turnInstructions}\\n\\n${userMessage}` : userMessage;\n return {\n sessionConversation,\n userMessage: finalUserMessage,\n imageAttachments,\n triggerAttribution,\n };\n}\n\nasync function buildInitialSystemPrompt(params: {\n office: Office;\n pathContext: RuntimePathContext;\n projection: ReturnType<typeof resolveWorkspaceProjection>;\n sandboxConfig: CreateRunnerOptions[\"sandboxConfig\"];\n}): Promise<string> {\n const { office, pathContext, projection, sandboxConfig } = params;\n const memory = await getMemory(projection);\n const { skills, skippedSkillLinks } = loadMikanSkills(\n office,\n pathContext.runtimeWorkspaceRoot,\n projection,\n );\n return buildSystemPrompt({\n workspacePath: pathContext.runtimeWorkspaceRoot,\n office,\n memory,\n sandboxConfig,\n platform: {\n name: \"chat\",\n formattingGuide: \"\",\n channels: [],\n users: [],\n trustModel: \"membership\",\n },\n skills,\n projection,\n skippedSkillLinks,\n });\n}\n\nasync function rollbackRunnerResource(label: string, cleanup: () => Promise<void>): Promise<void> {\n try {\n await cleanup();\n } catch (error) {\n log.logWarning(`Runner rollback failed to ${label}`, String(error));\n }\n}\n\nasync function openRunnerSessionManager(params: {\n contextFile: string;\n runtimeWorkspaceRoot: string;\n sessionKey: string;\n threadRootMessage: ThreadRootMessage | null;\n}) {\n const { contextFile, runtimeWorkspaceRoot, sessionKey, threadRootMessage } = params;\n const sessionManager = await openManagedSession(contextFile, runtimeWorkspaceRoot);\n try {\n const threadSessionName = buildThreadSessionName(threadRootMessage);\n if (\n isThreadSessionKey(sessionKey) &&\n threadSessionName &&\n (await sessionManager.getSessionName()) !== threadSessionName\n ) {\n await sessionManager.setSessionName(threadSessionName);\n }\n return sessionManager;\n } catch (error) {\n await rollbackRunnerResource(\"close the session writer\", () => sessionManager.close());\n throw error;\n }\n}\n\nasync function createRunnerAgentSession(params: {\n workspaceDir: string;\n systemPrompt: string;\n model: Model<Api>;\n agentConfig: ReturnType<typeof resolveConversationSettings>;\n tools: ReturnType<typeof createMikanTools>[\"tools\"];\n toolContext: ExecutionToolContext;\n sessionManager: Awaited<ReturnType<typeof openManagedSession>>;\n modelRegistry: MikanModels;\n conversationId: string;\n signal?: AbortSignal;\n}) {\n const {\n workspaceDir,\n systemPrompt,\n model,\n agentConfig,\n tools,\n toolContext,\n sessionManager,\n modelRegistry,\n signal,\n } = params;\n const mcpTools = await sessionManager.connectMcp(agentConfig.mcpServers ?? {}, signal);\n return createConfiguredAgentSession({\n workspaceDir,\n systemPrompt,\n model,\n thinkingLevel: agentConfig.thinkingLevel,\n tools: [...tools, ...mcpTools.map(adaptAgentTool)],\n toolContext,\n sessionStore: sessionManager,\n models: modelRegistry,\n });\n}\n\ntype PreparedTurnParams = {\n prepared: PreparedRunContext;\n presentation: RunPresentation;\n message: ConversationMessage;\n responder: ConversationResponder;\n platform: MessagingInfo;\n runState: RunnerSessionState;\n session: MikanAgentSession;\n model: Model<Api>;\n agentConfig: ReturnType<typeof resolveConversationSettings>;\n sessionUuid: string;\n conversationId: string;\n contextFile: string;\n sessionView: CreateRunnerOptions[\"sessionView\"];\n};\n\nasync function runPreparedTurn(params: PreparedTurnParams): Promise<{\n stopReason: string;\n errorMessage?: string;\n}> {\n const {\n prepared,\n presentation,\n message,\n responder,\n platform,\n runState,\n session,\n model,\n agentConfig,\n sessionUuid,\n conversationId,\n contextFile,\n sessionView,\n } = params;\n if (runState.logCtx) {\n log.logAgentRunStart(runState.logCtx, model.provider, model.id, model.name);\n }\n\n updateActiveSpanAttribution({\n provider: model.provider,\n model: model.id,\n channel_id: prepared.sessionConversation,\n session_id: sessionUuid,\n \"mikan.input.message_count\": 1,\n \"mikan.input.characters\": prepared.userMessage.length,\n \"mikan.input.attachment_count\": message.attachments?.length ?? 0,\n \"mikan.input.image_count\": prepared.imageAttachments.length,\n \"mikan.input.has_text\": prepared.userMessage.length > 0,\n });\n addLifecycleEvent(\"agent.prompt.sent\", {\n provider: model.provider,\n model: agentConfig.model,\n channel_id: prepared.sessionConversation,\n session_id: sessionUuid,\n attachment_count: message.attachments?.length ?? 0,\n image_attachment_count: prepared.imageAttachments.length,\n });\n\n const isEventRun = message.id.startsWith(\"event:\");\n await session.prompt(prepared.userMessage, {\n ...(prepared.imageAttachments.length > 0 ? { images: prepared.imageAttachments } : {}),\n ...(isEventRun ? { budget: DEFAULT_EVENT_BUDGET } : {}),\n });\n await presentation.wait();\n\n const sessionViewTokenStore = sessionView?.tokenStore;\n const sessionViewPortalBaseUrl = sessionView?.portalBaseUrl;\n let sessionViewLink: string | undefined;\n const createSessionViewLink =\n sessionViewTokenStore && sessionViewPortalBaseUrl\n ? () => {\n if (!sessionViewLink) {\n const token = sessionViewTokenStore.create({\n platform: platform.name as PlatformName,\n platformUserId: message.userId,\n conversationId,\n sessionKey: message.sessionKey,\n sessionFile: contextFile,\n platformUserName: message.userName,\n });\n sessionViewLink = `${sessionViewPortalBaseUrl}/session?token=${token.token}`;\n }\n return sessionViewLink;\n }\n : undefined;\n\n await finalizeRunResponse(responder, session, runState, {\n triggerSessionLink: isEventTriggerAttribution(prepared.triggerAttribution)\n ? createSessionViewLink?.()\n : undefined,\n createOverflowLink: createSessionViewLink,\n platform: platform.name,\n model,\n sessionConversation: prepared.sessionConversation,\n sessionUuid,\n });\n await reportUsageSummary({\n session,\n runState,\n responder,\n platform,\n model,\n agentConfig,\n sessionConversation: prepared.sessionConversation,\n sessionUuid,\n waitForQueue: presentation.wait,\n });\n return { stopReason: runState.stopReason, errorMessage: runState.errorMessage };\n}\n\ntype MikanToolBindings = ReturnType<typeof createMikanTools>;\n\ntype RunnerInterfaceParams = {\n conversationId: string;\n conversationDir: string;\n sessionKey: string;\n office: Office;\n sessionUuid: string;\n contextFile: string;\n sessionView: CreateRunnerOptions[\"sessionView\"];\n runState: RunnerSessionState;\n executor: Executor;\n resolveForRun: RunnerExecutionContext[\"resolveForRun\"];\n session: MikanAgentSession;\n model: Model<Api>;\n agentConfig: ReturnType<typeof resolveConversationSettings>;\n sessionManager: Awaited<ReturnType<typeof openManagedSession>>;\n chatSessionManager: ChatHistorySync;\n toolBindings: MikanToolBindings;\n};\n\nfunction createRunnerInterface(params: RunnerInterfaceParams): PiAgentWrapper {\n const {\n conversationId,\n conversationDir,\n sessionKey,\n office,\n sessionUuid,\n contextFile,\n sessionView,\n runState,\n executor,\n resolveForRun,\n session,\n model,\n agentConfig,\n sessionManager,\n chatSessionManager,\n toolBindings,\n } = params;\n return {\n async syncChatHistory(currentMessageId?: string): Promise<void> {\n await chatSessionManager.syncSessionManager({\n conversationDir,\n sessionKey,\n sessionManager,\n currentMessageId,\n });\n },\n\n async run(message, responder, platform) {\n const prepared = await prepareRunContext({\n message,\n responder,\n platform,\n office,\n executor,\n resolveForRun,\n session,\n setEventContext: toolBindings.setEventContext,\n setSandboxContext: toolBindings.setSandboxContext,\n setUploadFunction: toolBindings.setUploadFunction,\n setImageUploadFunction: toolBindings.setImageUploadFunction,\n setReactFunction: toolBindings.setReactFunction,\n bindPlatformToolPacks: toolBindings.bindPlatformToolPacks,\n });\n const presentation = activateRunPresentation(runState, {\n responder,\n sessionConversation: prepared.sessionConversation,\n userName: message.userName,\n sessionUuid,\n triggerAttribution: prepared.triggerAttribution,\n });\n try {\n return await runPreparedTurn({\n prepared,\n presentation,\n message,\n responder,\n platform,\n runState,\n session,\n model,\n agentConfig,\n sessionUuid,\n conversationId,\n contextFile,\n sessionView,\n });\n } finally {\n presentation.dispose();\n }\n },\n\n abort(): void {\n session.abort();\n },\n\n async dispose(): Promise<void> {\n await sessionManager.close();\n },\n\n getCurrentStep(): { toolName?: string; label?: string } | undefined {\n const first = runState.pendingTools.values().next().value;\n if (!first) return undefined;\n return {\n toolName: first.toolName,\n label: (first.args as { label?: string })?.label,\n };\n },\n };\n}\n\nasync function finishRunnerCreation(params: {\n options: CreateRunnerOptions;\n conversationId: string;\n conversationDir: string;\n workspaceDir: string;\n executor: Executor;\n resolveForRun: RunnerExecutionContext[\"resolveForRun\"];\n model: Model<Api>;\n modelRegistry: MikanModels;\n agentConfig: ReturnType<typeof resolveConversationSettings>;\n systemPrompt: string;\n sessionManager: Awaited<ReturnType<typeof openManagedSession>>;\n toolBindings: MikanToolBindings;\n toolContext: ExecutionToolContext;\n}): Promise<PiAgentWrapper> {\n const {\n options,\n conversationId,\n conversationDir,\n workspaceDir,\n executor,\n resolveForRun,\n model,\n modelRegistry,\n agentConfig,\n systemPrompt,\n sessionManager,\n toolBindings,\n toolContext,\n } = params;\n const { sessionKey, office, sessionScope, sessionView } = options;\n const { contextFile } = sessionScope;\n try {\n const sessionUuid = extractSessionUuid(contextFile);\n const chatSessionManager = new ChatHistorySync();\n const session = await createRunnerAgentSession({\n workspaceDir,\n systemPrompt,\n model,\n agentConfig,\n tools: toolBindings.tools,\n toolContext,\n sessionManager,\n modelRegistry,\n conversationId,\n signal: options.signal,\n });\n options.signal?.throwIfAborted();\n\n const runState = createRunState();\n attachSessionEventHandlers({ session, runState, model, agentConfig });\n\n return createRunnerInterface({\n conversationId,\n conversationDir,\n sessionKey,\n office,\n sessionUuid,\n contextFile,\n sessionView,\n runState,\n executor,\n resolveForRun,\n session,\n model,\n agentConfig,\n sessionManager,\n chatSessionManager,\n toolBindings,\n });\n } catch (error) {\n await rollbackRunnerResource(\"close the session writer\", () => sessionManager.close());\n throw error;\n }\n}\n\nexport async function createRunner(options: CreateRunnerOptions): Promise<PiAgentWrapper> {\n options.signal?.throwIfAborted();\n const {\n sandboxConfig,\n sessionKey,\n office,\n trustModel,\n sessionScope,\n vaultManager,\n provisioner,\n resourceController,\n platformToolPackFactories,\n } = options;\n const conversationId = office.address.conversationId;\n const conversationDir = office.dir;\n const workspaceDir = office.workspace.root;\n const resolvedAgentConfig = resolveConversationSettings(office);\n const mcpServers = await resolveRunnerMcpServers({\n office,\n trustModel,\n platformWorkspaceId: options.platformWorkspaceId,\n servers: resolvedAgentConfig.mcpServers,\n openConnector: options.openConnector,\n signal: options.signal,\n });\n options.signal?.throwIfAborted();\n const agentConfig = { ...resolvedAgentConfig, mcpServers };\n\n const projection = resolveWorkspaceProjection(office);\n // Bootstrap validation fails runner creation early. resolveForRun repeats\n // the check against the actor-specific decision before any provider call.\n assertSandboxSupportsWorkspacePolicy(\n sandboxConfig,\n projection.doorPolicy,\n projection.promptSources.globalMemoryReadOnly === true,\n );\n const { executor, resolveForRun } = createRunnerExecutionContext(\n sandboxConfig,\n vaultManager,\n provisioner,\n office.workspace,\n );\n const pathContext = getUnresolvedSandboxPathContext(sandboxConfig, workspaceDir);\n // The env wraps the stable executor wrapper, which delegates to the\n // actor-resolved executor per call, so one env serves every run.\n const toolContext: ExecutionToolContext = {\n env: createSandboxExecutionEnv(executor, sandboxConfig.type, pathContext.runtimeWorkspaceRoot),\n };\n\n const modelRegistry = options.models ?? MikanModels.create();\n if (modelRegistry.getError()) {\n log.logWarning(\"models.json load error\", modelRegistry.getError()!);\n }\n const model = modelRegistry.resolve(agentConfig.provider, agentConfig.model);\n\n // Create tools (per-runner, with per-runner upload function setter)\n const toolBindings = createMikanTools(\n executor,\n workspaceDir,\n { sandbox: sandboxConfig, resourceController: resourceController ?? provisioner },\n platformToolPackFactories ?? [],\n {\n model,\n getApiKey: () => modelRegistry.getApiKeyForProvider(model.provider),\n // The conversation's own office dir: mounted into the sandbox, unlike\n // the workspace base — generated images must land somewhere the agent\n // (and a future run) can still reach.\n outputDir: conversationDir,\n },\n );\n\n const systemPrompt = await buildInitialSystemPrompt({\n office,\n pathContext,\n projection,\n sandboxConfig,\n });\n options.signal?.throwIfAborted();\n const { contextFile, threadRootMessage } = sessionScope;\n const sessionManager = await openRunnerSessionManager({\n contextFile,\n runtimeWorkspaceRoot: pathContext.runtimeWorkspaceRoot,\n sessionKey,\n threadRootMessage,\n });\n return finishRunnerCreation({\n options,\n conversationId,\n conversationDir,\n workspaceDir,\n executor,\n resolveForRun,\n model,\n modelRegistry,\n agentConfig,\n systemPrompt,\n sessionManager,\n toolBindings,\n toolContext,\n });\n}\n"]}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import type { ObservabilityAttributes, ReportUserFacingErrorOptions, RunScopeContext, SubagentOutcomeReport } from "./types.js";
|
|
2
2
|
export type { ObservabilityAttributes, RunScopeContext } from "./types.js";
|
|
3
|
-
export { telemetryIdentifier } from "./privacy.js";
|
|
4
3
|
export interface ObservabilitySpan {
|
|
5
4
|
end(options?: {
|
|
6
5
|
attributes?: ObservabilityAttributes;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/observability/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/observability/index.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EACV,uBAAuB,EACvB,4BAA4B,EAC5B,eAAe,EACf,qBAAqB,EACtB,MAAM,YAAY,CAAC;AAEpB,YAAY,EAAE,uBAAuB,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE3E,MAAM,WAAW,iBAAiB;IAChC,GAAG,CAAC,OAAO,CAAC,EAAE;QAAE,UAAU,CAAC,EAAE,uBAAuB,CAAC;QAAC,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,IAAI,CAAC;CAChF;AACD,YAAY,EAAE,4BAA4B,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AACtF,O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CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAwBvF;AAED,wBAAgB,qBAAqB,CACnC,KAAK,EAAE,OAAO,EACd,OAAO,EAAE,4BAA4B,GACpC,MAAM,GAAG,SAAS,CAQpB;AAED,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAO/D;AAED,wBAAsB,qBAAqB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAsB/E;AAQD,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,qBAAqB,GAAG,MAAM,GAAG,SAAS,CAuDvF;AAED,wBAAgB,yBAAyB,CACvC,KAAK,EAAE,OAAO,EACd,MAAM,EAAE,IAAI,CAAC,qBAAqB,EAAE,QAAQ,GAAG,MAAM,GAAG,SAAS,CAAC,GACjE,MAAM,GAAG,SAAS,CAUpB"}
|
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
import { metrics, SpanStatusCode, trace } from "@opentelemetry/api";
|
|
2
2
|
import { addSentryBreadcrumb, captureSentryError, closeSentry, recordSentryCounter, recordSentryDistribution, recordSentryGauge, sanitizeTelemetryString, sanitizeValue, withSentryRunScope, } from "./sentry.js";
|
|
3
3
|
import { isOpenTelemetryMetricsEnabled, shutdownOpenTelemetry } from "./otel.js";
|
|
4
|
-
import { telemetryIdentifier } from "./privacy.js";
|
|
5
|
-
export { telemetryIdentifier } from "./privacy.js";
|
|
6
4
|
export { sanitizeBreadcrumb } from "./sentry.js";
|
|
7
5
|
const tracer = trace.getTracer("@geminixiang/mikan");
|
|
8
6
|
const meter = metrics.getMeter("@geminixiang/mikan");
|
|
@@ -69,24 +67,22 @@ export function recordGauge(name, value, options = {}) {
|
|
|
69
67
|
gauge.record(value, safeAttributes);
|
|
70
68
|
}
|
|
71
69
|
export function createRunAttributionAttributes(context) {
|
|
72
|
-
const conversationId = telemetryIdentifier("conv", context.conversationId);
|
|
73
|
-
const sessionId = telemetryIdentifier("session", context.sessionKey);
|
|
74
70
|
return metricAttributes({
|
|
75
|
-
conversation_id: conversationId,
|
|
76
|
-
channel_id: conversationId,
|
|
77
|
-
session_key:
|
|
78
|
-
message_id:
|
|
71
|
+
conversation_id: context.conversationId,
|
|
72
|
+
channel_id: context.conversationId,
|
|
73
|
+
session_key: context.sessionKey,
|
|
74
|
+
message_id: context.messageId,
|
|
79
75
|
platform: context.platform,
|
|
80
76
|
conversation_kind: context.conversationKind,
|
|
81
|
-
user_id:
|
|
82
|
-
thread_id: context.threadTs
|
|
77
|
+
user_id: context.userId,
|
|
78
|
+
thread_id: context.threadTs,
|
|
83
79
|
provider: context.provider,
|
|
84
80
|
model: context.model,
|
|
85
81
|
"gen_ai.operation.name": "invoke_agent",
|
|
86
82
|
"gen_ai.agent.name": "mikan",
|
|
87
|
-
"gen_ai.conversation.id":
|
|
83
|
+
"gen_ai.conversation.id": context.sessionKey,
|
|
88
84
|
"openinference.span.kind": "AGENT",
|
|
89
|
-
"session.id":
|
|
85
|
+
"session.id": context.sessionKey,
|
|
90
86
|
});
|
|
91
87
|
}
|
|
92
88
|
export async function withRunSpan(context, body) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/observability/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,cAAc,EAAE,KAAK,EAAmB,MAAM,oBAAoB,CAAC;AACrF,OAAO,EACL,mBAAmB,EACnB,kBAAkB,EAClB,WAAW,EACX,mBAAmB,EACnB,wBAAwB,EACxB,iBAAiB,EACjB,uBAAuB,EACvB,aAAa,EACb,kBAAkB,GACnB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,6BAA6B,EAAE,qBAAqB,EAAE,MAAM,WAAW,CAAC;AACjF,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AASnD,OAAO,EAAE,mBAAmB,EAAE,MAAM,c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es } from \"@opentelemetry/api\";\nimport {\n addSentryBreadcrumb,\n captureSentryError,\n closeSentry,\n recordSentryCounter,\n recordSentryDistribution,\n recordSentryGauge,\n sanitizeTelemetryString,\n sanitizeValue,\n withSentryRunScope,\n} from \"./sentry.js\";\nimport { isOpenTelemetryMetricsEnabled, shutdownOpenTelemetry } from \"./otel.js\";\nimport { telemetryIdentifier } from \"./privacy.js\";\nimport type {\n ObservabilityAttributes,\n ReportUserFacingErrorOptions,\n RunScopeContext,\n SubagentOutcomeReport,\n} from \"./types.js\";\n\nexport type { ObservabilityAttributes, RunScopeContext } from \"./types.js\";\nexport { telemetryIdentifier } from \"./privacy.js\";\n\nexport interface ObservabilitySpan {\n end(options?: { attributes?: ObservabilityAttributes; error?: unknown }): void;\n}\nexport type { ReportUserFacingErrorOptions, SubagentOutcomeReport } from \"./types.js\";\nexport { sanitizeBreadcrumb } from \"./sentry.js\";\n\nconst tracer = trace.getTracer(\"@geminixiang/mikan\");\nconst meter = metrics.getMeter(\"@geminixiang/mikan\");\nconst counters = new Map<string, ReturnType<typeof meter.createCounter>>();\nconst histograms = new Map<string, ReturnType<typeof meter.createHistogram>>();\nconst gauges = new Map<string, ReturnType<typeof meter.createGauge>>();\n\nexport function metricAttributes(\n attributes: Record<string, string | number | boolean | undefined>,\n): ObservabilityAttributes {\n return Object.fromEntries(\n Object.entries(attributes).flatMap(([key, value]) => {\n if (value === undefined) return [];\n const sanitized = sanitizeValue(value, key);\n return typeof sanitized === \"string\" ||\n typeof sanitized === \"number\" ||\n typeof sanitized === \"boolean\"\n ? [[key, sanitized] as const]\n : [];\n }),\n );\n}\n\nexport function recordCounter(\n name: string,\n value: number,\n attributes: ObservabilityAttributes = {},\n): void {\n const safeAttributes = metricAttributes(attributes);\n if (!isOpenTelemetryMetricsEnabled()) {\n recordSentryCounter(name, value, safeAttributes);\n return;\n }\n let counter = counters.get(name);\n if (!counter) {\n counter = meter.createCounter(name);\n counters.set(name, counter);\n }\n counter.add(value, safeAttributes as Attributes);\n}\n\nexport function recordDistribution(\n name: string,\n value: number,\n options: { unit?: string; attributes?: ObservabilityAttributes } = {},\n): void {\n const safeAttributes = metricAttributes(options.attributes ?? {});\n if (!isOpenTelemetryMetricsEnabled()) {\n recordSentryDistribution(name, value, {\n ...(options.unit ? { unit: options.unit } : {}),\n attributes: safeAttributes,\n });\n return;\n }\n const key = `${name}\\0${options.unit ?? \"\"}`;\n let histogram = histograms.get(key);\n if (!histogram) {\n histogram = meter.createHistogram(name, options.unit ? { unit: options.unit } : undefined);\n histograms.set(key, histogram);\n }\n histogram.record(value, safeAttributes as Attributes);\n}\n\nexport function recordGauge(\n name: string,\n value: number,\n options: { unit?: string; attributes?: ObservabilityAttributes } = {},\n): void {\n const safeAttributes = metricAttributes(options.attributes ?? {});\n if (!isOpenTelemetryMetricsEnabled()) {\n recordSentryGauge(name, value, {\n ...(options.unit ? { unit: options.unit } : {}),\n attributes: safeAttributes,\n });\n return;\n }\n const key = `${name}\\0${options.unit ?? \"\"}`;\n let gauge = gauges.get(key);\n if (!gauge) {\n gauge = meter.createGauge(name, options.unit ? { unit: options.unit } : undefined);\n gauges.set(key, gauge);\n }\n gauge.record(value, safeAttributes as Attributes);\n}\n\nexport function createRunAttributionAttributes(context: RunScopeContext): ObservabilityAttributes {\n const conversationId = telemetryIdentifier(\"conv\", context.conversationId);\n const sessionId = telemetryIdentifier(\"session\", context.sessionKey);\n return metricAttributes({\n conversation_id: conversationId,\n channel_id: conversationId,\n session_key: sessionId,\n message_id: telemetryIdentifier(\"message\", context.messageId),\n platform: context.platform,\n conversation_kind: context.conversationKind,\n user_id: telemetryIdentifier(\"user\", context.userId),\n thread_id: context.threadTs ? telemetryIdentifier(\"thread\", context.threadTs) : undefined,\n provider: context.provider,\n model: context.model,\n \"gen_ai.operation.name\": \"invoke_agent\",\n \"gen_ai.agent.name\": \"mikan\",\n \"gen_ai.conversation.id\": sessionId,\n \"openinference.span.kind\": \"AGENT\",\n \"session.id\": sessionId,\n });\n}\n\nexport async function withRunSpan<T>(context: RunScopeContext, body: () => Promise<T>): Promise<T> {\n const attribution = createRunAttributionAttributes(context);\n return tracer.startActiveSpan(\"agent.run\", { attributes: attribution as Attributes }, (span) =>\n withSentryRunScope(context, async () => {\n try {\n return await body();\n } catch (error) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: safeErrorType(error) });\n throw error;\n } finally {\n span.end();\n }\n }),\n );\n}\n\nexport function startOperationSpan(\n name: string,\n attributes: ObservabilityAttributes = {},\n): ObservabilitySpan {\n const span = tracer.startSpan(name, {\n attributes: metricAttributes(attributes) as Attributes,\n });\n return {\n end(options = {}) {\n if (options.attributes) {\n span.setAttributes(metricAttributes(options.attributes) as Attributes);\n }\n if (options.error !== undefined) {\n const errorType = safeErrorType(options.error);\n span.setAttribute(\"error.type\", errorType);\n span.setStatus({ code: SpanStatusCode.ERROR, message: errorType });\n }\n span.end();\n },\n };\n}\n\nexport function updateActiveSpanAttribution(attributes: ObservabilityAttributes): void {\n trace.getActiveSpan()?.setAttributes(metricAttributes(attributes) as Attributes);\n}\n\nexport function addLifecycleEvent(\n name: string,\n attributes?: Record<string, string | number | boolean | undefined>,\n): void {\n const safeAttributes = attributes ? metricAttributes(attributes) : undefined;\n trace.getActiveSpan()?.addEvent(name, safeAttributes as Attributes | undefined);\n addSentryBreadcrumb(name, safeAttributes);\n}\n\n/** Record a deliberately shaped diagnostic payload; the Sentry adapter sanitizes it again. */\nexport function recordDiagnosticEvent(name: string, data: Record<string, unknown>): void {\n const spanAttributes = metricAttributes(\n Object.fromEntries(\n Object.entries(data).filter((entry): entry is [string, string | number | boolean] => {\n const value = entry[1];\n return typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\";\n }),\n ),\n );\n trace.getActiveSpan()?.addEvent(name, spanAttributes as Attributes);\n const recovered = name === \"slack.update.recovered\";\n addSentryBreadcrumb(\n recovered\n ? \"Slack update recovered\"\n : name === \"slack.update.rejected\"\n ? \"Slack update rejected\"\n : name,\n data,\n {\n category: name.startsWith(\"slack.update.\") ? \"slack.update\" : \"diagnostic\",\n level: name.endsWith(\".rejected\") ? \"warning\" : \"info\",\n log: recovered,\n },\n );\n}\n\nexport function reportUserFacingError(\n error: unknown,\n options: ReportUserFacingErrorOptions,\n): string | undefined {\n if (options.expected) return undefined;\n const span = trace.getActiveSpan();\n if (span) {\n span.setAttribute(\"error.type\", safeErrorType(error));\n span.setStatus({ code: SpanStatusCode.ERROR, message: safeErrorType(error) });\n }\n return captureSentryError(error, options);\n}\n\nexport function captureError(error: unknown): string | undefined {\n return reportUserFacingError(error, {\n domain: \"mikan\",\n surface: \"process\",\n operation: \"shutdown\",\n severity: \"error\",\n });\n}\n\nexport async function shutdownObservability(timeoutMs: number): Promise<boolean> {\n let openTelemetryFailure: unknown;\n try {\n await shutdownOpenTelemetry();\n } catch (error) {\n openTelemetryFailure = error;\n }\n\n let sentryClosed: boolean;\n try {\n sentryClosed = await closeSentry(timeoutMs);\n } catch (error) {\n if (openTelemetryFailure !== undefined) {\n const failure = new Error(\"Observability shutdown failed\", { cause: error });\n Object.assign(failure, { errors: [openTelemetryFailure, error] });\n throw failure;\n }\n throw new Error(\"Sentry shutdown failed\", { cause: error });\n }\n\n if (openTelemetryFailure !== undefined) throw openTelemetryFailure;\n return sentryClosed;\n}\n\nfunction safeErrorType(error: unknown): string {\n if (error instanceof Error && /^[A-Za-z][A-Za-z0-9_.-]{0,79}$/.test(error.name))\n return error.name;\n return \"Error\";\n}\n\nexport function recordSubagentOutcome(report: SubagentOutcomeReport): string | undefined {\n const attributes = metricAttributes({\n status: report.status,\n profile: report.profile,\n mode: report.mode,\n });\n recordCounter(\"agent.subagent.runs\", 1, attributes);\n if (report.durationMs !== undefined) {\n recordDistribution(\"agent.subagent.duration\", report.durationMs, {\n unit: \"millisecond\",\n attributes,\n });\n }\n addLifecycleEvent(\"agent.subagent.completed\", {\n item_id: report.itemId,\n status: report.status,\n profile: report.profile,\n mode: report.mode,\n turns: report.turns,\n tool_calls: report.toolCalls,\n tokens: report.tokens,\n cost_usd: report.costUsd,\n duration_ms: report.durationMs,\n cleanup_pending: report.cleanupPending,\n });\n if (report.status !== \"failed\" && report.status !== \"invalid_output\") return undefined;\n const errorClass = sanitizeTelemetryString(\n (report.error ?? report.status).split(\":\")[0]!.trim(),\n ).slice(0, 80);\n return reportUserFacingError(\n new Error(`Subagent ${report.status}: ${report.error ?? \"no error detail\"}`),\n {\n domain: \"subagent\",\n surface: \"subagent_tool\",\n operation: \"run\",\n severity: \"error\",\n toolName: \"subagent\",\n fingerprint: [\"subagent\", report.status, errorClass],\n tags: {\n subagent_status: report.status,\n subagent_profile: report.profile,\n subagent_mode: report.mode,\n cleanup_pending: report.cleanupPending,\n },\n context: {\n itemId: report.itemId,\n error: report.error,\n turns: report.turns,\n toolCalls: report.toolCalls,\n tokens: report.tokens,\n costUsd: report.costUsd,\n durationMs: report.durationMs,\n },\n },\n );\n}\n\nexport function reportSubagentLaunchError(\n error: unknown,\n report: Pick<SubagentOutcomeReport, \"itemId\" | \"mode\" | \"profile\">,\n): string | undefined {\n return reportUserFacingError(error, {\n domain: \"subagent\",\n surface: \"subagent_tool\",\n operation: \"launch\",\n severity: \"error\",\n toolName: \"subagent\",\n tags: { subagent_profile: report.profile, subagent_mode: report.mode },\n context: { itemId: report.itemId },\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/observability/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,cAAc,EAAE,KAAK,EAAmB,MAAM,oBAAoB,CAAC;AACrF,OAAO,EACL,mBAAmB,EACnB,kBAAkB,EAClB,WAAW,EACX,mBAAmB,EACnB,wBAAwB,EACxB,iBAAiB,EACjB,uBAAuB,EACvB,aAAa,EACb,kBAAkB,GACnB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,6BAA6B,EAAE,qBAAqB,EAAE,MAAM,WAAW,CAAC;AAcjF,OAAO,EAAE,kBAAkB,EAAE,MAA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AU,CAAC;QACpD,IAAI,EAAE;YACJ,eAAe,EAAE,MAAM,CAAC,MAAM;YAC9B,gBAAgB,EAAE,MAAM,CAAC,OAAO;YAChC,aAAa,EAAE,MAAM,CAAC,IAAI;YAC1B,eAAe,EAAE,MAAM,CAAC,cAAc;SACvC;QACD,OAAO,EAAE;YACP,MAAM,EAAE,MAAM,CAAC,MAAM;YACrB,KAAK,EAAE,MAAM,CAAC,KAAK;YACnB,KAAK,EAAE,MAAM,CAAC,KAAK;YACnB,SAAS,EAAE,MAAM,CAAC,SAAS;YAC3B,MAAM,EAAE,MAAM,CAAC,MAAM;YACrB,OAAO,EAAE,MAAM,CAAC,OAAO;YACvB,UAAU,EAAE,MAAM,CAAC,UAAU;SAC9B;KACF,CACF,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,yBAAyB,CACvC,KAAc,EACd,MAAkE;IAElE,OAAO,qBAAqB,CAAC,KAAK,EAAE;QAClC,MAAM,EAAE,UAAU;QAClB,OAAO,EAAE,eAAe;QACxB,SAAS,EAAE,QAAQ;QACnB,QAAQ,EAAE,OAAO;QACjB,QAAQ,EAAE,UAAU;QACpB,IAAI,EAAE,EAAE,gBAAgB,EAAE,MAAM,CAAC,OAAO,EAAE,aAAa,EAAE,MAAM,CAAC,IAAI,EAAE;QACtE,OAAO,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE;KACnC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { metrics, SpanStatusCode, trace, type Attributes } from \"@opentelemetry/api\";\nimport {\n addSentryBreadcrumb,\n captureSentryError,\n closeSentry,\n recordSentryCounter,\n recordSentryDistribution,\n recordSentryGauge,\n sanitizeTelemetryString,\n sanitizeValue,\n withSentryRunScope,\n} from \"./sentry.js\";\nimport { isOpenTelemetryMetricsEnabled, shutdownOpenTelemetry } from \"./otel.js\";\nimport type {\n ObservabilityAttributes,\n ReportUserFacingErrorOptions,\n RunScopeContext,\n SubagentOutcomeReport,\n} from \"./types.js\";\n\nexport type { ObservabilityAttributes, RunScopeContext } from \"./types.js\";\n\nexport interface ObservabilitySpan {\n end(options?: { attributes?: ObservabilityAttributes; error?: unknown }): void;\n}\nexport type { ReportUserFacingErrorOptions, SubagentOutcomeReport } from \"./types.js\";\nexport { sanitizeBreadcrumb } from \"./sentry.js\";\n\nconst tracer = trace.getTracer(\"@geminixiang/mikan\");\nconst meter = metrics.getMeter(\"@geminixiang/mikan\");\nconst counters = new Map<string, ReturnType<typeof meter.createCounter>>();\nconst histograms = new Map<string, ReturnType<typeof meter.createHistogram>>();\nconst gauges = new Map<string, ReturnType<typeof meter.createGauge>>();\n\nexport function metricAttributes(\n attributes: Record<string, string | number | boolean | undefined>,\n): ObservabilityAttributes {\n return Object.fromEntries(\n Object.entries(attributes).flatMap(([key, value]) => {\n if (value === undefined) return [];\n const sanitized = sanitizeValue(value, key);\n return typeof sanitized === \"string\" ||\n typeof sanitized === \"number\" ||\n typeof sanitized === \"boolean\"\n ? [[key, sanitized] as const]\n : [];\n }),\n );\n}\n\nexport function recordCounter(\n name: string,\n value: number,\n attributes: ObservabilityAttributes = {},\n): void {\n const safeAttributes = metricAttributes(attributes);\n if (!isOpenTelemetryMetricsEnabled()) {\n recordSentryCounter(name, value, safeAttributes);\n return;\n }\n let counter = counters.get(name);\n if (!counter) {\n counter = meter.createCounter(name);\n counters.set(name, counter);\n }\n counter.add(value, safeAttributes as Attributes);\n}\n\nexport function recordDistribution(\n name: string,\n value: number,\n options: { unit?: string; attributes?: ObservabilityAttributes } = {},\n): void {\n const safeAttributes = metricAttributes(options.attributes ?? {});\n if (!isOpenTelemetryMetricsEnabled()) {\n recordSentryDistribution(name, value, {\n ...(options.unit ? { unit: options.unit } : {}),\n attributes: safeAttributes,\n });\n return;\n }\n const key = `${name}\\0${options.unit ?? \"\"}`;\n let histogram = histograms.get(key);\n if (!histogram) {\n histogram = meter.createHistogram(name, options.unit ? { unit: options.unit } : undefined);\n histograms.set(key, histogram);\n }\n histogram.record(value, safeAttributes as Attributes);\n}\n\nexport function recordGauge(\n name: string,\n value: number,\n options: { unit?: string; attributes?: ObservabilityAttributes } = {},\n): void {\n const safeAttributes = metricAttributes(options.attributes ?? {});\n if (!isOpenTelemetryMetricsEnabled()) {\n recordSentryGauge(name, value, {\n ...(options.unit ? { unit: options.unit } : {}),\n attributes: safeAttributes,\n });\n return;\n }\n const key = `${name}\\0${options.unit ?? \"\"}`;\n let gauge = gauges.get(key);\n if (!gauge) {\n gauge = meter.createGauge(name, options.unit ? { unit: options.unit } : undefined);\n gauges.set(key, gauge);\n }\n gauge.record(value, safeAttributes as Attributes);\n}\n\nexport function createRunAttributionAttributes(context: RunScopeContext): ObservabilityAttributes {\n return metricAttributes({\n conversation_id: context.conversationId,\n channel_id: context.conversationId,\n session_key: context.sessionKey,\n message_id: context.messageId,\n platform: context.platform,\n conversation_kind: context.conversationKind,\n user_id: context.userId,\n thread_id: context.threadTs,\n provider: context.provider,\n model: context.model,\n \"gen_ai.operation.name\": \"invoke_agent\",\n \"gen_ai.agent.name\": \"mikan\",\n \"gen_ai.conversation.id\": context.sessionKey,\n \"openinference.span.kind\": \"AGENT\",\n \"session.id\": context.sessionKey,\n });\n}\n\nexport async function withRunSpan<T>(context: RunScopeContext, body: () => Promise<T>): Promise<T> {\n const attribution = createRunAttributionAttributes(context);\n return tracer.startActiveSpan(\"agent.run\", { attributes: attribution as Attributes }, (span) =>\n withSentryRunScope(context, async () => {\n try {\n return await body();\n } catch (error) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: safeErrorType(error) });\n throw error;\n } finally {\n span.end();\n }\n }),\n );\n}\n\nexport function startOperationSpan(\n name: string,\n attributes: ObservabilityAttributes = {},\n): ObservabilitySpan {\n const span = tracer.startSpan(name, {\n attributes: metricAttributes(attributes) as Attributes,\n });\n return {\n end(options = {}) {\n if (options.attributes) {\n span.setAttributes(metricAttributes(options.attributes) as Attributes);\n }\n if (options.error !== undefined) {\n const errorType = safeErrorType(options.error);\n span.setAttribute(\"error.type\", errorType);\n span.setStatus({ code: SpanStatusCode.ERROR, message: errorType });\n }\n span.end();\n },\n };\n}\n\nexport function updateActiveSpanAttribution(attributes: ObservabilityAttributes): void {\n trace.getActiveSpan()?.setAttributes(metricAttributes(attributes) as Attributes);\n}\n\nexport function addLifecycleEvent(\n name: string,\n attributes?: Record<string, string | number | boolean | undefined>,\n): void {\n const safeAttributes = attributes ? metricAttributes(attributes) : undefined;\n trace.getActiveSpan()?.addEvent(name, safeAttributes as Attributes | undefined);\n addSentryBreadcrumb(name, safeAttributes);\n}\n\n/** Record a deliberately shaped diagnostic payload; the Sentry adapter sanitizes it again. */\nexport function recordDiagnosticEvent(name: string, data: Record<string, unknown>): void {\n const spanAttributes = metricAttributes(\n Object.fromEntries(\n Object.entries(data).filter((entry): entry is [string, string | number | boolean] => {\n const value = entry[1];\n return typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\";\n }),\n ),\n );\n trace.getActiveSpan()?.addEvent(name, spanAttributes as Attributes);\n const recovered = name === \"slack.update.recovered\";\n addSentryBreadcrumb(\n recovered\n ? \"Slack update recovered\"\n : name === \"slack.update.rejected\"\n ? \"Slack update rejected\"\n : name,\n data,\n {\n category: name.startsWith(\"slack.update.\") ? \"slack.update\" : \"diagnostic\",\n level: name.endsWith(\".rejected\") ? \"warning\" : \"info\",\n log: recovered,\n },\n );\n}\n\nexport function reportUserFacingError(\n error: unknown,\n options: ReportUserFacingErrorOptions,\n): string | undefined {\n if (options.expected) return undefined;\n const span = trace.getActiveSpan();\n if (span) {\n span.setAttribute(\"error.type\", safeErrorType(error));\n span.setStatus({ code: SpanStatusCode.ERROR, message: safeErrorType(error) });\n }\n return captureSentryError(error, options);\n}\n\nexport function captureError(error: unknown): string | undefined {\n return reportUserFacingError(error, {\n domain: \"mikan\",\n surface: \"process\",\n operation: \"shutdown\",\n severity: \"error\",\n });\n}\n\nexport async function shutdownObservability(timeoutMs: number): Promise<boolean> {\n let openTelemetryFailure: unknown;\n try {\n await shutdownOpenTelemetry();\n } catch (error) {\n openTelemetryFailure = error;\n }\n\n let sentryClosed: boolean;\n try {\n sentryClosed = await closeSentry(timeoutMs);\n } catch (error) {\n if (openTelemetryFailure !== undefined) {\n const failure = new Error(\"Observability shutdown failed\", { cause: error });\n Object.assign(failure, { errors: [openTelemetryFailure, error] });\n throw failure;\n }\n throw new Error(\"Sentry shutdown failed\", { cause: error });\n }\n\n if (openTelemetryFailure !== undefined) throw openTelemetryFailure;\n return sentryClosed;\n}\n\nfunction safeErrorType(error: unknown): string {\n if (error instanceof Error && /^[A-Za-z][A-Za-z0-9_.-]{0,79}$/.test(error.name))\n return error.name;\n return \"Error\";\n}\n\nexport function recordSubagentOutcome(report: SubagentOutcomeReport): string | undefined {\n const attributes = metricAttributes({\n status: report.status,\n profile: report.profile,\n mode: report.mode,\n });\n recordCounter(\"agent.subagent.runs\", 1, attributes);\n if (report.durationMs !== undefined) {\n recordDistribution(\"agent.subagent.duration\", report.durationMs, {\n unit: \"millisecond\",\n attributes,\n });\n }\n addLifecycleEvent(\"agent.subagent.completed\", {\n item_id: report.itemId,\n status: report.status,\n profile: report.profile,\n mode: report.mode,\n turns: report.turns,\n tool_calls: report.toolCalls,\n tokens: report.tokens,\n cost_usd: report.costUsd,\n duration_ms: report.durationMs,\n cleanup_pending: report.cleanupPending,\n });\n if (report.status !== \"failed\" && report.status !== \"invalid_output\") return undefined;\n const errorClass = sanitizeTelemetryString(\n (report.error ?? report.status).split(\":\")[0]!.trim(),\n ).slice(0, 80);\n return reportUserFacingError(\n new Error(`Subagent ${report.status}: ${report.error ?? \"no error detail\"}`),\n {\n domain: \"subagent\",\n surface: \"subagent_tool\",\n operation: \"run\",\n severity: \"error\",\n toolName: \"subagent\",\n fingerprint: [\"subagent\", report.status, errorClass],\n tags: {\n subagent_status: report.status,\n subagent_profile: report.profile,\n subagent_mode: report.mode,\n cleanup_pending: report.cleanupPending,\n },\n context: {\n itemId: report.itemId,\n error: report.error,\n turns: report.turns,\n toolCalls: report.toolCalls,\n tokens: report.tokens,\n costUsd: report.costUsd,\n durationMs: report.durationMs,\n },\n },\n );\n}\n\nexport function reportSubagentLaunchError(\n error: unknown,\n report: Pick<SubagentOutcomeReport, \"itemId\" | \"mode\" | \"profile\">,\n): string | undefined {\n return reportUserFacingError(error, {\n domain: \"subagent\",\n surface: \"subagent_tool\",\n operation: \"launch\",\n severity: \"error\",\n toolName: \"subagent\",\n tags: { subagent_profile: report.profile, subagent_mode: report.mode },\n context: { itemId: report.itemId },\n });\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sentry.d.ts","sourceRoot":"","sources":["../../src/observability/sentry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,UAAU,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AACpF,OAAO,KAAK,MAAM,MAAM,cAAc,CAAC;AAiEvC,YAAY,EACV,4BAA4B,EAC5B,2BAA2B,EAC3B,qBAAqB,EACrB,qBAAqB,EACrB,iBAAiB,EACjB,wBAAwB,GACzB,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"sentry.d.ts","sourceRoot":"","sources":["../../src/observability/sentry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,UAAU,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AACpF,OAAO,KAAK,MAAM,MAAM,cAAc,CAAC;AAiEvC,YAAY,EACV,4BAA4B,EAC5B,2BAA2B,EAC3B,qBAAqB,EACrB,qBAAqB,EACrB,iBAAiB,EACjB,wBAAwB,GACzB,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EACV,4BAA4B,EAC5B,2BAA2B,EAC3B,qBAAqB,EAErB,qBAAqB,EACrB,iBAAiB,EACjB,wBAAwB,EACzB,MAAM,YAAY,CAAC;AASpB,wBAAgB,uBAAuB,CAAC,GAAG,CAAC,EAAE,MAAM,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qB,EAAE,QAAQ,GAAG,MAAM,GAAG,SAAS,CAAC,GACjE,MAAM,GAAG,SAAS,CAUpB"}
|
|
@@ -59,7 +59,6 @@ const TOKEN_PATTERNS = [
|
|
|
59
59
|
/\bAIza[0-9A-Za-z_-]{20,}\b/,
|
|
60
60
|
/\bgh[pousr]_[A-Za-z0-9]{20,}\b/,
|
|
61
61
|
];
|
|
62
|
-
import { telemetryIdentifier } from "./privacy.js";
|
|
63
62
|
const traceAttribution = new Map();
|
|
64
63
|
export function createSentryInitOptions(dsn, customOpenTelemetry = false) {
|
|
65
64
|
return {
|
|
@@ -178,17 +177,15 @@ function setOptionalTag(scope, key, value) {
|
|
|
178
177
|
scope.setTag(key, value);
|
|
179
178
|
}
|
|
180
179
|
export function createRunAttributionAttributes(context) {
|
|
181
|
-
const conversationId = telemetryIdentifier("conv", context.conversationId);
|
|
182
|
-
const sessionId = telemetryIdentifier("session", context.sessionKey);
|
|
183
180
|
return metricAttributes({
|
|
184
|
-
conversation_id: conversationId,
|
|
185
|
-
channel_id: conversationId,
|
|
186
|
-
session_key:
|
|
187
|
-
message_id:
|
|
181
|
+
conversation_id: context.conversationId,
|
|
182
|
+
channel_id: context.conversationId,
|
|
183
|
+
session_key: context.sessionKey,
|
|
184
|
+
message_id: context.messageId,
|
|
188
185
|
platform: context.platform,
|
|
189
186
|
conversation_kind: context.conversationKind,
|
|
190
|
-
user_id:
|
|
191
|
-
thread_id: context.threadTs
|
|
187
|
+
user_id: context.userId,
|
|
188
|
+
thread_id: context.threadTs,
|
|
192
189
|
provider: context.provider,
|
|
193
190
|
model: context.model,
|
|
194
191
|
});
|
|
@@ -211,7 +208,7 @@ export function applyRunScope(scope, context) {
|
|
|
211
208
|
scope.setTag(key, value);
|
|
212
209
|
}
|
|
213
210
|
scope.setAttributes(attributes);
|
|
214
|
-
// Agent Monitoring groups spans by
|
|
211
|
+
// Agent Monitoring groups spans by the platform session identifier.
|
|
215
212
|
scope.setUser({ id: String(attributes.user_id) });
|
|
216
213
|
scope.setConversationId(String(attributes.session_key));
|
|
217
214
|
scope.setContext("agent_run", {
|