@geminixiang/mikan 1.0.0-beta.43 → 1.0.0-beta.45
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 +32 -0
- package/dist/adapters/discord/bot.d.ts.map +1 -1
- package/dist/adapters/discord/bot.js +3 -17
- package/dist/adapters/discord/bot.js.map +1 -1
- package/dist/adapters/discord/components.d.ts +2 -7
- package/dist/adapters/discord/components.d.ts.map +1 -1
- package/dist/adapters/discord/components.js.map +1 -1
- package/dist/adapters/discord/types.d.ts +7 -0
- package/dist/adapters/discord/types.d.ts.map +1 -1
- package/dist/adapters/discord/types.js.map +1 -1
- package/dist/adapters/github/bot.d.ts.map +1 -1
- package/dist/adapters/github/bot.js +10 -2
- package/dist/adapters/github/bot.js.map +1 -1
- package/dist/adapters/github/types.d.ts +5 -0
- package/dist/adapters/github/types.d.ts.map +1 -1
- package/dist/adapters/github/types.js.map +1 -1
- package/dist/adapters/github/webhook.d.ts +2 -5
- package/dist/adapters/github/webhook.d.ts.map +1 -1
- package/dist/adapters/github/webhook.js.map +1 -1
- package/dist/adapters/markdown-tables.d.ts +2 -7
- package/dist/adapters/markdown-tables.d.ts.map +1 -1
- package/dist/adapters/markdown-tables.js.map +1 -1
- package/dist/adapters/slack/assistant.d.ts +2 -30
- package/dist/adapters/slack/assistant.d.ts.map +1 -1
- package/dist/adapters/slack/assistant.js +1 -0
- package/dist/adapters/slack/assistant.js.map +1 -1
- package/dist/adapters/slack/bot.d.ts +3 -4
- package/dist/adapters/slack/bot.d.ts.map +1 -1
- package/dist/adapters/slack/bot.js +19 -64
- package/dist/adapters/slack/bot.js.map +1 -1
- package/dist/adapters/slack/types.d.ts +29 -0
- package/dist/adapters/slack/types.d.ts.map +1 -1
- package/dist/adapters/slack/types.js.map +1 -1
- package/dist/adapters/telegram/bot.d.ts.map +1 -1
- package/dist/adapters/telegram/bot.js +39 -65
- package/dist/adapters/telegram/bot.js.map +1 -1
- package/dist/adapters/types.d.ts +7 -0
- package/dist/adapters/types.d.ts.map +1 -1
- package/dist/adapters/types.js.map +1 -1
- package/dist/agent/catalog.d.ts +34 -0
- package/dist/agent/catalog.d.ts.map +1 -0
- package/dist/agent/catalog.js +236 -0
- package/dist/agent/catalog.js.map +1 -0
- package/dist/agent/execution.d.ts +32 -0
- package/dist/agent/execution.d.ts.map +1 -0
- package/dist/agent/execution.js +169 -0
- package/dist/agent/execution.js.map +1 -0
- package/dist/agent/index.d.ts +9 -0
- package/dist/agent/index.d.ts.map +1 -0
- package/dist/agent/index.js +8 -0
- package/dist/agent/index.js.map +1 -0
- package/dist/agent/presenter.d.ts +46 -0
- package/dist/agent/presenter.d.ts.map +1 -0
- package/dist/agent/presenter.js +673 -0
- package/dist/agent/presenter.js.map +1 -0
- package/dist/agent/prompt.d.ts +30 -0
- package/dist/agent/prompt.d.ts.map +1 -0
- package/dist/agent/prompt.js +355 -0
- package/dist/agent/prompt.js.map +1 -0
- package/dist/agent/runner.d.ts +10 -0
- package/dist/agent/runner.d.ts.map +1 -0
- package/dist/agent/runner.js +441 -0
- package/dist/agent/runner.js.map +1 -0
- package/dist/agent/types.d.ts +99 -0
- package/dist/agent/types.d.ts.map +1 -0
- package/dist/agent/types.js +4 -0
- package/dist/agent/types.js.map +1 -0
- package/dist/cli/boot.d.ts.map +1 -1
- package/dist/cli/boot.js +5 -2
- package/dist/cli/boot.js.map +1 -1
- package/dist/cli/sessions.d.ts +2 -0
- package/dist/cli/sessions.d.ts.map +1 -0
- package/dist/cli/sessions.js +78 -0
- package/dist/cli/sessions.js.map +1 -0
- package/dist/cli/types.d.ts +3 -1
- package/dist/cli/types.d.ts.map +1 -1
- package/dist/cli/types.js.map +1 -1
- package/dist/commands/login.d.ts.map +1 -1
- package/dist/commands/login.js +12 -4
- package/dist/commands/login.js.map +1 -1
- package/dist/commands/manifest.d.ts.map +1 -1
- package/dist/commands/manifest.js +3 -0
- package/dist/commands/manifest.js.map +1 -1
- package/dist/commands/registry.d.ts.map +1 -1
- package/dist/commands/registry.js +25 -10
- package/dist/commands/registry.js.map +1 -1
- package/dist/commands/sandbox.js +1 -1
- package/dist/commands/sandbox.js.map +1 -1
- package/dist/commands/types.d.ts +6 -0
- package/dist/commands/types.d.ts.map +1 -1
- package/dist/commands/types.js.map +1 -1
- package/dist/config.d.ts +10 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +36 -0
- package/dist/config.js.map +1 -1
- package/dist/execution-resolver.js +1 -1
- package/dist/execution-resolver.js.map +1 -1
- package/dist/harness/event-format.d.ts +7 -0
- package/dist/harness/event-format.d.ts.map +1 -1
- package/dist/harness/event-format.js +17 -0
- package/dist/harness/event-format.js.map +1 -1
- package/dist/harness/extensions/loader.d.ts.map +1 -1
- package/dist/harness/extensions/loader.js +12 -2
- package/dist/harness/extensions/loader.js.map +1 -1
- package/dist/harness/extensions/registry.d.ts +14 -1
- package/dist/harness/extensions/registry.d.ts.map +1 -1
- package/dist/harness/extensions/registry.js +49 -3
- package/dist/harness/extensions/registry.js.map +1 -1
- package/dist/harness/index.d.ts +3 -3
- package/dist/harness/index.d.ts.map +1 -1
- package/dist/harness/index.js +2 -2
- package/dist/harness/index.js.map +1 -1
- package/dist/harness/runner.d.ts +1 -2
- package/dist/harness/runner.d.ts.map +1 -1
- package/dist/harness/runner.js +27 -40
- package/dist/harness/runner.js.map +1 -1
- package/dist/harness/session-store.d.ts +50 -51
- package/dist/harness/session-store.d.ts.map +1 -1
- package/dist/harness/session-store.js +439 -271
- package/dist/harness/session-store.js.map +1 -1
- package/dist/harness/subagent-runner.d.ts +1 -1
- package/dist/harness/subagent-runner.d.ts.map +1 -1
- package/dist/harness/subagent-runner.js +9 -5
- package/dist/harness/subagent-runner.js.map +1 -1
- package/dist/harness/subagent-slots.d.ts.map +1 -0
- package/dist/harness/subagent-slots.js.map +1 -0
- package/dist/harness/types.d.ts +29 -16
- package/dist/harness/types.d.ts.map +1 -1
- package/dist/harness/types.js +1 -1
- package/dist/harness/types.js.map +1 -1
- package/dist/harness/usage.d.ts +9 -4
- package/dist/harness/usage.d.ts.map +1 -1
- package/dist/harness/usage.js +9 -3
- package/dist/harness/usage.js.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/main.js +5 -0
- package/dist/main.js.map +1 -1
- package/dist/mcp/loader.d.ts +11 -0
- package/dist/mcp/loader.d.ts.map +1 -0
- package/dist/mcp/loader.js +126 -0
- package/dist/mcp/loader.js.map +1 -0
- package/dist/mcp/types.d.ts +38 -0
- package/dist/mcp/types.d.ts.map +1 -0
- package/dist/mcp/types.js +2 -0
- package/dist/mcp/types.js.map +1 -0
- package/dist/provisioner.d.ts +1 -0
- package/dist/provisioner.d.ts.map +1 -1
- package/dist/provisioner.js +22 -3
- package/dist/provisioner.js.map +1 -1
- package/dist/runtime/conversation-runtime.d.ts.map +1 -1
- package/dist/runtime/conversation-runtime.js +44 -25
- package/dist/runtime/conversation-runtime.js.map +1 -1
- package/dist/runtime/session-lifecycle.d.ts +13 -0
- package/dist/runtime/session-lifecycle.d.ts.map +1 -1
- package/dist/runtime/session-lifecycle.js +62 -1
- package/dist/runtime/session-lifecycle.js.map +1 -1
- package/dist/runtime/types.d.ts +1 -1
- package/dist/runtime/types.d.ts.map +1 -1
- package/dist/runtime/types.js.map +1 -1
- package/dist/sandbox/identity.d.ts +12 -5
- package/dist/sandbox/identity.d.ts.map +1 -1
- package/dist/sandbox/identity.js +14 -5
- package/dist/sandbox/identity.js.map +1 -1
- package/dist/sessions/chat-history-sync.d.ts +2 -2
- package/dist/sessions/chat-history-sync.d.ts.map +1 -1
- package/dist/sessions/chat-history-sync.js +48 -50
- package/dist/sessions/chat-history-sync.js.map +1 -1
- package/dist/sessions/migrate-v3.d.ts +18 -0
- package/dist/sessions/migrate-v3.d.ts.map +1 -0
- package/dist/sessions/migrate-v3.js +373 -0
- package/dist/sessions/migrate-v3.js.map +1 -0
- package/dist/sessions/rotation.js +4 -2
- package/dist/sessions/rotation.js.map +1 -1
- package/dist/sessions/store.d.ts +1 -1
- package/dist/sessions/store.d.ts.map +1 -1
- package/dist/sessions/store.js +19 -36
- package/dist/sessions/store.js.map +1 -1
- package/dist/sessions/types.d.ts +1 -2
- package/dist/sessions/types.d.ts.map +1 -1
- package/dist/sessions/types.js.map +1 -1
- package/dist/settings-mutation.d.ts.map +1 -1
- package/dist/settings-mutation.js +6 -1
- package/dist/settings-mutation.js.map +1 -1
- package/dist/tools/event.d.ts.map +1 -1
- package/dist/tools/event.js +2 -12
- package/dist/tools/event.js.map +1 -1
- package/dist/tools/index.d.ts +2 -3
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +0 -1
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/sandbox.d.ts +2 -2
- package/dist/tools/sandbox.d.ts.map +1 -1
- package/dist/tools/sandbox.js +1 -1
- package/dist/tools/sandbox.js.map +1 -1
- package/dist/types.d.ts +8 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/web/admin/portal.d.ts.map +1 -1
- package/dist/web/admin/portal.js +323 -27
- package/dist/web/admin/portal.js.map +1 -1
- package/dist/web/session-view/portal.js +6 -6
- package/dist/web/session-view/portal.js.map +1 -1
- package/dist/web/session-view/service.d.ts +2 -2
- package/dist/web/session-view/service.d.ts.map +1 -1
- package/dist/web/session-view/service.js +51 -75
- package/dist/web/session-view/service.js.map +1 -1
- package/package.json +4 -3
- package/dist/agent.d.ts +0 -34
- package/dist/agent.d.ts.map +0 -1
- package/dist/agent.js +0 -1820
- package/dist/agent.js.map +0 -1
- package/dist/tools/subagent-slots.d.ts.map +0 -1
- package/dist/tools/subagent-slots.js.map +0 -1
- /package/dist/{tools → harness}/subagent-slots.d.ts +0 -0
- /package/dist/{tools → harness}/subagent-slots.js +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"presenter.js","sourceRoot":"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AC,CAAC,CAAC,WAAW,KAAK,CAAC,QAAQ,KAAK,KAAK,CAAC,UAAU,KAAK,CAC7H,CAAC;YACF,MAAM,IAAI,GAAG,kCAAkC,KAAK,CAAC,MAAM,IAAI,CAAC;YAChE,cAAc,CAAC;gBACb,SAAS,EAAE,mBAAmB;gBAC9B,SAAS,EAAE,oBAAoB,CAAC,MAAM,CAAC,QAAQ,EAAE,MAAM,CAAC,cAAc,CAAC;gBACvE,KAAK,EAAE,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE;aACpC,CAAC,CAAC;YACH,KAAK,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,iBAAiB,CAAC,IAAI,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,EAAE,iBAAiB,CAAC,CAAC;QAChG,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;;;;GAMG","sourcesContent":["import { type Api, type Model } from \"@earendil-works/pi-ai\";\nimport type { MikanAgentSession } from \"../harness/index.js\";\nimport {\n mergeSubagentProgress,\n parseSubagentProgressSnapshot,\n renderSubagentDashboard,\n settleSubagentProgress,\n} from \"../subagent-progress.js\";\nimport type { ConversationResponder, SubagentProgressSnapshot } from \"../adapter.js\";\nimport type { AgentEventPayload } from \"../types.js\";\nimport type { resolveConversationSettings } from \"../config.js\";\nimport * as log from \"../log.js\";\nimport {\n addLifecycleBreadcrumb,\n metricAttributes,\n reportUserFacingError,\n} from \"../observability/sentry.js\";\nimport * as Sentry from \"@sentry/node\";\nimport { emitAgentEvent } from \"../agent-events.js\";\nimport { appendTriggerAttribution } from \"./prompt.js\";\nimport type { RunnerSessionState, UsageReportContext } from \"./types.js\";\n\nfunction createEmptyUsageTotals() {\n return {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n };\n}\n\nexport function createRunState(): RunnerSessionState {\n return {\n responder: null,\n logCtx: null,\n queue: null,\n pendingTools: new Map<string, { toolName: string; args: unknown; startTime: number }>(),\n toolProgress: new Map<string, { label: string; status: \"running\" | \"done\" | \"error\" }>(),\n subagentProgress: new Map<string, SubagentProgressSnapshot>(),\n completedSubagentProgress: [],\n subagentToolCalls: new Set<string>(),\n subagentProgressShown: false,\n suppressResponseDeltas: false,\n lastSubagentProgressAt: 0,\n toolProgressTimer: undefined,\n totalUsage: createEmptyUsageTotals(),\n llmCallCount: 0,\n stopReason: \"stop\",\n errorMessage: undefined,\n reportedLlmError: false,\n finalResponseHandledByTool: false,\n triggerAttribution: undefined,\n };\n}\n\nexport function resetRunState(\n runState: RunnerSessionState,\n responder: ConversationResponder,\n sessionConversation: string,\n userName: string | undefined,\n sessionUuid: string,\n triggerAttribution: string | undefined,\n): void {\n runState.responder = responder;\n runState.logCtx = {\n conversationId: sessionConversation,\n userName,\n conversationName: undefined,\n sessionId: sessionUuid,\n };\n runState.pendingTools.clear();\n runState.toolProgress.clear();\n runState.subagentProgress.clear();\n runState.completedSubagentProgress = [];\n runState.subagentToolCalls.clear();\n runState.subagentProgressShown = false;\n runState.suppressResponseDeltas = false;\n runState.lastSubagentProgressAt = 0;\n if (runState.toolProgressTimer) clearTimeout(runState.toolProgressTimer);\n runState.toolProgressTimer = undefined;\n runState.totalUsage = createEmptyUsageTotals();\n runState.llmCallCount = 0;\n runState.stopReason = \"stop\";\n runState.errorMessage = undefined;\n runState.reportedLlmError = false;\n runState.finalResponseHandledByTool = false;\n runState.triggerAttribution = triggerAttribution;\n}\n\nexport function createRunQueue(\n responder: ConversationResponder,\n runState: RunnerSessionState,\n): {\n queue: { enqueue(fn: () => Promise<void>, errorContext: string): void };\n wait: () => Promise<void>;\n} {\n let queueChain = Promise.resolve();\n return {\n queue: {\n enqueue(fn: () => Promise<void>, errorContext: string): void {\n queueChain = queueChain.then(async () => {\n if (runState.finalResponseHandledByTool) return;\n try {\n await fn();\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log.logWarning(`API error (${errorContext})`, errMsg);\n try {\n await responder.respondDiagnostic(`Error: ${errMsg}`, { style: \"error\" });\n } catch {\n // Ignore\n }\n }\n });\n },\n },\n wait: () => queueChain,\n };\n}\n\nfunction getFinalAssistantText(session: MikanAgentSession): string {\n const lastAssistant = session.messages.findLast((message) => message.role === \"assistant\");\n return (\n lastAssistant?.content\n .filter((content): content is { type: \"text\"; text: string } => content.type === \"text\")\n .map((content) => content.text)\n .join(\"\\n\") || \"\"\n );\n}\n\nexport function isEventTriggerAttribution(triggerAttribution: string | undefined): boolean {\n return triggerAttribution?.startsWith(\"[event:\") === true;\n}\n\nfunction extractToolLabel(toolName: string, args: unknown): string {\n const label = (args as { label?: unknown } | undefined)?.label;\n if (typeof label !== \"string\") return toolName;\n return label.trim() || toolName;\n}\n\n/** Non-subagent tool activity lines; subagent calls render as the dashboard. */\nfunction formatToolProgress(runState: RunnerSessionState): string {\n const lines = Array.from(runState.toolProgress.entries()).flatMap(([toolCallId, item]) => {\n if (runState.subagentToolCalls.has(toolCallId)) return [];\n const marker = item.status === \"running\" ? \"•\" : item.status === \"error\" ? \"✗\" : \"✓\";\n return [`${marker} ${item.label}`];\n });\n return lines.join(\"\\n\");\n}\n\nfunction formatResponseWithToolProgress(text: string, runState: RunnerSessionState): string {\n const progress = formatToolProgress(runState);\n return [progress, text].filter(Boolean).join(\"\\n\\n\");\n}\n\n/**\n * The one dashboard render path. A responder that overrides\n * `replaceSubagentProgress` converts the snapshot for a pipeline that is not\n * response-source Markdown (Telegram HTML); every other platform receives the\n * Markdown dashboard — \"dashboard, blank line, answer\" — through\n * `replaceResponse`, the same conversion as any response.\n */\nasync function replaceWithSubagentDashboard(\n responder: ConversationResponder,\n snapshot: SubagentProgressSnapshot,\n finalText?: string,\n options?: { createOverflowLink?: () => string },\n): Promise<void> {\n if (responder.replaceSubagentProgress) {\n await responder.replaceSubagentProgress(snapshot, finalText);\n return;\n }\n const dashboard = renderSubagentDashboard(snapshot);\n await responder.replaceResponse(finalText ? `${dashboard}\\n\\n${finalText}` : dashboard, options);\n}\n\nasync function replaceResponseWithToolProgress(\n responder: ConversationResponder,\n runState: RunnerSessionState,\n subagentProgress = mergeSubagentProgress([...runState.subagentProgress.values()]),\n): Promise<void> {\n if (subagentProgress) {\n await replaceWithSubagentDashboard(responder, subagentProgress);\n return;\n }\n const progress = formatToolProgress(runState);\n if (progress) await responder.replaceResponse(progress);\n}\n\nconst TOOL_PROGRESS_DEBOUNCE_MS = 500;\nconst SUBAGENT_PROGRESS_THROTTLE_MS = 2000;\n\nfunction subagentProgressDelay(runState: RunnerSessionState): number {\n if (!runState.subagentProgressShown) return 0;\n return Math.max(0, runState.lastSubagentProgressAt + SUBAGENT_PROGRESS_THROTTLE_MS - Date.now());\n}\n\nfunction scheduleToolProgressUpdate(\n responder: ConversationResponder,\n runState: RunnerSessionState,\n): void {\n if (runState.toolProgressTimer) return;\n const subagentProgress = mergeSubagentProgress([...runState.subagentProgress.values()]);\n const delay = subagentProgress ? subagentProgressDelay(runState) : TOOL_PROGRESS_DEBOUNCE_MS;\n runState.toolProgressTimer = setTimeout(() => {\n runState.toolProgressTimer = undefined;\n const snapshot = mergeSubagentProgress([...runState.subagentProgress.values()]);\n if (snapshot) {\n runState.subagentProgressShown = true;\n runState.lastSubagentProgressAt = Date.now();\n }\n runState.queue?.enqueue(\n () => replaceResponseWithToolProgress(responder, runState, snapshot),\n \"tool progress update\",\n );\n }, delay);\n runState.toolProgressTimer.unref();\n}\n\nfunction flushToolProgressUpdate(\n responder: ConversationResponder,\n runState: RunnerSessionState,\n): void {\n if (runState.toolProgressTimer) clearTimeout(runState.toolProgressTimer);\n runState.toolProgressTimer = undefined;\n const subagentProgress = mergeSubagentProgress([...runState.subagentProgress.values()]);\n if (subagentProgress) {\n runState.subagentProgressShown = true;\n runState.lastSubagentProgressAt = Date.now();\n }\n runState.queue?.enqueue(\n () => replaceResponseWithToolProgress(responder, runState, subagentProgress),\n \"tool progress update\",\n );\n}\n\nfunction extractSubagentProgress(partialResult: unknown): SubagentProgressSnapshot | undefined {\n if (!partialResult || typeof partialResult !== \"object\") return undefined;\n const details = (partialResult as { details?: unknown }).details;\n if (!details || typeof details !== \"object\") return undefined;\n return parseSubagentProgressSnapshot((details as { progress?: unknown }).progress);\n}\n\nexport async function finalizeRunResponse(\n responder: ConversationResponder,\n session: MikanAgentSession,\n runState: RunnerSessionState,\n options?: {\n triggerAttribution?: string;\n triggerSessionLink?: string;\n createOverflowLink?: () => string;\n platform?: string;\n model?: Model<Api>;\n sessionConversation?: string;\n sessionUuid?: string;\n },\n): Promise<void> {\n if (runState.stopReason === \"error\" && runState.errorMessage) {\n if (!runState.reportedLlmError) {\n runState.reportedLlmError = true;\n reportUserFacingError(new Error(\"LLM run completed with error stop reason\"), {\n domain: \"llm\",\n surface: \"assistant_response\",\n operation: \"llm_turn\",\n severity: \"error\",\n platform: options?.platform,\n provider: options?.model?.provider,\n model: options?.model?.name,\n stopReason: runState.stopReason,\n context: {\n sessionConversation: options?.sessionConversation,\n sessionUuid: options?.sessionUuid,\n hasErrorMessage: true,\n llmCallCount: runState.llmCallCount,\n },\n });\n }\n try {\n await responder.replaceResponse(\"_Sorry, something went wrong_\");\n await responder.respondDiagnostic(`Error: ${runState.errorMessage}`, {\n style: \"error\",\n });\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log.logWarning(\"Failed to post error message\", errMsg);\n reportUserFacingError(err, {\n domain: \"chat_platform\",\n surface: \"final_response\",\n operation: \"finalize_error_response\",\n severity: \"error\",\n platform: options?.platform,\n context: {\n sessionConversation: options?.sessionConversation,\n sessionUuid: options?.sessionUuid,\n stopReason: runState.stopReason,\n },\n });\n }\n return;\n }\n\n const finalText = getFinalAssistantText(session);\n if (runState.finalResponseHandledByTool) {\n log.logInfo(\"Final response already handled by tool - skipping final replacement\");\n return;\n }\n if (finalText.trim() === \"[SILENT]\" || finalText.trim().startsWith(\"[SILENT]\")) {\n try {\n await responder.deleteResponse();\n log.logInfo(\"Silent response - deleted message and thread\");\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log.logWarning(\"Failed to delete message for silent response\", errMsg);\n }\n return;\n }\n\n if (!finalText.trim()) return;\n\n try {\n const finalResponse = appendTriggerAttribution(\n finalText,\n options?.triggerAttribution,\n options?.triggerSessionLink,\n );\n const finalDashboard = mergeSubagentProgress(runState.completedSubagentProgress);\n if (finalDashboard) {\n await replaceWithSubagentDashboard(responder, finalDashboard, finalResponse, {\n createOverflowLink: options?.createOverflowLink,\n });\n return;\n }\n await responder.replaceResponse(formatResponseWithToolProgress(finalResponse, runState), {\n createOverflowLink: options?.createOverflowLink,\n });\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log.logWarning(\"Failed to replace message with final text\", errMsg);\n reportUserFacingError(err, {\n domain: \"chat_platform\",\n surface: \"final_response\",\n operation: \"replace_final_response\",\n severity: \"error\",\n platform: options?.platform,\n context: {\n sessionConversation: options?.sessionConversation,\n sessionUuid: options?.sessionUuid,\n finalTextLength: finalText.length,\n },\n });\n }\n}\n\nexport async function reportUsageSummary(ctx: UsageReportContext): Promise<void> {\n const {\n session,\n runState,\n responder,\n platform,\n model,\n agentConfig,\n sessionConversation,\n sessionUuid,\n waitForQueue,\n } = ctx;\n const lastAssistantMessage = session.messages\n .slice()\n .toReversed()\n .find(\n (message): message is Extract<typeof message, { role: \"assistant\" }> =>\n message.role === \"assistant\" && message.stopReason !== \"aborted\",\n );\n\n const contextTokens = lastAssistantMessage\n ? lastAssistantMessage.usage.input +\n lastAssistantMessage.usage.output +\n lastAssistantMessage.usage.cacheRead +\n lastAssistantMessage.usage.cacheWrite\n : 0;\n const contextWindow = model.contextWindow || 200000;\n\n const { totalUsage } = runState;\n const runMetricAttributes = metricAttributes({\n provider: model.provider,\n model: agentConfig.model,\n channel_id: sessionConversation,\n session_id: sessionUuid,\n stop_reason: runState.stopReason,\n llm_calls: runState.llmCallCount,\n });\n Sentry.metrics.distribution(\"agent.run.tokens_in\", totalUsage.input, {\n attributes: runMetricAttributes,\n });\n Sentry.metrics.distribution(\"agent.run.tokens_out\", totalUsage.output, {\n attributes: runMetricAttributes,\n });\n Sentry.metrics.distribution(\"agent.run.cache_read\", totalUsage.cacheRead, {\n attributes: runMetricAttributes,\n });\n Sentry.metrics.distribution(\"agent.run.cache_write\", totalUsage.cacheWrite, {\n attributes: runMetricAttributes,\n });\n Sentry.metrics.distribution(\"agent.run.cost\", totalUsage.cost.total, {\n attributes: runMetricAttributes,\n });\n Sentry.metrics.gauge(\"agent.context.utilization\", contextTokens / contextWindow, {\n unit: \"ratio\",\n attributes: runMetricAttributes,\n });\n\n const summary = log.logUsageSummary(\n runState.logCtx!,\n runState.totalUsage,\n contextTokens,\n contextWindow,\n );\n if (platform.diagnostics?.showUsageSummary === true) {\n runState.queue!.enqueue(\n () => responder.respondDiagnostic(summary, { style: \"muted\" }),\n \"usage summary\",\n );\n await waitForQueue();\n }\n}\n\nfunction extractToolResultText(result: unknown): string {\n if (typeof result === \"string\") {\n return result;\n }\n\n if (\n result &&\n typeof result === \"object\" &&\n \"content\" in result &&\n Array.isArray((result as { content: unknown }).content)\n ) {\n const content = (result as { content: Array<{ type: string; text?: string }> }).content;\n const textParts: string[] = [];\n for (const part of content) {\n if (part.type === \"text\" && part.text) {\n textParts.push(part.text);\n }\n }\n if (textParts.length > 0) {\n return textParts.join(\"\\n\");\n }\n }\n\n return JSON.stringify(result);\n}\n\nasync function noopResponderMethod(): Promise<void> {}\n\nexport function createNoopResponder(): ConversationResponder {\n return {\n respond: noopResponderMethod,\n replaceResponse: noopResponderMethod,\n respondDiagnostic: noopResponderMethod,\n respondToolResult: noopResponderMethod,\n setTyping: noopResponderMethod,\n setWorking: noopResponderMethod,\n uploadFile: noopResponderMethod,\n deleteResponse: noopResponderMethod,\n };\n}\n\nexport function formatAgentActorName(userName: string | undefined, fallback: string): string {\n return userName ? `DM:${userName}` : fallback;\n}\n\nexport function sendAgentEvent(payload: {\n sessionId: string;\n actorName: string;\n event: AgentEventPayload;\n}): void {\n emitAgentEvent({ source: \"mikan\", ...payload });\n}\n\n// ponytail: additive SSE mirror only; keep responder rendering here until another frontend needs the same stream.\nexport function attachSessionEventHandlers(params: {\n session: MikanAgentSession;\n runState: RunnerSessionState;\n model: Model<Api>;\n agentConfig: ReturnType<typeof resolveConversationSettings>;\n}): void {\n const { session, runState, model, agentConfig } = params;\n session.subscribe(async (event) => {\n if (!runState.responder || !runState.logCtx || !runState.queue) return;\n\n const { responder, logCtx, queue, pendingTools } = runState;\n const baseAttrs = { channel_id: logCtx.conversationId, session_id: logCtx.sessionId };\n const agentEventSessionId = logCtx.sessionId ?? logCtx.conversationId;\n\n if (event.type === \"tool_execution_start\") {\n const args = (event.args ?? {}) as { label?: string };\n const label = args.label || event.toolName;\n sendAgentEvent({\n sessionId: agentEventSessionId,\n actorName: formatAgentActorName(logCtx.userName, logCtx.conversationId),\n event: {\n kind: \"toolStart\",\n toolId: event.toolCallId,\n toolName: event.toolName,\n input: { label },\n },\n });\n\n pendingTools.set(event.toolCallId, {\n toolName: event.toolName,\n args: event.args,\n startTime: Date.now(),\n });\n runState.toolProgress.set(event.toolCallId, {\n label: extractToolLabel(event.toolName, event.args),\n status: \"running\",\n });\n if (event.toolName === \"subagent\") {\n runState.subagentToolCalls.add(event.toolCallId);\n } else {\n queue.enqueue(\n () => replaceResponseWithToolProgress(responder, runState),\n \"tool progress update\",\n );\n }\n addLifecycleBreadcrumb(\"agent.tool.started\", {\n tool: event.toolName,\n ...baseAttrs,\n });\n\n log.logToolStart(logCtx, event.toolName, label, event.args as Record<string, unknown>);\n return;\n }\n\n if (event.type === \"tool_execution_update\") {\n const subagentProgress = extractSubagentProgress(event.partialResult);\n if (subagentProgress) {\n runState.subagentProgress.set(event.toolCallId, subagentProgress);\n runState.subagentToolCalls.add(event.toolCallId);\n runState.suppressResponseDeltas = true;\n scheduleToolProgressUpdate(responder, runState);\n }\n return;\n }\n\n if (event.type === \"tool_execution_end\") {\n const resultStr = extractToolResultText(event.result);\n const pending = pendingTools.get(event.toolCallId);\n sendAgentEvent({\n sessionId: agentEventSessionId,\n actorName: formatAgentActorName(logCtx.userName, logCtx.conversationId),\n event: { kind: \"toolEnd\", toolId: event.toolCallId },\n });\n const progress = runState.toolProgress.get(event.toolCallId);\n if (progress) progress.status = event.isError ? \"error\" : \"done\";\n const subagentProgress = runState.subagentProgress.get(event.toolCallId);\n if (subagentProgress) {\n runState.subagentProgress.set(\n event.toolCallId,\n settleSubagentProgress(subagentProgress, event.isError),\n );\n }\n flushToolProgressUpdate(responder, runState);\n const completedProgress = runState.subagentProgress.get(event.toolCallId);\n if (completedProgress) runState.completedSubagentProgress.push(completedProgress);\n runState.subagentProgress.delete(event.toolCallId);\n pendingTools.delete(event.toolCallId);\n const durationMs = pending ? Date.now() - pending.startTime : 0;\n\n Sentry.metrics.count(\"agent.tool.calls\", 1, {\n attributes: metricAttributes({\n tool: event.toolName,\n error: String(event.isError),\n ...baseAttrs,\n }),\n });\n Sentry.metrics.distribution(\"agent.tool.duration\", durationMs, {\n unit: \"millisecond\",\n attributes: metricAttributes({\n tool: event.toolName,\n ...baseAttrs,\n }),\n });\n addLifecycleBreadcrumb(\"agent.tool.completed\", {\n tool: event.toolName,\n error: event.isError,\n duration_ms: durationMs,\n ...baseAttrs,\n });\n\n if (event.isError) {\n log.logToolError(logCtx, event.toolName, durationMs, resultStr);\n } else {\n log.logToolSuccess(logCtx, event.toolName, durationMs, resultStr);\n if (event.toolName === \"slack_blockkit\") {\n runState.finalResponseHandledByTool = true;\n }\n }\n\n return;\n }\n\n if (event.type === \"message_start\") {\n if (event.message.role === \"assistant\") {\n runState.llmCallCount += 1;\n sendAgentEvent({\n sessionId: agentEventSessionId,\n actorName: formatAgentActorName(logCtx.userName, logCtx.conversationId),\n event: { kind: \"sessionStart\" },\n });\n addLifecycleBreadcrumb(\"agent.llm.call.started\", {\n call_index: runState.llmCallCount,\n provider: model.provider,\n model: agentConfig.model,\n ...baseAttrs,\n });\n log.logResponseStart(logCtx);\n }\n return;\n }\n\n if (event.type === \"message_update\") {\n const assistantMessageEvent = (\n event as {\n assistantMessageEvent?: { type?: string; delta?: string };\n }\n ).assistantMessageEvent;\n if (assistantMessageEvent?.type === \"text_delta\" && assistantMessageEvent.delta) {\n sendAgentEvent({\n sessionId: agentEventSessionId,\n actorName: formatAgentActorName(logCtx.userName, logCtx.conversationId),\n event: { kind: \"responseDelta\", delta: assistantMessageEvent.delta },\n });\n if (responder.appendResponseDelta && !runState.suppressResponseDeltas) {\n queue.enqueue(async () => {\n await responder.appendResponseDelta?.(assistantMessageEvent.delta ?? \"\");\n }, \"response delta\");\n }\n }\n return;\n }\n\n if (event.type === \"message_end\") {\n if (event.message.role === \"assistant\") {\n const assistantMsg = event.message;\n\n if (assistantMsg.stopReason) {\n runState.stopReason = assistantMsg.stopReason;\n // The settling message is the authority for both fields: a retry\n // that recovered must clear the earlier attempt's error, or the\n // run would report success and a stale errorMessage together.\n runState.errorMessage = assistantMsg.errorMessage;\n }\n\n if (assistantMsg.usage) {\n runState.totalUsage.input += assistantMsg.usage.input;\n runState.totalUsage.output += assistantMsg.usage.output;\n runState.totalUsage.cacheRead += assistantMsg.usage.cacheRead;\n runState.totalUsage.cacheWrite += assistantMsg.usage.cacheWrite;\n runState.totalUsage.cost.input += assistantMsg.usage.cost.input;\n runState.totalUsage.cost.output += assistantMsg.usage.cost.output;\n runState.totalUsage.cost.cacheRead += assistantMsg.usage.cost.cacheRead;\n runState.totalUsage.cost.cacheWrite += assistantMsg.usage.cost.cacheWrite;\n runState.totalUsage.cost.total += assistantMsg.usage.cost.total;\n\n const llmAttributes = metricAttributes({\n provider: model.provider,\n model: agentConfig.model,\n ...baseAttrs,\n stop_reason: assistantMsg.stopReason,\n error: Boolean(assistantMsg.errorMessage),\n });\n Sentry.metrics.count(\"agent.llm.calls\", 1, { attributes: llmAttributes });\n Sentry.metrics.distribution(\"agent.llm.tokens_in\", assistantMsg.usage.input, {\n attributes: llmAttributes,\n });\n Sentry.metrics.distribution(\"agent.llm.tokens_out\", assistantMsg.usage.output, {\n attributes: llmAttributes,\n });\n if (assistantMsg.usage.cacheRead > 0) {\n Sentry.metrics.distribution(\"agent.llm.cache_read\", assistantMsg.usage.cacheRead, {\n attributes: llmAttributes,\n });\n }\n if (assistantMsg.usage.cacheWrite > 0) {\n Sentry.metrics.distribution(\"agent.llm.cache_write\", assistantMsg.usage.cacheWrite, {\n attributes: llmAttributes,\n });\n }\n Sentry.metrics.distribution(\"agent.llm.cost_per_turn\", assistantMsg.usage.cost.total, {\n attributes: llmAttributes,\n });\n addLifecycleBreadcrumb(\"agent.llm.call.completed\", {\n call_index: runState.llmCallCount,\n provider: model.provider,\n model: agentConfig.model,\n stop_reason: assistantMsg.stopReason,\n error: Boolean(assistantMsg.errorMessage),\n input_tokens: assistantMsg.usage.input,\n output_tokens: assistantMsg.usage.output,\n cost_total_usd: assistantMsg.usage.cost.total,\n });\n }\n\n const thinkingParts: string[] = [];\n const textParts: string[] = [];\n const hasToolCall = assistantMsg.content.some((part) =>\n [\"tool_use\", \"toolCall\", \"tool-call\"].includes((part as { type?: string }).type ?? \"\"),\n );\n for (const part of assistantMsg.content) {\n if (part.type === \"thinking\") {\n thinkingParts.push(part.thinking);\n } else if (part.type === \"text\") {\n textParts.push(part.text);\n }\n }\n\n const text = textParts.join(\"\\n\");\n\n for (const thinking of thinkingParts) {\n log.logThinking(logCtx, thinking);\n queue.enqueue(() => responder.respond(`_${thinking}_`), \"thinking main\");\n queue.enqueue(() => responder.respondDiagnostic(`_${thinking}_`), \"thinking diagnostic\");\n }\n\n if (text.trim() && !hasToolCall) {\n if (runState.finalResponseHandledByTool) return;\n const finalText = appendTriggerAttribution(\n formatResponseWithToolProgress(text, runState),\n runState.triggerAttribution,\n );\n log.logResponse(logCtx, text);\n sendAgentEvent({\n sessionId: agentEventSessionId,\n actorName: formatAgentActorName(logCtx.userName, logCtx.conversationId),\n event: { kind: \"responseFinal\", text: finalText },\n });\n sendAgentEvent({\n sessionId: agentEventSessionId,\n actorName: formatAgentActorName(logCtx.userName, logCtx.conversationId),\n event: { kind: \"turnEnd\" },\n });\n // A run that produced a subagent dashboard finalizes through it:\n // finalizeRunResponse renders \"dashboard, blank line, answer\", and a\n // finish here would first overwrite the dashboard with the bare\n // answer on every platform.\n if (runState.completedSubagentProgress.length > 0) return;\n if (responder.finishResponse) {\n queue.enqueue(async () => {\n await responder.finishResponse?.(finalText);\n }, \"response finish\");\n } else {\n queue.enqueue(() => responder.respond(finalText), \"response main\");\n }\n }\n }\n return;\n }\n\n if (event.type === \"compaction_start\") {\n const text = \"_Compacting context..._\";\n log.logInfo(`Auto-compaction started (reason: ${event.reason})`);\n sendAgentEvent({\n sessionId: agentEventSessionId,\n actorName: formatAgentActorName(logCtx.userName, logCtx.conversationId),\n event: { kind: \"diagnostic\", text },\n });\n queue.enqueue(() => responder.respond(text), \"compaction start\");\n return;\n }\n\n if (event.type === \"compaction_end\") {\n if (event.result) {\n log.logInfo(`Auto-compaction complete: ${event.result.tokensBefore} tokens compacted`);\n } else if (event.aborted) {\n log.logInfo(\"Auto-compaction aborted\");\n }\n return;\n }\n\n if (event.type === \"auto_retry_start\") {\n log.logWarning(`Retrying (${event.attempt}/${event.maxAttempts})`, event.errorMessage);\n sendAgentEvent({\n sessionId: agentEventSessionId,\n actorName: formatAgentActorName(logCtx.userName, logCtx.conversationId),\n event: { kind: \"sessionStart\" },\n });\n const text = `_Retrying (${event.attempt}/${event.maxAttempts})..._`;\n sendAgentEvent({\n sessionId: agentEventSessionId,\n actorName: formatAgentActorName(logCtx.userName, logCtx.conversationId),\n event: { kind: \"diagnostic\", text },\n });\n queue.enqueue(() => responder.respond(text), \"retry\");\n }\n\n if (event.type === \"budget_exceeded\") {\n log.logWarning(\n \"Run stopped by budget circuit breaker\",\n `${event.reason} (tokens=${event.tokens}, cost=${event.costUsd.toFixed(2)}, calls=${event.llmCalls}, ${event.durationMs}ms)`,\n );\n const text = `_Stopped: run budget exceeded (${event.reason})_`;\n sendAgentEvent({\n sessionId: agentEventSessionId,\n actorName: formatAgentActorName(logCtx.userName, logCtx.conversationId),\n event: { kind: \"diagnostic\", text },\n });\n queue.enqueue(() => responder.respondDiagnostic(text, { style: \"error\" }), \"budget exceeded\");\n }\n });\n}\n\n/**\n * Create a new PiAgentWrapper for a channel.\n * Sets up the session and subscribes to events once.\n *\n * Runner caching is handled by the caller (channelStates in main.ts).\n * This is a stateless factory function.\n */\n"]}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { Office } from "../office/index.js";
|
|
2
|
+
import type { AgentTool } from "@earendil-works/pi-agent-core";
|
|
3
|
+
import { type ImageContent } from "@earendil-works/pi-ai";
|
|
4
|
+
import { type MikanSkill } from "../harness/index.js";
|
|
5
|
+
import type { ConversationKind, ConversationMessage, MessagingInfo } from "../adapter.js";
|
|
6
|
+
import type { WorkspaceProjection } from "../workspace-projection/types.js";
|
|
7
|
+
import { type RuntimePathContext, type SandboxConfig } from "../sandbox/index.js";
|
|
8
|
+
export declare function buildPromptPayload(message: ConversationMessage, workspacePath: string, pathContext?: RuntimePathContext, readAttachment?: (runtimePath: string) => Promise<string>): Promise<{
|
|
9
|
+
userMessage: string;
|
|
10
|
+
imageAttachments: ImageContent[];
|
|
11
|
+
}>;
|
|
12
|
+
export declare function getMemory(projection: WorkspaceProjection): Promise<string>;
|
|
13
|
+
export declare function resolveTriggerAttribution(message: Pick<ConversationMessage, "id" | "text" | "userName">): string | undefined;
|
|
14
|
+
export declare function buildSystemPrompt(workspacePath: string, office: Office, conversationKind: ConversationKind, currentUserId: string | undefined, memory: string, sandboxConfig: SandboxConfig, platform: MessagingInfo, skills: MikanSkill[], projection: WorkspaceProjection, skippedSkillLinks?: string[]): string;
|
|
15
|
+
/**
|
|
16
|
+
* Instructions that vary per turn (event-trigger mode, response attribution).
|
|
17
|
+
* These are delivered with the user message rather than baked into the system
|
|
18
|
+
* prompt, so the system prompt stays cache-stable across a conversation's turns
|
|
19
|
+
* (in a multi-user channel the attribution line alone changes every turn).
|
|
20
|
+
* Returns an empty string when the turn needs no special framing.
|
|
21
|
+
*/
|
|
22
|
+
export declare function buildTurnInstructions(isEventTrigger: boolean, triggerAttribution: string | undefined, platformName: string): string;
|
|
23
|
+
export declare function appendTriggerAttribution(text: string, triggerAttribution: string | undefined, sessionLink?: string): string;
|
|
24
|
+
export declare function sessionDreamPrompt(conversationMemoryPath: string, toolNames: string[]): string;
|
|
25
|
+
export declare const SESSION_DREAM_BUDGET: {
|
|
26
|
+
maxDurationMs: number;
|
|
27
|
+
maxLlmCalls: number;
|
|
28
|
+
};
|
|
29
|
+
export declare function sessionDreamTools(tools: AgentTool[], conversationMemoryPath: string): AgentTool[];
|
|
30
|
+
//# sourceMappingURL=prompt.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prompt.d.ts","sourceRoot":"","sources":["../../src/agent/prompt.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAC/D,OAAO,EAAE,KAAK,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAC1D,OAAO,EAAyB,KAAK,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAG7E,OAAO,KAAK,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAC1F,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AAE5E,OAAO,EAAE,KAAK,kBAAkB,EAAE,KAAK,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAalF,wBAAsB,kBAAkB,CACtC,OAAO,EAAE,mBAAmB,EAC5B,aAAa,EAAE,MAAM,EACrB,WAAW,CAAC,EAAE,kBAAkB,EAChC,cAAc,CAAC,EAAE,CAAC,WAAW,EAAE,MAAM,KAAK,OAAO,CAAC,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+
import {} from "@earendil-works/pi-ai";
|
|
2
|
+
import { formatSkillsForPrompt } from "../harness/index.js";
|
|
3
|
+
import { lstatSync } from "node:fs";
|
|
4
|
+
import { readFile } from "node:fs/promises";
|
|
5
|
+
import * as log from "../log.js";
|
|
6
|
+
import {} from "../sandbox/index.js";
|
|
7
|
+
import { formatHistoryLine } from "../sessions/history-line.js";
|
|
8
|
+
import { buildRuntimePaths, collectMessageAttachments } from "./execution.js";
|
|
9
|
+
function formatTimestampedUserMessage(message) {
|
|
10
|
+
return formatHistoryLine({
|
|
11
|
+
date: new Date(),
|
|
12
|
+
userName: message.userName,
|
|
13
|
+
threadTs: message.threadTs,
|
|
14
|
+
text: message.text,
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
export async function buildPromptPayload(message, workspacePath, pathContext, readAttachment) {
|
|
18
|
+
let userMessage = formatTimestampedUserMessage(message);
|
|
19
|
+
const { imageAttachments, nonImagePaths } = await collectMessageAttachments(message, workspacePath, pathContext, readAttachment);
|
|
20
|
+
if (nonImagePaths.length > 0) {
|
|
21
|
+
userMessage += `\n\n<slack_attachments>\n${nonImagePaths.join("\n")}\n</slack_attachments>`;
|
|
22
|
+
}
|
|
23
|
+
return { userMessage, imageAttachments };
|
|
24
|
+
}
|
|
25
|
+
export async function getMemory(projection) {
|
|
26
|
+
const parts = [];
|
|
27
|
+
const workspaceMemoryPath = projection.promptSources.globalMemoryPath;
|
|
28
|
+
if (workspaceMemoryPath && isRegularFile(workspaceMemoryPath)) {
|
|
29
|
+
try {
|
|
30
|
+
const content = (await readFile(workspaceMemoryPath, "utf-8")).trim();
|
|
31
|
+
if (content) {
|
|
32
|
+
parts.push(`### Global Workspace Memory\n${content}`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
log.logWarning("Failed to read workspace memory", `${workspaceMemoryPath}: ${error}`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const conversationMemoryPath = projection.promptSources.conversationMemoryPath;
|
|
40
|
+
if (isRegularFile(conversationMemoryPath)) {
|
|
41
|
+
try {
|
|
42
|
+
const content = (await readFile(conversationMemoryPath, "utf-8")).trim();
|
|
43
|
+
if (content) {
|
|
44
|
+
parts.push(`### Conversation-Specific Memory\n${content}`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
log.logWarning("Failed to read conversation memory", `${conversationMemoryPath}: ${error}`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
if (parts.length === 0) {
|
|
52
|
+
return "(no working memory yet)";
|
|
53
|
+
}
|
|
54
|
+
return parts.join("\n\n");
|
|
55
|
+
}
|
|
56
|
+
function isRegularFile(path) {
|
|
57
|
+
try {
|
|
58
|
+
const stats = lstatSync(path);
|
|
59
|
+
return stats.isFile() && !stats.isSymbolicLink();
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
function buildEnvDescription(sandboxType, workspaceRoot) {
|
|
66
|
+
switch (sandboxType) {
|
|
67
|
+
case "image":
|
|
68
|
+
return `You are running inside a managed per-conversation container.
|
|
69
|
+
- Runtime workspace root: ${workspaceRoot}
|
|
70
|
+
- Bash commands start in: ${workspaceRoot}
|
|
71
|
+
- Install tools with the image's package manager
|
|
72
|
+
- Your changes persist for this user's container until it is recreated`;
|
|
73
|
+
case "container":
|
|
74
|
+
return `You are running inside a shared container.
|
|
75
|
+
- Runtime workspace root: ${workspaceRoot}
|
|
76
|
+
- Bash commands start in: ${workspaceRoot}
|
|
77
|
+
- Install tools with the container's package manager
|
|
78
|
+
- Your changes persist across sessions`;
|
|
79
|
+
case "firecracker":
|
|
80
|
+
return `You are running inside a Firecracker microVM.
|
|
81
|
+
- Runtime workspace root: ${workspaceRoot}
|
|
82
|
+
- Use cd or absolute paths; project files are under ${workspaceRoot}
|
|
83
|
+
- Install tools with: apt-get install <package> (Debian-based)
|
|
84
|
+
- Your changes persist across sessions`;
|
|
85
|
+
case "cloudflare":
|
|
86
|
+
return `You are running through a Cloudflare Sandbox bridge.
|
|
87
|
+
- Runtime workspace root: ${workspaceRoot}
|
|
88
|
+
- Bash commands start in: ${workspaceRoot}
|
|
89
|
+
- Your commands run in a remote container managed by Cloudflare
|
|
90
|
+
- Important: the remote filesystem is not automatically synced back to the host workspace`;
|
|
91
|
+
default:
|
|
92
|
+
return `You are running directly on the host machine.
|
|
93
|
+
- Runtime workspace root: ${workspaceRoot}
|
|
94
|
+
- Bash commands start in: ${process.cwd()}
|
|
95
|
+
- Be careful with system modifications`;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
export function resolveTriggerAttribution(message) {
|
|
99
|
+
const eventTextMatch = message.text.match(/^\[EVENT:([^:]+):/);
|
|
100
|
+
if (eventTextMatch)
|
|
101
|
+
return `[event: ${eventTextMatch[1]}]`;
|
|
102
|
+
const eventIdMatch = message.id.match(/^event:([^:]+)/);
|
|
103
|
+
if (eventIdMatch)
|
|
104
|
+
return `[event: ${eventIdMatch[1]}]`;
|
|
105
|
+
if (message.userName)
|
|
106
|
+
return `@${message.userName}`;
|
|
107
|
+
return undefined;
|
|
108
|
+
}
|
|
109
|
+
export function buildSystemPrompt(workspacePath, office, conversationKind, currentUserId, memory, sandboxConfig, platform, skills, projection, skippedSkillLinks = []) {
|
|
110
|
+
const { workspaceRoot, conversationPath, scratchPath } = buildRuntimePaths(workspacePath, office);
|
|
111
|
+
const sandboxType = sandboxConfig.type;
|
|
112
|
+
const isContainerLike = sandboxType === "container" || sandboxType === "image";
|
|
113
|
+
const isFirecracker = sandboxType === "firecracker";
|
|
114
|
+
// Format channel mappings
|
|
115
|
+
const channelMappings = platform.channels.length > 0
|
|
116
|
+
? platform.channels.map((c) => `${c.id}\t#${c.name}`).join("\n")
|
|
117
|
+
: "(no channels loaded)";
|
|
118
|
+
// Format user mappings
|
|
119
|
+
const userMappings = platform.users.length > 0
|
|
120
|
+
? platform.users.map((u) => `${u.id}\t@${u.userName}\t${u.displayName}`).join("\n")
|
|
121
|
+
: "(no users loaded)";
|
|
122
|
+
const envDescription = buildEnvDescription(sandboxType, workspaceRoot);
|
|
123
|
+
// Per-turn instructions (event-trigger mode, attribution) are delivered with
|
|
124
|
+
// the user message via buildTurnInstructions(), not baked in here, so this
|
|
125
|
+
// system prompt stays byte-stable across a conversation's turns and keeps the
|
|
126
|
+
// provider prompt cache warm (a changing system prefix invalidates the cache
|
|
127
|
+
// for the whole request, including the far larger conversation history).
|
|
128
|
+
const workspaceLayout = projection.layout === "full"
|
|
129
|
+
? `${workspaceRoot}/ contains the complete trusted workspace.`
|
|
130
|
+
: projection.layout === "shared-support"
|
|
131
|
+
? `${workspaceRoot}/ contains shared MEMORY.md, skills/, events/, and this conversation's directory.`
|
|
132
|
+
: `${conversationPath}/ is the only conversation workspace mounted; global memory, skills, and events are not available.`;
|
|
133
|
+
const skillStorageGuidance = projection.doorPolicy === "trusted"
|
|
134
|
+
? `Store shared skills in \`${workspaceRoot}/skills/<name>/\` or conversation-specific skills in \`${conversationPath}/skills/<name>/\`.`
|
|
135
|
+
: `Store skills in \`${conversationPath}/skills/<name>/\`; this office cannot access workspace-global skills.`;
|
|
136
|
+
const memoryGuidance = projection.doorPolicy === "trusted"
|
|
137
|
+
? `Write important shared knowledge to \`${workspaceRoot}/MEMORY.md\` and conversation-specific knowledge to \`${conversationPath}/MEMORY.md\`.`
|
|
138
|
+
: `Write durable knowledge only to \`${conversationPath}/MEMORY.md\`; this office cannot access workspace-global memory.`;
|
|
139
|
+
const systemLogPath = projection.layout === "conversation"
|
|
140
|
+
? `${conversationPath}/SYSTEM.md`
|
|
141
|
+
: `${workspaceRoot}/SYSTEM.md`;
|
|
142
|
+
const slackBlockKitInstructions = platform.name === "slack"
|
|
143
|
+
? `
|
|
144
|
+
## Slack Rendering
|
|
145
|
+
- The Slack adapter renders responses natively from standard Markdown. Answer in normal Markdown/GFM.
|
|
146
|
+
- Markdown pipe tables are rendered as native Slack tables.
|
|
147
|
+
- For interactive elements (buttons, select menus), use the slack_blockkit tool; user interactions arrive as "[Slack action] <action_id>: <value>" messages.
|
|
148
|
+
`
|
|
149
|
+
: "";
|
|
150
|
+
return `You are mikan, a ${platform.name} bot assistant. Be concise. No emojis.
|
|
151
|
+
|
|
152
|
+
## Context
|
|
153
|
+
- For current date/time, use: date
|
|
154
|
+
- You have access to previous conversation context including tool results from prior turns.
|
|
155
|
+
- For older human-readable history beyond your context, search \`log.jsonl\` (contains user messages and your final responses, but not tool results).
|
|
156
|
+
- Structured session history with tool results lives in \`${conversationPath}/sessions/\`.
|
|
157
|
+
- The active top-level session is selected by \`${conversationPath}/sessions/current\`, which points to a timestamped \`.jsonl\` file in the same directory.
|
|
158
|
+
- Scoped/thread sessions use fixed files at \`${conversationPath}/sessions/<scope_id>.jsonl\` (for example \`${conversationPath}/sessions/1777386320.800769.jsonl\`).
|
|
159
|
+
- If a user asks about something that should exist in conversation history but is not found in the current context window, do not answer "I don't know" or "I don't have that". Instead, search the thread session, top-level session, and \`log.jsonl\` before responding.
|
|
160
|
+
- User messages include a \`[in-thread:TS]\` marker when sent from within a platform thread/reply (TS is the thread or parent message identifier). Without this marker, the message is a top-level conversation message.
|
|
161
|
+
${platform.formattingGuide}${slackBlockKitInstructions}
|
|
162
|
+
|
|
163
|
+
## Platform IDs
|
|
164
|
+
Channels: ${channelMappings}
|
|
165
|
+
|
|
166
|
+
Users: ${userMappings}
|
|
167
|
+
|
|
168
|
+
When mentioning users, write <@userName> using the exact userName from the Users table above (e.g., <@mario>). Never invent handles from other platforms (GitHub, email); the platform adapter converts <@userName> to the platform's native mention form.
|
|
169
|
+
|
|
170
|
+
## Environment
|
|
171
|
+
${envDescription}
|
|
172
|
+
- Default place for clones, downloads, and experiments: ${scratchPath}
|
|
173
|
+
- Do not use host-only paths unless you are running in host mode and verified they exist.
|
|
174
|
+
|
|
175
|
+
## Workspace Layout
|
|
176
|
+
${workspaceLayout}
|
|
177
|
+
${projection.layout === "conversation"
|
|
178
|
+
? `${conversationPath}/ # This conversation`
|
|
179
|
+
: `${workspaceRoot}/
|
|
180
|
+
├── MEMORY.md # Global memory (all conversations)
|
|
181
|
+
├── skills/ # Global CLI tools you create
|
|
182
|
+
└── ${office.key}/ # This conversation`}
|
|
183
|
+
├── MEMORY.md # Conversation-specific memory
|
|
184
|
+
├── log.jsonl # Human-readable message history (no tool results)
|
|
185
|
+
├── sessions/ # Structured session history used for context reconstruction
|
|
186
|
+
│ ├── current # Active top-level session pointer
|
|
187
|
+
│ ├── <timestamp>_<id>.jsonl # Top-level session files
|
|
188
|
+
│ └── <scope_id>.jsonl # Scoped thread/reply session files
|
|
189
|
+
├── attachments/ # User-shared files
|
|
190
|
+
├── scratch/ # Working directory for clones/downloads/experiments: ${scratchPath}
|
|
191
|
+
└── skills/ # Conversation-specific tools
|
|
192
|
+
|
|
193
|
+
## Skills (Custom CLI Tools)
|
|
194
|
+
You can create reusable CLI tools for recurring tasks (email, APIs, data processing, etc.).
|
|
195
|
+
|
|
196
|
+
### Creating Skills
|
|
197
|
+
${skillStorageGuidance}
|
|
198
|
+
Each skill directory needs a \`SKILL.md\` with YAML frontmatter:
|
|
199
|
+
|
|
200
|
+
\`\`\`markdown
|
|
201
|
+
---
|
|
202
|
+
name: skill-name
|
|
203
|
+
description: Short description of what this skill does
|
|
204
|
+
---
|
|
205
|
+
|
|
206
|
+
# Skill Name
|
|
207
|
+
|
|
208
|
+
Usage instructions, examples, etc.
|
|
209
|
+
Scripts are in: {baseDir}/
|
|
210
|
+
\`\`\`
|
|
211
|
+
|
|
212
|
+
\`name\` and \`description\` are required. Use \`{baseDir}\` as placeholder for the skill's directory path.
|
|
213
|
+
|
|
214
|
+
### Available Skills
|
|
215
|
+
${skills.length > 0 ? formatSkillsForPrompt(skills) : "(no skills installed yet)"}${skippedSkillLinks.length > 0
|
|
216
|
+
? `\n\nNote: these skill entries were skipped because they are symlinks, which the host never follows when reading this conversation's skills: ${skippedSkillLinks.join(", ")}. Replace each with a real file or directory (for example \`cp -rL\`) to load it.`
|
|
217
|
+
: ""}
|
|
218
|
+
|
|
219
|
+
## Events
|
|
220
|
+
Use the \`event\` tool to schedule immediate, one-shot, or periodic follow-ups. It writes to the host-side mikan control plane and fills routing fields for the current conversation automatically.
|
|
221
|
+
|
|
222
|
+
Write event \`text\` as a self-contained future task with needed context, tone, and constraints because events do not inherit normal conversation history.
|
|
223
|
+
|
|
224
|
+
For one-shot reminders, include a timezone offset in \`at\`. For periodic events, use a cron schedule plus IANA timezone; assume ${Intl.DateTimeFormat().resolvedOptions().timeZone} when users omit timezone.
|
|
225
|
+
|
|
226
|
+
When events trigger, messages are prefixed like \`[EVENT:filename:type:time]\`. Immediate and one-shot events auto-delete after triggering; periodic events persist until deleted.
|
|
227
|
+
|
|
228
|
+
For periodic events where there's nothing to report, respond with exactly \`[SILENT]\`. Debounce external triggers; prefer one summarized event over many.
|
|
229
|
+
|
|
230
|
+
## Memory
|
|
231
|
+
${memoryGuidance}
|
|
232
|
+
Update it when you learn something important or when asked to remember something.
|
|
233
|
+
|
|
234
|
+
### Current Memory
|
|
235
|
+
${memory}
|
|
236
|
+
|
|
237
|
+
## System Configuration Log
|
|
238
|
+
Maintain ${systemLogPath} to log all environment modifications:
|
|
239
|
+
- Installed packages (apt install, npm install, uv pip install)
|
|
240
|
+
- Environment variables set
|
|
241
|
+
- Config files modified (~/.gitconfig, cron jobs, etc.)
|
|
242
|
+
- Skill dependencies installed
|
|
243
|
+
|
|
244
|
+
Update this file whenever you modify the environment. On fresh container, read it first to restore your setup.
|
|
245
|
+
|
|
246
|
+
## Log Queries (for older history)
|
|
247
|
+
Format: \`{"date":"...","ts":"...","user":"...","userName":"...","text":"...","isMessagingBot":false}\`
|
|
248
|
+
The log contains user messages and your final responses (not tool calls/results).
|
|
249
|
+
Use \`log.jsonl\` for quick grep-style history. Use \`${conversationPath}/sessions/\` when you need structured turns, tool outputs, or thread/session lineage.
|
|
250
|
+
${isContainerLike || isFirecracker ? "Install jq: apt-get install jq" : ""}
|
|
251
|
+
\`\`\`bash
|
|
252
|
+
# Recent messages
|
|
253
|
+
tail -30 log.jsonl | jq -c '{date: .date[0:19], user: (.userName // .user), text}'
|
|
254
|
+
|
|
255
|
+
# Search for specific topic
|
|
256
|
+
grep -i "topic" log.jsonl | jq -c '{date: .date[0:19], user: (.userName // .user), text}'
|
|
257
|
+
|
|
258
|
+
# Messages from specific user
|
|
259
|
+
grep '"userName":"mario"' log.jsonl | tail -20 | jq -c '{date: .date[0:19], text}'
|
|
260
|
+
|
|
261
|
+
# Inspect top-level session pointer and available session files
|
|
262
|
+
cat sessions/current
|
|
263
|
+
ls -1 sessions/
|
|
264
|
+
\`\`\`
|
|
265
|
+
|
|
266
|
+
## Tools
|
|
267
|
+
- bash: Run shell commands (primary tool). Install packages as needed.
|
|
268
|
+
- read: Read files
|
|
269
|
+
- write: Create/overwrite files
|
|
270
|
+
- edit: Surgical file edits
|
|
271
|
+
- event: Schedule immediate, one-shot, or periodic follow-ups
|
|
272
|
+
- sandbox: Inspect or temporarily adjust sandbox limits
|
|
273
|
+
- attach: Share files to the platform
|
|
274
|
+
|
|
275
|
+
Each tool requires a "label" parameter (shown to user).
|
|
276
|
+
`;
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Instructions that vary per turn (event-trigger mode, response attribution).
|
|
280
|
+
* These are delivered with the user message rather than baked into the system
|
|
281
|
+
* prompt, so the system prompt stays cache-stable across a conversation's turns
|
|
282
|
+
* (in a multi-user channel the attribution line alone changes every turn).
|
|
283
|
+
* Returns an empty string when the turn needs no special framing.
|
|
284
|
+
*/
|
|
285
|
+
export function buildTurnInstructions(isEventTrigger, triggerAttribution, platformName) {
|
|
286
|
+
const parts = [];
|
|
287
|
+
if (isEventTrigger) {
|
|
288
|
+
parts.push(`## Event Trigger Mode
|
|
289
|
+
- You are handling a scheduled/background event, not opening a brand new chat with a stranger.
|
|
290
|
+
- Treat the incoming user message as a self-contained task prepared by an earlier run.
|
|
291
|
+
- Complete the task directly. Avoid generic greetings, self-introductions, or boilerplate offers to help.
|
|
292
|
+
- For reminders/follow-ups, prefer a short direct response that sounds like a continuation of prior intent.
|
|
293
|
+
- If the event text includes tone, brevity, or language instructions, follow them literally.`);
|
|
294
|
+
}
|
|
295
|
+
if (triggerAttribution) {
|
|
296
|
+
parts.push(`## Attribution
|
|
297
|
+
Always end your final ${platformName} response and any GitHub issue/PR comments or descriptions you write via tools with:
|
|
298
|
+
_Triggered by ${triggerAttribution}_
|
|
299
|
+
|
|
300
|
+
Do not add this to \`[SILENT]\` responses.`);
|
|
301
|
+
}
|
|
302
|
+
return parts.join("\n\n");
|
|
303
|
+
}
|
|
304
|
+
export function appendTriggerAttribution(text, triggerAttribution, sessionLink) {
|
|
305
|
+
if (!triggerAttribution)
|
|
306
|
+
return text;
|
|
307
|
+
const trimmed = text.trimEnd();
|
|
308
|
+
const legacySuffix = `_Triggered by ${triggerAttribution}_`;
|
|
309
|
+
// Slack mrkdwn italics cannot span a URL — a `_..._` wrapping a link renders
|
|
310
|
+
// the underscores literally. Keep the session link outside the italic span.
|
|
311
|
+
const suffix = sessionLink ? `${legacySuffix} · session: ${sessionLink}` : legacySuffix;
|
|
312
|
+
if (trimmed.endsWith(suffix))
|
|
313
|
+
return text;
|
|
314
|
+
const body = trimmed.endsWith(legacySuffix)
|
|
315
|
+
? trimmed.slice(0, -legacySuffix.length).trimEnd()
|
|
316
|
+
: trimmed;
|
|
317
|
+
return `${body}\n\n${suffix}`;
|
|
318
|
+
}
|
|
319
|
+
export function sessionDreamPrompt(conversationMemoryPath, toolNames) {
|
|
320
|
+
// read/edit/write are core tools, so an empty grant does not arise today;
|
|
321
|
+
// the fallback only keeps this sentence coherent if that ever changes.
|
|
322
|
+
const grant = toolNames.length === 0
|
|
323
|
+
? "You have no tools in this run and cannot change memory. Say so and stop."
|
|
324
|
+
: `Your tools this run: ${toolNames.join(", ")}. Nothing else will execute, including tools used earlier in this transcript. ${conversationMemoryPath} is the only path you may write.`;
|
|
325
|
+
return [
|
|
326
|
+
"Before this conversation is reset or rotated, preserve only durable information worth carrying into future sessions of this same conversation.",
|
|
327
|
+
`Review the existing transcript and update only the conversation-specific MEMORY.md at ${conversationMemoryPath}.`,
|
|
328
|
+
grant,
|
|
329
|
+
"Do not modify the workspace-level global MEMORY.md. Information from one DM or channel must not be promoted into memory shared with other conversations by this maintenance run.",
|
|
330
|
+
"Preserve durable decisions, preferences, facts, and ongoing work specific to this conversation. Preserve the concrete values and details needed to resume the work; do not replace them with abstract categories, summaries of retention rules, or statements that merely say a kind of information is durable. An explicit user statement that a fact, preference, or decision should persist is strong evidence that its exact content is worth preserving.",
|
|
331
|
+
"Deduplicate against existing conversation memory. Do not preserve transient discussion, tool noise, secrets, speculative details, or test scaffolding. If there is nothing new worth preserving, make no changes. Do no unrelated work.",
|
|
332
|
+
].join("\n");
|
|
333
|
+
}
|
|
334
|
+
export const SESSION_DREAM_BUDGET = {
|
|
335
|
+
maxDurationMs: 2 * 60 * 1000,
|
|
336
|
+
maxLlmCalls: 10,
|
|
337
|
+
};
|
|
338
|
+
export function sessionDreamTools(tools, conversationMemoryPath) {
|
|
339
|
+
return tools
|
|
340
|
+
.filter((tool) => tool.name === "read" || tool.name === "edit" || tool.name === "write")
|
|
341
|
+
.map((tool) => {
|
|
342
|
+
if (tool.name === "read")
|
|
343
|
+
return tool;
|
|
344
|
+
return Object.assign({}, tool, {
|
|
345
|
+
execute: async (...args) => {
|
|
346
|
+
const params = args[1];
|
|
347
|
+
if (params.path !== conversationMemoryPath) {
|
|
348
|
+
throw new Error(`Session Dream may only modify ${conversationMemoryPath}`);
|
|
349
|
+
}
|
|
350
|
+
return tool.execute(...args);
|
|
351
|
+
},
|
|
352
|
+
});
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
//# sourceMappingURL=prompt.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prompt.js","sourceRoot":"","sources":["../../src/ag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G,IAAsC,EAAE,EAAE;gBAC3D,MAAM,MAAM,GAAG,IAAI,CAAC,CAAC,CAAuB,CAAC;gBAC7C,IAAI,MAAM,CAAC,IAAI,KAAK,sBAAsB,EAAE,CAAC;oBAC3C,MAAM,IAAI,KAAK,CAAC,iCAAiC,sBAAsB,EAAE,CAAC,CAAC;gBAC7E,CAAC;gBACD,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC;YAC/B,CAAC;SACF,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["import type { Office } from \"../office/index.js\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { type ImageContent } from \"@earendil-works/pi-ai\";\nimport { formatSkillsForPrompt, type MikanSkill } from \"../harness/index.js\";\nimport { lstatSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport type { ConversationKind, ConversationMessage, MessagingInfo } from \"../adapter.js\";\nimport type { WorkspaceProjection } from \"../workspace-projection/types.js\";\nimport * as log from \"../log.js\";\nimport { type RuntimePathContext, type SandboxConfig } from \"../sandbox/index.js\";\nimport { formatHistoryLine } from \"../sessions/history-line.js\";\nimport { buildRuntimePaths, collectMessageAttachments } from \"./execution.js\";\n\nfunction formatTimestampedUserMessage(message: ConversationMessage): string {\n return formatHistoryLine({\n date: new Date(),\n userName: message.userName,\n threadTs: message.threadTs,\n text: message.text,\n });\n}\n\nexport async function buildPromptPayload(\n message: ConversationMessage,\n workspacePath: string,\n pathContext?: RuntimePathContext,\n readAttachment?: (runtimePath: string) => Promise<string>,\n): Promise<{\n userMessage: string;\n imageAttachments: ImageContent[];\n}> {\n let userMessage = formatTimestampedUserMessage(message);\n const { imageAttachments, nonImagePaths } = await collectMessageAttachments(\n message,\n workspacePath,\n pathContext,\n readAttachment,\n );\n\n if (nonImagePaths.length > 0) {\n userMessage += `\\n\\n<slack_attachments>\\n${nonImagePaths.join(\"\\n\")}\\n</slack_attachments>`;\n }\n\n return { userMessage, imageAttachments };\n}\n\nexport async function getMemory(projection: WorkspaceProjection): Promise<string> {\n const parts: string[] = [];\n\n const workspaceMemoryPath = projection.promptSources.globalMemoryPath;\n if (workspaceMemoryPath && isRegularFile(workspaceMemoryPath)) {\n try {\n const content = (await readFile(workspaceMemoryPath, \"utf-8\")).trim();\n if (content) {\n parts.push(`### Global Workspace Memory\\n${content}`);\n }\n } catch (error) {\n log.logWarning(\"Failed to read workspace memory\", `${workspaceMemoryPath}: ${error}`);\n }\n }\n\n const conversationMemoryPath = projection.promptSources.conversationMemoryPath;\n if (isRegularFile(conversationMemoryPath)) {\n try {\n const content = (await readFile(conversationMemoryPath, \"utf-8\")).trim();\n if (content) {\n parts.push(`### Conversation-Specific Memory\\n${content}`);\n }\n } catch (error) {\n log.logWarning(\"Failed to read conversation memory\", `${conversationMemoryPath}: ${error}`);\n }\n }\n\n if (parts.length === 0) {\n return \"(no working memory yet)\";\n }\n\n return parts.join(\"\\n\\n\");\n}\n\nfunction isRegularFile(path: string): boolean {\n try {\n const stats = lstatSync(path);\n return stats.isFile() && !stats.isSymbolicLink();\n } catch {\n return false;\n }\n}\n\nfunction buildEnvDescription(sandboxType: SandboxConfig[\"type\"], workspaceRoot: string): string {\n switch (sandboxType) {\n case \"image\":\n return `You are running inside a managed per-conversation container.\n- Runtime workspace root: ${workspaceRoot}\n- Bash commands start in: ${workspaceRoot}\n- Install tools with the image's package manager\n- Your changes persist for this user's container until it is recreated`;\n case \"container\":\n return `You are running inside a shared container.\n- Runtime workspace root: ${workspaceRoot}\n- Bash commands start in: ${workspaceRoot}\n- Install tools with the container's package manager\n- Your changes persist across sessions`;\n case \"firecracker\":\n return `You are running inside a Firecracker microVM.\n- Runtime workspace root: ${workspaceRoot}\n- Use cd or absolute paths; project files are under ${workspaceRoot}\n- Install tools with: apt-get install <package> (Debian-based)\n- Your changes persist across sessions`;\n case \"cloudflare\":\n return `You are running through a Cloudflare Sandbox bridge.\n- Runtime workspace root: ${workspaceRoot}\n- Bash commands start in: ${workspaceRoot}\n- Your commands run in a remote container managed by Cloudflare\n- Important: the remote filesystem is not automatically synced back to the host workspace`;\n default:\n return `You are running directly on the host machine.\n- Runtime workspace root: ${workspaceRoot}\n- Bash commands start in: ${process.cwd()}\n- Be careful with system modifications`;\n }\n}\n\nexport function resolveTriggerAttribution(\n message: Pick<ConversationMessage, \"id\" | \"text\" | \"userName\">,\n): string | undefined {\n const eventTextMatch = message.text.match(/^\\[EVENT:([^:]+):/);\n if (eventTextMatch) return `[event: ${eventTextMatch[1]}]`;\n const eventIdMatch = message.id.match(/^event:([^:]+)/);\n if (eventIdMatch) return `[event: ${eventIdMatch[1]}]`;\n if (message.userName) return `@${message.userName}`;\n return undefined;\n}\n\nexport function buildSystemPrompt(\n workspacePath: string,\n office: Office,\n conversationKind: ConversationKind,\n currentUserId: string | undefined,\n memory: string,\n sandboxConfig: SandboxConfig,\n platform: MessagingInfo,\n skills: MikanSkill[],\n projection: WorkspaceProjection,\n skippedSkillLinks: string[] = [],\n): string {\n const { workspaceRoot, conversationPath, scratchPath } = buildRuntimePaths(workspacePath, office);\n const sandboxType = sandboxConfig.type;\n const isContainerLike = sandboxType === \"container\" || sandboxType === \"image\";\n const isFirecracker = sandboxType === \"firecracker\";\n\n // Format channel mappings\n const channelMappings =\n platform.channels.length > 0\n ? platform.channels.map((c) => `${c.id}\\t#${c.name}`).join(\"\\n\")\n : \"(no channels loaded)\";\n\n // Format user mappings\n const userMappings =\n platform.users.length > 0\n ? platform.users.map((u) => `${u.id}\\t@${u.userName}\\t${u.displayName}`).join(\"\\n\")\n : \"(no users loaded)\";\n\n const envDescription = buildEnvDescription(sandboxType, workspaceRoot);\n // Per-turn instructions (event-trigger mode, attribution) are delivered with\n // the user message via buildTurnInstructions(), not baked in here, so this\n // system prompt stays byte-stable across a conversation's turns and keeps the\n // provider prompt cache warm (a changing system prefix invalidates the cache\n // for the whole request, including the far larger conversation history).\n const workspaceLayout =\n projection.layout === \"full\"\n ? `${workspaceRoot}/ contains the complete trusted workspace.`\n : projection.layout === \"shared-support\"\n ? `${workspaceRoot}/ contains shared MEMORY.md, skills/, events/, and this conversation's directory.`\n : `${conversationPath}/ is the only conversation workspace mounted; global memory, skills, and events are not available.`;\n const skillStorageGuidance =\n projection.doorPolicy === \"trusted\"\n ? `Store shared skills in \\`${workspaceRoot}/skills/<name>/\\` or conversation-specific skills in \\`${conversationPath}/skills/<name>/\\`.`\n : `Store skills in \\`${conversationPath}/skills/<name>/\\`; this office cannot access workspace-global skills.`;\n const memoryGuidance =\n projection.doorPolicy === \"trusted\"\n ? `Write important shared knowledge to \\`${workspaceRoot}/MEMORY.md\\` and conversation-specific knowledge to \\`${conversationPath}/MEMORY.md\\`.`\n : `Write durable knowledge only to \\`${conversationPath}/MEMORY.md\\`; this office cannot access workspace-global memory.`;\n const systemLogPath =\n projection.layout === \"conversation\"\n ? `${conversationPath}/SYSTEM.md`\n : `${workspaceRoot}/SYSTEM.md`;\n const slackBlockKitInstructions =\n platform.name === \"slack\"\n ? `\n## Slack Rendering\n- The Slack adapter renders responses natively from standard Markdown. Answer in normal Markdown/GFM.\n- Markdown pipe tables are rendered as native Slack tables.\n- For interactive elements (buttons, select menus), use the slack_blockkit tool; user interactions arrive as \"[Slack action] <action_id>: <value>\" messages.\n`\n : \"\";\n\n return `You are mikan, a ${platform.name} bot assistant. Be concise. No emojis.\n\n## Context\n- For current date/time, use: date\n- You have access to previous conversation context including tool results from prior turns.\n- For older human-readable history beyond your context, search \\`log.jsonl\\` (contains user messages and your final responses, but not tool results).\n- Structured session history with tool results lives in \\`${conversationPath}/sessions/\\`.\n- The active top-level session is selected by \\`${conversationPath}/sessions/current\\`, which points to a timestamped \\`.jsonl\\` file in the same directory.\n- Scoped/thread sessions use fixed files at \\`${conversationPath}/sessions/<scope_id>.jsonl\\` (for example \\`${conversationPath}/sessions/1777386320.800769.jsonl\\`).\n- If a user asks about something that should exist in conversation history but is not found in the current context window, do not answer \"I don't know\" or \"I don't have that\". Instead, search the thread session, top-level session, and \\`log.jsonl\\` before responding.\n- User messages include a \\`[in-thread:TS]\\` marker when sent from within a platform thread/reply (TS is the thread or parent message identifier). Without this marker, the message is a top-level conversation message.\n${platform.formattingGuide}${slackBlockKitInstructions}\n\n## Platform IDs\nChannels: ${channelMappings}\n\nUsers: ${userMappings}\n\nWhen mentioning users, write <@userName> using the exact userName from the Users table above (e.g., <@mario>). Never invent handles from other platforms (GitHub, email); the platform adapter converts <@userName> to the platform's native mention form.\n\n## Environment\n${envDescription}\n- Default place for clones, downloads, and experiments: ${scratchPath}\n- Do not use host-only paths unless you are running in host mode and verified they exist.\n\n## Workspace Layout\n${workspaceLayout}\n${\n projection.layout === \"conversation\"\n ? `${conversationPath}/ # This conversation`\n : `${workspaceRoot}/\n├── MEMORY.md # Global memory (all conversations)\n├── skills/ # Global CLI tools you create\n└── ${office.key}/ # This conversation`\n}\n ├── MEMORY.md # Conversation-specific memory\n ├── log.jsonl # Human-readable message history (no tool results)\n ├── sessions/ # Structured session history used for context reconstruction\n │ ├── current # Active top-level session pointer\n │ ├── <timestamp>_<id>.jsonl # Top-level session files\n │ └── <scope_id>.jsonl # Scoped thread/reply session files\n ├── attachments/ # User-shared files\n ├── scratch/ # Working directory for clones/downloads/experiments: ${scratchPath}\n └── skills/ # Conversation-specific tools\n\n## Skills (Custom CLI Tools)\nYou can create reusable CLI tools for recurring tasks (email, APIs, data processing, etc.).\n\n### Creating Skills\n${skillStorageGuidance}\nEach skill directory needs a \\`SKILL.md\\` with YAML frontmatter:\n\n\\`\\`\\`markdown\n---\nname: skill-name\ndescription: Short description of what this skill does\n---\n\n# Skill Name\n\nUsage instructions, examples, etc.\nScripts are in: {baseDir}/\n\\`\\`\\`\n\n\\`name\\` and \\`description\\` are required. Use \\`{baseDir}\\` as placeholder for the skill's directory path.\n\n### Available Skills\n${skills.length > 0 ? formatSkillsForPrompt(skills) : \"(no skills installed yet)\"}${\n skippedSkillLinks.length > 0\n ? `\\n\\nNote: these skill entries were skipped because they are symlinks, which the host never follows when reading this conversation's skills: ${skippedSkillLinks.join(\", \")}. Replace each with a real file or directory (for example \\`cp -rL\\`) to load it.`\n : \"\"\n }\n\n## Events\nUse the \\`event\\` tool to schedule immediate, one-shot, or periodic follow-ups. It writes to the host-side mikan control plane and fills routing fields for the current conversation automatically.\n\nWrite event \\`text\\` as a self-contained future task with needed context, tone, and constraints because events do not inherit normal conversation history.\n\nFor one-shot reminders, include a timezone offset in \\`at\\`. For periodic events, use a cron schedule plus IANA timezone; assume ${Intl.DateTimeFormat().resolvedOptions().timeZone} when users omit timezone.\n\nWhen events trigger, messages are prefixed like \\`[EVENT:filename:type:time]\\`. Immediate and one-shot events auto-delete after triggering; periodic events persist until deleted.\n\nFor periodic events where there's nothing to report, respond with exactly \\`[SILENT]\\`. Debounce external triggers; prefer one summarized event over many.\n\n## Memory\n${memoryGuidance}\nUpdate it when you learn something important or when asked to remember something.\n\n### Current Memory\n${memory}\n\n## System Configuration Log\nMaintain ${systemLogPath} to log all environment modifications:\n- Installed packages (apt install, npm install, uv pip install)\n- Environment variables set\n- Config files modified (~/.gitconfig, cron jobs, etc.)\n- Skill dependencies installed\n\nUpdate this file whenever you modify the environment. On fresh container, read it first to restore your setup.\n\n## Log Queries (for older history)\nFormat: \\`{\"date\":\"...\",\"ts\":\"...\",\"user\":\"...\",\"userName\":\"...\",\"text\":\"...\",\"isMessagingBot\":false}\\`\nThe log contains user messages and your final responses (not tool calls/results).\nUse \\`log.jsonl\\` for quick grep-style history. Use \\`${conversationPath}/sessions/\\` when you need structured turns, tool outputs, or thread/session lineage.\n${isContainerLike || isFirecracker ? \"Install jq: apt-get install jq\" : \"\"}\n\\`\\`\\`bash\n# Recent messages\ntail -30 log.jsonl | jq -c '{date: .date[0:19], user: (.userName // .user), text}'\n\n# Search for specific topic\ngrep -i \"topic\" log.jsonl | jq -c '{date: .date[0:19], user: (.userName // .user), text}'\n\n# Messages from specific user\ngrep '\"userName\":\"mario\"' log.jsonl | tail -20 | jq -c '{date: .date[0:19], text}'\n\n# Inspect top-level session pointer and available session files\ncat sessions/current\nls -1 sessions/\n\\`\\`\\`\n\n## Tools\n- bash: Run shell commands (primary tool). Install packages as needed.\n- read: Read files\n- write: Create/overwrite files\n- edit: Surgical file edits\n- event: Schedule immediate, one-shot, or periodic follow-ups\n- sandbox: Inspect or temporarily adjust sandbox limits\n- attach: Share files to the platform\n\nEach tool requires a \"label\" parameter (shown to user).\n`;\n}\n\n/**\n * Instructions that vary per turn (event-trigger mode, response attribution).\n * These are delivered with the user message rather than baked into the system\n * prompt, so the system prompt stays cache-stable across a conversation's turns\n * (in a multi-user channel the attribution line alone changes every turn).\n * Returns an empty string when the turn needs no special framing.\n */\nexport function buildTurnInstructions(\n isEventTrigger: boolean,\n triggerAttribution: string | undefined,\n platformName: string,\n): string {\n const parts: string[] = [];\n if (isEventTrigger) {\n parts.push(`## Event Trigger Mode\n- You are handling a scheduled/background event, not opening a brand new chat with a stranger.\n- Treat the incoming user message as a self-contained task prepared by an earlier run.\n- Complete the task directly. Avoid generic greetings, self-introductions, or boilerplate offers to help.\n- For reminders/follow-ups, prefer a short direct response that sounds like a continuation of prior intent.\n- If the event text includes tone, brevity, or language instructions, follow them literally.`);\n }\n if (triggerAttribution) {\n parts.push(`## Attribution\nAlways end your final ${platformName} response and any GitHub issue/PR comments or descriptions you write via tools with:\n_Triggered by ${triggerAttribution}_\n\nDo not add this to \\`[SILENT]\\` responses.`);\n }\n return parts.join(\"\\n\\n\");\n}\n\nexport function appendTriggerAttribution(\n text: string,\n triggerAttribution: string | undefined,\n sessionLink?: string,\n): string {\n if (!triggerAttribution) return text;\n const trimmed = text.trimEnd();\n const legacySuffix = `_Triggered by ${triggerAttribution}_`;\n // Slack mrkdwn italics cannot span a URL — a `_..._` wrapping a link renders\n // the underscores literally. Keep the session link outside the italic span.\n const suffix = sessionLink ? `${legacySuffix} · session: ${sessionLink}` : legacySuffix;\n if (trimmed.endsWith(suffix)) return text;\n const body = trimmed.endsWith(legacySuffix)\n ? trimmed.slice(0, -legacySuffix.length).trimEnd()\n : trimmed;\n return `${body}\\n\\n${suffix}`;\n}\n\nexport function sessionDreamPrompt(conversationMemoryPath: string, toolNames: string[]): string {\n // read/edit/write are core tools, so an empty grant does not arise today;\n // the fallback only keeps this sentence coherent if that ever changes.\n const grant =\n toolNames.length === 0\n ? \"You have no tools in this run and cannot change memory. Say so and stop.\"\n : `Your tools this run: ${toolNames.join(\", \")}. Nothing else will execute, including tools used earlier in this transcript. ${conversationMemoryPath} is the only path you may write.`;\n return [\n \"Before this conversation is reset or rotated, preserve only durable information worth carrying into future sessions of this same conversation.\",\n `Review the existing transcript and update only the conversation-specific MEMORY.md at ${conversationMemoryPath}.`,\n grant,\n \"Do not modify the workspace-level global MEMORY.md. Information from one DM or channel must not be promoted into memory shared with other conversations by this maintenance run.\",\n \"Preserve durable decisions, preferences, facts, and ongoing work specific to this conversation. Preserve the concrete values and details needed to resume the work; do not replace them with abstract categories, summaries of retention rules, or statements that merely say a kind of information is durable. An explicit user statement that a fact, preference, or decision should persist is strong evidence that its exact content is worth preserving.\",\n \"Deduplicate against existing conversation memory. Do not preserve transient discussion, tool noise, secrets, speculative details, or test scaffolding. If there is nothing new worth preserving, make no changes. Do no unrelated work.\",\n ].join(\"\\n\");\n}\n\nexport const SESSION_DREAM_BUDGET = {\n maxDurationMs: 2 * 60 * 1000,\n maxLlmCalls: 10,\n};\n\nexport function sessionDreamTools(tools: AgentTool[], conversationMemoryPath: string): AgentTool[] {\n return tools\n .filter((tool) => tool.name === \"read\" || tool.name === \"edit\" || tool.name === \"write\")\n .map((tool) => {\n if (tool.name === \"read\") return tool;\n return Object.assign({}, tool, {\n execute: async (...args: Parameters<AgentTool[\"execute\"]>) => {\n const params = args[1] as { path?: unknown };\n if (params.path !== conversationMemoryPath) {\n throw new Error(`Session Dream may only modify ${conversationMemoryPath}`);\n }\n return tool.execute(...args);\n },\n });\n });\n}\n"]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { CreateRunnerOptions, PiAgentWrapper } from "../types.js";
|
|
2
|
+
/**
|
|
3
|
+
* The dream run reads a transcript in which the agent held its full tool set,
|
|
4
|
+
* but `sessionDreamTools` has since narrowed it. Left to infer its grant from
|
|
5
|
+
* the transcript, the model calls a tool it no longer holds and burns one of
|
|
6
|
+
* its five turns on the failure — so the grant is stated, and derived from the
|
|
7
|
+
* tools actually handed to the run rather than restated by hand.
|
|
8
|
+
*/
|
|
9
|
+
export declare function createRunner(options: CreateRunnerOptions): Promise<PiAgentWrapper>;
|
|
10
|
+
//# sourceMappingURL=runner.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runner.d.ts","sourceRoot":"","sources":["../../src/agent/runner.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAiB,cAAc,EAAE,MAAM,aAAa,CAAC;AAmQtF;;;;;;GAMG;AACH,wBAAsB,YAAY,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,cAAc,CAAC,CAmbxF"}
|