Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(teammates): deliver current baseline to resumed Codex chats
zqchris89570d07bcce
diff --git a/apps/desktop/src/main/maker-ipc/teammateGuide.ts b/apps/desktop/src/main/maker-ipc/teammateGuide.tsindex d162ed9435..8fb35343bb 100644--- a/apps/desktop/src/main/maker-ipc/teammateGuide.ts+++ b/apps/desktop/src/main/maker-ipc/teammateGuide.ts@@ -23,6 +23,7 @@ export function buildTeammateGuide('The application in this guide is the host providing teammate, task and settings tools, not the model provider or agent CLI. Use the host tools for these operations; provider documentation cannot tell you the application’s current settings or available controls.',...(helperAvailable ? [TEAMMATE_CONTROL_GUIDANCE,+ 'The preloaded teammate-guide is itself your shared baseline Skill. When asked which Skills or capabilities you have, identify this shared Skill, query `list_teammate_skills` for personal Skills, and distinguish those from optional external references returned by `get_teammate_state`. Empty references or an empty personal shelf never mean that you lack the shared teammate Skill or its operating procedures.','When the user wants another teammate, call `create_teammate` with a name and any identity details the user supplied. New teammates receive this same baseline and follow the user’s available default model; do not generate a fixed number of role Skills, prewrite a greeting, or require a profile form. Their personality, personal learning and memory remain independent.','When the user asks to change the application’s default model, use `get_app_default_model` to read the actual current selection and enabled options, then `set_app_default_model` with the returned id and a supported effort if requested. Check the confirmed result. This changes the same default used by new tasks and following teammates; it does not overwrite existing task choices or explicit teammate/global teammate chains. Do not use this global setter when asked to change only this teammate, edit configuration files, guess providers, enable hidden models, or call an auxiliary model.',`Use direct teammate tools for your own memory, Skills and teammates. When work needs another capability, use \`find_teammate_capabilities\` through the helper’s teammate tools to search existing Skills, MCP connections or built-in tools, then \`set_teammate_capability\` to join it. References reuse existing installations and authorization; do not copy credentials or edit shared sources. New mounts take effect next turn in this same task.${pluginGuidance} Discover only what the work needs; do not repeatedly list the whole tool surface.`,diff --git a/packages/lizi-mcps/src/xdt-helper/bot_capabilities.ts b/packages/lizi-mcps/src/xdt-helper/bot_capabilities.tsindex c957311022..7f2cc7bfa4 100644--- a/packages/lizi-mcps/src/xdt-helper/bot_capabilities.ts+++ b/packages/lizi-mcps/src/xdt-helper/bot_capabilities.ts@@ -64,6 +64,7 @@ export interface BotControlState {/** Same instructions in the runtime baseline and tool descriptions. */export const TEAMMATE_CONTROL_GUIDANCE = ['Use `get_teammate_state` to inspect your current profile, stable chat, configured model candidates, memory switch and capability references. Candidates and selected references are not proof of the model or tools running this turn; the live runtime and registered tools are authoritative.',+ 'The references arrays contain optional external grants, not the shared teammate guide or your personal Skill shelf. Empty references do not mean you have no Skills. Use `list_teammate_skills` to inspect personal Skills; report the preloaded shared guide separately.','Use `update_teammate_profile` only when the user asks to change your name, introduction or identity; read the current version first and patch only the requested fields. Changes apply next turn without replacing memory, Skills, model settings or chat history.','Use `get_capabilities` for application features and UI guidance. It describes the product, not a permission grant or proof that every feature is available here. Use the matching live tool to act, and verify its result before claiming success.',].join('\n');diff --git a/packages/maker-core/src/agents/codex/app-server/protocol.ts b/packages/maker-core/src/agents/codex/app-server/protocol.tsindex 52f87460b8..f2f091a220 100644--- a/packages/maker-core/src/agents/codex/app-server/protocol.ts+++ b/packages/maker-core/src/agents/codex/app-server/protocol.ts@@ -1224,6 +1224,7 @@ export const Method = {SkillsList: 'skills/list',ThreadStart: 'thread/start',ThreadResume: 'thread/resume',+ ThreadInjectItems: 'thread/inject_items',ThreadFork: 'thread/fork',ThreadRollback: 'thread/rollback',ThreadTurnsList: 'thread/turns/list',diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex f336adc26c..2f0400df3e 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -5384,6 +5384,47 @@ describe('CodexAgent.startSession developerInstructions', () => {await handle.close();});+ it.each([false, true])('requires current teammate baseline delivery on native resume (injection rejected: %s)', async (rejectInjection) => {+ const agent = new CodexAgent(createDeps({}));+ const host = installFakeHost(agent, method => {+ if (method !== Method.ThreadInjectItems) return undefined;+ if (rejectInjection) throw new Error('instruction injection rejected');+ return {};+ }, { userAgent: 'mock-codex/0.153.4' });+ const started = agent.startSession({+ sessionId: 'old-teammate', resumeSessionId: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',+ codexHistoryHasProductPrompt: true,+ workingDir: '/repo', model: 'gpt-5.6-luna', providerId: 'openai', effort: 'medium',+ botProfilePrompt: 'EXISTING USER PERSONA', botProfileContextPrompt: 'CURRENT TEAMMATE GUIDE',+ botRuntimeProfile: {+ botId: 'old', profileVersion: 5,+ skillPolicy: { mode: 'allowlist', configured: [], catalog: [] },+ mcpPolicy: { mode: 'allowlist', configured: [], catalog: [] },+ toolsetPolicy: { mode: 'allowlist', configured: [], catalog: [] },+ },+ });+ if (rejectInjection) {+ await expect(started).rejects.toThrow('instruction injection rejected');+ expect(host.request.mock.calls.some(([method]) => method === Method.ThreadStart || method === Method.TurnStart)).toBe(false);+ return;+ }+ const handle = await started;+ const calls = host.request.mock.calls;+ const resume = calls.findIndex(([method]) => method === Method.ThreadResume);+ const inject = calls.findIndex(([method]) => method === Method.ThreadInjectItems);+ expect(inject).toBeGreaterThan(resume);+ expect((calls[resume][1] as { developerInstructions?: string }).developerInstructions).toContain('CURRENT TEAMMATE GUIDE');+ expect(calls.some(([method]) => method === Method.ThreadStart)).toBe(false);+ expect(calls.some(([method]) => method === Method.TurnStart)).toBe(false);+ const params = calls[inject][1] as { threadId: string; items: Array<{ role: string; content: Array<{ text: string }> }> };+ expect(params.threadId).toBe('resume-thread-id');+ expect(params.items[0].role).toBe('developer');+ expect(params.items[0].content[0].text).toContain('CURRENT TEAMMATE GUIDE');+ expect(params.items[0].content[0].text).toContain('EXISTING USER PERSONA');+ expect(handle.codexProductPromptDelivery).toEqual({ threadId: 'resume-thread-id', historyHasProductPrompt: true });+ await handle.close();+ });+it('keeps thread/start developerInstructions identical to proxy resume registered text for the same prompt inputs', async () => {const runtimeConfig = { systemPrompt: 'HOST PRODUCT PROMPT' };const userPrompt = [diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex b560c93d65..af46f0cc66 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -183,6 +183,7 @@ import {readCodexRolloutModelProvider,sanitizeCodexForkRolloutFileInPlace,} from './rollout-sanitize.js';+import { hasCurrentTeammateInstructions, teammateRuntimeInstructionItem } from './teammate-runtime-instructions.js';import { CodexHistoryRecoveryRequiredError, isCodexHistoryRecoveryRequired } from './history-recovery.js';import { CodexForkError, type CodexForkStage } from './fork-error.js';import { resolveForkTurnAnchor } from './fork-turn-anchor.js';@@ -3213,7 +3214,7 @@ export class CodexAgent extends BaseAgent {// ── Maker Memory: 启动时预拉 MEMORY.md 索引 + 写入规范段 ────────────────// thread/start 仍把 developerInstructions 写入新 thread; thread/resume 在普通非 proxy// 路径只在 host 明确告知历史未含产品 prompt 时补发一次,避免常规 resume 重复堆积。- // WS thread 恢复时则始终携带当前值:Codex 的 SessionMeta 不持久化该字段,冷恢复若只+ // WS 与 teammate thread 恢复时始终携带当前值:Codex 的 SessionMeta 不持久化该字段,冷恢复若只// 依赖历史里的旧 developer message,后续 compact 重建 canonical context 时会丢产品// prompt。Codex 0.145 对仍在内存中的 loaded thread 会忽略 resume override,且冷恢复// 首轮的 steady-state diff 不补一条发生变化的 plain developer_instructions;正常@@ -6186,7 +6187,7 @@ export class CodexAgent extends BaseAgent {const shouldSendNativeDeveloperInstructions =!!developerInstructions&& !useProxyChannel- && (threadUsesWebSocket || opts.codexHistoryHasProductPrompt !== true);+ && (!!opts.botRuntimeProfile || threadUsesWebSocket || opts.codexHistoryHasProductPrompt !== true);const params: ThreadResumeParams = {threadId: opts.resumeSessionId,...(preparedResumePath ? { path: preparedResumePath } : {}),@@ -6233,6 +6234,21 @@ export class CodexAgent extends BaseAgent {workspacePermissionProfileActive = currentWorkspacePermissionProfile() !== undefined;workspacePermissionProfileFingerprint = currentWorkspacePermissionProfileFingerprint();threadMayHaveRollout = true;+ // A historical developer message is not evidence that the current teammate+ // baseline reached the model. Native resume overrides update configuration,+ // but do not replace old model-visible instructions. Append through the+ // native history API before exposing the refreshed runtime as ready.+ if (opts.botRuntimeProfile && developerInstructions && !useProxyChannel) {+ const current = teammateRuntimeInstructionItem(developerInstructions);+ if (!await hasCurrentTeammateInstructions(opts.remoteHostId ? undefined : sessionRolloutPath, current.marker)) {+ assertCurrentHost('thread/inject_items');+ await host.request(Method.ThreadInjectItems, { threadId, items: [current.item] }, {+ timeoutMs: CRITICAL_THREAD_RPC_TIMEOUT_MS,+ });+ assertCurrentHost('thread/inject_items');+ }+ codexProductPromptDelivery = { threadId, historyHasProductPrompt: true };+ }// Resumed app-server threads may have sticky collaborationMode='plan' from// a previous handle whose plan cycle ended without a follow-up turn. Since// that sticky state lives server-side, conservatively send mode:'default'diff --git a/packages/maker-core/src/agents/codex/teammate-runtime-instructions.test.ts b/packages/maker-core/src/agents/codex/teammate-runtime-instructions.test.tsnew file mode 100644index 0000000000..51711c5e4a--- /dev/null+++ b/packages/maker-core/src/agents/codex/teammate-runtime-instructions.test.ts@@ -0,0 +1,41 @@+import { mkdtemp, writeFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, beforeEach, expect, it } from 'vitest';+import { hasCurrentTeammateInstructions, teammateRuntimeInstructionItem } from './teammate-runtime-instructions';+let root: string;+let file: string;+beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'teammate-runtime-context-')); file = join(root, 'rollout.jsonl'); });+afterEach(async () => { await rm(root, { recursive: true, force: true }); });+const entry = (text: string) => JSON.stringify({ type: 'response_item', payload: teammateRuntimeInstructionItem(text).item }) + '\n';+it('requires delivery for an old thread whose historical prompt has no baseline', async () => {+ await writeFile(file, JSON.stringify({ type: 'response_item', payload: { role: 'developer', content: [{ text: 'OLD PERSONA ONLY' }] } }) + '\n');+ expect(await hasCurrentTeammateInstructions(file, teammateRuntimeInstructionItem('CURRENT BASELINE').marker)).toBe(false);+});+it('deduplicates the same generation but refreshes changed instructions', async () => {+ await writeFile(file, entry('BASELINE A'));+ expect(await hasCurrentTeammateInstructions(file, teammateRuntimeInstructionItem('BASELINE A').marker)).toBe(true);+ expect(await hasCurrentTeammateInstructions(file, teammateRuntimeInstructionItem('BASELINE B').marker)).toBe(false);+ await writeFile(file, entry('BASELINE A') + entry('BASELINE B'));+ expect(await hasCurrentTeammateInstructions(file, teammateRuntimeInstructionItem('BASELINE A').marker)).toBe(false);+});+it('does not trust a user or tool echo as a delivery receipt', async () => {+ const item = teammateRuntimeInstructionItem('BASELINE').item;+ await writeFile(file, JSON.stringify({ type: 'response_item', payload: { ...item, role: 'user' } }) + '\n');+ expect(await hasCurrentTeammateInstructions(file, teammateRuntimeInstructionItem('BASELINE').marker)).toBe(false);+});+it('re-delivers when the proof is absent, compacted or outside the bounded tail', async () => {+ const marker = teammateRuntimeInstructionItem('BASELINE').marker;+ expect(await hasCurrentTeammateInstructions(undefined, marker)).toBe(false);+ expect(await hasCurrentTeammateInstructions(file, marker)).toBe(false);+ await writeFile(file, entry('BASELINE') + JSON.stringify({ type: 'compacted', payload: { message: 'x'.repeat(300000) } }) + '\n');+ expect(await hasCurrentTeammateInstructions(file, marker)).toBe(false);+});++it('does not accept a delivery marker from before a compaction boundary', async () => {+ const marker = teammateRuntimeInstructionItem('BASELINE').marker;+ await writeFile(file, entry('BASELINE') + JSON.stringify({ type: 'compacted', payload: { message: 'brief summary' } }) + '\n');+ expect(await hasCurrentTeammateInstructions(file, marker)).toBe(false);+ await writeFile(file, JSON.stringify({ type: 'compacted', payload: { message: 'brief summary' } }) + '\n' + entry('BASELINE'));+ expect(await hasCurrentTeammateInstructions(file, marker)).toBe(true);+});diff --git a/packages/maker-core/src/agents/codex/teammate-runtime-instructions.ts b/packages/maker-core/src/agents/codex/teammate-runtime-instructions.tsnew file mode 100644index 0000000000..f8be9f0b50--- /dev/null+++ b/packages/maker-core/src/agents/codex/teammate-runtime-instructions.ts@@ -0,0 +1,46 @@+import { createHash } from 'node:crypto';+import { open } from 'node:fs/promises';++const PREFIX = '<!-- teammate-runtime-context:';+const TAIL_BYTES = 256 * 1024;++/** Native resume config alone does not replace the developer items in a historical thread. */+export function teammateRuntimeInstructionItem(instructions: string) {+ const hash = createHash('sha256').update(instructions).digest('hex');+ const marker = `${PREFIX}${hash} -->`;+ return {+ marker,+ item: {+ type: 'message', role: 'developer',+ content: [{ type: 'input_text', text: `${marker}\nCurrent teammate runtime instructions replace earlier host-provided teammate operating instructions and capability snapshots. Conversation history remains intact.\n\n${instructions}` }],+ },+ };+}++/** Bounded dedupe only. A missing/compacted/unreadable marker means re-deliver, never skip the guide. */+export async function hasCurrentTeammateInstructions(rolloutPath: string | undefined, marker: string): Promise<boolean> {+ if (!rolloutPath) return false;+ let file;+ try {+ file = await open(rolloutPath, 'r');+ const { size } = await file.stat();+ const start = Math.max(0, size - TAIL_BYTES);+ const bytes = Buffer.alloc(size - start);+ const { bytesRead } = await file.read(bytes, 0, bytes.length, start);+ const lines = bytes.subarray(0, bytesRead).toString('utf8').split('\n');+ if (start > 0) lines.shift();+ for (let i = lines.length - 1; i >= 0; i--) {+ let row;+ try { row = JSON.parse(lines[i]); } catch { continue; }+ if (row.type === 'compacted') return false;+ if (row.type !== 'response_item' || row.payload?.role !== 'developer') continue;+ const text = (row.payload.content ?? []).map((part: { text?: string }) => part.text ?? '').join('\n');+ if (text.startsWith(PREFIX)) return text.startsWith(`${marker}\n`);+ }+ return false;+ } catch {+ return false;+ } finally {+ await file?.close();+ }+}