File size: 8,131 Bytes
68d7816 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 | import {
KIMI_CODE_PROVIDER_NAME,
OAuthError,
fetchChatTitle,
kimiCodeToolsUrl,
parseKimiCodeCustomHeaders,
resolveKimiCodeRuntimeAuth,
} from '@moonshot-ai/kimi-code-oauth';
import { ScopeActivation, registerScopedService } from '#/_base/di/scope';
import { LifecycleScope } from '#/app/scopes';
import { ILogService } from '#/_base/log/log';
import { IOAuthService } from '#/app/auth/auth';
import { IEventService } from '#/app/event/event';
import { IAgentLifecycleService, MAIN_AGENT_ID } from '#/session/agentLifecycle/agentLifecycle';
import { IHostRequestHeaders } from '#/llm-adapter/model/host-request-headers';
import { IProviderService } from '#/llm-adapter/provider/provider';
import { isOAuthCatalogVendor } from '#/llm-adapter/provider/provider-definition';
import { ISessionContext } from '#/session/sessionContext/sessionContext';
import { ISessionMetadata } from '#/session/sessionMetadata/sessionMetadata';
import { SessionMetaUpdated } from '#/session/sessionMetadata/sessionMetaEvents';
import { IAgentTitlePromptSource } from './agentTitlePromptSource';
import { ISessionTitleService, type SessionTitleSource } from './sessionTitle';
const MAX_GENERATED_TITLE_LENGTH = 200;
const MAX_TITLE_INPUT_LENGTH = 1000;
const MAX_TITLE_PROMPTS = 3;
const MAX_TITLE_USER_SEGMENT = 400;
const MAX_TITLE_FIRST_TURN_ASSISTANT = 300;
const MAX_TITLE_DIGEST_USER_SEGMENT = 200;
const MAX_TITLE_DIGEST_ASSISTANT = 200;
const MAX_TITLE_DIGEST_INPUT_LENGTH = 3000;
export class SessionTitleService implements ISessionTitleService {
declare readonly _serviceBrand: undefined;
private _shared: Promise<string | undefined> | undefined;
constructor(
@ISessionContext private readonly ctx: ISessionContext,
@ISessionMetadata private readonly metadata: ISessionMetadata,
@IAgentLifecycleService private readonly agentLifecycle: IAgentLifecycleService,
@IEventService private readonly eventService: IEventService,
@IProviderService private readonly providers: IProviderService,
@IOAuthService private readonly oauth: IOAuthService,
@IHostRequestHeaders private readonly hostHeaders: IHostRequestHeaders,
@ILogService private readonly log: ILogService,
) {}
async generateTitle(opts?: {
force?: boolean;
source?: SessionTitleSource;
}): Promise<string | undefined> {
const force = opts?.force === true;
const source = opts?.source ?? 'user_prompts';
if (force) return this.generateTitleOnce(true, source);
if (this._shared !== undefined) return this._shared;
const tracked = this.generateTitleOnce(false, source).finally(() => {
if (this._shared === tracked) this._shared = undefined;
});
this._shared = tracked;
return tracked;
}
private async generateTitleOnce(
force: boolean,
source: SessionTitleSource,
): Promise<string | undefined> {
const current = await this.metadata.read();
if (!force) {
if (current.titleKind === 'custom') return undefined;
if (current.titleKind === 'generated') return undefined;
}
const main = this.agentLifecycle.handleOf(MAIN_AGENT_ID);
if (main === undefined) return undefined;
const promptSource = main.accessor.get(IAgentTitlePromptSource);
const input = await composeTitleInput(promptSource, source);
if (input === undefined) return undefined;
return this.generateAndApply(input, force);
}
private async generateAndApply(
chatContent: string,
force: boolean,
): Promise<string | undefined> {
const current = await this.metadata.read();
if (!force && current.titleKind === 'custom') return undefined;
const provider = this.providers.get(KIMI_CODE_PROVIDER_NAME);
if (
provider === undefined ||
!isOAuthCatalogVendor(provider.type) ||
provider.oauth === undefined
) {
return undefined;
}
const runtimeAuth = resolveKimiCodeRuntimeAuth({
configuredBaseUrl: provider.baseUrl,
configuredOAuthRef: provider.oauth,
});
const tokenProvider = this.oauth.resolveTokenProvider(
KIMI_CODE_PROVIDER_NAME,
runtimeAuth.oauthRef,
);
if (tokenProvider === undefined) return undefined;
let token: string;
try {
token = await tokenProvider.getAccessToken();
} catch (error) {
if (!(error instanceof OAuthError)) throw error;
this.log.debug(`chat_title request unavailable: ${error.message}`);
return undefined;
}
const requestTitle = (accessToken: string) =>
fetchChatTitle(kimiCodeToolsUrl(runtimeAuth.baseUrl), accessToken, chatContent, {
headers: {
...parseKimiCodeCustomHeaders(),
...this.hostHeaders.headers,
...provider.customHeaders,
},
});
let result = await requestTitle(token);
if (result.kind === 'error' && result.status === 401) {
try {
token = await tokenProvider.getAccessToken({ force: true });
} catch (error) {
if (!(error instanceof OAuthError)) throw error;
this.log.debug(`chat_title request unavailable: ${error.message}`);
return undefined;
}
result = await requestTitle(token);
}
if (result.kind !== 'ok') {
this.log.debug(`chat_title request failed: ${result.message}`);
return undefined;
}
const title = result.title.slice(0, MAX_GENERATED_TITLE_LENGTH);
const applied = await this.metadata.setGeneratedTitleIfUncustomized(title, { force });
if (!applied) return undefined;
this.eventService.publish(
new SessionMetaUpdated({
payload: {
agentId: 'main',
sessionId: this.ctx.sessionId,
title,
patch: { title, isCustomTitle: false },
},
}),
);
return title;
}
}
function titleInputFromPrompts(prompts: readonly string[]): string | undefined {
if (prompts.length === 0) return undefined;
return prompts
.map((prompt) => `user: ${prompt.slice(0, MAX_TITLE_USER_SEGMENT)}`)
.join('\n')
.slice(0, MAX_TITLE_INPUT_LENGTH);
}
async function composeTitleInput(
promptSource: IAgentTitlePromptSource,
source: SessionTitleSource,
): Promise<string | undefined> {
if (source === 'first_turn') {
const excerpt = await promptSource.firstTurnExcerpt();
if (excerpt.user === undefined || excerpt.assistant === undefined) return undefined;
return [
`user: ${excerpt.user.slice(0, MAX_TITLE_USER_SEGMENT)}`,
`assistant: ${excerpt.assistant.slice(0, MAX_TITLE_FIRST_TURN_ASSISTANT)}`,
].join('\n');
}
if (source === 'digest') {
const excerpt = await promptSource.digestExcerpt();
const turns: string[][] = [];
for (const turn of excerpt.turns) {
const group = [`user: ${turn.user.slice(0, MAX_TITLE_DIGEST_USER_SEGMENT)}`];
if (turn.assistant !== undefined) {
group.push(`assistant: ${turn.assistant.slice(0, MAX_TITLE_DIGEST_ASSISTANT)}`);
}
turns.push(group);
}
return elideTitleDigestTurns(turns);
}
return titleInputFromPrompts(await promptSource.firstUserPrompts(MAX_TITLE_PROMPTS));
}
const TITLE_DIGEST_ELISION_MARKER = '...';
function elideTitleDigestTurns(turns: readonly (readonly string[])[]): string | undefined {
if (turns.length === 0) return undefined;
const joined = turns.flat().join('\n');
if (joined.length <= MAX_TITLE_DIGEST_INPUT_LENGTH) return joined;
let budget = MAX_TITLE_DIGEST_INPUT_LENGTH - TITLE_DIGEST_ELISION_MARKER.length - 2;
const head: string[] = [];
for (const line of turns[0]!) {
if (budget < line.length + 1) break;
head.push(line);
budget -= line.length + 1;
}
const tail: string[] = [];
for (let index = turns.length - 1; index >= 1; index--) {
const group = turns[index]!;
const cost = group.reduce((sum, line) => sum + line.length + 1, 0);
if (budget < cost) break;
tail.unshift(...group);
budget -= cost;
}
return [...head, TITLE_DIGEST_ELISION_MARKER, ...tail].join('\n');
}
registerScopedService(
LifecycleScope.Session,
ISessionTitleService,
SessionTitleService,
ScopeActivation.OnScopeCreated,
'sessionTitle',
);
|