@geminixiang/mikan 0.4.1 → 0.4.3
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 +14 -0
- package/dist/adapters/slack/context.d.ts.map +1 -1
- package/dist/adapters/slack/context.js +7 -422
- package/dist/adapters/slack/context.js.map +1 -1
- package/dist/adapters/slack/response-lifecycle.d.ts +11 -0
- package/dist/adapters/slack/response-lifecycle.d.ts.map +1 -0
- package/dist/adapters/slack/response-lifecycle.js +426 -0
- package/dist/adapters/slack/response-lifecycle.js.map +1 -0
- package/dist/adapters/slack/tools/attach.d.ts.map +1 -1
- package/dist/adapters/slack/tools/attach.js +3 -4
- package/dist/adapters/slack/tools/attach.js.map +1 -1
- package/dist/agent.d.ts +1 -0
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +19 -11
- package/dist/agent.js.map +1 -1
- package/dist/log.d.ts +1 -0
- package/dist/log.d.ts.map +1 -1
- package/dist/log.js +5 -0
- package/dist/log.js.map +1 -1
- package/dist/model-registry.d.ts +4 -0
- package/dist/model-registry.d.ts.map +1 -0
- package/dist/model-registry.js +7 -0
- package/dist/model-registry.js.map +1 -0
- package/dist/trigger.d.ts.map +1 -1
- package/dist/trigger.js +12 -4
- package/dist/trigger.js.map +1 -1
- package/dist/web/admin/portal.d.ts.map +1 -1
- package/dist/web/admin/portal.js +18 -6
- package/dist/web/admin/portal.js.map +1 -1
- package/dist/web/admin/provider-models.d.ts +10 -0
- package/dist/web/admin/provider-models.d.ts.map +1 -0
- package/dist/web/admin/provider-models.js +104 -0
- package/dist/web/admin/provider-models.js.map +1 -0
- package/package.json +1 -1
package/dist/log.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"log.js","sourceRoot":"","sources":["../src/log.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;A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CAAC,cAAc,OAAO,EAAE,CAAC,CAAC;AACvC,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,QAAgB;IAC3C,OAAO,CAAC,GAAG,CAAC,yBAAyB,QAAQ,iBAAiB,CAAC,CAAC;IAChE,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;AAClB,CAAC;AAED,MAAM,UAAU,eAAe;IAC7B,OAAO,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC;AACrC,CAAC;AAED,WAAW;AACX,MAAM,UAAU,gBAAgB,CAAC,YAAoB;IACnD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,SAAS,EAAE,yBAAyB,YAAY,cAAc,CAAC,CAAC,CAAC;AAC7F,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,WAAmB,EAAE,YAAoB;IAC1E,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,SAAS,EAAE,gBAAgB,WAAW,KAAK,YAAY,WAAW,CAAC,CAAC,CAAC;AACjG,CAAC;AAED,MAAM,UAAU,mBAAmB,CAAC,aAAqB,EAAE,UAAkB;IAC3E,MAAM,QAAQ,GAAG,CAAC,UAAU,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;IAChD,OAAO,CAAC,GAAG,CACT,KAAK,CAAC,IAAI,CACR,GAAG,SAAS,EAAE,gCAAgC,aAAa,gBAAgB,QAAQ,GAAG,CACvF,CACF,CAAC;AACJ,CAAC","sourcesContent":["import chalk from \"chalk\";\nimport { formatToolArgs } from \"./adapters/shared.js\";\n\nexport type { LogContext } from \"./types.js\";\nimport type { LogContext } from \"./types.js\";\n\nfunction timestamp(): string {\n const now = new Date();\n const hh = String(now.getHours()).padStart(2, \"0\");\n const mm = String(now.getMinutes()).padStart(2, \"0\");\n const ss = String(now.getSeconds()).padStart(2, \"0\");\n return `[${hh}:${mm}:${ss}]`;\n}\n\nfunction formatContext(ctx: LogContext): string {\n const session = ctx.sessionId ? `:${ctx.sessionId}` : \"\";\n if (ctx.conversationId.startsWith(\"D\")) {\n return `[DM:${ctx.userName || ctx.conversationId}${session}]`;\n }\n const conversation = ctx.conversationName || ctx.conversationId;\n const user = ctx.userName || \"unknown\";\n return `[${conversation.startsWith(\"#\") ? conversation : `#${conversation}`}:${user}${session}]`;\n}\n\n// Keep stdout/stderr lines manageable when echoing tool/agent output. Long bodies\n// flow through Sentry and session storage; the console stream just needs a preview.\nconst LOG_PREVIEW_MAX = 1000;\n\nfunction truncate(text: string, maxLen: number): string {\n if (text.length <= maxLen) return text;\n return `${text.substring(0, maxLen)}\\n(truncated at ${maxLen} chars)`;\n}\n\n// User messages\nexport function logUserMessage(ctx: LogContext, text: string): void {\n console.log(chalk.green(`${timestamp()} ${formatContext(ctx)} ${text}`));\n}\n\n// Tool execution\nexport function logToolStart(\n ctx: LogContext,\n toolName: string,\n label: string,\n args: Record<string, unknown>,\n): void {\n const formattedArgs = formatToolArgs(args);\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} ↳ ${toolName}: ${label}`));\n if (formattedArgs) {\n // Indent the args\n const indented = formattedArgs\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n }\n}\n\nexport function logToolSuccess(\n ctx: LogContext,\n toolName: string,\n durationMs: number,\n result: string,\n): void {\n const duration = (durationMs / 1000).toFixed(1);\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} ✓ ${toolName} (${duration}s)`));\n\n const truncated = truncate(result, LOG_PREVIEW_MAX);\n if (truncated) {\n const indented = truncated\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n }\n}\n\nexport function logToolError(\n ctx: LogContext,\n toolName: string,\n durationMs: number,\n error: string,\n): void {\n const duration = (durationMs / 1000).toFixed(1);\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} ✗ ${toolName} (${duration}s)`));\n\n const truncated = truncate(error, LOG_PREVIEW_MAX);\n const indented = truncated\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n}\n\n// Response streaming\nexport function logResponseStart(ctx: LogContext): void {\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} → Streaming response...`));\n}\n\nexport function logThinking(ctx: LogContext, thinking: string): void {\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} 💭 Thinking`));\n const truncated = truncate(thinking, LOG_PREVIEW_MAX);\n const indented = truncated\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n}\n\nexport function logResponse(ctx: LogContext, text: string): void {\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} 💬 Response`));\n const truncated = truncate(text, LOG_PREVIEW_MAX);\n const indented = truncated\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n}\n\n// System\nexport function logInfo(message: string): void {\n console.log(chalk.blue(`${timestamp()} [system] ${message}`));\n}\n\nexport function logWarning(message: string, details?: string): void {\n console.log(chalk.yellow(`${timestamp()} [system] ⚠ ${message}`));\n if (details) {\n const indented = details\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n }\n}\n\nexport function logAgentError(ctx: LogContext | \"system\", error: string): void {\n const context = ctx === \"system\" ? \"[system]\" : formatContext(ctx);\n console.log(chalk.yellow(`${timestamp()} ${context} ✗ Agent error`));\n const indented = error\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n}\n\nfunction formatTokenCount(count: number): string {\n if (count < 1000) return count.toString();\n if (count < 10000) return `${(count / 1000).toFixed(1)}k`;\n if (count < 1000000) return `${Math.round(count / 1000)}k`;\n return `${(count / 1000000).toFixed(1)}M`;\n}\n\n// Usage summary\nexport function logUsageSummary(\n ctx: LogContext,\n usage: {\n input: number;\n output: number;\n cacheRead: number;\n cacheWrite: number;\n cost: { input: number; output: number; cacheRead: number; cacheWrite: number; total: number };\n },\n contextTokens?: number,\n contextWindow?: number,\n): string {\n const lines: string[] = [];\n lines.push(\"_Usage Summary_\");\n lines.push(`Tokens: ${usage.input.toLocaleString()} in, ${usage.output.toLocaleString()} out`);\n if (usage.cacheRead > 0 || usage.cacheWrite > 0) {\n lines.push(\n `Cache: ${usage.cacheRead.toLocaleString()} read, ${usage.cacheWrite.toLocaleString()} write`,\n );\n }\n if (contextTokens && contextWindow) {\n const contextPercent = ((contextTokens / contextWindow) * 100).toFixed(1);\n lines.push(\n `Context: ${formatTokenCount(contextTokens)} / ${formatTokenCount(contextWindow)} (${contextPercent}%)`,\n );\n }\n lines.push(\n `Cost: $${usage.cost.input.toFixed(4)} in, $${usage.cost.output.toFixed(4)} out` +\n (usage.cacheRead > 0 || usage.cacheWrite > 0\n ? `, $${usage.cost.cacheRead.toFixed(4)} cache read, $${usage.cost.cacheWrite.toFixed(4)} cache write`\n : \"\"),\n );\n lines.push(`*Total: $${usage.cost.total.toFixed(4)}*`);\n\n const summary = lines.join(\"\\n\");\n\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} 💰 Usage`));\n console.log(\n chalk.dim(\n ` ${usage.input.toLocaleString()} in + ${usage.output.toLocaleString()} out` +\n (usage.cacheRead > 0 || usage.cacheWrite > 0\n ? ` (${usage.cacheRead.toLocaleString()} cache read, ${usage.cacheWrite.toLocaleString()} cache write)`\n : \"\") +\n ` = $${usage.cost.total.toFixed(4)}`,\n ),\n );\n\n return summary;\n}\n\n// Startup (no context needed)\nexport function logStartup(workingDir: string, sandbox: string): void {\n console.log(\"Starting mikan...\");\n console.log(` Working directory: ${workingDir}`);\n console.log(` Sandbox: ${sandbox}`);\n}\n\nexport function logConnected(platform: string): void {\n console.log(`⚡️ Mikan connected to ${platform} and listening!`);\n console.log(\"\");\n}\n\nexport function logDisconnected(): void {\n console.log(\"Mikan disconnected.\");\n}\n\n// Backfill\nexport function logBackfillStart(channelCount: number): void {\n console.log(chalk.blue(`${timestamp()} [system] Backfilling ${channelCount} channels...`));\n}\n\nexport function logBackfillChannel(channelName: string, messageCount: number): void {\n console.log(chalk.blue(`${timestamp()} [system] #${channelName}: ${messageCount} messages`));\n}\n\nexport function logBackfillComplete(totalMessages: number, durationMs: number): void {\n const duration = (durationMs / 1000).toFixed(1);\n console.log(\n chalk.blue(\n `${timestamp()} [system] Backfill complete: ${totalMessages} messages in ${duration}s`,\n ),\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"log.js","sourceRoot":"","sources":["../src/log.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAKtD,SAAS,SAAS;IAChB,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;IACvB,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;IACnD,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,CAAC,UAAU,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;IACrD,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,CAAC,UAAU,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;IACrD,OAAO,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,CAAC;AAC/B,CAAC;AAED,SAAS,aAAa,CAAC,GAAe;IACpC,MAAM,OAAO,GAAG,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IACzD,IAAI,GAAG,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;QACvC,OAAO,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C,YAAoB;IACnD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,SAAS,EAAE,yBAAyB,YAAY,cAAc,CAAC,CAAC,CAAC;AAC7F,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,WAAmB,EAAE,YAAoB;IAC1E,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,SAAS,EAAE,gBAAgB,WAAW,KAAK,YAAY,WAAW,CAAC,CAAC,CAAC;AACjG,CAAC;AAED,MAAM,UAAU,mBAAmB,CAAC,aAAqB,EAAE,UAAkB;IAC3E,MAAM,QAAQ,GAAG,CAAC,UAAU,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;IAChD,OAAO,CAAC,GAAG,CACT,KAAK,CAAC,IAAI,CACR,GAAG,SAAS,EAAE,gCAAgC,aAAa,gBAAgB,QAAQ,GAAG,CACvF,CACF,CAAC;AACJ,CAAC","sourcesContent":["import chalk from \"chalk\";\nimport { formatToolArgs } from \"./adapters/shared.js\";\n\nexport type { LogContext } from \"./types.js\";\nimport type { LogContext } from \"./types.js\";\n\nfunction timestamp(): string {\n const now = new Date();\n const hh = String(now.getHours()).padStart(2, \"0\");\n const mm = String(now.getMinutes()).padStart(2, \"0\");\n const ss = String(now.getSeconds()).padStart(2, \"0\");\n return `[${hh}:${mm}:${ss}]`;\n}\n\nfunction formatContext(ctx: LogContext): string {\n const session = ctx.sessionId ? `:${ctx.sessionId}` : \"\";\n if (ctx.conversationId.startsWith(\"D\")) {\n return `[DM:${ctx.userName || ctx.conversationId}${session}]`;\n }\n const conversation = ctx.conversationName || ctx.conversationId;\n const user = ctx.userName || \"unknown\";\n return `[${conversation.startsWith(\"#\") ? conversation : `#${conversation}`}:${user}${session}]`;\n}\n\n// Keep stdout/stderr lines manageable when echoing tool/agent output. Long bodies\n// flow through Sentry and session storage; the console stream just needs a preview.\nconst LOG_PREVIEW_MAX = 1000;\n\nfunction truncate(text: string, maxLen: number): string {\n if (text.length <= maxLen) return text;\n return `${text.substring(0, maxLen)}\\n(truncated at ${maxLen} chars)`;\n}\n\n// User messages\nexport function logUserMessage(ctx: LogContext, text: string): void {\n console.log(chalk.green(`${timestamp()} ${formatContext(ctx)} ${text}`));\n}\n\n// Tool execution\nexport function logToolStart(\n ctx: LogContext,\n toolName: string,\n label: string,\n args: Record<string, unknown>,\n): void {\n const formattedArgs = formatToolArgs(args);\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} ↳ ${toolName}: ${label}`));\n if (formattedArgs) {\n // Indent the args\n const indented = formattedArgs\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n }\n}\n\nexport function logToolSuccess(\n ctx: LogContext,\n toolName: string,\n durationMs: number,\n result: string,\n): void {\n const duration = (durationMs / 1000).toFixed(1);\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} ✓ ${toolName} (${duration}s)`));\n\n const truncated = truncate(result, LOG_PREVIEW_MAX);\n if (truncated) {\n const indented = truncated\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n }\n}\n\nexport function logToolError(\n ctx: LogContext,\n toolName: string,\n durationMs: number,\n error: string,\n): void {\n const duration = (durationMs / 1000).toFixed(1);\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} ✗ ${toolName} (${duration}s)`));\n\n const truncated = truncate(error, LOG_PREVIEW_MAX);\n const indented = truncated\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n}\n\n// Agent run\nexport function logAgentRunStart(\n ctx: LogContext,\n provider: string,\n model: string,\n modelName?: string,\n): void {\n const displayName = modelName && modelName !== model ? ` (${modelName})` : \"\";\n console.log(\n chalk.blue(\n `${timestamp()} ${formatContext(ctx)} ▶ Agent run: ${provider}/${model}${displayName}`,\n ),\n );\n}\n\n// Response streaming\nexport function logResponseStart(ctx: LogContext): void {\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} → Streaming response...`));\n}\n\nexport function logThinking(ctx: LogContext, thinking: string): void {\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} 💭 Thinking`));\n const truncated = truncate(thinking, LOG_PREVIEW_MAX);\n const indented = truncated\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n}\n\nexport function logResponse(ctx: LogContext, text: string): void {\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} 💬 Response`));\n const truncated = truncate(text, LOG_PREVIEW_MAX);\n const indented = truncated\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n}\n\n// System\nexport function logInfo(message: string): void {\n console.log(chalk.blue(`${timestamp()} [system] ${message}`));\n}\n\nexport function logWarning(message: string, details?: string): void {\n console.log(chalk.yellow(`${timestamp()} [system] ⚠ ${message}`));\n if (details) {\n const indented = details\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n }\n}\n\nexport function logAgentError(ctx: LogContext | \"system\", error: string): void {\n const context = ctx === \"system\" ? \"[system]\" : formatContext(ctx);\n console.log(chalk.yellow(`${timestamp()} ${context} ✗ Agent error`));\n const indented = error\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n}\n\nfunction formatTokenCount(count: number): string {\n if (count < 1000) return count.toString();\n if (count < 10000) return `${(count / 1000).toFixed(1)}k`;\n if (count < 1000000) return `${Math.round(count / 1000)}k`;\n return `${(count / 1000000).toFixed(1)}M`;\n}\n\n// Usage summary\nexport function logUsageSummary(\n ctx: LogContext,\n usage: {\n input: number;\n output: number;\n cacheRead: number;\n cacheWrite: number;\n cost: { input: number; output: number; cacheRead: number; cacheWrite: number; total: number };\n },\n contextTokens?: number,\n contextWindow?: number,\n): string {\n const lines: string[] = [];\n lines.push(\"_Usage Summary_\");\n lines.push(`Tokens: ${usage.input.toLocaleString()} in, ${usage.output.toLocaleString()} out`);\n if (usage.cacheRead > 0 || usage.cacheWrite > 0) {\n lines.push(\n `Cache: ${usage.cacheRead.toLocaleString()} read, ${usage.cacheWrite.toLocaleString()} write`,\n );\n }\n if (contextTokens && contextWindow) {\n const contextPercent = ((contextTokens / contextWindow) * 100).toFixed(1);\n lines.push(\n `Context: ${formatTokenCount(contextTokens)} / ${formatTokenCount(contextWindow)} (${contextPercent}%)`,\n );\n }\n lines.push(\n `Cost: $${usage.cost.input.toFixed(4)} in, $${usage.cost.output.toFixed(4)} out` +\n (usage.cacheRead > 0 || usage.cacheWrite > 0\n ? `, $${usage.cost.cacheRead.toFixed(4)} cache read, $${usage.cost.cacheWrite.toFixed(4)} cache write`\n : \"\"),\n );\n lines.push(`*Total: $${usage.cost.total.toFixed(4)}*`);\n\n const summary = lines.join(\"\\n\");\n\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} 💰 Usage`));\n console.log(\n chalk.dim(\n ` ${usage.input.toLocaleString()} in + ${usage.output.toLocaleString()} out` +\n (usage.cacheRead > 0 || usage.cacheWrite > 0\n ? ` (${usage.cacheRead.toLocaleString()} cache read, ${usage.cacheWrite.toLocaleString()} cache write)`\n : \"\") +\n ` = $${usage.cost.total.toFixed(4)}`,\n ),\n );\n\n return summary;\n}\n\n// Startup (no context needed)\nexport function logStartup(workingDir: string, sandbox: string): void {\n console.log(\"Starting mikan...\");\n console.log(` Working directory: ${workingDir}`);\n console.log(` Sandbox: ${sandbox}`);\n}\n\nexport function logConnected(platform: string): void {\n console.log(`⚡️ Mikan connected to ${platform} and listening!`);\n console.log(\"\");\n}\n\nexport function logDisconnected(): void {\n console.log(\"Mikan disconnected.\");\n}\n\n// Backfill\nexport function logBackfillStart(channelCount: number): void {\n console.log(chalk.blue(`${timestamp()} [system] Backfilling ${channelCount} channels...`));\n}\n\nexport function logBackfillChannel(channelName: string, messageCount: number): void {\n console.log(chalk.blue(`${timestamp()} [system] #${channelName}: ${messageCount} messages`));\n}\n\nexport function logBackfillComplete(totalMessages: number, durationMs: number): void {\n const duration = (durationMs / 1000).toFixed(1);\n console.log(\n chalk.blue(\n `${timestamp()} [system] Backfill complete: ${totalMessages} messages in ${duration}s`,\n ),\n );\n}\n"]}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { type Api, type Model } from "@earendil-works/pi-ai";
|
|
2
|
+
import { ModelRegistry } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
export declare function resolveConfiguredModel(modelRegistry: ModelRegistry, provider: string, modelId: string): Model<Api>;
|
|
4
|
+
//# sourceMappingURL=model-registry.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"model-registry.d.ts","sourceRoot":"","sources":["../src/model-registry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,GAAG,EAAE,KAAK,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,aAAa,EAAE,MAAM,iCAAiC,CAAC;AAEhE,wBAAgB,sBAAsB,CACpC,aAAa,EAAE,aAAa,EAC5B,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,GACd,KAAK,CAAC,GAAG,CAAC,CAOZ","sourcesContent":["import { type Api, type Model } from \"@earendil-works/pi-ai\";\nimport { ModelRegistry } from \"@earendil-works/pi-coding-agent\";\n\nexport function resolveConfiguredModel(\n modelRegistry: ModelRegistry,\n provider: string,\n modelId: string,\n): Model<Api> {\n const model = modelRegistry.find(provider, modelId) as Model<Api> | undefined;\n if (model) return model;\n\n throw new Error(\n `Unknown model \"${provider}/${modelId}\". Configure it in pi models.json or choose a registered model.`,\n );\n}\n"]}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export function resolveConfiguredModel(modelRegistry, provider, modelId) {
|
|
2
|
+
const model = modelRegistry.find(provider, modelId);
|
|
3
|
+
if (model)
|
|
4
|
+
return model;
|
|
5
|
+
throw new Error(`Unknown model "${provider}/${modelId}". Configure it in pi models.json or choose a registered model.`);
|
|
6
|
+
}
|
|
7
|
+
//# sourceMappingURL=model-registry.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"model-registry.js","sourceRoot":"","sources":["../src/model-registry.ts"],"names":[],"mappings":"AAGA,MAAM,UAAU,sBAAsB,CACpC,aAA4B,EAC5B,QAAgB,EAChB,OAAe;IAEf,MAAM,KAAK,GAAG,aAAa,CAAC,IAAI,CAAC,QAAQ,EAAE,OAAO,CAA2B,CAAC;IAC9E,IAAI,KAAK;QAAE,OAAO,KAAK,CAAC;IAExB,MAAM,IAAI,KAAK,CACb,kBAAkB,QAAQ,IAAI,OAAO,iEAAiE,CACvG,CAAC;AACJ,CAAC","sourcesContent":["import { type Api, type Model } from \"@earendil-works/pi-ai\";\nimport { ModelRegistry } from \"@earendil-works/pi-coding-agent\";\n\nexport function resolveConfiguredModel(\n modelRegistry: ModelRegistry,\n provider: string,\n modelId: string,\n): Model<Api> {\n const model = modelRegistry.find(provider, modelId) as Model<Api> | undefined;\n if (model) return model;\n\n throw new Error(\n `Unknown model \"${provider}/${modelId}\". Configure it in pi models.json or choose a registered model.`,\n );\n}\n"]}
|
package/dist/trigger.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trigger.d.ts","sourceRoot":"","sources":["../src/trigger.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"trigger.d.ts","sourceRoot":"","sources":["../src/trigger.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAS7C,YAAY,EAAE,cAAc,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC/E,OAAO,KAAK,EAAE,cAAc,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAE/E;;;GAGG;AACH,wBAAgB,aAAa,CAC3B,MAAM,EAAE,OAAO,CAAC,aAAa,EAAE,sBAAsB,CAAC,GACrD,aAAa,CAEf;AAED;;;;GAIG;AACH,wBAAsB,uBAAuB,CAAC,KAAK,EAAE;IACnD,KAAK,EAAE,QAAQ,CAAC;IAChB,UAAU,EAAE,MAAM,GAAG,SAAS,CAAC;IAC/B,KAAK,CAAC,EAAE,cAAc,CAAC;IACvB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,GAAG,OAAO,CAAC,aAAa,CAAC,CA4BzB","sourcesContent":["import { completeSimple } from \"@earendil-works/pi-ai\";\nimport { AuthStorage, ModelRegistry } from \"@earendil-works/pi-coding-agent\";\nimport type { BotEvent } from \"./adapter.js\";\nimport { loadAutoReplyJudgeModel, loadConversationAutoReplyConfig } from \"./config.js\";\nimport * as log from \"./log.js\";\nimport { homedir } from \"os\";\nimport { join } from \"path\";\nimport { resolveConfiguredModel } from \"./model-registry.js\";\n\nconst JUDGE_TIMEOUT_MS = 10_000;\n\nexport type { AutoReplyJudge, TriggerIntent, TriggerResult } from \"./types.js\";\nimport type { AutoReplyJudge, TriggerIntent, TriggerResult } from \"./types.js\";\n\n/**\n * Trivially decide non-auto-reply intents synchronously. For \"auto-reply-candidate\"\n * callers must use {@link evaluateAutoReplyPolicy}.\n */\nexport function decideTrigger(\n intent: Exclude<TriggerIntent, \"auto-reply-candidate\">,\n): TriggerResult {\n return { trigger: true, reason: intent };\n}\n\n/**\n * Decide whether to auto-reply. Never throws — judge errors and timeouts are\n * folded into a `trigger: false` result with a distinct reason, so adapters\n * can apply a single uniform \"do not trigger, but still log\" policy.\n */\nexport async function evaluateAutoReplyPolicy(input: {\n event: BotEvent;\n workingDir: string | undefined;\n judge?: AutoReplyJudge;\n timeoutMs?: number;\n}): Promise<TriggerResult> {\n const { event, workingDir, judge = judgeAutoReplyWithLlm, timeoutMs = JUDGE_TIMEOUT_MS } = input;\n if (!workingDir) return { trigger: false, reason: \"auto-reply-unconfigured\" };\n\n const conversationDir = join(workingDir, event.conversationId);\n\n try {\n const config = loadConversationAutoReplyConfig(conversationDir);\n if (!config.enabled) return { trigger: false, reason: \"auto-reply-disabled\" };\n if (config.rules.length === 0) {\n return { trigger: true, reason: \"auto-reply-enabled\" };\n }\n\n const shouldReply = await withTimeout(\n judge({ event, rules: config.rules, conversationDir }),\n timeoutMs,\n );\n return shouldReply\n ? { trigger: true, reason: \"auto-reply-rule-match\" }\n : { trigger: false, reason: \"auto-reply-rule-no-match\" };\n } catch (err) {\n if (err instanceof JudgeTimeoutError) {\n log.logWarning(\"Auto-reply judge timed out\", String(err));\n return { trigger: false, reason: \"auto-reply-judge-timeout\" };\n }\n log.logWarning(\"Auto-reply policy evaluation failed\", String(err));\n return { trigger: false, reason: \"auto-reply-judge-failed\" };\n }\n}\n\nclass JudgeTimeoutError extends Error {\n constructor(ms: number) {\n super(`auto-reply judge exceeded ${ms}ms`);\n this.name = \"JudgeTimeoutError\";\n }\n}\n\nfunction withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => reject(new JudgeTimeoutError(ms)), ms);\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (err) => {\n clearTimeout(timer);\n reject(err);\n },\n );\n });\n}\n\nasync function judgeAutoReplyWithLlm(input: {\n event: BotEvent;\n rules: string[];\n conversationDir: string;\n}): Promise<boolean> {\n const judgeConfig = loadAutoReplyJudgeModel(input.conversationDir);\n const modelRegistry = ModelRegistry.create(\n AuthStorage.create(join(homedir(), \".pi\", \"mikan\", \"auth.json\")),\n );\n const model = resolveConfiguredModel(modelRegistry, judgeConfig.provider, judgeConfig.model);\n const auth = await modelRegistry.getApiKeyAndHeaders(model);\n if (!auth.ok) {\n throw new Error(auth.error);\n }\n\n const answer = await completeSimple(\n model,\n {\n systemPrompt:\n \"You decide whether a bot should reply to a group/channel message. \" +\n \"Use only the rules provided by the user. Answer exactly YES or NO.\",\n messages: [\n {\n role: \"user\",\n timestamp: Date.now(),\n content: [\n \"Rules:\",\n ...input.rules.map((rule, index) => `${index + 1}. ${rule}`),\n \"\",\n \"Message:\",\n input.event.text,\n \"\",\n \"Should the bot reply? Answer exactly YES or NO.\",\n ].join(\"\\n\"),\n },\n ],\n },\n {\n temperature: 0,\n maxTokens: 4,\n reasoning: \"minimal\",\n apiKey: auth.apiKey,\n headers: auth.headers,\n },\n );\n const text = answer.content\n .filter((part) => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\")\n .trim()\n .toUpperCase();\n return /^YES\\b/.test(text);\n}\n"]}
|
package/dist/trigger.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
|
-
import { completeSimple
|
|
1
|
+
import { completeSimple } from "@earendil-works/pi-ai";
|
|
2
|
+
import { AuthStorage, ModelRegistry } from "@earendil-works/pi-coding-agent";
|
|
2
3
|
import { loadAutoReplyJudgeModel, loadConversationAutoReplyConfig } from "./config.js";
|
|
3
4
|
import * as log from "./log.js";
|
|
5
|
+
import { homedir } from "os";
|
|
4
6
|
import { join } from "path";
|
|
7
|
+
import { resolveConfiguredModel } from "./model-registry.js";
|
|
5
8
|
const JUDGE_TIMEOUT_MS = 10_000;
|
|
6
9
|
/**
|
|
7
10
|
* Trivially decide non-auto-reply intents synchronously. For "auto-reply-candidate"
|
|
@@ -61,9 +64,12 @@ function withTimeout(promise, ms) {
|
|
|
61
64
|
}
|
|
62
65
|
async function judgeAutoReplyWithLlm(input) {
|
|
63
66
|
const judgeConfig = loadAutoReplyJudgeModel(input.conversationDir);
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
const
|
|
67
|
+
const modelRegistry = ModelRegistry.create(AuthStorage.create(join(homedir(), ".pi", "mikan", "auth.json")));
|
|
68
|
+
const model = resolveConfiguredModel(modelRegistry, judgeConfig.provider, judgeConfig.model);
|
|
69
|
+
const auth = await modelRegistry.getApiKeyAndHeaders(model);
|
|
70
|
+
if (!auth.ok) {
|
|
71
|
+
throw new Error(auth.error);
|
|
72
|
+
}
|
|
67
73
|
const answer = await completeSimple(model, {
|
|
68
74
|
systemPrompt: "You decide whether a bot should reply to a group/channel message. " +
|
|
69
75
|
"Use only the rules provided by the user. Answer exactly YES or NO.",
|
|
@@ -86,6 +92,8 @@ async function judgeAutoReplyWithLlm(input) {
|
|
|
86
92
|
temperature: 0,
|
|
87
93
|
maxTokens: 4,
|
|
88
94
|
reasoning: "minimal",
|
|
95
|
+
apiKey: auth.apiKey,
|
|
96
|
+
headers: auth.headers,
|
|
89
97
|
});
|
|
90
98
|
const text = answer.content
|
|
91
99
|
.filter((part) => part.type === "text")
|
package/dist/trigger.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trigger.js","sourceRoot":"","sources":["../src/trigger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,
|
|
1
|
+
{"version":3,"file":"trigger.js","sourceRoot":"","sources":["../src/trigger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,iCAAiC,CAAC;AAE7E,OAAO,EAAE,uBAAuB,EAAE,+BAA+B,EAAE,MAAM,aAAa,CAAC;AACvF,OAAO,KAAK,GAAG,MAAM,UAAU,CAAC;AAChC,OAAO,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAC7B,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAE7D,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAKhC;;;GAGG;AACH,MAAM,UAAU,aAAa,CAC3B,MAAsD;IAEtD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AAC3C,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAAC,KAK7C;IACC,MAAM,EAAE,KAAK,EAAE,U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,CAAC,KAAK,CAAC,CAAC;IAC5D,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC9B,CAAC;IAED,MAAM,MAAM,GAAG,MAAM,cAAc,CACjC,KAAK,EACL;QACE,YAAY,EACV,oEAAoE;YACpE,oEAAoE;QACtE,QAAQ,EAAE;YACR;gBACE,IAAI,EAAE,MAAM;gBACZ,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;gBACrB,OAAO,EAAE;oBACP,QAAQ;oBACR,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,GAAG,KAAK,GAAG,CAAC,KAAK,IAAI,EAAE,CAAC;oBAC5D,EAAE;oBACF,UAAU;oBACV,KAAK,CAAC,KAAK,CAAC,IAAI;oBAChB,EAAE;oBACF,iDAAiD;iBAClD,CAAC,IAAI,CAAC,IAAI,CAAC;aACb;SACF;KACF,EACD;QACE,WAAW,EAAE,CAAC;QACd,SAAS,EAAE,CAAC;QACZ,SAAS,EAAE,SAAS;QACpB,MAAM,EAAE,IAAI,CAAC,MAAM;QACnB,OAAO,EAAE,IAAI,CAAC,OAAO;KACtB,CACF,CAAC;IACF,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO;SACxB,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,MAAM,CAAC;SACtC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC;SACxB,IAAI,CAAC,EAAE,CAAC;SACR,IAAI,EAAE;SACN,WAAW,EAAE,CAAC;IACjB,OAAO,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC7B,CAAC","sourcesContent":["import { completeSimple } from \"@earendil-works/pi-ai\";\nimport { AuthStorage, ModelRegistry } from \"@earendil-works/pi-coding-agent\";\nimport type { BotEvent } from \"./adapter.js\";\nimport { loadAutoReplyJudgeModel, loadConversationAutoReplyConfig } from \"./config.js\";\nimport * as log from \"./log.js\";\nimport { homedir } from \"os\";\nimport { join } from \"path\";\nimport { resolveConfiguredModel } from \"./model-registry.js\";\n\nconst JUDGE_TIMEOUT_MS = 10_000;\n\nexport type { AutoReplyJudge, TriggerIntent, TriggerResult } from \"./types.js\";\nimport type { AutoReplyJudge, TriggerIntent, TriggerResult } from \"./types.js\";\n\n/**\n * Trivially decide non-auto-reply intents synchronously. For \"auto-reply-candidate\"\n * callers must use {@link evaluateAutoReplyPolicy}.\n */\nexport function decideTrigger(\n intent: Exclude<TriggerIntent, \"auto-reply-candidate\">,\n): TriggerResult {\n return { trigger: true, reason: intent };\n}\n\n/**\n * Decide whether to auto-reply. Never throws — judge errors and timeouts are\n * folded into a `trigger: false` result with a distinct reason, so adapters\n * can apply a single uniform \"do not trigger, but still log\" policy.\n */\nexport async function evaluateAutoReplyPolicy(input: {\n event: BotEvent;\n workingDir: string | undefined;\n judge?: AutoReplyJudge;\n timeoutMs?: number;\n}): Promise<TriggerResult> {\n const { event, workingDir, judge = judgeAutoReplyWithLlm, timeoutMs = JUDGE_TIMEOUT_MS } = input;\n if (!workingDir) return { trigger: false, reason: \"auto-reply-unconfigured\" };\n\n const conversationDir = join(workingDir, event.conversationId);\n\n try {\n const config = loadConversationAutoReplyConfig(conversationDir);\n if (!config.enabled) return { trigger: false, reason: \"auto-reply-disabled\" };\n if (config.rules.length === 0) {\n return { trigger: true, reason: \"auto-reply-enabled\" };\n }\n\n const shouldReply = await withTimeout(\n judge({ event, rules: config.rules, conversationDir }),\n timeoutMs,\n );\n return shouldReply\n ? { trigger: true, reason: \"auto-reply-rule-match\" }\n : { trigger: false, reason: \"auto-reply-rule-no-match\" };\n } catch (err) {\n if (err instanceof JudgeTimeoutError) {\n log.logWarning(\"Auto-reply judge timed out\", String(err));\n return { trigger: false, reason: \"auto-reply-judge-timeout\" };\n }\n log.logWarning(\"Auto-reply policy evaluation failed\", String(err));\n return { trigger: false, reason: \"auto-reply-judge-failed\" };\n }\n}\n\nclass JudgeTimeoutError extends Error {\n constructor(ms: number) {\n super(`auto-reply judge exceeded ${ms}ms`);\n this.name = \"JudgeTimeoutError\";\n }\n}\n\nfunction withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => reject(new JudgeTimeoutError(ms)), ms);\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (err) => {\n clearTimeout(timer);\n reject(err);\n },\n );\n });\n}\n\nasync function judgeAutoReplyWithLlm(input: {\n event: BotEvent;\n rules: string[];\n conversationDir: string;\n}): Promise<boolean> {\n const judgeConfig = loadAutoReplyJudgeModel(input.conversationDir);\n const modelRegistry = ModelRegistry.create(\n AuthStorage.create(join(homedir(), \".pi\", \"mikan\", \"auth.json\")),\n );\n const model = resolveConfiguredModel(modelRegistry, judgeConfig.provider, judgeConfig.model);\n const auth = await modelRegistry.getApiKeyAndHeaders(model);\n if (!auth.ok) {\n throw new Error(auth.error);\n }\n\n const answer = await completeSimple(\n model,\n {\n systemPrompt:\n \"You decide whether a bot should reply to a group/channel message. \" +\n \"Use only the rules provided by the user. Answer exactly YES or NO.\",\n messages: [\n {\n role: \"user\",\n timestamp: Date.now(),\n content: [\n \"Rules:\",\n ...input.rules.map((rule, index) => `${index + 1}. ${rule}`),\n \"\",\n \"Message:\",\n input.event.text,\n \"\",\n \"Should the bot reply? Answer exactly YES or NO.\",\n ].join(\"\\n\"),\n },\n ],\n },\n {\n temperature: 0,\n maxTokens: 4,\n reasoning: \"minimal\",\n apiKey: auth.apiKey,\n headers: auth.headers,\n },\n );\n const text = answer.content\n .filter((part) => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\")\n .trim()\n .toUpperCase();\n return /^YES\\b/.test(text);\n}\n"]}
|