Change branch() to use entryId instead of entryIndex

- AgentSession.branch(entryId: string) now takes entry ID
- SessionBeforeBranchEvent.entryId replaces entryIndex
- getUserMessagesForBranching() returns entryId
- Update RPC types and client
- Update UserMessageSelectorComponent
- Update hook examples and tests
- Update docs (hooks.md, sdk.md)
This commit is contained in:
Mario Zechner 2025-12-31 13:47:34 +01:00
parent 027d39aa33
commit 8e1e99ca05
12 changed files with 64 additions and 50 deletions

View file

@ -1498,21 +1498,20 @@ export class AgentSession {
}
/**
* Create a branch from a specific entry index.
* Create a branch from a specific entry.
* Emits before_branch/branch session events to hooks.
*
* @param entryIndex Index into session entries to branch from
* @param entryId ID of the entry to branch from
* @returns Object with:
* - selectedText: The text of the selected user message (for editor pre-fill)
* - cancelled: True if a hook cancelled the branch
*/
async branch(entryIndex: number): Promise<{ selectedText: string; cancelled: boolean }> {
async branch(entryId: string): Promise<{ selectedText: string; cancelled: boolean }> {
const previousSessionFile = this.sessionFile;
const entries = this.sessionManager.getEntries();
const selectedEntry = entries[entryIndex];
const selectedEntry = this.sessionManager.getEntry(entryId);
if (!selectedEntry || selectedEntry.type !== "message" || selectedEntry.message.role !== "user") {
throw new Error("Invalid entry index for branching");
throw new Error("Invalid entry ID for branching");
}
const selectedText = this._extractUserMessageText(selectedEntry.message.content);
@ -1523,7 +1522,7 @@ export class AgentSession {
if (this._hookRunner?.hasHandlers("session_before_branch")) {
const result = (await this._hookRunner.emit({
type: "session_before_branch",
entryIndex: entryIndex,
entryId,
})) as SessionBeforeBranchResult | undefined;
if (result?.cancel) {
@ -1729,18 +1728,17 @@ export class AgentSession {
/**
* Get all user messages from session for branch selector.
*/
getUserMessagesForBranching(): Array<{ entryIndex: number; text: string }> {
getUserMessagesForBranching(): Array<{ entryId: string; text: string }> {
const entries = this.sessionManager.getEntries();
const result: Array<{ entryIndex: number; text: string }> = [];
const result: Array<{ entryId: string; text: string }> = [];
for (let i = 0; i < entries.length; i++) {
const entry = entries[i];
for (const entry of entries) {
if (entry.type !== "message") continue;
if (entry.message.role !== "user") continue;
const text = this._extractUserMessageText(entry.message.content);
if (text) {
result.push({ entryIndex: i, text });
result.push({ entryId: entry.id, text });
}
}