Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🐘 fix: Preserve Authored Skills Across Approval Resumes (#17630)
lia-by-librechat[bot]3d3edaff01c4
diff --git a/api/server/controllers/agents/__tests__/resume.spec.js b/api/server/controllers/agents/__tests__/resume.spec.jsindex b5baf0c4a7..b995483df7 100644--- a/api/server/controllers/agents/__tests__/resume.spec.js+++ b/api/server/controllers/agents/__tests__/resume.spec.js@@ -3389,6 +3389,22 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => {expect(client.resumeCompletion).toHaveBeenCalledWith(expect.objectContaining({ runSteps }));});+ it('restores authored skills only from the claimed generation metadata', async () => {+ const authoredSkills = [+ { agentId: 'agent-1', name: 'new-skill', id: '507f1f77bcf86cd799439011', primed: true },+ ];+ mockGenerationJobManager.getJob.mockResolvedValue(+ makeToolApprovalJob({ metadata: { authoredSkills } }),+ );+ await post({ ...approveBody(), authoredSkills: [{ name: 'untrusted' }] });+ await settled;+ await flush();+ const client = await mockInitializeClient.mock.results[0].value.then((r) => r.client);+ expect(client.resumeCompletion).toHaveBeenCalledWith(+ expect.objectContaining({ authoredSkills }),+ );+ });+it('reapplies retained ask answers before resuming a later tool approval', async () => {mockGenerationJobManager.getJob.mockResolvedValue(makeToolApprovalJob({diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.jsindex 110d695da9..142688d369 100644--- a/api/server/controllers/agents/client.js+++ b/api/server/controllers/agents/client.js@@ -1,3 +1,4 @@+const { GraphEvents } = require('@librechat/agents');const { getMCPRequestContext } = require('~/server/services/MCPRequestContext');require('events').EventEmitter.defaultMaxListeners = 100;const { logger, MAX_AGENT_EVENT_ACTOR_ENCODING_LENGTH } = require('@librechat/data-schemas');@@ -51,6 +52,8 @@ const {computeAgentRequestFingerprint,computeLegacyAgentRequestFingerprint,getRunDiscoveredTools,+ captureAuthoredSkills,+ restoreAuthoredSkills,captureResumeModelParameters,pickResumeContext,getApprovalTtlMs,@@ -4225,6 +4228,7 @@ class AgentClient extends BaseClient {const pauseProjection = {expectedCreatedAt: this.jobCreatedAt,...(staged.discoveredTools.length > 0 ? { discoveredTools: staged.discoveredTools } : {}),+ authoredSkills: staged.authoredSkills,...(staged.activityPhaseSnapshot == null? {}: { activityPhaseSnapshot: staged.activityPhaseSnapshot }),@@ -4525,6 +4529,9 @@ class AgentClient extends BaseClient {interruptId: interrupt.interruptId,interruptType: interrupt.payload.type,discoveredTools,+ authoredSkills: captureAuthoredSkills(+ this.options.eventHandlers?.[GraphEvents.ON_TOOL_EXECUTE],+ ),activityPhaseSnapshot: this.activityPhaseWiring?.snapshot?.(),compactionSemanticIndex: createCompactionSemanticIndexProjection(this.compactionSemanticIndexSnapshot,@@ -5431,9 +5438,14 @@ class AgentClient extends BaseClient {commandOptions,userMCPAuthMap,discoveredToolNames,+ authoredSkills,activityPhaseSnapshot,compactionSemanticIndex,}) {+ restoreAuthoredSkills(+ this.options.eventHandlers?.[GraphEvents.ON_TOOL_EXECUTE],+ authoredSkills,+ );/** The seeded state is on the job before the run is rebuilt, so a Stop* during rebuild still persists it onto the stopped response. */await this.publishRunContextMeta?.();diff --git a/api/server/controllers/agents/client.test.js b/api/server/controllers/agents/client.test.jsindex a7a7754baa..a22ebf9ef3 100644--- a/api/server/controllers/agents/client.test.js+++ b/api/server/controllers/agents/client.test.js@@ -25,6 +25,7 @@ const { Constants, ContentTypes, EModelEndpoint, ErrorTypes } = require('librechconst {GenerationJobManager,createStreamServices,+ createToolExecuteHandler,registerToolApprovalHook,clearToolApprovalHooks,getPluginHookSource,@@ -1083,6 +1084,46 @@ describe('AgentClient - interrupt discovery persistence', () => {});it('makes the run discovery snapshot durable when the run pauses', async () => {+ const skillId = new (require('mongoose').Types.ObjectId)();+ const authoredSkill = { _id: skillId, name: 'new-skill', body: '# Authored', version: 1 };+ const authorReq = {+ user: { id: 'user-123', _id: new (require('mongoose').Types.ObjectId)() },+ config: {},+ };+ const toolHandler = createToolExecuteHandler({+ loadTools: async () => ({+ loadedTools: [],+ configurable: {+ req: authorReq,+ accessibleSkillIds: [],+ skillAuthoringAvailable: true,+ fileAuthoringToolNames: new Set(['create_file', 'edit_file']),+ },+ }),+ getSkillByName: async () => null,+ canCreateSkill: async () => true,+ createSkill: async () => ({ skill: authoredSkill, warnings: [] }),+ grantSkillOwner: async () => undefined,+ });+ const [created] = await new Promise((resolve, reject) =>+ toolHandler.handle('on_tool_execute', {+ agentId: 'agent-123',+ configurable: { req: authorReq },+ toolCalls: [+ {+ id: 'create-skill',+ name: 'create_file',+ args: {+ path: 'skills/new-skill/SKILL.md',+ content: '---\nname: new-skill\ndescription: Resume\n---\n# Authored\n',+ },+ },+ ],+ resolve,+ reject,+ }),+ );+ expect(created.status).toBe('success');const streamId = 'conversation-discovered-pause';const job = await GenerationJobManager.createJob(streamId, 'user-123', streamId);const client = new AgentClient({@@ -1103,6 +1144,7 @@ describe('AgentClient - interrupt discovery persistence', () => {artifactPromises: [],});client.conversationId = streamId;+ client.options.eventHandlers = { on_tool_execute: toolHandler };client.responseMessageId = 'response-discovered-pause';client.jobCreatedAt = job.createdAt;client.compactionSemanticIndexSnapshot = {@@ -1138,6 +1180,14 @@ describe('AgentClient - interrupt discovery persistence', () => {const paused = await GenerationJobManager.getJob(streamId);expect(paused?.status).toBe('requires_action');expect(paused?.metadata.discoveredTools).toEqual(['save_issue_mcp_linear']);+ expect(paused?.metadata.authoredSkills).toEqual([+ {+ agentId: 'agent-123',+ name: 'new-skill',+ id: skillId.toString(),+ primed: true,+ },+ ]);expect(paused?.metadata.compactionSemanticIndex).toEqual({version: 1,entries: client.compactionSemanticIndexSnapshot.entries,diff --git a/api/server/controllers/agents/resume.js b/api/server/controllers/agents/resume.jsindex 19155a606b..545b2a3844 100644--- a/api/server/controllers/agents/resume.js+++ b/api/server/controllers/agents/resume.js@@ -2003,6 +2003,7 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle)// Replay deferred tools discovered before the pause (captured at pause). The rebuilt// graph passes `messages: []`, so without these the model would lose their schemas.discoveredToolNames: job.metadata?.discoveredTools,+ authoredSkills: job.metadata?.authoredSkills,activityPhaseSnapshot: job.metadata?.activityPhaseSnapshot,compactionSemanticIndex: job.metadata?.compactionSemanticIndex,});diff --git a/packages/api/src/agents/authored.spec.ts b/packages/api/src/agents/authored.spec.tsnew file mode 100644index 0000000000..7acff8f575--- /dev/null+++ b/packages/api/src/agents/authored.spec.ts@@ -0,0 +1,42 @@+import { AuthoredSkillState, captureAuthoredSkills, restoreAuthoredSkills } from './authored';++const id = '507f1f77bcf86cd799439011';+const handler = () => ({ handle: jest.fn() });++test('keeps authoring scopes separate and preserves unconsumed bindings across re-pause', () => {+ const original = new AuthoredSkillState();+ const first = handler();+ original.bind(first);+ original.record({ agentId: 'a', executionId: 'child-1' }, { name: 'created', id, primed: true });+ const snapshot = captureAuthoredSkills(first);+ const resumed = new AuthoredSkillState();+ const second = handler();+ resumed.bind(second);+ restoreAuthoredSkills(second, JSON.parse(JSON.stringify(snapshot)));+ expect(resumed.take({ agentId: 'b', executionId: 'child-1' }, new Set(['created']))).toEqual([]);+ expect(resumed.take({ agentId: 'a', executionId: 'child-2' }, new Set(['created']))).toEqual([]);+ expect(resumed.take({ agentId: 'a' }, new Set(['created']))).toEqual([]);+ expect(captureAuthoredSkills(second)).toEqual(snapshot);+ expect(resumed.take({ agentId: 'a', executionId: 'child-1' }, new Set(['created']))).toEqual(+ snapshot,+ );+ resumed.confirm({ agentId: 'a', executionId: 'child-1' }, 'created');+ expect(resumed.take({ agentId: 'a', executionId: 'child-1' }, new Set(['created']))).toEqual([]);+ snapshot[0].name = 'mutated';+ expect(captureAuthoredSkills(first)[0].name).toBe('created');+});++test('does not downgrade an existing prime during same-author recovery', () => {+ const state = new AuthoredSkillState();+ state.record({ agentId: 'a' }, { name: 'created', id, primed: true });+ state.record({ agentId: 'a' }, { name: 'created', id, primed: false });+ expect(state.snapshot()[0].primed).toBe(true);+});++test('round-trips every valid name shape accepted by skill authoring', () => {+ const original = new AuthoredSkillState();+ original.record({ agentId: 'a' }, { name: 'valid--name-', id, primed: false });+ const resumed = new AuthoredSkillState();+ resumed.restore(original.snapshot());+ expect(resumed.snapshot()).toEqual(original.snapshot());+});diff --git a/packages/api/src/agents/authored.ts b/packages/api/src/agents/authored.tsnew file mode 100644index 0000000000..c058b0aa40--- /dev/null+++ b/packages/api/src/agents/authored.ts@@ -0,0 +1,99 @@+import { SKILL_NAME_PATTERN } from 'librechat-data-provider';+import type { EventHandler, SubagentExecutionContext } from '@librechat/agents';++/** Server-owned identity, not skill content or permission grants. */+export interface AuthoredSkillBinding {+ agentId: string;+ executionId?: string;+ name: string;+ id: string;+ primed: boolean;+}++type Scope = Pick<AuthoredSkillBinding, 'agentId' | 'executionId'>;++const states = new WeakMap<EventHandler, AuthoredSkillState>();++export function captureAuthoredSkills(handler?: EventHandler): AuthoredSkillBinding[] {+ return handler == null ? [] : (states.get(handler)?.snapshot() ?? []);+}++export function restoreAuthoredSkills(+ handler: EventHandler | undefined,+ bindings: readonly AuthoredSkillBinding[] | undefined,+): void {+ if (handler != null && bindings != null) states.get(handler)?.restore(bindings);+}++/** One handler belongs to one authenticated generation segment. */+export class AuthoredSkillState {+ private readonly bindings = new Map<string, AuthoredSkillBinding>();+ private readonly pending = new Map<string, AuthoredSkillBinding>();++ bind(handler: EventHandler): void {+ states.set(handler, this);+ }++ scope(agentId?: string, context?: SubagentExecutionContext): Scope {+ return {+ agentId: agentId ?? '',+ executionId: context?.ancestry[context.ancestry.length - 1]?.subagentRunId,+ };+ }++ private key(scope: Scope, name?: string): string {+ return JSON.stringify([scope.agentId, scope.executionId ?? null, name ?? null]);+ }++ record(scope: Scope, binding: Pick<AuthoredSkillBinding, 'name' | 'id' | 'primed'>): void {+ const key = this.key(scope, binding.name);+ const previous = this.bindings.get(key);+ this.bindings.set(key, {+ ...scope,+ ...binding,+ primed: binding.primed || (previous?.id === binding.id && previous.primed === true),+ });+ }++ snapshot(): AuthoredSkillBinding[] {+ return [...this.bindings.values()].map((binding) => ({ ...binding }));+ }++ restore(bindings: readonly AuthoredSkillBinding[]): void {+ for (const binding of bindings) {+ if (+ typeof binding.agentId !== 'string' ||+ (binding.executionId != null && typeof binding.executionId !== 'string') ||+ typeof binding.name !== 'string' ||+ !SKILL_NAME_PATTERN.test(binding.name) ||+ typeof binding.id !== 'string' ||+ !/^[a-f0-9]{24}$/i.test(binding.id)+ ) {+ continue;+ }+ const copy = { ...binding, primed: binding.primed === true };+ const key = this.key(copy, copy.name);+ this.bindings.set(key, copy);+ this.pending.set(key, copy);+ }+ }++ get hasPending(): boolean {+ return this.pending.size > 0;+ }++ confirm(scope: Scope, name: string): void {+ this.pending.delete(this.key(scope, name));+ }++ take(scope: Scope, names: ReadonlySet<string>): AuthoredSkillBinding[] {+ const bindings: AuthoredSkillBinding[] = [];+ for (const name of names) {+ const key = this.key(scope, name);+ const binding = this.pending.get(key);+ if (binding == null) continue;+ bindings.push(binding);+ }+ return bindings;+ }+}diff --git a/packages/api/src/agents/handlers.spec.ts b/packages/api/src/agents/handlers.spec.tsindex c7baabe333..bc56be1d70 100644--- a/packages/api/src/agents/handlers.spec.ts+++ b/packages/api/src/agents/handlers.spec.ts@@ -26,6 +26,7 @@ import {ToolExecuteOptions,} from './handlers';import { markSandboxReady } from './prewarm';+import { captureAuthoredSkills, restoreAuthoredSkills } from './authored';import { ContentFilterError } from '../middleware/contentFilter';import { WorkspaceToolHttpError } from '../code/workspace';import { createAttachedWorkspaceBashTool, stampCommandExecutor } from '../code/command';@@ -3290,6 +3291,180 @@ describe('createToolExecuteHandler', () => {});}+ it.each([+ 'allowed',+ 'revoked',+ 'replaced',+ 'missing',+ 'hidden',+ 'disabled',+ 'unprimed',+ 'unprimed-hidden',+ 'deleted-later',+ ])('restores authored identity into a fresh handler after approval: %s', async (scenario) => {+ const skill = {+ _id: SKILL_ID,+ name: 'resumed-skill',+ body: '---\nname: resumed-skill\ndescription: Resume regression\n---\n# Authored body\n',+ description: 'Resume regression',+ version: 1,+ fileCount: 0,+ };+ let stored = false;+ const twinId = new Types.ObjectId();+ const getSkillByName = jest.fn(async (name: string, ids: Array<{ toString(): string }>) => {+ if (ids.some((id) => id.toString() === twinId.toString())) {+ return { ...skill, _id: twinId, body: '# Same-name twin' };+ }+ return stored &&+ name === skill.name &&+ ids.some((id) => id.toString() === SKILL_ID.toString())+ ? { ...skill, disableModelInvocation: scenario.endsWith('hidden') }+ : null;+ });+ const saveSkillFileContent = jest.fn(async () => ({+ bytes: 9,+ relativePath: 'references/a.md',+ }));+ const getAuthorSkillByName = jest.fn(async () =>+ scenario === 'missing'+ ? null+ : {+ ...skill,+ disableModelInvocation: scenario.endsWith('hidden'),+ _id: scenario === 'replaced' ? new Types.ObjectId() : SKILL_ID,+ },+ );+ const dependencies = {+ getSkillByName,+ createSkill: jest.fn(async () => {+ stored = true;+ return { skill, warnings: [] };+ }),+ getAuthorSkillByName,+ getSkillFileByPath: jest.fn(async () => null),+ saveSkillFileContent,+ };+ const original = makeAuthoringHandler(dependencies, { accessibleSkillIds: [] });+ const [created] = await invokeHandlerWithConfig(+ original,+ [+ {+ id: 'create-main',+ name: 'create_file',+ args: { path: 'skills/resumed-skill/SKILL.md', content: skill.body },+ },+ ],+ { req, accessibleSkillIds: [] },+ );+ expect(created.status).toBe('success');+ // JSON round-trip and a new handler/configurable model a different resume replica.+ const bindings = JSON.parse(JSON.stringify(captureAuthoredSkills(original)));+ expect(bindings).toEqual([+ {+ agentId: '',+ name: skill.name,+ id: SKILL_ID.toString(),+ primed: true,+ },+ ]);+ if (scenario.startsWith('unprimed')) bindings[0].primed = false;+ const resumed = makeAuthoringHandler(+ {+ ...dependencies,+ canEditSkill: jest.fn(async () => scenario !== 'revoked'),+ },+ {+ accessibleSkillIds: [twinId],+ skillAuthoringAvailable: scenario !== 'disabled',+ skillPrimedIdsByName: { [skill.name]: twinId.toString() },+ },+ );+ restoreAuthoredSkills(resumed, bindings);+ const fresh = { req, accessibleSkillIds: [], activeSkillNames: new Set(['unrelated']) };+ const [bundled] = await invokeHandlerWithConfig(+ resumed,+ [+ {+ id: 'create-reference',+ name: 'create_file',+ args: { path: 'skills/resumed-skill/references/a.md', content: 'reference' },+ },+ ],+ fresh,+ );+ const allowed = ['allowed', 'hidden', 'unprimed', 'deleted-later'].includes(scenario);+ expect(bundled.status).toBe(allowed ? 'success' : 'error');+ expect(saveSkillFileContent).toHaveBeenCalledTimes(allowed ? 1 : 0);+ if (scenario === 'deleted-later') {+ stored = false;+ getAuthorSkillByName.mockResolvedValue({+ ...skill,+ _id: twinId,+ disableModelInvocation: false,+ });+ }+ const stillAllowed = allowed && scenario !== 'deleted-later';+ const [laterWrite] = await invokeHandlerWithConfig(+ resumed,+ [+ {+ id: 'later-reference',+ name: 'create_file',+ args: { path: 'skills/resumed-skill/references/b.md', content: 'later' },+ },+ ],+ fresh,+ );+ expect(laterWrite.status).toBe(stillAllowed ? 'success' : 'error');+ if (stillAllowed) {+ expect(saveSkillFileContent.mock.calls).toHaveLength(2);+ expect(saveSkillFileContent).toHaveBeenLastCalledWith(+ expect.objectContaining({ skillId: SKILL_ID }),+ );+ }+ const [read] = await invokeHandlerWithConfig(+ resumed,+ [+ {+ id: 'read-authored',+ name: Constants.READ_FILE,+ args: { path: 'skills/resumed-skill/SKILL.md' },+ },+ ],+ fresh,+ );+ expect(read.status).toBe(stillAllowed ? 'success' : 'error');+ if (stillAllowed) {+ expect(String(read.content)).toContain('# Authored body');+ expect(String(read.content)).not.toContain('# Same-name twin');+ }++ const [invoked] = await invokeHandlerWithConfig(+ resumed,+ [+ {+ id: 'invoke-authored',+ name: Constants.SKILL_TOOL,+ args: { skillName: skill.name },+ },+ ],+ fresh,+ );+ expect(invoked.status).toBe(['allowed', 'unprimed'].includes(scenario) ? 'success' : 'error');+ if (scenario.endsWith('hidden')) expect(invoked.errorMessage).toContain('cannot be invoked');+ if (scenario === 'disabled') expect(getAuthorSkillByName).not.toHaveBeenCalled();+ if (scenario === 'deleted-later') {+ expect(saveSkillFileContent).toHaveBeenCalledTimes(1);+ expect(captureAuthoredSkills(resumed)).toEqual(bindings);+ }+ if (scenario === 'allowed') {+ expect(JSON.stringify(invoked.injectedMessages)).toContain('# Authored body');+ // A second pause before another tool call retains the exact binding.+ expect(captureAuthoredSkills(resumed)).toEqual(bindings);+ }+ });+it('creates a new SKILL.md through create_file', async () => {const createSkill = jest.fn(async () => ({skill: {diff --git a/packages/api/src/agents/handlers.ts b/packages/api/src/agents/handlers.tsindex 75807fdcb9..f8d1928118 100644--- a/packages/api/src/agents/handlers.ts+++ b/packages/api/src/agents/handlers.ts@@ -62,6 +62,7 @@ import type { SandboxTextReader } from '~/files/code/text';import type { WorkspaceEditMatching } from '~/code/edits';import type { CodeExecutionContext } from './execution';import type { TextContentFragment } from '~/protection';+import type { AuthoredSkillBinding } from './authored';import type { RunFileSession } from './files/session';import type { ServerRequest } from '~/types';import type { TextEdit } from './edits';@@ -162,6 +163,7 @@ import { deleteSkillWithRetry } from '~/skills/cleanup';import { resolveDownloadPath } from '~/storage/path';import { parseFrontmatter } from '../skills/import';import { HostEditError } from './files/matching';+import { AuthoredSkillState } from './authored';import { cleanCodeToolOutput } from './cleanup';import { primeSkillFiles } from './skillFiles';import { instrumentPtcToolMap } from './ptc';@@ -287,6 +289,8 @@ export function createOwnedToolEndHandler(}export interface ToolExecuteOptions {+ /** Host observer, called only after authoring has bound an authorized identity. */+ onSkillAuthored?: (binding: Pick<AuthoredSkillBinding, 'name' | 'id' | 'primed'>) => void;/** Host-captured authority ceiling, never runnable/model metadata. */scheduledMCPExecution?: Pick<ScheduleMCPExecution, 'enrolled' | 'identity'>;/**@@ -2970,9 +2974,10 @@ async function resolveSkillForAuthoring(const skillPrimedIdsByName =(mergedConfigurable?.skillPrimedIdsByName as Record<string, string> | undefined) ?? {};- const primedIdString = skillPrimedIdsByName[skillName];- if (primedIdString) {- return await getSkillByName(skillName, [new Types.ObjectId(primedIdString)], {});+ const pinnedIdString =+ getAuthoredSkillId(skillName, mergedConfigurable) ?? skillPrimedIdsByName[skillName];+ if (pinnedIdString) {+ return await getSkillByName(skillName, [new Types.ObjectId(pinnedIdString)], {});}const accessibleIds = (mergedConfigurable?.accessibleSkillIds as Types.ObjectId[]) ?? [];@@ -3003,10 +3008,12 @@ async function resolveAuthorSkillForCurrentUser({return null;}const skill = await options.getAuthorSkillByName({ req, name: skillName });- if (!skill) {+ const authoredId = getAuthoredSkillId(skillName, mergedConfigurable);+ if (!skill || (authoredId != null && skill._id.toString() !== authoredId)) {return null;}rememberAuthoredSkill([mergedConfigurable, sourceConfigurable], skill, { prime: false });+ options.onSkillAuthored?.({ name: skill.name, id: skill._id.toString(), primed: false });return skill;}@@ -3066,7 +3073,9 @@ function isSkillPrimedForAuthoring(): boolean {const skillPrimedIdsByName =(mergedConfigurable.skillPrimedIdsByName as Record<string, string> | undefined) ?? {};- return typeof skillPrimedIdsByName[skillName] === 'string';+ const primedId = skillPrimedIdsByName[skillName];+ const authoredId = getAuthoredSkillId(skillName, mergedConfigurable);+ return typeof primedId === 'string' && (authoredId == null || authoredId === primedId);}function isSkillKnownToCurrentRun(@@ -3659,6 +3668,11 @@ async function writeSkillMd({throw error;}rememberAuthoredSkill([mergedConfigurable, sourceConfigurable], result.skill);+ options.onSkillAuthored?.({+ name: result.skill.name,+ id: result.skill._id.toString(),+ primed: true,+ });const surfacedWarnings = surfaceSkillAuthoringWarnings(result.warnings);const invocationHint = authoredSkillInvocationHint(structured.frontmatter);return successResult(@@ -4769,13 +4783,13 @@ async function handleReadFileCall(let skillPrimedIdsByName =(mergedConfigurable?.skillPrimedIdsByName as Record<string, string> | undefined) ?? {};let primedIdString = skillPrimedIdsByName[skillName];- let isPrimedThisTurn = primedIdString != null;+ let isPrimedThisTurn = isSkillPrimedForAuthoring(skillName, mergedConfigurable);const refreshSkillReadScope = () => {accessibleIds = (mergedConfigurable?.accessibleSkillIds as Types.ObjectId[]) ?? [];skillPrimedIdsByName =(mergedConfigurable?.skillPrimedIdsByName as Record<string, string> | undefined) ?? {};primedIdString = skillPrimedIdsByName[skillName];- isPrimedThisTurn = primedIdString != null;+ isPrimedThisTurn = isSkillPrimedForAuthoring(skillName, mergedConfigurable);};let recoveredAuthorSkill: AuthoringSkill | null | undefined;const recoverAuthorSkill = async () => {@@ -4902,9 +4916,10 @@ async function handleReadFileCall((rather than relying on mongoose's string auto-cast in `$in` queries)keeps the value correct for any future consumer that compares with`.equals()` or `===`. */- const lookupAccessibleIds = primedIdString ? [new Types.ObjectId(primedIdString)] : accessibleIds;+ const pinnedIdString = getAuthoredSkillId(skillName, mergedConfigurable) ?? primedIdString;+ const lookupAccessibleIds = pinnedIdString ? [new Types.ObjectId(pinnedIdString)] : accessibleIds;const lookupOptions: { preferUserInvocable?: boolean; preferModelInvocable?: boolean } =- primedIdString ? {} : { preferModelInvocable: true };+ pinnedIdString ? {} : { preferModelInvocable: true };let skill = await getSkillByName(skillName, lookupAccessibleIds, lookupOptions);if (!skill) {skill = await recoverAuthorSkill();@@ -5646,7 +5661,9 @@ function getToolFailureFeedback(content: ToolExecuteResult['content']): string {return messages.join('\n') || 'Tool execution failed.';}-export function createToolExecuteHandler(options: ToolExecuteOptions): EventHandler {+export function createToolExecuteHandler(handlerOptions: ToolExecuteOptions): EventHandler {+ const authoredSkills = new AuthoredSkillState();+ const resumedSkillConfigurables = new Map<string, Record<string, unknown>>();const {scheduledMCPExecution,runSignal: hostRunSignal,@@ -5664,9 +5681,9 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHandordinaryToolCancellation = false,backgroundCompletionResultMaxChars = AGENT_BACKGROUND_COMPLETION_RESULT_MAX_CHARS_DEFAULT,provisionFiles,- } = options;+ } = handlerOptions;- return {+ const handler: EventHandler = {handle: async (_event: string, data: ToolExecuteBatchRequest) => {const {toolCalls,@@ -5681,6 +5698,11 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHandconst executionContext = (data as ToolExecuteBatchRequest & { executionContext?: SubagentExecutionContext }).executionContext;+ const authoredScope = authoredSkills.scope(agentId, executionContext);+ const options: ToolExecuteOptions = {+ ...handlerOptions,+ onSkillAuthored: (binding) => authoredSkills.record(authoredScope, binding),+ };// Only the SDK-owned batch field may establish a child execution. Runtime// configurable and callback metadata can otherwise carry inherited values./**@@ -5801,10 +5823,73 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHand);const toolMap = new Map(loadedTools.map((t) => [t.name, t]));const loadedConfigurable = toolConfigurable as Record<string, unknown> | undefined;- const mergedConfigurable = mergeToolConfigurables(- sourceConfigurable,- loadedConfigurable,- );+ const authoredScopeKey = JSON.stringify(authoredScope);+ let resumedSkillConfigurable = resumedSkillConfigurables.get(authoredScopeKey);+ const baseConfigurable = mergeToolConfigurables(sourceConfigurable, loadedConfigurable);+ // Restored identity wins; current capability and request fields still come from loadTools.+ const mergedConfigurable = resumedSkillConfigurable+ ? mergeToolConfigurables(resumedSkillConfigurable, baseConfigurable)+ : baseConfigurable;+ if (authoredSkills.hasPending) {+ const requestedSkills = new Map<string, ToolCallRequest[]>();+ for (const tc of allowedToolCalls) {+ const args = tc.args as { path?: unknown; skillName?: unknown };+ let skillName: string | undefined;+ if (tc.name === Constants.SKILL_TOOL && typeof args.skillName === 'string') {+ skillName = args.skillName;+ } else if (+ typeof args.path === 'string' &&+ (args.path.startsWith(SKILL_FILE_PREFIX) ||+ (tc.name === Constants.READ_FILE && !args.path.startsWith('workspace/'))) &&+ (tc.name === Constants.READ_FILE ||+ isHostFileAuthoringToolCall(tc.name, mergedConfigurable))+ ) {+ const path = args.path.startsWith(SKILL_FILE_PREFIX)+ ? args.path.slice(SKILL_FILE_PREFIX.length)+ : args.path;+ skillName = path.split('/')[0];+ }+ if (skillName)+ requestedSkills.set(skillName, [...(requestedSkills.get(skillName) ?? []), tc]);+ }+ const restored = authoredSkills.take(authoredScope, new Set(requestedSkills.keys()));+ if (restored.length > 0) {+ const req = mergedConfigurable.req as ServerRequest | undefined;+ await Promise.all(+ restored.map(async (binding) => {+ const skill =+ isSkillAuthoringAvailable(mergedConfigurable) &&+ req &&+ options.getAuthorSkillByName+ ? await options.getAuthorSkillByName({ req, name: binding.name })+ : null;+ const allowed =+ skill &&+ skill._id.toString() === binding.id &&+ req &&+ options.canEditSkill &&+ (await options.canEditSkill({ req, skillId: skill._id }));+ if (!allowed || !skill) {+ for (const tc of requestedSkills.get(binding.name) ?? []) {+ preloadedNameBlocks.set(+ tc,+ errorResult(tc, `Skill "${binding.name}" not found or not accessible.`),+ );+ }+ return;+ }+ if (!resumedSkillConfigurable) {+ resumedSkillConfigurable = {};+ resumedSkillConfigurables.set(authoredScopeKey, resumedSkillConfigurable);+ }+ rememberAuthoredSkill([mergedConfigurable, resumedSkillConfigurable], skill, {+ prime: binding.primed,+ });+ authoredSkills.confirm(authoredScope, binding.name);+ }),+ );+ }+ }if (mergedConfigurable != null) mergedConfigurable.executionContext = executionContext;/* The graph populated each call's code-session context from the sessions that* existed at run start, before this batch provisioned anything, and nothing@@ -7862,4 +7947,6 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHand}},};+ authoredSkills.bind(handler);+ return handler;}diff --git a/packages/api/src/agents/index.ts b/packages/api/src/agents/index.tsindex fb0b2653cd..834b335059 100644--- a/packages/api/src/agents/index.ts+++ b/packages/api/src/agents/index.ts@@ -99,3 +99,4 @@ export * from './remote';export * from './queuedTurns';export * from './queuedTurnHttp';export * from './files/index';+export { captureAuthoredSkills, restoreAuthoredSkills } from './authored';diff --git a/packages/api/src/stream/ApprovalLifecycle.ts b/packages/api/src/stream/ApprovalLifecycle.tsindex 9b15fd2be0..926d4d72bf 100644--- a/packages/api/src/stream/ApprovalLifecycle.ts+++ b/packages/api/src/stream/ApprovalLifecycle.ts@@ -11,6 +11,7 @@ import type {SteerQueueItem,} from '~/stream/interfaces/IJobStore';import type { ActivityPhaseSnapshot } from '~/agents/activityPhases/runtime';+import type { AuthoredSkillBinding } from '~/agents/authored';import {JobStatusTransitionDeadlineError,isPendingActionExpired,@@ -33,6 +34,7 @@ export interface ApprovalLifecycleCallbacks {export interface ApprovalPauseOptions {discoveredTools?: string[];+ authoredSkills?: AuthoredSkillBinding[];activityPhaseSnapshot?: ActivityPhaseSnapshot;compactionSemanticIndex?: ICompactionSemanticIndexProjection;/** Calibration and fading state at the pause; seeds the resumed run's pruner. */@@ -153,6 +155,7 @@ export class ApprovalLifecycle {...(discoveredTools != null && discoveredTools.length > 0? { discoveredTools: [...discoveredTools] }: {}),+ ...(options.authoredSkills != null ? { authoredSkills: options.authoredSkills } : {}),...(activityPhaseSnapshot != null ? { activityPhaseSnapshot } : {}),...(compactionSemanticIndex != null ? { compactionSemanticIndex } : {}),...(contextMeta != null ? { contextMeta } : {}),diff --git a/packages/api/src/stream/GenerationJobManager.ts b/packages/api/src/stream/GenerationJobManager.tsindex 1864758b48..08ddd067ad 100644--- a/packages/api/src/stream/GenerationJobManager.ts+++ b/packages/api/src/stream/GenerationJobManager.ts@@ -3164,6 +3164,7 @@ class GenerationJobManagerClass {// Surface deferred tools discovered before the pause so the resume route can// replay them into createRun (the rebuilt graph passes `messages: []`).discoveredTools: jobData.discoveredTools,+ authoredSkills: jobData.authoredSkills,activityPhaseSnapshot: jobData.activityPhaseSnapshot,compactionSemanticIndex: jobData.compactionSemanticIndex,contextMeta: jobData.contextMeta,diff --git a/packages/api/src/stream/__tests__/RedisJobStore.spec.ts b/packages/api/src/stream/__tests__/RedisJobStore.spec.tsindex e8a7a63790..c4bf31bdc3 100644--- a/packages/api/src/stream/__tests__/RedisJobStore.spec.ts+++ b/packages/api/src/stream/__tests__/RedisJobStore.spec.ts@@ -366,6 +366,9 @@ describe('RedisJobStore', () => {preserveForScheduleReconcile: true,promptTokens: 0,discoveredTools: [],+ authoredSkills: [+ { agentId: 'a', name: 'new-skill', id: '507f1f77bcf86cd799439011', primed: true },+ ],contextMeta: {calibrationRatio: 1.25,encoding: 'claude',@@ -478,6 +481,9 @@ describe('RedisJobStore', () => {preserveForScheduleReconcile: true,promptTokens: 0,discoveredTools: [],+ authoredSkills: [+ { agentId: 'a', name: 'new-skill', id: '507f1f77bcf86cd799439011', primed: true },+ ],contextMeta: {calibrationRatio: 1.25,encoding: 'claude',@@ -537,6 +543,9 @@ describe('RedisJobStore', () => {preserveForScheduleReconcile: '1',promptTokens: '0',discoveredTools: '[]',+ authoredSkills: JSON.stringify([+ { agentId: 'a', name: 'new-skill', id: '507f1f77bcf86cd799439011', primed: true },+ ]),resolvedAskUserQuestions: JSON.stringify([{request: { question: 'Deploy where?' },diff --git a/packages/api/src/stream/__tests__/RedisJobStore.stream_integration.spec.ts b/packages/api/src/stream/__tests__/RedisJobStore.stream_integration.spec.tsindex 96664ad4e0..a9c732ca5c 100644--- a/packages/api/src/stream/__tests__/RedisJobStore.stream_integration.spec.ts+++ b/packages/api/src/stream/__tests__/RedisJobStore.stream_integration.spec.ts@@ -1584,6 +1584,9 @@ describe('RedisJobStore Integration Tests', () => {},agentEventLegacyTurnToken: 'legacy-hitl-token',discoveredTools: ['deep_tool'],+ authoredSkills: [+ { agentId: 'a', name: 'new-skill', id: '507f1f77bcf86cd799439011', primed: true },+ ],userSubmittedPaths: ['/content/0/tool_call/args'],userSubmittedMessageFieldPaths: [{ path: '/content/0/tool_call/output', field: 'answer' }],});@@ -1603,6 +1606,7 @@ describe('RedisJobStore Integration Tests', () => {});expect(turn1?.agentEventLegacyTurnToken).toBe('legacy-hitl-token');expect(turn1?.discoveredTools).toEqual(['deep_tool']);+ expect(turn1?.authoredSkills).toHaveLength(1);expect(turn1?.userSubmittedPaths).toEqual(['/content/0/tool_call/args']);expect(turn1?.userSubmittedMessageFieldPaths).toEqual([{ path: '/content/0/tool_call/output', field: 'answer' },@@ -1623,6 +1627,7 @@ describe('RedisJobStore Integration Tests', () => {expect(turn2?.agentEventSuspension).toBeUndefined();expect(turn2?.agentEventLegacyTurnToken).toBeUndefined();expect(turn2?.discoveredTools).toBeUndefined();+ expect(turn2?.authoredSkills).toBeUndefined();expect(turn2?.userSubmittedPaths).toBeUndefined();expect(turn2?.userSubmittedMessageFieldPaths).toBeUndefined();diff --git a/packages/api/src/stream/__tests__/pendingAction.spec.ts b/packages/api/src/stream/__tests__/pendingAction.spec.tsindex 4933cbb9a2..e56deb6075 100644--- a/packages/api/src/stream/__tests__/pendingAction.spec.ts+++ b/packages/api/src/stream/__tests__/pendingAction.spec.ts@@ -214,12 +214,18 @@ describe('ApprovalLifecycle via GenerationJobManager.approvals (in-memory)', ()expect(await manager.approvals.pause(streamId, action, {discoveredTools: ['save_issue_mcp_linear'],+ authoredSkills: [+ { agentId: 'a', name: 'new-skill', id: '507f1f77bcf86cd799439011', primed: true },+ ],}),).toBe(true);const paused = await manager.getJob(streamId);expect(paused?.status).toBe('requires_action');expect(paused?.metadata.discoveredTools).toEqual(['save_issue_mcp_linear']);+ expect(paused?.metadata.authoredSkills).toEqual([+ { agentId: 'a', name: 'new-skill', id: '507f1f77bcf86cd799439011', primed: true },+ ]);});test('persists activity phase state in the same transition as the pause', async () => {diff --git a/packages/api/src/stream/implementations/RedisJobStore.ts b/packages/api/src/stream/implementations/RedisJobStore.tsindex ff96a3b803..b7403ffbab 100644--- a/packages/api/src/stream/implementations/RedisJobStore.ts+++ b/packages/api/src/stream/implementations/RedisJobStore.ts@@ -5750,6 +5750,7 @@ export class RedisJobStore implements IJobStoreV2 {detachedAgentEventTerminalStatus,// Deferred tools discovered before a HITL pause; replayed into createRun on resume.discoveredTools: data.discoveredTools ? JSON.parse(data.discoveredTools) : undefined,+ authoredSkills: data.authoredSkills ? JSON.parse(data.authoredSkills) : undefined,activityPhaseSnapshot: data.activityPhaseSnapshot? JSON.parse(data.activityPhaseSnapshot): undefined,diff --git a/packages/api/src/stream/interfaces/IJobStore.ts b/packages/api/src/stream/interfaces/IJobStore.tsindex 6ff437d7cf..7f3f38f0d7 100644--- a/packages/api/src/stream/interfaces/IJobStore.ts+++ b/packages/api/src/stream/interfaces/IJobStore.ts@@ -16,6 +16,7 @@ import type { ActivityPhaseSnapshot } from '~/agents/activityPhases/runtime';import type { ReplayLimits, ReplayPublication } from '../internal/replay';import type { ResolvedAskUserQuestion } from '~/agents/hitl/resume';import type { RecoveredSteerPayload } from '../SteerRecovery';+import type { AuthoredSkillBinding } from '~/agents/authored';import type { MCPRuntimeRequestBody } from '~/mcp/types';/**@@ -205,6 +206,8 @@ export interface SerializableJobData {* the discovered tool schemas.*/discoveredTools?: string[];+ /** Skill identities authored by this generation, reauthorized on resume. */+ authoredSkills?: AuthoredSkillBinding[];/** Bounded collector state for continuing a phase across HITL resume. */activityPhaseSnapshot?: ActivityPhaseSnapshot;/** Exact bounded compaction guidance captured atomically with a HITL pause. */@@ -520,6 +523,7 @@ export type JobMetadataPatch = Partial<| 'preserveForScheduleReconcile'| 'promptTokens'| 'discoveredTools'+ | 'authoredSkills'| 'activityPhaseSnapshot'| 'compactionSemanticIndex'| 'contextMeta'diff --git a/packages/api/src/stream/metadata.ts b/packages/api/src/stream/metadata.tsindex 61455d2161..c83ff543b7 100644--- a/packages/api/src/stream/metadata.ts+++ b/packages/api/src/stream/metadata.ts@@ -120,6 +120,9 @@ export function sanitizeJobMetadata(metadata: Partial<GenerationJobMetadata>): Jif (metadata.discoveredTools) {patch.discoveredTools = metadata.discoveredTools;}+ if (metadata.authoredSkills) {+ patch.authoredSkills = metadata.authoredSkills;+ }if (metadata.activityPhaseSnapshot) {patch.activityPhaseSnapshot = metadata.activityPhaseSnapshot;}diff --git a/packages/api/src/types/stream.ts b/packages/api/src/types/stream.tsindex f478ee3052..9b5d8f1e5d 100644--- a/packages/api/src/types/stream.ts+++ b/packages/api/src/types/stream.ts@@ -13,6 +13,7 @@ import type {import type { ActivityPhaseSnapshot } from '~/agents/activityPhases/runtime';import type { EarlyBufferOverflowState } from './earlyBufferRecovery';import type { ResolvedAskUserQuestion } from '../agents/hitl/resume';+import type { AuthoredSkillBinding } from '~/agents/authored';import type { MCPRuntimeRequestBody } from '../mcp/types';import type { ServerSentEvent } from './events';@@ -100,6 +101,7 @@ export interface GenerationJobMetadata {* without them the rebuilt model would lose the discovered tool schemas.*/discoveredTools?: string[];+ authoredSkills?: AuthoredSkillBinding[];/** Bounded collector state for continuing a phase across HITL resume. */activityPhaseSnapshot?: ActivityPhaseSnapshot;/** Exact bounded compaction guidance captured atomically with a HITL pause. */