@geminixiang/mikan 0.2.0
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 +324 -0
- package/LICENSE +22 -0
- package/README.md +297 -0
- package/dist/adapter.d.ts +134 -0
- package/dist/adapter.d.ts.map +1 -0
- package/dist/adapter.js +2 -0
- package/dist/adapter.js.map +1 -0
- package/dist/adapters/discord/bot.d.ts +63 -0
- package/dist/adapters/discord/bot.d.ts.map +1 -0
- package/dist/adapters/discord/bot.js +577 -0
- package/dist/adapters/discord/bot.js.map +1 -0
- package/dist/adapters/discord/context.d.ts +9 -0
- package/dist/adapters/discord/context.d.ts.map +1 -0
- package/dist/adapters/discord/context.js +245 -0
- package/dist/adapters/discord/context.js.map +1 -0
- package/dist/adapters/discord/index.d.ts +3 -0
- package/dist/adapters/discord/index.d.ts.map +1 -0
- package/dist/adapters/discord/index.js +3 -0
- package/dist/adapters/discord/index.js.map +1 -0
- package/dist/adapters/shared.d.ts +91 -0
- package/dist/adapters/shared.d.ts.map +1 -0
- package/dist/adapters/shared.js +191 -0
- package/dist/adapters/shared.js.map +1 -0
- package/dist/adapters/slack/bot.d.ts +139 -0
- package/dist/adapters/slack/bot.d.ts.map +1 -0
- package/dist/adapters/slack/bot.js +1272 -0
- package/dist/adapters/slack/bot.js.map +1 -0
- package/dist/adapters/slack/branch-manager.d.ts +28 -0
- package/dist/adapters/slack/branch-manager.d.ts.map +1 -0
- package/dist/adapters/slack/branch-manager.js +117 -0
- package/dist/adapters/slack/branch-manager.js.map +1 -0
- package/dist/adapters/slack/context.d.ts +12 -0
- package/dist/adapters/slack/context.d.ts.map +1 -0
- package/dist/adapters/slack/context.js +327 -0
- package/dist/adapters/slack/context.js.map +1 -0
- package/dist/adapters/slack/index.d.ts +3 -0
- package/dist/adapters/slack/index.d.ts.map +1 -0
- package/dist/adapters/slack/index.js +3 -0
- package/dist/adapters/slack/index.js.map +1 -0
- package/dist/adapters/slack/session.d.ts +38 -0
- package/dist/adapters/slack/session.d.ts.map +1 -0
- package/dist/adapters/slack/session.js +66 -0
- package/dist/adapters/slack/session.js.map +1 -0
- package/dist/adapters/slack/tools/attach.d.ts +12 -0
- package/dist/adapters/slack/tools/attach.d.ts.map +1 -0
- package/dist/adapters/slack/tools/attach.js +40 -0
- package/dist/adapters/slack/tools/attach.js.map +1 -0
- package/dist/adapters/telegram/bot.d.ts +51 -0
- package/dist/adapters/telegram/bot.d.ts.map +1 -0
- package/dist/adapters/telegram/bot.js +430 -0
- package/dist/adapters/telegram/bot.js.map +1 -0
- package/dist/adapters/telegram/context.d.ts +9 -0
- package/dist/adapters/telegram/context.d.ts.map +1 -0
- package/dist/adapters/telegram/context.js +190 -0
- package/dist/adapters/telegram/context.js.map +1 -0
- package/dist/adapters/telegram/html.d.ts +3 -0
- package/dist/adapters/telegram/html.d.ts.map +1 -0
- package/dist/adapters/telegram/html.js +98 -0
- package/dist/adapters/telegram/html.js.map +1 -0
- package/dist/adapters/telegram/index.d.ts +3 -0
- package/dist/adapters/telegram/index.d.ts.map +1 -0
- package/dist/adapters/telegram/index.js +3 -0
- package/dist/adapters/telegram/index.js.map +1 -0
- package/dist/agent.d.ts +36 -0
- package/dist/agent.d.ts.map +1 -0
- package/dist/agent.js +1147 -0
- package/dist/agent.js.map +1 -0
- package/dist/commands/auto-reply.d.ts +5 -0
- package/dist/commands/auto-reply.d.ts.map +1 -0
- package/dist/commands/auto-reply.js +79 -0
- package/dist/commands/auto-reply.js.map +1 -0
- package/dist/commands/index.d.ts +5 -0
- package/dist/commands/index.d.ts.map +1 -0
- package/dist/commands/index.js +18 -0
- package/dist/commands/index.js.map +1 -0
- package/dist/commands/login.d.ts +5 -0
- package/dist/commands/login.d.ts.map +1 -0
- package/dist/commands/login.js +91 -0
- package/dist/commands/login.js.map +1 -0
- package/dist/commands/model.d.ts +14 -0
- package/dist/commands/model.d.ts.map +1 -0
- package/dist/commands/model.js +110 -0
- package/dist/commands/model.js.map +1 -0
- package/dist/commands/new.d.ts +5 -0
- package/dist/commands/new.d.ts.map +1 -0
- package/dist/commands/new.js +24 -0
- package/dist/commands/new.js.map +1 -0
- package/dist/commands/parse.d.ts +7 -0
- package/dist/commands/parse.d.ts.map +1 -0
- package/dist/commands/parse.js +17 -0
- package/dist/commands/parse.js.map +1 -0
- package/dist/commands/registry.d.ts +4 -0
- package/dist/commands/registry.d.ts.map +1 -0
- package/dist/commands/registry.js +9 -0
- package/dist/commands/registry.js.map +1 -0
- package/dist/commands/sandbox.d.ts +10 -0
- package/dist/commands/sandbox.d.ts.map +1 -0
- package/dist/commands/sandbox.js +83 -0
- package/dist/commands/sandbox.js.map +1 -0
- package/dist/commands/session-view.d.ts +5 -0
- package/dist/commands/session-view.d.ts.map +1 -0
- package/dist/commands/session-view.js +62 -0
- package/dist/commands/session-view.js.map +1 -0
- package/dist/commands/types.d.ts +41 -0
- package/dist/commands/types.d.ts.map +1 -0
- package/dist/commands/types.js +2 -0
- package/dist/commands/types.js.map +1 -0
- package/dist/commands/utils.d.ts +8 -0
- package/dist/commands/utils.d.ts.map +1 -0
- package/dist/commands/utils.js +14 -0
- package/dist/commands/utils.js.map +1 -0
- package/dist/config.d.ts +59 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +370 -0
- package/dist/config.js.map +1 -0
- package/dist/context.d.ts +17 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +24 -0
- package/dist/context.js.map +1 -0
- package/dist/conversation-history.d.ts +16 -0
- package/dist/conversation-history.d.ts.map +1 -0
- package/dist/conversation-history.js +144 -0
- package/dist/conversation-history.js.map +1 -0
- package/dist/download.d.ts +2 -0
- package/dist/download.d.ts.map +1 -0
- package/dist/download.js +89 -0
- package/dist/download.js.map +1 -0
- package/dist/env.d.ts +3 -0
- package/dist/env.d.ts.map +1 -0
- package/dist/env.js +12 -0
- package/dist/env.js.map +1 -0
- package/dist/events.d.ts +85 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +483 -0
- package/dist/events.js.map +1 -0
- package/dist/execution-resolver.d.ts +25 -0
- package/dist/execution-resolver.d.ts.map +1 -0
- package/dist/execution-resolver.js +167 -0
- package/dist/execution-resolver.js.map +1 -0
- package/dist/file-guards.d.ts +9 -0
- package/dist/file-guards.d.ts.map +1 -0
- package/dist/file-guards.js +56 -0
- package/dist/file-guards.js.map +1 -0
- package/dist/fs-atomic.d.ts +10 -0
- package/dist/fs-atomic.d.ts.map +1 -0
- package/dist/fs-atomic.js +45 -0
- package/dist/fs-atomic.js.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -0
- package/dist/instrument.d.ts +2 -0
- package/dist/instrument.d.ts.map +1 -0
- package/dist/instrument.js +10 -0
- package/dist/instrument.js.map +1 -0
- package/dist/log.d.ts +36 -0
- package/dist/log.d.ts.map +1 -0
- package/dist/log.js +206 -0
- package/dist/log.js.map +1 -0
- package/dist/login/index.d.ts +42 -0
- package/dist/login/index.d.ts.map +1 -0
- package/dist/login/index.js +239 -0
- package/dist/login/index.js.map +1 -0
- package/dist/login/portal.d.ts +19 -0
- package/dist/login/portal.d.ts.map +1 -0
- package/dist/login/portal.js +1544 -0
- package/dist/login/portal.js.map +1 -0
- package/dist/login/session.d.ts +26 -0
- package/dist/login/session.d.ts.map +1 -0
- package/dist/login/session.js +56 -0
- package/dist/login/session.js.map +1 -0
- package/dist/main.d.ts +3 -0
- package/dist/main.d.ts.map +1 -0
- package/dist/main.js +366 -0
- package/dist/main.js.map +1 -0
- package/dist/provisioner.d.ts +83 -0
- package/dist/provisioner.d.ts.map +1 -0
- package/dist/provisioner.js +500 -0
- package/dist/provisioner.js.map +1 -0
- package/dist/runtime/conversation-orchestrator.d.ts +40 -0
- package/dist/runtime/conversation-orchestrator.d.ts.map +1 -0
- package/dist/runtime/conversation-orchestrator.js +183 -0
- package/dist/runtime/conversation-orchestrator.js.map +1 -0
- package/dist/runtime/index.d.ts +2 -0
- package/dist/runtime/index.d.ts.map +1 -0
- package/dist/runtime/index.js +2 -0
- package/dist/runtime/index.js.map +1 -0
- package/dist/runtime/session-runtime.d.ts +26 -0
- package/dist/runtime/session-runtime.d.ts.map +1 -0
- package/dist/runtime/session-runtime.js +221 -0
- package/dist/runtime/session-runtime.js.map +1 -0
- package/dist/sandbox/cloudflare.d.ts +15 -0
- package/dist/sandbox/cloudflare.d.ts.map +1 -0
- package/dist/sandbox/cloudflare.js +138 -0
- package/dist/sandbox/cloudflare.js.map +1 -0
- package/dist/sandbox/container.d.ts +16 -0
- package/dist/sandbox/container.d.ts.map +1 -0
- package/dist/sandbox/container.js +138 -0
- package/dist/sandbox/container.js.map +1 -0
- package/dist/sandbox/errors.d.ts +6 -0
- package/dist/sandbox/errors.d.ts.map +1 -0
- package/dist/sandbox/errors.js +11 -0
- package/dist/sandbox/errors.js.map +1 -0
- package/dist/sandbox/firecracker.d.ts +17 -0
- package/dist/sandbox/firecracker.d.ts.map +1 -0
- package/dist/sandbox/firecracker.js +212 -0
- package/dist/sandbox/firecracker.js.map +1 -0
- package/dist/sandbox/host.d.ts +11 -0
- package/dist/sandbox/host.d.ts.map +1 -0
- package/dist/sandbox/host.js +89 -0
- package/dist/sandbox/host.js.map +1 -0
- package/dist/sandbox/image.d.ts +5 -0
- package/dist/sandbox/image.d.ts.map +1 -0
- package/dist/sandbox/image.js +30 -0
- package/dist/sandbox/image.js.map +1 -0
- package/dist/sandbox/index.d.ts +22 -0
- package/dist/sandbox/index.d.ts.map +1 -0
- package/dist/sandbox/index.js +54 -0
- package/dist/sandbox/index.js.map +1 -0
- package/dist/sandbox/path-context.d.ts +4 -0
- package/dist/sandbox/path-context.d.ts.map +1 -0
- package/dist/sandbox/path-context.js +20 -0
- package/dist/sandbox/path-context.js.map +1 -0
- package/dist/sandbox/types.d.ts +67 -0
- package/dist/sandbox/types.d.ts.map +1 -0
- package/dist/sandbox/types.js +2 -0
- package/dist/sandbox/types.js.map +1 -0
- package/dist/sandbox/utils.d.ts +4 -0
- package/dist/sandbox/utils.d.ts.map +1 -0
- package/dist/sandbox/utils.js +51 -0
- package/dist/sandbox/utils.js.map +1 -0
- package/dist/sentry.d.ts +50 -0
- package/dist/sentry.d.ts.map +1 -0
- package/dist/sentry.js +257 -0
- package/dist/sentry.js.map +1 -0
- package/dist/session-view/command.d.ts +5 -0
- package/dist/session-view/command.d.ts.map +1 -0
- package/dist/session-view/command.js +7 -0
- package/dist/session-view/command.js.map +1 -0
- package/dist/session-view/portal.d.ts +16 -0
- package/dist/session-view/portal.d.ts.map +1 -0
- package/dist/session-view/portal.js +1822 -0
- package/dist/session-view/portal.js.map +1 -0
- package/dist/session-view/service.d.ts +34 -0
- package/dist/session-view/service.d.ts.map +1 -0
- package/dist/session-view/service.js +434 -0
- package/dist/session-view/service.js.map +1 -0
- package/dist/session-view/store.d.ts +18 -0
- package/dist/session-view/store.d.ts.map +1 -0
- package/dist/session-view/store.js +36 -0
- package/dist/session-view/store.js.map +1 -0
- package/dist/sessions/metadata.d.ts +15 -0
- package/dist/sessions/metadata.d.ts.map +1 -0
- package/dist/sessions/metadata.js +11 -0
- package/dist/sessions/metadata.js.map +1 -0
- package/dist/sessions/policy.d.ts +13 -0
- package/dist/sessions/policy.d.ts.map +1 -0
- package/dist/sessions/policy.js +23 -0
- package/dist/sessions/policy.js.map +1 -0
- package/dist/sessions/store.d.ts +103 -0
- package/dist/sessions/store.d.ts.map +1 -0
- package/dist/sessions/store.js +349 -0
- package/dist/sessions/store.js.map +1 -0
- package/dist/store.d.ts +58 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +152 -0
- package/dist/store.js.map +1 -0
- package/dist/tool-diagnostics.d.ts +2 -0
- package/dist/tool-diagnostics.d.ts.map +1 -0
- package/dist/tool-diagnostics.js +7 -0
- package/dist/tool-diagnostics.js.map +1 -0
- package/dist/tools/bash.d.ts +10 -0
- package/dist/tools/bash.d.ts.map +1 -0
- package/dist/tools/bash.js +80 -0
- package/dist/tools/bash.js.map +1 -0
- package/dist/tools/edit.d.ts +11 -0
- package/dist/tools/edit.d.ts.map +1 -0
- package/dist/tools/edit.js +133 -0
- package/dist/tools/edit.js.map +1 -0
- package/dist/tools/event.d.ts +62 -0
- package/dist/tools/event.d.ts.map +1 -0
- package/dist/tools/event.js +138 -0
- package/dist/tools/event.js.map +1 -0
- package/dist/tools/index.d.ts +14 -0
- package/dist/tools/index.d.ts.map +1 -0
- package/dist/tools/index.js +23 -0
- package/dist/tools/index.js.map +1 -0
- package/dist/tools/read.d.ts +11 -0
- package/dist/tools/read.d.ts.map +1 -0
- package/dist/tools/read.js +136 -0
- package/dist/tools/read.js.map +1 -0
- package/dist/tools/truncate.d.ts +57 -0
- package/dist/tools/truncate.d.ts.map +1 -0
- package/dist/tools/truncate.js +184 -0
- package/dist/tools/truncate.js.map +1 -0
- package/dist/tools/write.d.ts +10 -0
- package/dist/tools/write.d.ts.map +1 -0
- package/dist/tools/write.js +33 -0
- package/dist/tools/write.js.map +1 -0
- package/dist/trigger.d.ts +31 -0
- package/dist/trigger.d.ts.map +1 -0
- package/dist/trigger.js +98 -0
- package/dist/trigger.js.map +1 -0
- package/dist/ui-copy.d.ts +12 -0
- package/dist/ui-copy.d.ts.map +1 -0
- package/dist/ui-copy.js +36 -0
- package/dist/ui-copy.js.map +1 -0
- package/dist/vault-routing.d.ts +4 -0
- package/dist/vault-routing.d.ts.map +1 -0
- package/dist/vault-routing.js +16 -0
- package/dist/vault-routing.js.map +1 -0
- package/dist/vault.d.ts +72 -0
- package/dist/vault.d.ts.map +1 -0
- package/dist/vault.js +281 -0
- package/dist/vault.js.map +1 -0
- package/package.json +83 -0
package/dist/agent.js
ADDED
|
@@ -0,0 +1,1147 @@
|
|
|
1
|
+
import { Agent } from "@earendil-works/pi-agent-core";
|
|
2
|
+
import { getModel } from "@earendil-works/pi-ai";
|
|
3
|
+
import { AgentSession, AuthStorage, convertToLlm, DefaultResourceLoader, formatSkillsForPrompt, getAgentDir, loadSkillsFromDir, ModelRegistry, SettingsManager, } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { existsSync, readFileSync } from "fs";
|
|
5
|
+
import { mkdir, readFile, writeFile } from "fs/promises";
|
|
6
|
+
import { homedir } from "os";
|
|
7
|
+
import { join, posix } from "path";
|
|
8
|
+
import { loadAgentConfigForConversation } from "./config.js";
|
|
9
|
+
import { ActorExecutionResolver } from "./execution-resolver.js";
|
|
10
|
+
import * as log from "./log.js";
|
|
11
|
+
import { reportUserFacingError } from "./sentry.js";
|
|
12
|
+
import { createExecutor, } from "./sandbox/index.js";
|
|
13
|
+
import { createMountedRuntimePathContext } from "./sandbox/path-context.js";
|
|
14
|
+
import { addLifecycleBreadcrumb, metricAttributes } from "./sentry.js";
|
|
15
|
+
import { extractSessionUuid, openManagedSession, } from "./sessions/store.js";
|
|
16
|
+
import { shouldSurfaceToolDiagnostic } from "./tool-diagnostics.js";
|
|
17
|
+
import { createMikanTools } from "./tools/index.js";
|
|
18
|
+
import * as Sentry from "@sentry/node";
|
|
19
|
+
const IMAGE_MIME_TYPES = {
|
|
20
|
+
jpg: "image/jpeg",
|
|
21
|
+
jpeg: "image/jpeg",
|
|
22
|
+
png: "image/png",
|
|
23
|
+
gif: "image/gif",
|
|
24
|
+
webp: "image/webp",
|
|
25
|
+
};
|
|
26
|
+
function getImageMimeType(filename) {
|
|
27
|
+
return IMAGE_MIME_TYPES[filename.toLowerCase().split(".").pop() || ""];
|
|
28
|
+
}
|
|
29
|
+
function buildThreadSessionName(message) {
|
|
30
|
+
const text = message?.text?.trim();
|
|
31
|
+
if (!text)
|
|
32
|
+
return undefined;
|
|
33
|
+
const userLabel = message?.userName || message?.user || "unknown";
|
|
34
|
+
return `[${userLabel}]: ${text}`;
|
|
35
|
+
}
|
|
36
|
+
async function getMemory(conversationDir) {
|
|
37
|
+
const parts = [];
|
|
38
|
+
// Read workspace-level memory (shared across all conversations)
|
|
39
|
+
const workspaceMemoryPath = join(conversationDir, "..", "MEMORY.md");
|
|
40
|
+
if (existsSync(workspaceMemoryPath)) {
|
|
41
|
+
try {
|
|
42
|
+
const content = (await readFile(workspaceMemoryPath, "utf-8")).trim();
|
|
43
|
+
if (content) {
|
|
44
|
+
parts.push(`### Global Workspace Memory\n${content}`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
log.logWarning("Failed to read workspace memory", `${workspaceMemoryPath}: ${error}`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
// Read conversation-specific memory
|
|
52
|
+
const conversationMemoryPath = join(conversationDir, "MEMORY.md");
|
|
53
|
+
if (existsSync(conversationMemoryPath)) {
|
|
54
|
+
try {
|
|
55
|
+
const content = (await readFile(conversationMemoryPath, "utf-8")).trim();
|
|
56
|
+
if (content) {
|
|
57
|
+
parts.push(`### Conversation-Specific Memory\n${content}`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
log.logWarning("Failed to read conversation memory", `${conversationMemoryPath}: ${error}`);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (parts.length === 0) {
|
|
65
|
+
return "(no working memory yet)";
|
|
66
|
+
}
|
|
67
|
+
return parts.join("\n\n");
|
|
68
|
+
}
|
|
69
|
+
function loadMikanSkills(conversationDir, workspacePath) {
|
|
70
|
+
const skillMap = new Map();
|
|
71
|
+
// conversationDir is the host path (e.g., /Users/.../data/C0A34FL8PMH)
|
|
72
|
+
// hostWorkspacePath is the parent directory on host
|
|
73
|
+
// workspacePath is the container path (e.g., /workspace)
|
|
74
|
+
const hostWorkspacePath = join(conversationDir, "..");
|
|
75
|
+
// Helper to translate host paths to container paths
|
|
76
|
+
const translatePath = (hostPath) => {
|
|
77
|
+
if (hostPath.startsWith(hostWorkspacePath)) {
|
|
78
|
+
return workspacePath + hostPath.slice(hostWorkspacePath.length);
|
|
79
|
+
}
|
|
80
|
+
return hostPath;
|
|
81
|
+
};
|
|
82
|
+
// Load workspace-level skills (global)
|
|
83
|
+
const workspaceSkillsDir = join(hostWorkspacePath, "skills");
|
|
84
|
+
for (const skill of loadSkillsFromDir({ dir: workspaceSkillsDir, source: "workspace" }).skills) {
|
|
85
|
+
// Translate paths to container paths for system prompt
|
|
86
|
+
skill.filePath = translatePath(skill.filePath);
|
|
87
|
+
skill.baseDir = translatePath(skill.baseDir);
|
|
88
|
+
skillMap.set(skill.name, skill);
|
|
89
|
+
}
|
|
90
|
+
// Load conversation-specific skills (override workspace skills on collision)
|
|
91
|
+
const conversationSkillsDir = join(conversationDir, "skills");
|
|
92
|
+
for (const skill of loadSkillsFromDir({ dir: conversationSkillsDir, source: "channel" }).skills) {
|
|
93
|
+
skill.filePath = translatePath(skill.filePath);
|
|
94
|
+
skill.baseDir = translatePath(skill.baseDir);
|
|
95
|
+
skillMap.set(skill.name, skill);
|
|
96
|
+
}
|
|
97
|
+
return Array.from(skillMap.values());
|
|
98
|
+
}
|
|
99
|
+
function buildRuntimePaths(runtimeWorkspaceRoot, conversationId) {
|
|
100
|
+
const workspaceRoot = runtimeWorkspaceRoot.replace(/\/+$/, "") || "/";
|
|
101
|
+
const conversationPath = posix.join(workspaceRoot, conversationId);
|
|
102
|
+
return {
|
|
103
|
+
workspaceRoot,
|
|
104
|
+
conversationPath,
|
|
105
|
+
scratchPath: posix.join(conversationPath, "scratch"),
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
function buildEnvDescription(sandboxType, workspaceRoot) {
|
|
109
|
+
switch (sandboxType) {
|
|
110
|
+
case "image":
|
|
111
|
+
return `You are running inside a managed per-user container.
|
|
112
|
+
- Runtime workspace root: ${workspaceRoot}
|
|
113
|
+
- Bash commands start in: ${workspaceRoot}
|
|
114
|
+
- Install tools with the image's package manager
|
|
115
|
+
- Your changes persist for this user's container until it is recreated`;
|
|
116
|
+
case "container":
|
|
117
|
+
return `You are running inside a shared container.
|
|
118
|
+
- Runtime workspace root: ${workspaceRoot}
|
|
119
|
+
- Bash commands start in: ${workspaceRoot}
|
|
120
|
+
- Install tools with the container's package manager
|
|
121
|
+
- Your changes persist across sessions`;
|
|
122
|
+
case "firecracker":
|
|
123
|
+
return `You are running inside a Firecracker microVM.
|
|
124
|
+
- Runtime workspace root: ${workspaceRoot}
|
|
125
|
+
- Use cd or absolute paths; project files are under ${workspaceRoot}
|
|
126
|
+
- Install tools with: apt-get install <package> (Debian-based)
|
|
127
|
+
- Your changes persist across sessions`;
|
|
128
|
+
case "cloudflare":
|
|
129
|
+
return `You are running through a Cloudflare Sandbox bridge.
|
|
130
|
+
- Runtime workspace root: ${workspaceRoot}
|
|
131
|
+
- Bash commands start in: ${workspaceRoot}
|
|
132
|
+
- Your commands run in a remote container managed by Cloudflare
|
|
133
|
+
- Important: the remote filesystem is not automatically synced back to the host workspace`;
|
|
134
|
+
default:
|
|
135
|
+
return `You are running directly on the host machine.
|
|
136
|
+
- Runtime workspace root: ${workspaceRoot}
|
|
137
|
+
- Bash commands start in: ${process.cwd()}
|
|
138
|
+
- Be careful with system modifications`;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
export function buildEventFilesystemInstructions(sandboxType, workspaceRoot) {
|
|
142
|
+
if (sandboxType === "host" || sandboxType === "container" || sandboxType === "image") {
|
|
143
|
+
return `Events live in the host-side mikan control plane and are mounted at \`${workspaceRoot}/events/\` in this runtime.
|
|
144
|
+
|
|
145
|
+
Prefer the \`event\` tool over manually writing JSON files; it fills \`platform\`, \`conversationId\`, \`conversationKind\`, and \`userId\` for the current conversation automatically.
|
|
146
|
+
|
|
147
|
+
### Creating Events Manually
|
|
148
|
+
Only do this when you need to create events from a script. Use unique filenames to avoid overwriting existing events. Include a timestamp or random suffix:
|
|
149
|
+
\`\`\`bash
|
|
150
|
+
cat > ${workspaceRoot}/events/dentist-reminder-$(date +%s).json << 'EOF'
|
|
151
|
+
{"type": "one-shot", "platform": "<platform>", "conversationId": "<conversationId>", "conversationKind": "<direct|shared>", "userId": "<requester userId>", "text": "Dentist tomorrow", "at": "2025-12-14T09:00:00+01:00"}
|
|
152
|
+
EOF
|
|
153
|
+
\`\`\`
|
|
154
|
+
|
|
155
|
+
### Managing Events
|
|
156
|
+
- List: \`ls ${workspaceRoot}/events/\`
|
|
157
|
+
- View: \`cat ${workspaceRoot}/events/foo.json\`
|
|
158
|
+
- Delete/cancel: \`rm ${workspaceRoot}/events/foo.json\``;
|
|
159
|
+
}
|
|
160
|
+
return `Events live in the host-side mikan control plane, not necessarily in this runtime filesystem.
|
|
161
|
+
|
|
162
|
+
Use the \`event\` tool to create events. It writes to the correct host-side events directory and fills \`platform\`, \`conversationId\`, \`conversationKind\`, and \`userId\` for the current conversation automatically.
|
|
163
|
+
|
|
164
|
+
Do not create event files with bash in \`${workspaceRoot}/events/\` from this sandbox unless you have explicitly verified that path is mounted back to the host-side mikan events directory.`;
|
|
165
|
+
}
|
|
166
|
+
export function resolveTriggerAttribution(message) {
|
|
167
|
+
const eventTextMatch = message.text.match(/^\[EVENT:([^:]+):/);
|
|
168
|
+
if (eventTextMatch)
|
|
169
|
+
return `[event: ${eventTextMatch[1]}]`;
|
|
170
|
+
const eventIdMatch = message.id.match(/^event:([^:]+)/);
|
|
171
|
+
if (eventIdMatch)
|
|
172
|
+
return `[event: ${eventIdMatch[1]}]`;
|
|
173
|
+
if (message.userName)
|
|
174
|
+
return `@${message.userName}`;
|
|
175
|
+
return undefined;
|
|
176
|
+
}
|
|
177
|
+
function buildSystemPrompt(workspacePath, conversationId, conversationKind, currentUserId, memory, sandboxConfig, platform, skills, isEventTrigger = false, triggerAttribution) {
|
|
178
|
+
const { workspaceRoot, conversationPath, scratchPath } = buildRuntimePaths(workspacePath, conversationId);
|
|
179
|
+
const sandboxType = sandboxConfig.type;
|
|
180
|
+
const isContainerLike = sandboxType === "container" || sandboxType === "image";
|
|
181
|
+
const isFirecracker = sandboxType === "firecracker";
|
|
182
|
+
// Format channel mappings
|
|
183
|
+
const channelMappings = platform.channels.length > 0
|
|
184
|
+
? platform.channels.map((c) => `${c.id}\t#${c.name}`).join("\n")
|
|
185
|
+
: "(no channels loaded)";
|
|
186
|
+
// Format user mappings
|
|
187
|
+
const userMappings = platform.users.length > 0
|
|
188
|
+
? platform.users.map((u) => `${u.id}\t@${u.userName}\t${u.displayName}`).join("\n")
|
|
189
|
+
: "(no users loaded)";
|
|
190
|
+
const envDescription = buildEnvDescription(sandboxType, workspaceRoot);
|
|
191
|
+
const eventFilesystemInstructions = buildEventFilesystemInstructions(sandboxType, workspaceRoot);
|
|
192
|
+
const eventTriggerInstructions = isEventTrigger
|
|
193
|
+
? `
|
|
194
|
+
## Event Trigger Mode
|
|
195
|
+
- You are handling a scheduled/background event, not opening a brand new chat with a stranger.
|
|
196
|
+
- Treat the incoming user message as a self-contained task prepared by an earlier run.
|
|
197
|
+
- Complete the task directly. Avoid generic greetings, self-introductions, or boilerplate offers to help.
|
|
198
|
+
- For reminders/follow-ups, prefer a short direct response that sounds like a continuation of prior intent.
|
|
199
|
+
- If the event text includes tone, brevity, or language instructions, follow them literally.
|
|
200
|
+
`
|
|
201
|
+
: "";
|
|
202
|
+
const attributionInstructions = triggerAttribution
|
|
203
|
+
? `
|
|
204
|
+
## Attribution
|
|
205
|
+
Always end your final ${platform.name} response and any GitHub issue/PR comments or descriptions you write via tools with:
|
|
206
|
+
_Triggered by ${triggerAttribution}_
|
|
207
|
+
|
|
208
|
+
Do not add this to \`[SILENT]\` responses.
|
|
209
|
+
`
|
|
210
|
+
: "";
|
|
211
|
+
return `You are mikan, a ${platform.name} bot assistant. Be concise. No emojis.
|
|
212
|
+
|
|
213
|
+
## Context
|
|
214
|
+
- For current date/time, use: date
|
|
215
|
+
- You have access to previous conversation context including tool results from prior turns.
|
|
216
|
+
- For older human-readable history beyond your context, search \`log.jsonl\` (contains user messages and your final responses, but not tool results).
|
|
217
|
+
- Structured session history with tool results lives in \`${conversationPath}/sessions/\`.
|
|
218
|
+
- The active top-level session is selected by \`${conversationPath}/sessions/current\`, which points to a timestamped \`.jsonl\` file in the same directory.
|
|
219
|
+
- Scoped/thread sessions use fixed files at \`${conversationPath}/sessions/<scope_id>.jsonl\` (for example \`${conversationPath}/sessions/1777386320.800769.jsonl\`).
|
|
220
|
+
- 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.
|
|
221
|
+
- 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.
|
|
222
|
+
${eventTriggerInstructions}
|
|
223
|
+
${platform.formattingGuide}
|
|
224
|
+
|
|
225
|
+
## Platform IDs
|
|
226
|
+
Channels: ${channelMappings}
|
|
227
|
+
|
|
228
|
+
Users: ${userMappings}
|
|
229
|
+
|
|
230
|
+
When mentioning users, use <@username> format (e.g., <@mario>).
|
|
231
|
+
|
|
232
|
+
## Environment
|
|
233
|
+
${envDescription}
|
|
234
|
+
- Default place for clones, downloads, and experiments: ${scratchPath}
|
|
235
|
+
- Do not use host-only paths unless you are running in host mode and verified they exist.
|
|
236
|
+
|
|
237
|
+
## Workspace Layout
|
|
238
|
+
${workspaceRoot}/
|
|
239
|
+
├── MEMORY.md # Global memory (all conversations)
|
|
240
|
+
├── skills/ # Global CLI tools you create
|
|
241
|
+
└── ${conversationId}/ # This conversation
|
|
242
|
+
├── MEMORY.md # Conversation-specific memory
|
|
243
|
+
├── log.jsonl # Human-readable message history (no tool results)
|
|
244
|
+
├── sessions/ # Structured session history used for context reconstruction
|
|
245
|
+
│ ├── current # Active top-level session pointer
|
|
246
|
+
│ ├── <timestamp>_<id>.jsonl # Top-level session files
|
|
247
|
+
│ └── <scope_id>.jsonl # Scoped thread/reply session files
|
|
248
|
+
├── attachments/ # User-shared files
|
|
249
|
+
├── scratch/ # Working directory for clones/downloads/experiments: ${scratchPath}
|
|
250
|
+
└── skills/ # Conversation-specific tools
|
|
251
|
+
|
|
252
|
+
## Skills (Custom CLI Tools)
|
|
253
|
+
You can create reusable CLI tools for recurring tasks (email, APIs, data processing, etc.).
|
|
254
|
+
|
|
255
|
+
### Creating Skills
|
|
256
|
+
Store in \`${workspaceRoot}/skills/<name>/\` (global) or \`${conversationPath}/skills/<name>/\` (conversation-specific).
|
|
257
|
+
Each skill directory needs a \`SKILL.md\` with YAML frontmatter:
|
|
258
|
+
|
|
259
|
+
\`\`\`markdown
|
|
260
|
+
---
|
|
261
|
+
name: skill-name
|
|
262
|
+
description: Short description of what this skill does
|
|
263
|
+
---
|
|
264
|
+
|
|
265
|
+
# Skill Name
|
|
266
|
+
|
|
267
|
+
Usage instructions, examples, etc.
|
|
268
|
+
Scripts are in: {baseDir}/
|
|
269
|
+
\`\`\`
|
|
270
|
+
|
|
271
|
+
\`name\` and \`description\` are required. Use \`{baseDir}\` as placeholder for the skill's directory path.
|
|
272
|
+
|
|
273
|
+
### Available Skills
|
|
274
|
+
${skills.length > 0 ? formatSkillsForPrompt(skills) : "(no skills installed yet)"}
|
|
275
|
+
|
|
276
|
+
## Events
|
|
277
|
+
You can schedule events that wake you up at specific times or when external things happen.
|
|
278
|
+
${eventFilesystemInstructions}
|
|
279
|
+
|
|
280
|
+
### Event Types
|
|
281
|
+
|
|
282
|
+
**Immediate** - Triggers as soon as harness sees the file. Use in scripts/webhooks to signal external events.
|
|
283
|
+
\`\`\`json
|
|
284
|
+
{"type": "immediate", "platform": "${platform.name}", "conversationId": "${conversationId}", "conversationKind": "${conversationKind}", "userId": "${currentUserId ?? "<requester userId>"}", "text": "New GitHub issue opened"}
|
|
285
|
+
\`\`\`
|
|
286
|
+
|
|
287
|
+
**One-shot** - Triggers once at a specific time. Use for reminders.
|
|
288
|
+
\`\`\`json
|
|
289
|
+
{"type": "one-shot", "platform": "${platform.name}", "conversationId": "${conversationId}", "conversationKind": "${conversationKind}", "userId": "${currentUserId ?? "<requester userId>"}", "text": "Remind Mario about dentist", "at": "2025-12-15T09:00:00+01:00"}
|
|
290
|
+
\`\`\`
|
|
291
|
+
|
|
292
|
+
**Periodic** - Triggers on a cron schedule. Use for recurring tasks.
|
|
293
|
+
\`\`\`json
|
|
294
|
+
{"type": "periodic", "platform": "${platform.name}", "conversationId": "${conversationId}", "conversationKind": "${conversationKind}", "userId": "${currentUserId ?? "<requester userId>"}", "text": "Check inbox and summarize", "schedule": "0 9 * * 1-5", "timezone": "${Intl.DateTimeFormat().resolvedOptions().timeZone}"}
|
|
295
|
+
\`\`\`
|
|
296
|
+
|
|
297
|
+
### Cron Format
|
|
298
|
+
\`minute hour day-of-month month day-of-week\`
|
|
299
|
+
- \`0 9 * * *\` = daily at 9:00
|
|
300
|
+
- \`0 9 * * 1-5\` = weekdays at 9:00
|
|
301
|
+
- \`30 14 * * 1\` = Mondays at 14:30
|
|
302
|
+
- \`0 0 1 * *\` = first of each month at midnight
|
|
303
|
+
|
|
304
|
+
### Timezones
|
|
305
|
+
All \`at\` timestamps must include offset (e.g., \`+01:00\`). Periodic events use IANA timezone names. The harness runs in ${Intl.DateTimeFormat().resolvedOptions().timeZone}. When users mention times without timezone, assume ${Intl.DateTimeFormat().resolvedOptions().timeZone}.
|
|
306
|
+
|
|
307
|
+
### Platform and Credential Routing
|
|
308
|
+
Set \`platform\` to the target bot platform (\`${platform.name}\` for this conversation). Include it explicitly to avoid ambiguity.
|
|
309
|
+
|
|
310
|
+
Set \`userId\` to the platform userId of whoever asked for the event. When the event fires, tool execution routes using that user's vault selection in per-user modes. In \`container:<name>\`, events use the container's single shared vault.
|
|
311
|
+
|
|
312
|
+
When scheduling an event, write \`text\` as a self-contained task for your future self. Include the minimum necessary context, tone, and constraints in the text itself because events do not inherit normal conversation history. Good: \`Please remind the user that break time is over and it is time to return to class. Keep it brief, in Traditional Chinese, and do not ask follow-up questions.\` Bad: \`back to class\`.
|
|
313
|
+
|
|
314
|
+
### When Events Trigger
|
|
315
|
+
You receive a message like:
|
|
316
|
+
\`\`\`
|
|
317
|
+
[EVENT:dentist-reminder.json:one-shot:2025-12-14T09:00:00+01:00] Dentist tomorrow
|
|
318
|
+
\`\`\`
|
|
319
|
+
Immediate and one-shot events auto-delete after triggering. Periodic events persist until you delete them.
|
|
320
|
+
|
|
321
|
+
### Silent Completion
|
|
322
|
+
For periodic events where there's nothing to report, respond with just \`[SILENT]\` (no other text). This deletes the status message and posts nothing to the platform. Use this to avoid spamming the channel when periodic checks find nothing actionable.
|
|
323
|
+
|
|
324
|
+
### Debouncing
|
|
325
|
+
When writing programs that create immediate events (email watchers, webhook handlers, etc.), always debounce. If 50 emails arrive in a minute, don't create 50 immediate events. Instead collect events over a window and create ONE immediate event summarizing what happened, or just signal "new activity, check inbox" rather than per-item events. Or simpler: use a periodic event to check for new items every N minutes instead of immediate events.
|
|
326
|
+
|
|
327
|
+
### Limits
|
|
328
|
+
Maximum 5 events can be queued. Don't create excessive immediate or periodic events.
|
|
329
|
+
|
|
330
|
+
## Memory
|
|
331
|
+
Write to MEMORY.md files to persist context across conversations.
|
|
332
|
+
- Global (${workspaceRoot}/MEMORY.md): skills, preferences, project info
|
|
333
|
+
- Conversation (${conversationPath}/MEMORY.md): conversation-specific decisions, ongoing work
|
|
334
|
+
Update when you learn something important or when asked to remember something.
|
|
335
|
+
|
|
336
|
+
### Current Memory
|
|
337
|
+
${memory}
|
|
338
|
+
|
|
339
|
+
## System Configuration Log
|
|
340
|
+
Maintain ${workspaceRoot}/SYSTEM.md to log all environment modifications:
|
|
341
|
+
- Installed packages (apt install, npm install, uv pip install)
|
|
342
|
+
- Environment variables set
|
|
343
|
+
- Config files modified (~/.gitconfig, cron jobs, etc.)
|
|
344
|
+
- Skill dependencies installed
|
|
345
|
+
|
|
346
|
+
Update this file whenever you modify the environment. On fresh container, read it first to restore your setup.
|
|
347
|
+
|
|
348
|
+
## Log Queries (for older history)
|
|
349
|
+
Format: \`{"date":"...","ts":"...","user":"...","userName":"...","text":"...","isBot":false}\`
|
|
350
|
+
The log contains user messages and your final responses (not tool calls/results).
|
|
351
|
+
Use \`log.jsonl\` for quick grep-style history. Use \`${conversationPath}/sessions/\` when you need structured turns, tool outputs, or branch lineage.
|
|
352
|
+
${isContainerLike || isFirecracker ? "Install jq: apt-get install jq" : ""}
|
|
353
|
+
${attributionInstructions}
|
|
354
|
+
\`\`\`bash
|
|
355
|
+
# Recent messages
|
|
356
|
+
tail -30 log.jsonl | jq -c '{date: .date[0:19], user: (.userName // .user), text}'
|
|
357
|
+
|
|
358
|
+
# Search for specific topic
|
|
359
|
+
grep -i "topic" log.jsonl | jq -c '{date: .date[0:19], user: (.userName // .user), text}'
|
|
360
|
+
|
|
361
|
+
# Messages from specific user
|
|
362
|
+
grep '"userName":"mario"' log.jsonl | tail -20 | jq -c '{date: .date[0:19], text}'
|
|
363
|
+
|
|
364
|
+
# Inspect top-level session pointer and available session files
|
|
365
|
+
cat sessions/current
|
|
366
|
+
ls -1 sessions/
|
|
367
|
+
\`\`\`
|
|
368
|
+
|
|
369
|
+
## Tools
|
|
370
|
+
- bash: Run shell commands (primary tool). Install packages as needed.
|
|
371
|
+
- read: Read files
|
|
372
|
+
- write: Create/overwrite files
|
|
373
|
+
- edit: Surgical file edits
|
|
374
|
+
- attach: Share files to the platform
|
|
375
|
+
|
|
376
|
+
Each tool requires a "label" parameter (shown to user).
|
|
377
|
+
`;
|
|
378
|
+
}
|
|
379
|
+
function truncate(text, maxLen) {
|
|
380
|
+
if (text.length <= maxLen)
|
|
381
|
+
return text;
|
|
382
|
+
return `${text.substring(0, maxLen - 3)}...`;
|
|
383
|
+
}
|
|
384
|
+
export function getUnresolvedSandboxPathContext(sandboxConfig, hostWorkspaceRoot) {
|
|
385
|
+
if (sandboxConfig.type === "image") {
|
|
386
|
+
return createMountedRuntimePathContext(hostWorkspaceRoot, "/workspace");
|
|
387
|
+
}
|
|
388
|
+
return createExecutor(sandboxConfig).getPathContext(hostWorkspaceRoot);
|
|
389
|
+
}
|
|
390
|
+
function createRunnerExecutionContext(sandboxConfig, vaultManager, provisioner, workspaceDir, hostWorkspacePath) {
|
|
391
|
+
const executionResolver = vaultManager &&
|
|
392
|
+
sandboxConfig.type !== "host" &&
|
|
393
|
+
(vaultManager.isEnabled() ||
|
|
394
|
+
sandboxConfig.type === "container" ||
|
|
395
|
+
sandboxConfig.type === "image" ||
|
|
396
|
+
sandboxConfig.type === "cloudflare" ||
|
|
397
|
+
sandboxConfig.type === "firecracker")
|
|
398
|
+
? new ActorExecutionResolver(sandboxConfig, vaultManager, provisioner, workspaceDir)
|
|
399
|
+
: undefined;
|
|
400
|
+
// activeExecutor is replaced at the start of each run() call when executionResolver
|
|
401
|
+
// is present, so the stable `executor` wrapper always delegates to the latest resolved value.
|
|
402
|
+
let activeExecutor = executionResolver !== undefined
|
|
403
|
+
? createExecutor({ type: "host" })
|
|
404
|
+
: createExecutor(sandboxConfig);
|
|
405
|
+
const executor = {
|
|
406
|
+
exec(command, options) {
|
|
407
|
+
return activeExecutor.exec(command, options);
|
|
408
|
+
},
|
|
409
|
+
getWorkspacePath(hostPath) {
|
|
410
|
+
return activeExecutor.getWorkspacePath(hostPath);
|
|
411
|
+
},
|
|
412
|
+
getSandboxConfig() {
|
|
413
|
+
return activeExecutor.getSandboxConfig();
|
|
414
|
+
},
|
|
415
|
+
getPathContext(hostWorkspaceRoot) {
|
|
416
|
+
return activeExecutor.getPathContext(hostWorkspaceRoot);
|
|
417
|
+
},
|
|
418
|
+
};
|
|
419
|
+
return {
|
|
420
|
+
executionResolver,
|
|
421
|
+
executor,
|
|
422
|
+
getPathContext: () => executor.getPathContext(hostWorkspacePath),
|
|
423
|
+
async resolveExecutorForRun(context) {
|
|
424
|
+
if (!executionResolver)
|
|
425
|
+
return;
|
|
426
|
+
activeExecutor = await executionResolver.resolve(context);
|
|
427
|
+
},
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
async function createConfiguredAgentSession(params) {
|
|
431
|
+
const { conversationId, workspaceDir, runtimeWorkspaceRoot, systemPrompt, model, thinkingLevel, tools, sessionManager, settingsManager, } = params;
|
|
432
|
+
const authStorage = AuthStorage.create(join(homedir(), ".pi", "mikan", "auth.json"));
|
|
433
|
+
const modelRegistry = ModelRegistry.create(authStorage);
|
|
434
|
+
const agent = new Agent({
|
|
435
|
+
initialState: {
|
|
436
|
+
systemPrompt,
|
|
437
|
+
model,
|
|
438
|
+
thinkingLevel,
|
|
439
|
+
tools,
|
|
440
|
+
},
|
|
441
|
+
convertToLlm,
|
|
442
|
+
getApiKey: async () => {
|
|
443
|
+
const key = await modelRegistry.getApiKeyForProvider(model.provider);
|
|
444
|
+
if (!key) {
|
|
445
|
+
throw new Error(`No API key for provider "${model.provider}". Set the appropriate environment variable or configure via auth.json`);
|
|
446
|
+
}
|
|
447
|
+
return key;
|
|
448
|
+
},
|
|
449
|
+
});
|
|
450
|
+
const loadedSession = sessionManager.buildSessionContext();
|
|
451
|
+
if (loadedSession.messages.length > 0) {
|
|
452
|
+
agent.state.messages = loadedSession.messages;
|
|
453
|
+
log.logInfo(`[${conversationId}] Reloaded ${loadedSession.messages.length} messages from session context`);
|
|
454
|
+
}
|
|
455
|
+
const resourceLoader = new DefaultResourceLoader({
|
|
456
|
+
cwd: workspaceDir,
|
|
457
|
+
agentDir: getAgentDir(),
|
|
458
|
+
systemPrompt,
|
|
459
|
+
});
|
|
460
|
+
try {
|
|
461
|
+
await resourceLoader.reload();
|
|
462
|
+
const extResult = resourceLoader.getExtensions();
|
|
463
|
+
if (extResult.errors.length > 0) {
|
|
464
|
+
for (const err of extResult.errors) {
|
|
465
|
+
log.logWarning(`[${conversationId}] Extension load error: ${err.path}`, err.error);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
log.logInfo(`[${conversationId}] Loaded ${extResult.extensions.length} extension(s): ${extResult.extensions.map((extension) => extension.path).join(", ")}`);
|
|
469
|
+
}
|
|
470
|
+
catch (error) {
|
|
471
|
+
log.logWarning(`[${conversationId}] Failed to load resources`, String(error));
|
|
472
|
+
}
|
|
473
|
+
const baseToolsOverride = Object.fromEntries(tools.map((tool) => [tool.name, tool]));
|
|
474
|
+
const session = new AgentSession({
|
|
475
|
+
agent,
|
|
476
|
+
sessionManager,
|
|
477
|
+
settingsManager,
|
|
478
|
+
cwd: runtimeWorkspaceRoot,
|
|
479
|
+
modelRegistry,
|
|
480
|
+
resourceLoader,
|
|
481
|
+
baseToolsOverride,
|
|
482
|
+
});
|
|
483
|
+
return { agent, session };
|
|
484
|
+
}
|
|
485
|
+
function createEmptyUsageTotals() {
|
|
486
|
+
return {
|
|
487
|
+
input: 0,
|
|
488
|
+
output: 0,
|
|
489
|
+
cacheRead: 0,
|
|
490
|
+
cacheWrite: 0,
|
|
491
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
function createRunState() {
|
|
495
|
+
return {
|
|
496
|
+
responseCtx: null,
|
|
497
|
+
logCtx: null,
|
|
498
|
+
queue: null,
|
|
499
|
+
pendingTools: new Map(),
|
|
500
|
+
totalUsage: createEmptyUsageTotals(),
|
|
501
|
+
llmCallCount: 0,
|
|
502
|
+
stopReason: "stop",
|
|
503
|
+
errorMessage: undefined,
|
|
504
|
+
reportedLlmError: false,
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
function resetRunState(runState, responseCtx, sessionConversation, userName, sessionUuid) {
|
|
508
|
+
runState.responseCtx = responseCtx;
|
|
509
|
+
runState.logCtx = {
|
|
510
|
+
conversationId: sessionConversation,
|
|
511
|
+
userName,
|
|
512
|
+
conversationName: undefined,
|
|
513
|
+
sessionId: sessionUuid,
|
|
514
|
+
};
|
|
515
|
+
runState.pendingTools.clear();
|
|
516
|
+
runState.totalUsage = createEmptyUsageTotals();
|
|
517
|
+
runState.llmCallCount = 0;
|
|
518
|
+
runState.stopReason = "stop";
|
|
519
|
+
runState.errorMessage = undefined;
|
|
520
|
+
runState.reportedLlmError = false;
|
|
521
|
+
}
|
|
522
|
+
function createRunQueue(responseCtx) {
|
|
523
|
+
let queueChain = Promise.resolve();
|
|
524
|
+
return {
|
|
525
|
+
queue: {
|
|
526
|
+
enqueue(fn, errorContext) {
|
|
527
|
+
queueChain = queueChain.then(async () => {
|
|
528
|
+
try {
|
|
529
|
+
await fn();
|
|
530
|
+
}
|
|
531
|
+
catch (err) {
|
|
532
|
+
const errMsg = err instanceof Error ? err.message : String(err);
|
|
533
|
+
log.logWarning(`API error (${errorContext})`, errMsg);
|
|
534
|
+
try {
|
|
535
|
+
await responseCtx.respondDiagnostic(`Error: ${errMsg}`, { style: "error" });
|
|
536
|
+
}
|
|
537
|
+
catch {
|
|
538
|
+
// Ignore
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
});
|
|
542
|
+
},
|
|
543
|
+
},
|
|
544
|
+
wait: () => queueChain,
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
function padTwoDigits(n) {
|
|
548
|
+
return n.toString().padStart(2, "0");
|
|
549
|
+
}
|
|
550
|
+
function formatTimestampedUserMessage(message) {
|
|
551
|
+
const now = new Date();
|
|
552
|
+
const offset = -now.getTimezoneOffset();
|
|
553
|
+
const offsetSign = offset >= 0 ? "+" : "-";
|
|
554
|
+
const offsetHours = padTwoDigits(Math.floor(Math.abs(offset) / 60));
|
|
555
|
+
const offsetMins = padTwoDigits(Math.abs(offset) % 60);
|
|
556
|
+
const timestamp = `${now.getFullYear()}-${padTwoDigits(now.getMonth() + 1)}-${padTwoDigits(now.getDate())} ` +
|
|
557
|
+
`${padTwoDigits(now.getHours())}:${padTwoDigits(now.getMinutes())}:${padTwoDigits(now.getSeconds())}` +
|
|
558
|
+
`${offsetSign}${offsetHours}:${offsetMins}`;
|
|
559
|
+
const threadContext = message.threadTs ? ` [in-thread:${message.threadTs}]` : "";
|
|
560
|
+
return `[${timestamp}] [${message.userName || "unknown"}]${threadContext}: ${message.text}`;
|
|
561
|
+
}
|
|
562
|
+
function collectMessageAttachments(message, workspacePath) {
|
|
563
|
+
const imageAttachments = [];
|
|
564
|
+
const nonImagePaths = [];
|
|
565
|
+
for (const attachment of message.attachments || []) {
|
|
566
|
+
const fullPath = `${workspacePath}/${attachment.localPath}`;
|
|
567
|
+
const mimeType = getImageMimeType(attachment.localPath);
|
|
568
|
+
if (mimeType && existsSync(fullPath)) {
|
|
569
|
+
try {
|
|
570
|
+
imageAttachments.push({
|
|
571
|
+
type: "image",
|
|
572
|
+
mimeType,
|
|
573
|
+
data: readFileSync(fullPath).toString("base64"),
|
|
574
|
+
});
|
|
575
|
+
}
|
|
576
|
+
catch {
|
|
577
|
+
nonImagePaths.push(fullPath);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
else {
|
|
581
|
+
nonImagePaths.push(fullPath);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
return { imageAttachments, nonImagePaths };
|
|
585
|
+
}
|
|
586
|
+
function buildPromptPayload(message, workspacePath) {
|
|
587
|
+
let userMessage = formatTimestampedUserMessage(message);
|
|
588
|
+
const { imageAttachments, nonImagePaths } = collectMessageAttachments(message, workspacePath);
|
|
589
|
+
if (nonImagePaths.length > 0) {
|
|
590
|
+
userMessage += `\n\n<slack_attachments>\n${nonImagePaths.join("\n")}\n</slack_attachments>`;
|
|
591
|
+
}
|
|
592
|
+
return { userMessage, imageAttachments };
|
|
593
|
+
}
|
|
594
|
+
async function writePromptDebugContext(conversationDir, systemPrompt, session, userMessage, imageAttachmentCount) {
|
|
595
|
+
const debugContext = {
|
|
596
|
+
systemPrompt,
|
|
597
|
+
messages: session.messages,
|
|
598
|
+
newUserMessage: userMessage,
|
|
599
|
+
imageAttachmentCount,
|
|
600
|
+
};
|
|
601
|
+
await writeFile(join(conversationDir, "last_prompt.jsonl"), JSON.stringify(debugContext, null, 2));
|
|
602
|
+
}
|
|
603
|
+
function getFinalAssistantText(session) {
|
|
604
|
+
const lastAssistant = session.messages.filter((message) => message.role === "assistant").pop();
|
|
605
|
+
return (lastAssistant?.content
|
|
606
|
+
.filter((content) => content.type === "text")
|
|
607
|
+
.map((content) => content.text)
|
|
608
|
+
.join("\n") || "");
|
|
609
|
+
}
|
|
610
|
+
export function appendTriggerAttribution(text, triggerAttribution) {
|
|
611
|
+
if (!triggerAttribution)
|
|
612
|
+
return text;
|
|
613
|
+
const suffix = `_Triggered by ${triggerAttribution}_`;
|
|
614
|
+
if (text.trimEnd().endsWith(suffix))
|
|
615
|
+
return text;
|
|
616
|
+
return `${text.trimEnd()}\n\n${suffix}`;
|
|
617
|
+
}
|
|
618
|
+
async function finalizeRunResponse(responseCtx, session, runState, options) {
|
|
619
|
+
if (runState.stopReason === "error" && runState.errorMessage) {
|
|
620
|
+
if (!runState.reportedLlmError) {
|
|
621
|
+
runState.reportedLlmError = true;
|
|
622
|
+
reportUserFacingError(new Error("LLM run completed with error stop reason"), {
|
|
623
|
+
domain: "llm",
|
|
624
|
+
surface: "assistant_response",
|
|
625
|
+
operation: "llm_turn",
|
|
626
|
+
severity: "error",
|
|
627
|
+
platform: options?.platform,
|
|
628
|
+
provider: options?.model?.provider,
|
|
629
|
+
model: options?.model?.name,
|
|
630
|
+
stopReason: runState.stopReason,
|
|
631
|
+
context: {
|
|
632
|
+
sessionConversation: options?.sessionConversation,
|
|
633
|
+
sessionUuid: options?.sessionUuid,
|
|
634
|
+
hasErrorMessage: true,
|
|
635
|
+
llmCallCount: runState.llmCallCount,
|
|
636
|
+
},
|
|
637
|
+
});
|
|
638
|
+
}
|
|
639
|
+
try {
|
|
640
|
+
await responseCtx.replaceResponse("_Sorry, something went wrong_");
|
|
641
|
+
await responseCtx.respondDiagnostic(`Error: ${runState.errorMessage}`, {
|
|
642
|
+
style: "error",
|
|
643
|
+
});
|
|
644
|
+
}
|
|
645
|
+
catch (err) {
|
|
646
|
+
const errMsg = err instanceof Error ? err.message : String(err);
|
|
647
|
+
log.logWarning("Failed to post error message", errMsg);
|
|
648
|
+
reportUserFacingError(err, {
|
|
649
|
+
domain: "chat_platform",
|
|
650
|
+
surface: "final_response",
|
|
651
|
+
operation: "finalize_error_response",
|
|
652
|
+
severity: "error",
|
|
653
|
+
platform: options?.platform,
|
|
654
|
+
context: {
|
|
655
|
+
sessionConversation: options?.sessionConversation,
|
|
656
|
+
sessionUuid: options?.sessionUuid,
|
|
657
|
+
stopReason: runState.stopReason,
|
|
658
|
+
},
|
|
659
|
+
});
|
|
660
|
+
}
|
|
661
|
+
return;
|
|
662
|
+
}
|
|
663
|
+
const finalText = getFinalAssistantText(session);
|
|
664
|
+
if (finalText.trim() === "[SILENT]" || finalText.trim().startsWith("[SILENT]")) {
|
|
665
|
+
try {
|
|
666
|
+
await responseCtx.deleteResponse();
|
|
667
|
+
log.logInfo("Silent response - deleted message and thread");
|
|
668
|
+
}
|
|
669
|
+
catch (err) {
|
|
670
|
+
const errMsg = err instanceof Error ? err.message : String(err);
|
|
671
|
+
log.logWarning("Failed to delete message for silent response", errMsg);
|
|
672
|
+
}
|
|
673
|
+
return;
|
|
674
|
+
}
|
|
675
|
+
if (!finalText.trim())
|
|
676
|
+
return;
|
|
677
|
+
try {
|
|
678
|
+
await responseCtx.replaceResponse(appendTriggerAttribution(finalText, options?.triggerAttribution), { createOverflowLink: options?.createOverflowLink });
|
|
679
|
+
}
|
|
680
|
+
catch (err) {
|
|
681
|
+
const errMsg = err instanceof Error ? err.message : String(err);
|
|
682
|
+
log.logWarning("Failed to replace message with final text", errMsg);
|
|
683
|
+
reportUserFacingError(err, {
|
|
684
|
+
domain: "chat_platform",
|
|
685
|
+
surface: "final_response",
|
|
686
|
+
operation: "replace_final_response",
|
|
687
|
+
severity: "error",
|
|
688
|
+
platform: options?.platform,
|
|
689
|
+
context: {
|
|
690
|
+
sessionConversation: options?.sessionConversation,
|
|
691
|
+
sessionUuid: options?.sessionUuid,
|
|
692
|
+
finalTextLength: finalText.length,
|
|
693
|
+
},
|
|
694
|
+
});
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
async function reportUsageSummary(ctx) {
|
|
698
|
+
const { session, runState, responseCtx, platform, model, agentConfig, sessionConversation, sessionUuid, waitForQueue, } = ctx;
|
|
699
|
+
if (runState.totalUsage.cost.total <= 0)
|
|
700
|
+
return;
|
|
701
|
+
const lastAssistantMessage = session.messages
|
|
702
|
+
.slice()
|
|
703
|
+
.toReversed()
|
|
704
|
+
.find((message) => message.role === "assistant" && message.stopReason !== "aborted");
|
|
705
|
+
const contextTokens = lastAssistantMessage
|
|
706
|
+
? lastAssistantMessage.usage.input +
|
|
707
|
+
lastAssistantMessage.usage.output +
|
|
708
|
+
lastAssistantMessage.usage.cacheRead +
|
|
709
|
+
lastAssistantMessage.usage.cacheWrite
|
|
710
|
+
: 0;
|
|
711
|
+
const contextWindow = model.contextWindow || 200000;
|
|
712
|
+
const { totalUsage } = runState;
|
|
713
|
+
const runMetricAttributes = metricAttributes({
|
|
714
|
+
provider: model.provider,
|
|
715
|
+
model: agentConfig.model,
|
|
716
|
+
channel_id: sessionConversation,
|
|
717
|
+
session_id: sessionUuid,
|
|
718
|
+
stop_reason: runState.stopReason,
|
|
719
|
+
llm_calls: runState.llmCallCount,
|
|
720
|
+
});
|
|
721
|
+
Sentry.metrics.distribution("agent.run.tokens_in", totalUsage.input, {
|
|
722
|
+
attributes: runMetricAttributes,
|
|
723
|
+
});
|
|
724
|
+
Sentry.metrics.distribution("agent.run.tokens_out", totalUsage.output, {
|
|
725
|
+
attributes: runMetricAttributes,
|
|
726
|
+
});
|
|
727
|
+
Sentry.metrics.distribution("agent.run.cache_read", totalUsage.cacheRead, {
|
|
728
|
+
attributes: runMetricAttributes,
|
|
729
|
+
});
|
|
730
|
+
Sentry.metrics.distribution("agent.run.cache_write", totalUsage.cacheWrite, {
|
|
731
|
+
attributes: runMetricAttributes,
|
|
732
|
+
});
|
|
733
|
+
Sentry.metrics.distribution("agent.run.cost", totalUsage.cost.total, {
|
|
734
|
+
attributes: runMetricAttributes,
|
|
735
|
+
});
|
|
736
|
+
Sentry.metrics.gauge("agent.context.utilization", contextTokens / contextWindow, {
|
|
737
|
+
unit: "ratio",
|
|
738
|
+
attributes: runMetricAttributes,
|
|
739
|
+
});
|
|
740
|
+
const summary = log.logUsageSummary(runState.logCtx, runState.totalUsage, contextTokens, contextWindow);
|
|
741
|
+
if (platform.diagnostics?.showUsageSummary === true) {
|
|
742
|
+
runState.queue.enqueue(() => responseCtx.respondDiagnostic(summary, { style: "muted" }), "usage summary");
|
|
743
|
+
await waitForQueue();
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
function reloadSessionMessages(sessionManager, conversationId, agent) {
|
|
747
|
+
const messages = sessionManager.buildSessionContext().messages;
|
|
748
|
+
if (messages.length > 0) {
|
|
749
|
+
agent.state.messages = messages;
|
|
750
|
+
log.logInfo(`[${conversationId}] Reloaded ${messages.length} messages from context`);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
async function prepareRunContext(params) {
|
|
754
|
+
const { message, responseCtx, platform, conversationId, conversationDir, sessionUuid, runState, executor, executionResolver, resolveExecutorForRun, getPathContext, sessionManager, session, agent, setEventContext, setUploadFunction, } = params;
|
|
755
|
+
let pathContext = params.pathContext;
|
|
756
|
+
const sessionConversation = message.sessionKey.split(":")[0];
|
|
757
|
+
await mkdir(join(conversationDir, "scratch"), { recursive: true });
|
|
758
|
+
if (executionResolver) {
|
|
759
|
+
await resolveExecutorForRun({
|
|
760
|
+
platform: platform.name,
|
|
761
|
+
userId: message.userId,
|
|
762
|
+
conversationId,
|
|
763
|
+
});
|
|
764
|
+
pathContext = getPathContext();
|
|
765
|
+
}
|
|
766
|
+
reloadSessionMessages(sessionManager, conversationId, agent);
|
|
767
|
+
const memory = await getMemory(conversationDir);
|
|
768
|
+
const skills = loadMikanSkills(conversationDir, pathContext.runtimeWorkspaceRoot);
|
|
769
|
+
const triggerAttribution = resolveTriggerAttribution(message);
|
|
770
|
+
const systemPrompt = buildSystemPrompt(pathContext.runtimeWorkspaceRoot, conversationId, message.conversationKind, message.userId, memory, executor.getSandboxConfig(), platform, skills, message.id.startsWith("event:"), triggerAttribution);
|
|
771
|
+
session.agent.state.systemPrompt = systemPrompt;
|
|
772
|
+
setEventContext({
|
|
773
|
+
platform: platform.name,
|
|
774
|
+
conversationId,
|
|
775
|
+
conversationKind: message.conversationKind,
|
|
776
|
+
userId: message.userId,
|
|
777
|
+
});
|
|
778
|
+
setUploadFunction(async (filePath, title) => {
|
|
779
|
+
const hostPath = translateRuntimePathToHost(filePath, pathContext);
|
|
780
|
+
await responseCtx.uploadFile(hostPath, title);
|
|
781
|
+
});
|
|
782
|
+
resetRunState(runState, responseCtx, sessionConversation, message.userName, sessionUuid);
|
|
783
|
+
const runQueue = createRunQueue(responseCtx);
|
|
784
|
+
runState.queue = runQueue.queue;
|
|
785
|
+
log.logInfo(`Context sizes - system: ${systemPrompt.length} chars, memory: ${memory.length} chars`);
|
|
786
|
+
log.logInfo(`Channels: ${platform.channels.length}, Users: ${platform.users.length}`);
|
|
787
|
+
const { userMessage, imageAttachments } = buildPromptPayload(message, pathContext.runtimeWorkspaceRoot);
|
|
788
|
+
await writePromptDebugContext(conversationDir, systemPrompt, session, userMessage, imageAttachments.length);
|
|
789
|
+
return {
|
|
790
|
+
sessionConversation,
|
|
791
|
+
runQueue,
|
|
792
|
+
userMessage,
|
|
793
|
+
imageAttachments,
|
|
794
|
+
triggerAttribution,
|
|
795
|
+
pathContext,
|
|
796
|
+
};
|
|
797
|
+
}
|
|
798
|
+
function attachSessionEventHandlers(params) {
|
|
799
|
+
const { session, runState, model, agentConfig } = params;
|
|
800
|
+
session.subscribe(async (event) => {
|
|
801
|
+
if (!runState.responseCtx || !runState.logCtx || !runState.queue)
|
|
802
|
+
return;
|
|
803
|
+
const { responseCtx, logCtx, queue, pendingTools } = runState;
|
|
804
|
+
const baseAttrs = { channel_id: logCtx.conversationId, session_id: logCtx.sessionId };
|
|
805
|
+
if (event.type === "tool_execution_start") {
|
|
806
|
+
const args = (event.args ?? {});
|
|
807
|
+
const label = args.label || event.toolName;
|
|
808
|
+
pendingTools.set(event.toolCallId, {
|
|
809
|
+
toolName: event.toolName,
|
|
810
|
+
args: event.args,
|
|
811
|
+
startTime: Date.now(),
|
|
812
|
+
});
|
|
813
|
+
addLifecycleBreadcrumb("agent.tool.started", {
|
|
814
|
+
tool: event.toolName,
|
|
815
|
+
...baseAttrs,
|
|
816
|
+
});
|
|
817
|
+
log.logToolStart(logCtx, event.toolName, label, event.args);
|
|
818
|
+
return;
|
|
819
|
+
}
|
|
820
|
+
if (event.type === "tool_execution_end") {
|
|
821
|
+
const resultStr = extractToolResultText(event.result);
|
|
822
|
+
const pending = pendingTools.get(event.toolCallId);
|
|
823
|
+
pendingTools.delete(event.toolCallId);
|
|
824
|
+
const durationMs = pending ? Date.now() - pending.startTime : 0;
|
|
825
|
+
Sentry.metrics.count("agent.tool.calls", 1, {
|
|
826
|
+
attributes: metricAttributes({
|
|
827
|
+
tool: event.toolName,
|
|
828
|
+
error: String(event.isError),
|
|
829
|
+
...baseAttrs,
|
|
830
|
+
}),
|
|
831
|
+
});
|
|
832
|
+
Sentry.metrics.distribution("agent.tool.duration", durationMs, {
|
|
833
|
+
unit: "millisecond",
|
|
834
|
+
attributes: metricAttributes({
|
|
835
|
+
tool: event.toolName,
|
|
836
|
+
...baseAttrs,
|
|
837
|
+
}),
|
|
838
|
+
});
|
|
839
|
+
addLifecycleBreadcrumb("agent.tool.completed", {
|
|
840
|
+
tool: event.toolName,
|
|
841
|
+
error: event.isError,
|
|
842
|
+
duration_ms: durationMs,
|
|
843
|
+
...baseAttrs,
|
|
844
|
+
});
|
|
845
|
+
if (event.isError) {
|
|
846
|
+
log.logToolError(logCtx, event.toolName, durationMs, resultStr);
|
|
847
|
+
}
|
|
848
|
+
else {
|
|
849
|
+
log.logToolSuccess(logCtx, event.toolName, durationMs, resultStr);
|
|
850
|
+
}
|
|
851
|
+
if (shouldSurfaceToolDiagnostic(event.toolName)) {
|
|
852
|
+
const toolResult = {
|
|
853
|
+
toolName: event.toolName,
|
|
854
|
+
label: pending?.args ? pending.args.label : undefined,
|
|
855
|
+
args: pending?.args,
|
|
856
|
+
result: truncate(resultStr, TOOL_RESULT_DIAGNOSTIC_CAP),
|
|
857
|
+
isError: event.isError,
|
|
858
|
+
durationMs,
|
|
859
|
+
};
|
|
860
|
+
queue.enqueue(() => responseCtx.respondToolResult(toolResult), "tool result diagnostic");
|
|
861
|
+
}
|
|
862
|
+
if (event.isError && shouldSurfaceToolDiagnostic(event.toolName)) {
|
|
863
|
+
queue.enqueue(() => responseCtx.respond(`_Error: ${truncate(resultStr, 200)}_`), "tool error");
|
|
864
|
+
}
|
|
865
|
+
return;
|
|
866
|
+
}
|
|
867
|
+
if (event.type === "message_start") {
|
|
868
|
+
if (event.message.role === "assistant") {
|
|
869
|
+
runState.llmCallCount += 1;
|
|
870
|
+
addLifecycleBreadcrumb("agent.llm.call.started", {
|
|
871
|
+
call_index: runState.llmCallCount,
|
|
872
|
+
provider: model.provider,
|
|
873
|
+
model: agentConfig.model,
|
|
874
|
+
...baseAttrs,
|
|
875
|
+
});
|
|
876
|
+
log.logResponseStart(logCtx);
|
|
877
|
+
}
|
|
878
|
+
return;
|
|
879
|
+
}
|
|
880
|
+
if (event.type === "message_end") {
|
|
881
|
+
if (event.message.role === "assistant") {
|
|
882
|
+
const assistantMsg = event.message;
|
|
883
|
+
if (assistantMsg.stopReason) {
|
|
884
|
+
runState.stopReason = assistantMsg.stopReason;
|
|
885
|
+
}
|
|
886
|
+
if (assistantMsg.errorMessage) {
|
|
887
|
+
runState.errorMessage = assistantMsg.errorMessage;
|
|
888
|
+
}
|
|
889
|
+
if (assistantMsg.usage) {
|
|
890
|
+
runState.totalUsage.input += assistantMsg.usage.input;
|
|
891
|
+
runState.totalUsage.output += assistantMsg.usage.output;
|
|
892
|
+
runState.totalUsage.cacheRead += assistantMsg.usage.cacheRead;
|
|
893
|
+
runState.totalUsage.cacheWrite += assistantMsg.usage.cacheWrite;
|
|
894
|
+
runState.totalUsage.cost.input += assistantMsg.usage.cost.input;
|
|
895
|
+
runState.totalUsage.cost.output += assistantMsg.usage.cost.output;
|
|
896
|
+
runState.totalUsage.cost.cacheRead += assistantMsg.usage.cost.cacheRead;
|
|
897
|
+
runState.totalUsage.cost.cacheWrite += assistantMsg.usage.cost.cacheWrite;
|
|
898
|
+
runState.totalUsage.cost.total += assistantMsg.usage.cost.total;
|
|
899
|
+
const llmAttributes = metricAttributes({
|
|
900
|
+
provider: model.provider,
|
|
901
|
+
model: agentConfig.model,
|
|
902
|
+
...baseAttrs,
|
|
903
|
+
stop_reason: assistantMsg.stopReason,
|
|
904
|
+
error: Boolean(assistantMsg.errorMessage),
|
|
905
|
+
});
|
|
906
|
+
Sentry.metrics.count("agent.llm.calls", 1, { attributes: llmAttributes });
|
|
907
|
+
Sentry.metrics.distribution("agent.llm.tokens_in", assistantMsg.usage.input, {
|
|
908
|
+
attributes: llmAttributes,
|
|
909
|
+
});
|
|
910
|
+
Sentry.metrics.distribution("agent.llm.tokens_out", assistantMsg.usage.output, {
|
|
911
|
+
attributes: llmAttributes,
|
|
912
|
+
});
|
|
913
|
+
if (assistantMsg.usage.cacheRead > 0) {
|
|
914
|
+
Sentry.metrics.distribution("agent.llm.cache_read", assistantMsg.usage.cacheRead, {
|
|
915
|
+
attributes: llmAttributes,
|
|
916
|
+
});
|
|
917
|
+
}
|
|
918
|
+
if (assistantMsg.usage.cacheWrite > 0) {
|
|
919
|
+
Sentry.metrics.distribution("agent.llm.cache_write", assistantMsg.usage.cacheWrite, {
|
|
920
|
+
attributes: llmAttributes,
|
|
921
|
+
});
|
|
922
|
+
}
|
|
923
|
+
Sentry.metrics.distribution("agent.llm.cost_per_turn", assistantMsg.usage.cost.total, {
|
|
924
|
+
attributes: llmAttributes,
|
|
925
|
+
});
|
|
926
|
+
addLifecycleBreadcrumb("agent.llm.call.completed", {
|
|
927
|
+
call_index: runState.llmCallCount,
|
|
928
|
+
provider: model.provider,
|
|
929
|
+
model: agentConfig.model,
|
|
930
|
+
stop_reason: assistantMsg.stopReason,
|
|
931
|
+
error: Boolean(assistantMsg.errorMessage),
|
|
932
|
+
input_tokens: assistantMsg.usage.input,
|
|
933
|
+
output_tokens: assistantMsg.usage.output,
|
|
934
|
+
cost_total_usd: assistantMsg.usage.cost.total,
|
|
935
|
+
});
|
|
936
|
+
}
|
|
937
|
+
const thinkingParts = [];
|
|
938
|
+
const textParts = [];
|
|
939
|
+
for (const part of assistantMsg.content) {
|
|
940
|
+
if (part.type === "thinking") {
|
|
941
|
+
thinkingParts.push(part.thinking);
|
|
942
|
+
}
|
|
943
|
+
else if (part.type === "text") {
|
|
944
|
+
textParts.push(part.text);
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
const text = textParts.join("\n");
|
|
948
|
+
for (const thinking of thinkingParts) {
|
|
949
|
+
log.logThinking(logCtx, thinking);
|
|
950
|
+
queue.enqueue(() => responseCtx.respond(`_${thinking}_`), "thinking main");
|
|
951
|
+
queue.enqueue(() => responseCtx.respondDiagnostic(`_${thinking}_`), "thinking diagnostic");
|
|
952
|
+
}
|
|
953
|
+
if (text.trim()) {
|
|
954
|
+
log.logResponse(logCtx, text);
|
|
955
|
+
queue.enqueue(() => responseCtx.respond(text), "response main");
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
return;
|
|
959
|
+
}
|
|
960
|
+
if (event.type === "compaction_start") {
|
|
961
|
+
log.logInfo(`Auto-compaction started (reason: ${event.reason})`);
|
|
962
|
+
queue.enqueue(() => responseCtx.respond("_Compacting context..._"), "compaction start");
|
|
963
|
+
return;
|
|
964
|
+
}
|
|
965
|
+
if (event.type === "compaction_end") {
|
|
966
|
+
if (event.result) {
|
|
967
|
+
log.logInfo(`Auto-compaction complete: ${event.result.tokensBefore} tokens compacted`);
|
|
968
|
+
}
|
|
969
|
+
else if (event.aborted) {
|
|
970
|
+
log.logInfo("Auto-compaction aborted");
|
|
971
|
+
}
|
|
972
|
+
return;
|
|
973
|
+
}
|
|
974
|
+
if (event.type === "auto_retry_start") {
|
|
975
|
+
log.logWarning(`Retrying (${event.attempt}/${event.maxAttempts})`, event.errorMessage);
|
|
976
|
+
queue.enqueue(() => responseCtx.respond(`_Retrying (${event.attempt}/${event.maxAttempts})..._`), "retry");
|
|
977
|
+
}
|
|
978
|
+
});
|
|
979
|
+
}
|
|
980
|
+
// Cap raw tool output before handing it to adapters. Bash output can be MB; without
|
|
981
|
+
// this each adapter's splitter would fan it out into many sequential platform posts.
|
|
982
|
+
const TOOL_RESULT_DIAGNOSTIC_CAP = 8000;
|
|
983
|
+
function extractToolResultText(result) {
|
|
984
|
+
if (typeof result === "string") {
|
|
985
|
+
return result;
|
|
986
|
+
}
|
|
987
|
+
if (result &&
|
|
988
|
+
typeof result === "object" &&
|
|
989
|
+
"content" in result &&
|
|
990
|
+
Array.isArray(result.content)) {
|
|
991
|
+
const content = result.content;
|
|
992
|
+
const textParts = [];
|
|
993
|
+
for (const part of content) {
|
|
994
|
+
if (part.type === "text" && part.text) {
|
|
995
|
+
textParts.push(part.text);
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
if (textParts.length > 0) {
|
|
999
|
+
return textParts.join("\n");
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
return JSON.stringify(result);
|
|
1003
|
+
}
|
|
1004
|
+
/**
|
|
1005
|
+
* Create a new AgentRunner for a channel.
|
|
1006
|
+
* Sets up the session and subscribes to events once.
|
|
1007
|
+
*
|
|
1008
|
+
* Runner caching is handled by the caller (channelStates in main.ts).
|
|
1009
|
+
* This is a stateless factory function.
|
|
1010
|
+
*/
|
|
1011
|
+
export async function createRunner(sandboxConfig, sessionKey, conversationId, conversationDir, workspaceDir, sessionScope, vaultManager, provisioner, sessionView) {
|
|
1012
|
+
const agentConfig = loadAgentConfigForConversation(conversationDir);
|
|
1013
|
+
const workspaceBase = join(conversationDir, "..");
|
|
1014
|
+
const { executionResolver, executor, getPathContext, resolveExecutorForRun } = createRunnerExecutionContext(sandboxConfig, vaultManager, provisioner, workspaceDir, workspaceBase);
|
|
1015
|
+
let pathContext = getUnresolvedSandboxPathContext(sandboxConfig, workspaceBase);
|
|
1016
|
+
// Create tools (per-runner, with per-runner upload function setter)
|
|
1017
|
+
const { tools, setUploadFunction, setEventContext } = createMikanTools(executor, workspaceDir);
|
|
1018
|
+
// Resolve model from config. Config stores provider/model as user-provided strings,
|
|
1019
|
+
// while getModel's public overload is narrowed to generated known providers.
|
|
1020
|
+
const model = getModel(agentConfig.provider, agentConfig.model);
|
|
1021
|
+
// Initial system prompt (will be updated each run with fresh memory/channels/users/skills)
|
|
1022
|
+
const memory = await getMemory(conversationDir);
|
|
1023
|
+
const skills = loadMikanSkills(conversationDir, pathContext.runtimeWorkspaceRoot);
|
|
1024
|
+
const emptyPlatform = {
|
|
1025
|
+
name: "chat",
|
|
1026
|
+
formattingGuide: "",
|
|
1027
|
+
channels: [],
|
|
1028
|
+
users: [],
|
|
1029
|
+
};
|
|
1030
|
+
const systemPrompt = buildSystemPrompt(pathContext.runtimeWorkspaceRoot, conversationId, "shared", undefined, memory, sandboxConfig, emptyPlatform, skills);
|
|
1031
|
+
// Create session manager and settings manager. Top-level/private sessions
|
|
1032
|
+
// use the conversation's current pointer; scoped sessions use fixed files.
|
|
1033
|
+
// Platform-specific branch/fork behavior is resolved before runner creation.
|
|
1034
|
+
const isThread = sessionKey.includes(":");
|
|
1035
|
+
const { sessionDir, contextFile, threadRootMessage } = sessionScope;
|
|
1036
|
+
const sessionManager = openManagedSession(contextFile, sessionDir, pathContext.runtimeWorkspaceRoot);
|
|
1037
|
+
const threadSessionName = buildThreadSessionName(threadRootMessage);
|
|
1038
|
+
if (isThread && threadSessionName && sessionManager.getSessionName() !== threadSessionName) {
|
|
1039
|
+
sessionManager.appendSessionInfo(threadSessionName);
|
|
1040
|
+
}
|
|
1041
|
+
const sessionUuid = extractSessionUuid(contextFile);
|
|
1042
|
+
const settingsManager = SettingsManager.inMemory();
|
|
1043
|
+
const { agent, session } = await createConfiguredAgentSession({
|
|
1044
|
+
conversationId,
|
|
1045
|
+
workspaceDir,
|
|
1046
|
+
runtimeWorkspaceRoot: pathContext.runtimeWorkspaceRoot,
|
|
1047
|
+
systemPrompt,
|
|
1048
|
+
model,
|
|
1049
|
+
thinkingLevel: agentConfig.thinkingLevel,
|
|
1050
|
+
tools,
|
|
1051
|
+
sessionManager,
|
|
1052
|
+
settingsManager,
|
|
1053
|
+
});
|
|
1054
|
+
// Mutable per-run state - event handler references this
|
|
1055
|
+
const runState = createRunState();
|
|
1056
|
+
attachSessionEventHandlers({ session, runState, model, agentConfig });
|
|
1057
|
+
return {
|
|
1058
|
+
async run(message, responseCtx, platform) {
|
|
1059
|
+
const prepared = await prepareRunContext({
|
|
1060
|
+
message,
|
|
1061
|
+
responseCtx,
|
|
1062
|
+
platform,
|
|
1063
|
+
conversationId,
|
|
1064
|
+
conversationDir,
|
|
1065
|
+
sessionUuid,
|
|
1066
|
+
runState,
|
|
1067
|
+
executor,
|
|
1068
|
+
executionResolver,
|
|
1069
|
+
resolveExecutorForRun,
|
|
1070
|
+
getPathContext,
|
|
1071
|
+
sessionManager,
|
|
1072
|
+
session,
|
|
1073
|
+
agent,
|
|
1074
|
+
setEventContext,
|
|
1075
|
+
setUploadFunction,
|
|
1076
|
+
pathContext,
|
|
1077
|
+
});
|
|
1078
|
+
pathContext = prepared.pathContext;
|
|
1079
|
+
addLifecycleBreadcrumb("agent.prompt.sent", {
|
|
1080
|
+
provider: model.provider,
|
|
1081
|
+
model: agentConfig.model,
|
|
1082
|
+
channel_id: prepared.sessionConversation,
|
|
1083
|
+
session_id: sessionUuid,
|
|
1084
|
+
attachment_count: message.attachments?.length ?? 0,
|
|
1085
|
+
image_attachment_count: prepared.imageAttachments.length,
|
|
1086
|
+
});
|
|
1087
|
+
await session.prompt(prepared.userMessage, prepared.imageAttachments.length > 0 ? { images: prepared.imageAttachments } : undefined);
|
|
1088
|
+
// Wait for queued messages
|
|
1089
|
+
await prepared.runQueue.wait();
|
|
1090
|
+
const sessionViewTokenStore = sessionView?.tokenStore;
|
|
1091
|
+
const sessionViewPortalBaseUrl = sessionView?.portalBaseUrl;
|
|
1092
|
+
const createOverflowLink = sessionViewTokenStore && sessionViewPortalBaseUrl
|
|
1093
|
+
? () => {
|
|
1094
|
+
const token = sessionViewTokenStore.create(platform.name, message.userId, conversationId, message.sessionKey, contextFile, message.userName);
|
|
1095
|
+
return `${sessionViewPortalBaseUrl}/session?token=${token.token}`;
|
|
1096
|
+
}
|
|
1097
|
+
: undefined;
|
|
1098
|
+
await finalizeRunResponse(responseCtx, session, runState, {
|
|
1099
|
+
triggerAttribution: prepared.triggerAttribution,
|
|
1100
|
+
createOverflowLink,
|
|
1101
|
+
platform: platform.name,
|
|
1102
|
+
model,
|
|
1103
|
+
sessionConversation: prepared.sessionConversation,
|
|
1104
|
+
sessionUuid,
|
|
1105
|
+
});
|
|
1106
|
+
await reportUsageSummary({
|
|
1107
|
+
session,
|
|
1108
|
+
runState,
|
|
1109
|
+
responseCtx,
|
|
1110
|
+
platform,
|
|
1111
|
+
model,
|
|
1112
|
+
agentConfig,
|
|
1113
|
+
sessionConversation: prepared.sessionConversation,
|
|
1114
|
+
sessionUuid,
|
|
1115
|
+
waitForQueue: () => prepared.runQueue.wait(),
|
|
1116
|
+
});
|
|
1117
|
+
// Clear run state
|
|
1118
|
+
runState.responseCtx = null;
|
|
1119
|
+
runState.logCtx = null;
|
|
1120
|
+
runState.queue = null;
|
|
1121
|
+
return { stopReason: runState.stopReason, errorMessage: runState.errorMessage };
|
|
1122
|
+
},
|
|
1123
|
+
abort() {
|
|
1124
|
+
session.abort();
|
|
1125
|
+
},
|
|
1126
|
+
getCurrentStep() {
|
|
1127
|
+
const pending = runState.pendingTools;
|
|
1128
|
+
if (pending.size === 0)
|
|
1129
|
+
return undefined;
|
|
1130
|
+
// Get the first pending tool
|
|
1131
|
+
const first = pending.values().next().value;
|
|
1132
|
+
if (!first)
|
|
1133
|
+
return undefined;
|
|
1134
|
+
return {
|
|
1135
|
+
toolName: first.toolName,
|
|
1136
|
+
label: first.args?.label,
|
|
1137
|
+
};
|
|
1138
|
+
},
|
|
1139
|
+
};
|
|
1140
|
+
}
|
|
1141
|
+
export function translateRuntimePathToHost(runtimePath, pathContext) {
|
|
1142
|
+
return pathContext.runtimeToHostPath?.(runtimePath) ?? runtimePath;
|
|
1143
|
+
}
|
|
1144
|
+
export function buildInitialPathContextForTest(sandboxConfig, hostWorkspaceRoot) {
|
|
1145
|
+
return getUnresolvedSandboxPathContext(sandboxConfig, hostWorkspaceRoot);
|
|
1146
|
+
}
|
|
1147
|
+
//# sourceMappingURL=agent.js.map
|