Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(streaming): use per-message stream ids and oauth resolver

yushen37ec8ff5e001
diff --cc src/agent/providers/registry.ts
index 0000000000,50809def83..cd40648252
mode 000000,100644..100644
--- a/src/agent/providers/registry.ts
+++ b/src/agent/providers/registry.ts
@@@ -1,0 -1,275 +1,276 @@@
+ /**
+ * Provider Registry
+ *
+ * Central registry for all LLM providers with metadata,
+ * status checking, and display formatting.
+ */
+
+ import { credentialManager } from "../credentials.js";
+ import {
+ hasValidClaudeCliCredentials,
+ hasValidCodexCliCredentials,
+ } from "./oauth/cli-credentials.js";
+
+ // ============================================================
+ // Types
+ // ============================================================
+
+ export type AuthMethod = "api-key" | "oauth";
+
+ export interface ProviderInfo {
+ id: string;
+ name: string;
+ authMethod: AuthMethod;
+ available: boolean;
+ configured: boolean;
+ current: boolean;
+ defaultModel: string;
+ models: string[];
+ loginUrl?: string | undefined;
+ loginCommand?: string | undefined;
+ }
+
+ /** Static provider metadata (without runtime status) */
+ export interface ProviderMeta {
+ id: string;
+ name: string;
+ authMethod: AuthMethod;
+ defaultModel: string;
+ models: string[];
+ loginUrl?: string | undefined;
+ loginCommand?: string | undefined;
+ }
+
+ // ============================================================
+ // Provider Registry
+ // ============================================================
+
+ const PROVIDER_REGISTRY: Record<string, ProviderMeta> = {
+ "claude-code": {
+ id: "claude-code",
+ name: "Claude Code (OAuth)",
+ authMethod: "oauth",
+ defaultModel: "claude-opus-4-5",
+ models: ["claude-opus-4-5", "claude-sonnet-4-5", "claude-haiku-4-5"],
+ loginCommand: "claude login",
+ },
+ "openai-codex": {
+ id: "openai-codex",
+ name: "Codex (OAuth)",
+ authMethod: "oauth",
+ defaultModel: "gpt-5.2",
+ models: ["gpt-5.2", "gpt-5.2-codex", "gpt-5.1-codex", "gpt-5.1-codex-mini", "gpt-5.1-codex-max"],
+ loginCommand: "codex login",
+ },
+ "anthropic": {
+ id: "anthropic",
+ name: "Anthropic (API Key)",
+ authMethod: "api-key",
+ defaultModel: "claude-sonnet-4-5",
+ models: ["claude-opus-4-5", "claude-sonnet-4-5", "claude-haiku-4-5"],
+ loginUrl: "https://console.anthropic.com/",
+ },
+ "openai": {
+ id: "openai",
+ name: "OpenAI",
+ authMethod: "api-key",
+ defaultModel: "gpt-4o",
+ models: ["gpt-4o", "gpt-4o-mini", "o1", "o1-mini"],
+ loginUrl: "https://platform.openai.com/api-keys",
+ },
+ "kimi-coding": {
+ id: "kimi-coding",
+ name: "Kimi Code",
+ authMethod: "api-key",
+ defaultModel: "kimi-k2-thinking",
+ models: ["kimi-k2-thinking", "k2p5"],
+ loginUrl: "https://kimi.moonshot.cn/",
+ },
+ "google": {
+ id: "google",
+ name: "Google AI",
+ authMethod: "api-key",
+ defaultModel: "gemini-2.0-flash",
+ models: ["gemini-2.0-flash", "gemini-1.5-pro"],
+ loginUrl: "https://aistudio.google.com/apikey",
+ },
+ "groq": {
+ id: "groq",
+ name: "Groq",
+ authMethod: "api-key",
+ defaultModel: "llama-3.3-70b-versatile",
+ models: ["llama-3.3-70b-versatile", "mixtral-8x7b-32768"],
+ loginUrl: "https://console.groq.com/keys",
+ },
+ "mistral": {
+ id: "mistral",
+ name: "Mistral",
+ authMethod: "api-key",
+ defaultModel: "mistral-large-latest",
+ models: ["mistral-large-latest", "codestral-latest"],
+ loginUrl: "https://console.mistral.ai/api-keys",
+ },
+ "xai": {
+ id: "xai",
+ name: "xAI (Grok)",
+ authMethod: "api-key",
+ defaultModel: "grok-beta",
+ models: ["grok-beta", "grok-vision-beta"],
+ loginUrl: "https://console.x.ai/",
+ },
+ "openrouter": {
+ id: "openrouter",
+ name: "OpenRouter",
+ authMethod: "api-key",
+ defaultModel: "anthropic/claude-3.5-sonnet",
+ models: ["anthropic/claude-3.5-sonnet", "openai/gpt-4o"],
+ loginUrl: "https://openrouter.ai/keys",
+ },
+ };
+
+ /**
+ * Provider alias mapping for OAuth providers.
+ * Maps friendly names to actual pi-ai provider names.
+ */
+ export const PROVIDER_ALIAS: Record<string, string> = {
+ "claude-code": "anthropic", // Claude Code OAuth uses anthropic API
++ "openai-codex": "openai", // Codex OAuth uses OpenAI API
+ };
+
+ // ============================================================
+ // Status Checking
+ // ============================================================
+
+ /**
+ * Check if a provider is configured with API key in credentials.json5
+ */
+ function isApiKeyConfigured(providerId: string): boolean {
+ const config = credentialManager.getLlmProviderConfig(providerId);
+ return !!config?.apiKey;
+ }
+
+ /**
+ * Check if OAuth provider has valid credentials
+ */
+ function isOAuthAvailable(providerId: string): boolean {
+ if (providerId === "claude-code") {
+ return hasValidClaudeCliCredentials();
+ }
+ if (providerId === "openai-codex") {
+ return hasValidCodexCliCredentials();
+ }
+ return false;
+ }
+
+ /**
+ * Check if a provider uses OAuth authentication
+ */
+ export function isOAuthProvider(providerId: string): boolean {
+ const info = PROVIDER_REGISTRY[providerId];
+ return info?.authMethod === "oauth";
+ }
+
+ /**
+ * Check if provider is available (has valid credentials)
+ */
+ export function isProviderAvailable(providerId: string): boolean {
+ const info = PROVIDER_REGISTRY[providerId];
+ if (!info) return false;
+
+ if (info.authMethod === "oauth") {
+ return isOAuthAvailable(providerId);
+ }
+ return isApiKeyConfigured(providerId);
+ }
+
+ /**
+ * Get current provider from credentials
+ */
+ export function getCurrentProvider(): string {
+ return credentialManager.getLlmProvider() ?? "kimi-coding";
+ }
+
+ // ============================================================
+ // Provider Listing
+ // ============================================================
+
+ /**
+ * Get static provider metadata
+ */
+ export function getProviderMeta(providerId: string): ProviderMeta | undefined {
+ return PROVIDER_REGISTRY[providerId];
+ }
+
+ /**
+ * Get default model for a provider
+ */
+ export function getDefaultModel(providerId: string): string | undefined {
+ return PROVIDER_REGISTRY[providerId]?.defaultModel;
+ }
+
+ /**
+ * Get list of all providers with their runtime status
+ */
+ export function getProviderList(): ProviderInfo[] {
+ const currentProvider = getCurrentProvider();
+
+ return Object.values(PROVIDER_REGISTRY).map((meta) => {
+ const isOAuth = meta.authMethod === "oauth";
+ const available = isOAuth ? isOAuthAvailable(meta.id) : isApiKeyConfigured(meta.id);
+
+ // Check if this is the current provider
+ // For claude-code, check if current is "anthropic" and OAuth is available
+ let isCurrent = currentProvider === meta.id;
+ if (meta.id === "claude-code" && currentProvider === "anthropic") {
+ isCurrent = hasValidClaudeCliCredentials();
+ }
+
+ return {
+ ...meta,
+ available,
+ configured: available,
+ current: isCurrent,
+ };
+ });
+ }
+
+ /**
+ * Get available providers only
+ */
+ export function getAvailableProviders(): ProviderInfo[] {
+ return getProviderList().filter((p) => p.available);
+ }
+
+ // ============================================================
+ // Display Helpers
+ // ============================================================
+
+ /**
+ * Format provider for display
+ */
+ export function formatProviderStatus(provider: ProviderInfo): string {
+ const status = provider.available ? "✓" : "✗";
+ const current = provider.current ? " (current)" : "";
+ const auth = provider.authMethod === "oauth" ? " [OAuth]" : "";
+ return `${status} ${provider.name}${auth}${current}`;
+ }
+
+ /**
+ * Get login instructions for a provider
+ */
+ export function getLoginInstructions(providerId: string): string {
+ const info = PROVIDER_REGISTRY[providerId];
+ if (!info) return `Unknown provider: ${providerId}`;
+
+ if (info.authMethod === "oauth") {
+ if (info.loginCommand) {
+ return `Run: ${info.loginCommand}\nThen restart Super Multica to use the credentials.`;
+ }
+ }
+
+ if (info.loginUrl) {
+ return `Get your API key at: ${info.loginUrl}\nThen add it to ~/.super-multica/credentials.json5`;
+ }
+
+ return "No login instructions available.";
+ }
diff --cc src/agent/runner.ts
index dfccb9bcdc,7ac62bc620..90f5416af8
--- a/src/agent/runner.ts
+++ b/src/agent/runner.ts
@@@ -3,6 -3,6 +3,7 @@@ import { v7 as uuidv7 } from "uuid"
import type { AgentOptions, AgentRunResult } from "./types.js";
import { createAgentOutput } from "./cli/output.js";
import { resolveModel, resolveTools } from "./tools.js";
++import { resolveApiKey, resolveBaseUrl, resolveModelId } from "./providers/index.js";
import { SessionManager } from "./session/session-manager.js";
import { ProfileManager } from "./profile/index.js";
import { SkillManager } from "./skills/index.js";
@@@ -155,7 -162,7 +129,9 @@@ export class Agent
const compactionMode = options.compactionMode ?? "tokens"; // 默认使用 token 模式
// 获取 API Key(用于 summary 模式)
-- const summaryApiKey = compactionMode === "summary" ? resolveApiKey(model.provider, options.apiKey) : undefined;
++ const summaryApiKey = compactionMode === "summary"
++ ? resolveApiKey(resolvedProvider, options.apiKey)
++ : undefined;
// 创建 SessionManager(带 context window 配置)
this.session = new SessionManager({
diff --cc src/hub/hub.ts
index bee58b66d0,3d1eae3bd5..3d5deb7145
--- a/src/hub/hub.ts
+++ b/src/hub/hub.ts
@@@ -23,6 -22,6 +22,8 @@@ import { createUpdateGatewayHandler } f
export class Hub {
private readonly agents = new Map<string, AsyncAgent>();
private readonly agentSenders = new Map<string, string>();
++ private readonly agentStreamIds = new Map<string, string>();
++ private readonly agentStreamCounters = new Map<string, number>();
private readonly rpc: RpcDispatcher;
private client: GatewayClient;
url: string;
@@@ -145,32 -144,31 +146,71 @@@
addAgentRecord({ id: agent.sessionId, createdAt: Date.now() });
}
- // Internally consume messages produced by agent
- // Forward streaming events to the requesting client
- agent.onStream((payload) => {
- const targetDeviceId = this.agentSenders.get(agent.sessionId);
- if (targetDeviceId) {
- this.client.send(targetDeviceId, StreamAction, payload);
- }
- });
-
- // Internally consume messages produced by agent (fallback for non-stream scenarios)
++ // Internally consume agent output (AgentEvent stream + error Messages)
void this.consumeAgent(agent);
console.log(`Agent created: ${agent.sessionId}`);
return agent;
}
++ private getMessageIdFromEvent(event: unknown): string | undefined {
++ if (!event || typeof event !== "object") return undefined;
++ const maybeMsg = (event as { message?: unknown }).message;
++ if (!maybeMsg || typeof maybeMsg !== "object") return undefined;
++ const id = (maybeMsg as { id?: unknown }).id;
++ return typeof id === "string" && id.length > 0 ? id : undefined;
++ }
++
++ private beginStream(agentId: string, event: unknown): string {
++ const explicitId = this.getMessageIdFromEvent(event);
++ if (explicitId) {
++ this.agentStreamIds.set(agentId, explicitId);
++ return explicitId;
++ }
++ const next = (this.agentStreamCounters.get(agentId) ?? 0) + 1;
++ this.agentStreamCounters.set(agentId, next);
++ const fallback = `${agentId}:${next}`;
++ this.agentStreamIds.set(agentId, fallback);
++ return fallback;
++ }
++
++ private getActiveStreamId(agentId: string, event: unknown): string {
++ return this.agentStreamIds.get(agentId) ?? this.getMessageIdFromEvent(event) ?? agentId;
++ }
++
++ private endStream(agentId: string): void {
++ this.agentStreamIds.delete(agentId);
++ }
++
/** Internally read agent output and send via Gateway */
private async consumeAgent(agent: AsyncAgent): Promise<void> {
- for await (const msg of agent.read()) {
- console.log(`[${agent.sessionId}] ${msg.content}`);
+ for await (const item of agent.read()) {
const targetDeviceId = this.agentSenders.get(agent.sessionId);
- if (targetDeviceId) {
+ if (!targetDeviceId) continue;
+
+ if ("content" in item) {
+ // Legacy Message (error fallback)
+ console.log(`[${agent.sessionId}] ${item.content}`);
this.client.send(targetDeviceId, "message", {
agentId: agent.sessionId,
- content: msg.content,
+ content: item.content,
+ });
+ } else {
++ const maybeMessage = (item as { message?: { role?: string } }).message;
++ const isAssistantMessage = maybeMessage?.role === "assistant";
++ if (item.type === "message_start" && isAssistantMessage) {
++ this.beginStream(agent.sessionId, item);
++ }
++ const streamId = this.getActiveStreamId(agent.sessionId, item);
+ // Raw AgentEvent — forward via StreamAction
- this.client.send<StreamPayload>(targetDeviceId, StreamAction, {
- streamId: agent.sessionId,
- data: item,
++ this.client.send(targetDeviceId, StreamAction, {
++ streamId,
++ agentId: agent.sessionId,
++ event: item,
});
++ if (item.type === "message_end" && isAssistantMessage) {
++ this.endStream(agent.sessionId);
++ }
}
}
}
@@@ -213,6 -211,6 +253,8 @@@
agent.close();
this.agents.delete(id);
this.agentSenders.delete(id);
++ this.agentStreamIds.delete(id);
++ this.agentStreamCounters.delete(id);
removeAgentRecord(id);
return true;
}
@@@ -221,6 -219,6 +263,9 @@@
for (const [id, agent] of this.agents) {
agent.close();
this.agents.delete(id);
++ this.agentSenders.delete(id);
++ this.agentStreamIds.delete(id);
++ this.agentStreamCounters.delete(id);
}
this.client.disconnect();
console.log("Hub shut down");