首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >pi学习笔记-世界变化后如何重建状态

pi学习笔记-世界变化后如何重建状态

原创
作者头像
4cos90
发布于 2026-11-22 16:51:06
发布于 2026-11-22 16:51:06
30
举报

在看完之前几篇的代码之后,我们已经可以初步建立起pi的四层架构

层

用途

生命周期

session-entry

真值(append-only)

持久化

projection

模型

每次请求重建,用完即弃

context

agent-loop

在内存常驻,但是随着树操作,用projection刷新

emit event

UI/扩展

瞬态

session-> projection: buildSessionProjection ,前面几篇都是在这一层做同步操作。

context->projection->session-entry: declareToolChanges, agent loop里已见过例子,根据真实环境修正session-entry。

emit event -> 与ui层解耦,委托ui层自行处理。

现在我们找到了另外两个 session -> context 同步的方法:

代码语言:typescript
复制
// Update finalized context from the canonical session projection.
this._refreshFinalizedContext();
this._restoreToolsFromTranscript();

_refreshFinalizedContext

这个方法很简单,只有六行,做了三件事:

从Session里面重新build 一次 Projection。

把Projection里面message->id 的映射存入缓存 _entryIdsByMessage。

把context(agent.state.messages) 直接刷新成 projection.message。

代码语言:typescript
复制
    private readonly _entryIdsByMessage = new WeakMap<object, string>();
	private _refreshFinalizedContext(): void {
		const projection = this.sessionManager.buildSessionProjection();
		for (const entry of projection.entries) {
			for (const message of entry.messages) this._entryIdsByMessage.set(message, entry.sourceEntry.id);
		}
		this.agent.state.messages = projection.messages;
	}

第一眼看到 _entryIdsByMessage 有一些疑惑,但是其实这个缓存我们之前也用到过,在触发autocompact的时候,我们曾经调用的find方法找回 这条触发autocompact 的 assistanMessage的时候,就是到这个 _entryIdsByMessage 中找。

_entryIdsByMessage 的设计实际上保证了,每一个session中的entry,在projection创建的时候,都有一个对应的实例,而反过来当我们持有了这个实例,也一定能反过来找到对应的entry(如果找不到的话说明这个entry未存入session里,也就是正在流式输出的过程中状态,修复方式是给一个宽容的true,找到的话再比对这个entry的type是不是assistant)。

代码语言:typescript
复制
const assistantEntryId = this._findPersistedMessageEntryId(assistantMessage);
const assistantIsProjected =
	assistantEntryId === undefined ||
	currentProjection.entries.some(
		(entry) =>
			entry.sourceEntry.id === assistantEntryId &&
			entry.messages.some((message) => message.role === "assistant"),
	);

_restoreToolsFromTranscript

这个方法的功能 看起来是和 declareToolChanges 是类似的。

declareToolChanges 的功能是读取 session-entry 中的工具集,根据当前环境,修正成最终的tools,然后 覆写最后一条/追加一条 systemMessage,来对齐session和context.tools。

_restoreToolsFromTranscript 的功能是读取 session-entry 中的工具集,然后将当前环境的工具集,向着session-entry声明的工具集进行修正。

在进行一些session tree上的操作,重建会话后,工具集当然很有可能发生改变(the world may have changed while you were awaiting)。 这个方法就是为了对齐tools的变化。

代码语言:typescript
复制
	/**
	 * Restore the active tool loadout declared by the session transcript, if it declares one.
	 * Tools reachable only from other tools are never declared, but they do not depend on the active
	 * set, so the transcript's declarations are the whole loadout.
	 * @param modifiers `+name`/`-name` entries applied to the restored loadout.
	 */
	private _restoreToolsFromTranscript(modifiers: readonly string[] = []): void {
		this._pendingToolNames.clear();
		this._restoredToolNames.clear();
		// All system messages on the branch, including those before a compaction. Compaction snapshots
		// are derived from these, so replaying them gives the current loadout.
		const systemMessages = this.sessionManager
			.getBranch()
			.flatMap((entry) => (entry.type === "message" && entry.message.role === "system" ? [entry.message] : []));
		// No recorded loadout: keep the current tools.
		if (systemMessages.length === 0) return;
		// Tools the branch ever added or removed. Removed tools stay inactive.
		const mentioned = new Set(
			systemMessages
				.flatMap((message) => [...(message.toolsAdded ?? []), ...(message.toolsRemoved ?? [])])
				.map((tool) => tool.name),
		);
		// Extension tools the branch never mentioned were registered after it recorded its loadout, so
		// they are activated like newly registered tools. Built-in tools follow `defaultTools` instead.
		const newTools = [...this._toolRegistry.keys()].filter(
			(name) =>
				!mentioned.has(name) && !this._baseToolDefinitions.has(name) && this._isActivatedOnRegistration(name),
		);
		// The recorded loadout plus the new tools, with `--tools +name`/`-name` applied.
		const names = applyToolModifiers(
			[...getCurrentTools(systemMessages).map((tool) => tool.name), ...newTools],
			modifiers,
		);
		// Recorded tools that are not registered yet, such as MCP tools of servers still connecting, are
		// activated when they register. Excluded tools never register, so they are not kept pending.
		this._pendingToolNames = new Set(names.filter((name) => this._isAllowedTool(name)));
		this._restoredToolNames = new Set(
			applyToolModifiers(
				getCurrentTools(systemMessages).map((tool) => tool.name),
				modifiers,
			),
		);
		// Ignores names that are not registered.
		this._setActiveTools(names);
	}

systemMessages :从session中提取 systemMessages(声明工具变化) 的 entry。

mentioned:从systemMessages中提取出所有新增或者删除过的工具(在session中提到过的):

newTools: session中从未提到过,但是当前环境有安装的tools。

names:从 getCurrentTools(systemMessages) 中提取system中声明的tools(新增-删除)+ newTools(环境新装的tools) + modifiers(显式声明的tools变更) 三者合并计算得出最终的tools。

这个 modifiers 的case 我读到也是有一些疑虑的,用+代表增加工具,-代表减少工具 看起来是一个硬编码。

查了一下代码这个 + - 来自CLI参数,这种双符号 mini-DSL 是 Unix 的老传统(chmod +x、git push +refspec、包管理器的 +pkg)。好吧我没有意见了。

代码语言:typescript
复制
/**
 * Apply the `+name` and `-name` entries of `entries` to `base` in order: `+name` adds a tool and
 * `-name` removes one. Other entries are ignored.
 */
export function applyToolModifiers(base: readonly string[], entries: readonly string[]): string[] {
	const tools = [...base];
	for (const entry of entries) {
		if (!isToolModifier(entry)) continue;
		const name = entry.slice(1);
		const index = tools.indexOf(name);
		if (entry.startsWith("+") && index === -1 && name) tools.push(name);
		else if (entry.startsWith("-") && index !== -1) tools.splice(index, 1);
	}
	return tools;
}

_pendingToolNames 代表当前应该有,但还没有的tools(比如 MCP 服务器还在连接中),在this._setActiveTools(names) 时,会通过_applyToolLoadout 检查工具是否生效,如果已生效从 _pendingToolNames 中delete。未生效的留在 pending,等未来的注册事件(MCP 连上)触发兑现。

代码语言:typescript
复制
	private _setActiveTools(toolNames: string[]): void {
		const tools = this._applyToolLoadout(toolNames);
		for (const tool of tools) this._pendingToolNames.delete(tool.name);
		this._rebuildSystemPrompt(tools.map((tool) => tool.name));
	}

_restoredToolNames 代表这个session中声明的工具集合,当用户手动停用这个集合中的工具时,也意味着用户主动放弃了_pendingToolNames 中仍在等待连接的工具,将以用户可见的tools作为当前可用的工具(主动对齐用户可见范围) 。

代码语言:typescript
复制
	/**
	 * Set active tools by name.
	 * Only tools in the registry can be enabled. Unknown and hidden tool names are ignored.
	 * Also rebuilds the system prompt to reflect the new tool set.
	 * Changes take effect on the next agent turn.
	 */
	setActiveToolsByName(toolNames: string[]): void {
		const previous = this.getActiveToolNames();
		this._setActiveTools(toolNames);
		// A loadout that deactivates a tool of the restored one replaces it, and its pending tools are
		// dropped. One that only adds tools, like activating tool_search, keeps them, and so does one
		// that only deactivates tools outside the restored loadout, such as an extension's own tool that
		// the restore or reload activated as newly registered.
		const active = new Set(this.getActiveToolNames());
		if (previous.some((name) => !active.has(name) && this._restoredToolNames.has(name))) {
			this._pendingToolNames.clear();
		}
	}

_rebuildSystemPrompt

根据 names 中最终 Loadout 的tools,生成system prompt。

乍一读好像工具发生变更后,system prompt就会发生变化,会破坏前缀缓存。

幸好并非如此:

在发送systemprompt的时候,会对新旧的SystemPrompt做一次diff,然后只是将变化的部分生成一条system消息,作为updateMessage发送。

代码语言:typescript
复制
    const updateMessage = this._preparePromptAndToolLoadout(result.systemPromptOptions);
	/**
	 * Apply a prompt and tool loadout for the next request. Sets the executable tools and
	 * returns a system message patching the prompt sections the model currently has (replayed
	 * from `messages`), or undefined when the prompt is unchanged. Tool changes are declared by
	 * the agent loop before the request.
	 *
	 * A forced prompt does not affect the transcript: the structured sections are still diffed
	 * and persisted, and the forced text is projected onto the request by
	 * {@link _installAgentForcedPromptProjection}.
	 */
	private _preparePromptAndToolLoadout(
		options: NormalizedBuildSystemPromptOptions,
		messages: AgentMessage[] = this.agent.state.messages,
	): SystemMessage | undefined {
		options.selectedTools = this._applyToolLoadout(options.selectedTools).map((tool) => tool.name);
		// The tool list and rules must match the declarations the request carries.
		options.hiddenTools = [...this._hiddenDeclarations];
		const sections = diffSystemPromptSections(
			getCurrentSystemMessage(messages)?.sections ?? {},
			buildSystemPromptSections(options),
		);
		return sections ? { role: "system", content: "", sections, timestamp: Date.now() } : undefined;
	}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

目录
  • _refreshFinalizedContext
  • _restoreToolsFromTranscript
  • _rebuildSystemPrompt
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档